Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 10816, column 5
Passed-by-value struct argument contains uninitialized data (e.g., field: 'SavedInNonInstantiationSFINAEContext')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn360410/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn360410/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn360410/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn360410/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn360410/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn360410=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-11-053245-11877-1 -x c++ /build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp -faddrsig
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/LiteralSupport.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaInternal.h"
39#include "clang/Sema/Template.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43#include <map>
44#include <set>
45
46using namespace clang;
47
48//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
52namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
58 class CheckDefaultArgumentVisitor
59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60 Expr *DefaultArg;
61 Sema *S;
62
63 public:
64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65 : DefaultArg(defarg), S(s) {}
66
67 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
69 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70 bool VisitLambdaExpr(LambdaExpr *Lambda);
71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72 };
73
74 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
77 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
79 return IsInvalid;
80 }
81
82 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86 NamedDecl *Decl = DRE->getDecl();
87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
96 return S->Diag(DRE->getBeginLoc(),
97 diag::err_param_default_argument_references_param)
98 << Param->getDeclName() << DefaultArg->getSourceRange();
99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
103 if (VDecl->isLocalVarDecl())
104 return S->Diag(DRE->getBeginLoc(),
105 diag::err_param_default_argument_references_local)
106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
107 }
108
109 return false;
110 }
111
112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
117 return S->Diag(ThisE->getBeginLoc(),
118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
120 }
121
122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 131, __PRETTY_FUNCTION__))
;
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
146 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
147 }
148}
149
150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If we have a throw-all spec at this point, ignore the function.
166 if (ComputedEST == EST_None)
167 return;
168
169 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170 EST = EST_BasicNoexcept;
171
172 switch (EST) {
173 case EST_Unparsed:
174 case EST_Uninstantiated:
175 case EST_Unevaluated:
176 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 176)
;
177
178 // If this function can throw any exceptions, make a note of that.
179 case EST_MSAny:
180 case EST_None:
181 // FIXME: Whichever we see last of MSAny and None determines our result.
182 // We should make a consistent, order-independent choice here.
183 ClearExceptions();
184 ComputedEST = EST;
185 return;
186 case EST_NoexceptFalse:
187 ClearExceptions();
188 ComputedEST = EST_None;
189 return;
190 // FIXME: If the call to this decl is using any of its default arguments, we
191 // need to search them for potentially-throwing calls.
192 // If this function has a basic noexcept, it doesn't affect the outcome.
193 case EST_BasicNoexcept:
194 case EST_NoexceptTrue:
195 return;
196 // If we're still at noexcept(true) and there's a throw() callee,
197 // change to that specification.
198 case EST_DynamicNone:
199 if (ComputedEST == EST_BasicNoexcept)
200 ComputedEST = EST_DynamicNone;
201 return;
202 case EST_DependentNoexcept:
203 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 204)
204 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 204)
;
205 case EST_Dynamic:
206 break;
207 }
208 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 208, __PRETTY_FUNCTION__))
;
209 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 210, __PRETTY_FUNCTION__))
210 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 210, __PRETTY_FUNCTION__))
;
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (const auto &E : Proto->exceptions())
214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215 Exceptions.push_back(E);
216}
217
218void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219 if (!E || ComputedEST == EST_MSAny)
220 return;
221
222 // FIXME:
223 //
224 // C++0x [except.spec]p14:
225 // [An] implicit exception-specification specifies the type-id T if and
226 // only if T is allowed by the exception-specification of a function directly
227 // invoked by f's implicit definition; f shall allow all exceptions if any
228 // function it directly invokes allows all exceptions, and f shall allow no
229 // exceptions if every function it directly invokes allows no exceptions.
230 //
231 // Note in particular that if an implicit exception-specification is generated
232 // for a function containing a throw-expression, that specification can still
233 // be noexcept(true).
234 //
235 // Note also that 'directly invoked' is not defined in the standard, and there
236 // is no indication that we should only consider potentially-evaluated calls.
237 //
238 // Ultimately we should implement the intent of the standard: the exception
239 // specification should be the set of exceptions which can be thrown by the
240 // implicit definition. For now, we assume that any non-nothrow expression can
241 // throw any exception.
242
243 if (Self->canThrow(E))
244 ComputedEST = EST_None;
245}
246
247bool
248Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249 SourceLocation EqualLoc) {
250 if (RequireCompleteType(Param->getLocation(), Param->getType(),
251 diag::err_typecheck_decl_incomplete_type)) {
252 Param->setInvalidDecl();
253 return true;
254 }
255
256 // C++ [dcl.fct.default]p5
257 // A default argument expression is implicitly converted (clause
258 // 4) to the parameter type. The default argument expression has
259 // the same semantic constraints as the initializer expression in
260 // a declaration of a variable of the parameter type, using the
261 // copy-initialization semantics (8.5).
262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263 Param);
264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265 EqualLoc);
266 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268 if (Result.isInvalid())
269 return true;
270 Arg = Result.getAs<Expr>();
271
272 CheckCompletedExpr(Arg, EqualLoc);
273 Arg = MaybeCreateExprWithCleanups(Arg);
274
275 // Okay: add the default argument to the parameter
276 Param->setDefaultArg(Arg);
277
278 // We have already instantiated this parameter; provide each of the
279 // instantiations with the uninstantiated default argument.
280 UnparsedDefaultArgInstantiationsMap::iterator InstPos
281 = UnparsedDefaultArgInstantiations.find(Param);
282 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285
286 // We're done tracking this parameter's instantiations.
287 UnparsedDefaultArgInstantiations.erase(InstPos);
288 }
289
290 return false;
291}
292
293/// ActOnParamDefaultArgument - Check whether the default argument
294/// provided for a function parameter is well-formed. If so, attach it
295/// to the parameter declaration.
296void
297Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298 Expr *DefaultArg) {
299 if (!param || !DefaultArg)
300 return;
301
302 ParmVarDecl *Param = cast<ParmVarDecl>(param);
303 UnparsedDefaultArgLocs.erase(Param);
304
305 // Default arguments are only permitted in C++
306 if (!getLangOpts().CPlusPlus) {
307 Diag(EqualLoc, diag::err_param_default_argument)
308 << DefaultArg->getSourceRange();
309 Param->setInvalidDecl();
310 return;
311 }
312
313 // Check for unexpanded parameter packs.
314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315 Param->setInvalidDecl();
316 return;
317 }
318
319 // C++11 [dcl.fct.default]p3
320 // A default argument expression [...] shall not be specified for a
321 // parameter pack.
322 if (Param->isParameterPack()) {
323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324 << DefaultArg->getSourceRange();
325 return;
326 }
327
328 // Check that the default argument is well-formed
329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330 if (DefaultArgChecker.Visit(DefaultArg)) {
331 Param->setInvalidDecl();
332 return;
333 }
334
335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336}
337
338/// ActOnParamUnparsedDefaultArgument - We've seen a default
339/// argument for a function parameter, but we can't parse it yet
340/// because we're inside a class definition. Note that this default
341/// argument will be parsed later.
342void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343 SourceLocation EqualLoc,
344 SourceLocation ArgLoc) {
345 if (!param)
346 return;
347
348 ParmVarDecl *Param = cast<ParmVarDecl>(param);
349 Param->setUnparsedDefaultArg();
350 UnparsedDefaultArgLocs[Param] = ArgLoc;
351}
352
353/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354/// the default argument for the parameter param failed.
355void Sema::ActOnParamDefaultArgumentError(Decl *param,
356 SourceLocation EqualLoc) {
357 if (!param)
358 return;
359
360 ParmVarDecl *Param = cast<ParmVarDecl>(param);
361 Param->setInvalidDecl();
362 UnparsedDefaultArgLocs.erase(Param);
363 Param->setDefaultArg(new(Context)
364 OpaqueValueExpr(EqualLoc,
365 Param->getType().getNonReferenceType(),
366 VK_RValue));
367}
368
369/// CheckExtraCXXDefaultArguments - Check for any extra default
370/// arguments in the declarator, which is not a function declaration
371/// or definition and therefore is not permitted to have default
372/// arguments. This routine should be invoked for every declarator
373/// that is not a function declaration or definition.
374void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375 // C++ [dcl.fct.default]p3
376 // A default argument expression shall be specified only in the
377 // parameter-declaration-clause of a function declaration or in a
378 // template-parameter (14.1). It shall not be specified for a
379 // parameter pack. If it is specified in a
380 // parameter-declaration-clause, it shall not occur within a
381 // declarator or abstract-declarator of a parameter-declaration.
382 bool MightBeFunction = D.isFunctionDeclarationContext();
383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384 DeclaratorChunk &chunk = D.getTypeObject(i);
385 if (chunk.Kind == DeclaratorChunk::Function) {
386 if (MightBeFunction) {
387 // This is a function declaration. It can have default arguments, but
388 // keep looking in case its return type is a function type with default
389 // arguments.
390 MightBeFunction = false;
391 continue;
392 }
393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394 ++argIdx) {
395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396 if (Param->hasUnparsedDefaultArg()) {
397 std::unique_ptr<CachedTokens> Toks =
398 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
399 SourceRange SR;
400 if (Toks->size() > 1)
401 SR = SourceRange((*Toks)[1].getLocation(),
402 Toks->back().getLocation());
403 else
404 SR = UnparsedDefaultArgLocs[Param];
405 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406 << SR;
407 } else if (Param->getDefaultArg()) {
408 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
409 << Param->getDefaultArg()->getSourceRange();
410 Param->setDefaultArg(nullptr);
411 }
412 }
413 } else if (chunk.Kind != DeclaratorChunk::Paren) {
414 MightBeFunction = false;
415 }
416 }
417}
418
419static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
420 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
421 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
422 if (!PVD->hasDefaultArg())
423 return false;
424 if (!PVD->hasInheritedDefaultArg())
425 return true;
426 }
427 return false;
428}
429
430/// MergeCXXFunctionDecl - Merge two declarations of the same C++
431/// function, once we already know that they have the same
432/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
433/// error, false otherwise.
434bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
435 Scope *S) {
436 bool Invalid = false;
437
438 // The declaration context corresponding to the scope is the semantic
439 // parent, unless this is a local function declaration, in which case
440 // it is that surrounding function.
441 DeclContext *ScopeDC = New->isLocalExternDecl()
442 ? New->getLexicalDeclContext()
443 : New->getDeclContext();
444
445 // Find the previous declaration for the purpose of default arguments.
446 FunctionDecl *PrevForDefaultArgs = Old;
447 for (/**/; PrevForDefaultArgs;
448 // Don't bother looking back past the latest decl if this is a local
449 // extern declaration; nothing else could work.
450 PrevForDefaultArgs = New->isLocalExternDecl()
451 ? nullptr
452 : PrevForDefaultArgs->getPreviousDecl()) {
453 // Ignore hidden declarations.
454 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
455 continue;
456
457 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
458 !New->isCXXClassMember()) {
459 // Ignore default arguments of old decl if they are not in
460 // the same scope and this is not an out-of-line definition of
461 // a member function.
462 continue;
463 }
464
465 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
466 // If only one of these is a local function declaration, then they are
467 // declared in different scopes, even though isDeclInScope may think
468 // they're in the same scope. (If both are local, the scope check is
469 // sufficient, and if neither is local, then they are in the same scope.)
470 continue;
471 }
472
473 // We found the right previous declaration.
474 break;
475 }
476
477 // C++ [dcl.fct.default]p4:
478 // For non-template functions, default arguments can be added in
479 // later declarations of a function in the same
480 // scope. Declarations in different scopes have completely
481 // distinct sets of default arguments. That is, declarations in
482 // inner scopes do not acquire default arguments from
483 // declarations in outer scopes, and vice versa. In a given
484 // function declaration, all parameters subsequent to a
485 // parameter with a default argument shall have default
486 // arguments supplied in this or previous declarations. A
487 // default argument shall not be redefined by a later
488 // declaration (not even to the same value).
489 //
490 // C++ [dcl.fct.default]p6:
491 // Except for member functions of class templates, the default arguments
492 // in a member function definition that appears outside of the class
493 // definition are added to the set of default arguments provided by the
494 // member function declaration in the class definition.
495 for (unsigned p = 0, NumParams = PrevForDefaultArgs
496 ? PrevForDefaultArgs->getNumParams()
497 : 0;
498 p < NumParams; ++p) {
499 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
500 ParmVarDecl *NewParam = New->getParamDecl(p);
501
502 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
503 bool NewParamHasDfl = NewParam->hasDefaultArg();
504
505 if (OldParamHasDfl && NewParamHasDfl) {
506 unsigned DiagDefaultParamID =
507 diag::err_param_default_argument_redefinition;
508
509 // MSVC accepts that default parameters be redefined for member functions
510 // of template class. The new default parameter's value is ignored.
511 Invalid = true;
512 if (getLangOpts().MicrosoftExt) {
513 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
514 if (MD && MD->getParent()->getDescribedClassTemplate()) {
515 // Merge the old default argument into the new parameter.
516 NewParam->setHasInheritedDefaultArg();
517 if (OldParam->hasUninstantiatedDefaultArg())
518 NewParam->setUninstantiatedDefaultArg(
519 OldParam->getUninstantiatedDefaultArg());
520 else
521 NewParam->setDefaultArg(OldParam->getInit());
522 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
523 Invalid = false;
524 }
525 }
526
527 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
528 // hint here. Alternatively, we could walk the type-source information
529 // for NewParam to find the last source location in the type... but it
530 // isn't worth the effort right now. This is the kind of test case that
531 // is hard to get right:
532 // int f(int);
533 // void g(int (*fp)(int) = f);
534 // void g(int (*fp)(int) = &f);
535 Diag(NewParam->getLocation(), DiagDefaultParamID)
536 << NewParam->getDefaultArgRange();
537
538 // Look for the function declaration where the default argument was
539 // actually written, which may be a declaration prior to Old.
540 for (auto Older = PrevForDefaultArgs;
541 OldParam->hasInheritedDefaultArg(); /**/) {
542 Older = Older->getPreviousDecl();
543 OldParam = Older->getParamDecl(p);
544 }
545
546 Diag(OldParam->getLocation(), diag::note_previous_definition)
547 << OldParam->getDefaultArgRange();
548 } else if (OldParamHasDfl) {
549 // Merge the old default argument into the new parameter unless the new
550 // function is a friend declaration in a template class. In the latter
551 // case the default arguments will be inherited when the friend
552 // declaration will be instantiated.
553 if (New->getFriendObjectKind() == Decl::FOK_None ||
554 !New->getLexicalDeclContext()->isDependentContext()) {
555 // It's important to use getInit() here; getDefaultArg()
556 // strips off any top-level ExprWithCleanups.
557 NewParam->setHasInheritedDefaultArg();
558 if (OldParam->hasUnparsedDefaultArg())
559 NewParam->setUnparsedDefaultArg();
560 else if (OldParam->hasUninstantiatedDefaultArg())
561 NewParam->setUninstantiatedDefaultArg(
562 OldParam->getUninstantiatedDefaultArg());
563 else
564 NewParam->setDefaultArg(OldParam->getInit());
565 }
566 } else if (NewParamHasDfl) {
567 if (New->getDescribedFunctionTemplate()) {
568 // Paragraph 4, quoted above, only applies to non-template functions.
569 Diag(NewParam->getLocation(),
570 diag::err_param_default_argument_template_redecl)
571 << NewParam->getDefaultArgRange();
572 Diag(PrevForDefaultArgs->getLocation(),
573 diag::note_template_prev_declaration)
574 << false;
575 } else if (New->getTemplateSpecializationKind()
576 != TSK_ImplicitInstantiation &&
577 New->getTemplateSpecializationKind() != TSK_Undeclared) {
578 // C++ [temp.expr.spec]p21:
579 // Default function arguments shall not be specified in a declaration
580 // or a definition for one of the following explicit specializations:
581 // - the explicit specialization of a function template;
582 // - the explicit specialization of a member function template;
583 // - the explicit specialization of a member function of a class
584 // template where the class template specialization to which the
585 // member function specialization belongs is implicitly
586 // instantiated.
587 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
588 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
589 << New->getDeclName()
590 << NewParam->getDefaultArgRange();
591 } else if (New->getDeclContext()->isDependentContext()) {
592 // C++ [dcl.fct.default]p6 (DR217):
593 // Default arguments for a member function of a class template shall
594 // be specified on the initial declaration of the member function
595 // within the class template.
596 //
597 // Reading the tea leaves a bit in DR217 and its reference to DR205
598 // leads me to the conclusion that one cannot add default function
599 // arguments for an out-of-line definition of a member function of a
600 // dependent type.
601 int WhichKind = 2;
602 if (CXXRecordDecl *Record
603 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
604 if (Record->getDescribedClassTemplate())
605 WhichKind = 0;
606 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
607 WhichKind = 1;
608 else
609 WhichKind = 2;
610 }
611
612 Diag(NewParam->getLocation(),
613 diag::err_param_default_argument_member_template_redecl)
614 << WhichKind
615 << NewParam->getDefaultArgRange();
616 }
617 }
618 }
619
620 // DR1344: If a default argument is added outside a class definition and that
621 // default argument makes the function a special member function, the program
622 // is ill-formed. This can only happen for constructors.
623 if (isa<CXXConstructorDecl>(New) &&
624 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
625 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
626 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
627 if (NewSM != OldSM) {
628 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
629 assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 629, __PRETTY_FUNCTION__))
;
630 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
631 << NewParam->getDefaultArgRange() << NewSM;
632 Diag(Old->getLocation(), diag::note_previous_declaration);
633 }
634 }
635
636 const FunctionDecl *Def;
637 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
638 // template has a constexpr specifier then all its declarations shall
639 // contain the constexpr specifier.
640 if (New->isConstexpr() != Old->isConstexpr()) {
641 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
642 << New << New->isConstexpr();
643 Diag(Old->getLocation(), diag::note_previous_declaration);
644 Invalid = true;
645 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
646 Old->isDefined(Def) &&
647 // If a friend function is inlined but does not have 'inline'
648 // specifier, it is a definition. Do not report attribute conflict
649 // in this case, redefinition will be diagnosed later.
650 (New->isInlineSpecified() ||
651 New->getFriendObjectKind() == Decl::FOK_None)) {
652 // C++11 [dcl.fcn.spec]p4:
653 // If the definition of a function appears in a translation unit before its
654 // first declaration as inline, the program is ill-formed.
655 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
656 Diag(Def->getLocation(), diag::note_previous_definition);
657 Invalid = true;
658 }
659
660 // C++17 [temp.deduct.guide]p3:
661 // Two deduction guide declarations in the same translation unit
662 // for the same class template shall not have equivalent
663 // parameter-declaration-clauses.
664 if (isa<CXXDeductionGuideDecl>(New) &&
665 !New->isFunctionTemplateSpecialization()) {
666 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
667 Diag(Old->getLocation(), diag::note_previous_declaration);
668 }
669
670 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
671 // argument expression, that declaration shall be a definition and shall be
672 // the only declaration of the function or function template in the
673 // translation unit.
674 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
675 functionDeclHasDefaultArgument(Old)) {
676 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
677 Diag(Old->getLocation(), diag::note_previous_declaration);
678 Invalid = true;
679 }
680
681 return Invalid;
682}
683
684NamedDecl *
685Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
686 MultiTemplateParamsArg TemplateParamLists) {
687 assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 687, __PRETTY_FUNCTION__))
;
688 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
689
690 // The syntax only allows a decomposition declarator as a simple-declaration,
691 // a for-range-declaration, or a condition in Clang, but we parse it in more
692 // cases than that.
693 if (!D.mayHaveDecompositionDeclarator()) {
694 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
695 << Decomp.getSourceRange();
696 return nullptr;
697 }
698
699 if (!TemplateParamLists.empty()) {
700 // FIXME: There's no rule against this, but there are also no rules that
701 // would actually make it usable, so we reject it for now.
702 Diag(TemplateParamLists.front()->getTemplateLoc(),
703 diag::err_decomp_decl_template);
704 return nullptr;
705 }
706
707 Diag(Decomp.getLSquareLoc(),
708 !getLangOpts().CPlusPlus17
709 ? diag::ext_decomp_decl
710 : D.getContext() == DeclaratorContext::ConditionContext
711 ? diag::ext_decomp_decl_cond
712 : diag::warn_cxx14_compat_decomp_decl)
713 << Decomp.getSourceRange();
714
715 // The semantic context is always just the current context.
716 DeclContext *const DC = CurContext;
717
718 // C++1z [dcl.dcl]/8:
719 // The decl-specifier-seq shall contain only the type-specifier auto
720 // and cv-qualifiers.
721 auto &DS = D.getDeclSpec();
722 {
723 SmallVector<StringRef, 8> BadSpecifiers;
724 SmallVector<SourceLocation, 8> BadSpecifierLocs;
725 if (auto SCS = DS.getStorageClassSpec()) {
726 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
727 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
728 }
729 if (auto TSCS = DS.getThreadStorageClassSpec()) {
730 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
731 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
732 }
733 if (DS.isConstexprSpecified()) {
734 BadSpecifiers.push_back("constexpr");
735 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
736 }
737 if (DS.isInlineSpecified()) {
738 BadSpecifiers.push_back("inline");
739 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
740 }
741 if (!BadSpecifiers.empty()) {
742 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
743 Err << (int)BadSpecifiers.size()
744 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
745 // Don't add FixItHints to remove the specifiers; we do still respect
746 // them when building the underlying variable.
747 for (auto Loc : BadSpecifierLocs)
748 Err << SourceRange(Loc, Loc);
749 }
750 // We can't recover from it being declared as a typedef.
751 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
752 return nullptr;
753 }
754
755 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
756 QualType R = TInfo->getType();
757
758 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
759 UPPC_DeclarationType))
760 D.setInvalidType();
761
762 // The syntax only allows a single ref-qualifier prior to the decomposition
763 // declarator. No other declarator chunks are permitted. Also check the type
764 // specifier here.
765 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
766 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
767 (D.getNumTypeObjects() == 1 &&
768 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
769 Diag(Decomp.getLSquareLoc(),
770 (D.hasGroupingParens() ||
771 (D.getNumTypeObjects() &&
772 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
773 ? diag::err_decomp_decl_parens
774 : diag::err_decomp_decl_type)
775 << R;
776
777 // In most cases, there's no actual problem with an explicitly-specified
778 // type, but a function type won't work here, and ActOnVariableDeclarator
779 // shouldn't be called for such a type.
780 if (R->isFunctionType())
781 D.setInvalidType();
782 }
783
784 // Build the BindingDecls.
785 SmallVector<BindingDecl*, 8> Bindings;
786
787 // Build the BindingDecls.
788 for (auto &B : D.getDecompositionDeclarator().bindings()) {
789 // Check for name conflicts.
790 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
791 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
792 ForVisibleRedeclaration);
793 LookupName(Previous, S,
794 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
795
796 // It's not permitted to shadow a template parameter name.
797 if (Previous.isSingleResult() &&
798 Previous.getFoundDecl()->isTemplateParameter()) {
799 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
800 Previous.getFoundDecl());
801 Previous.clear();
802 }
803
804 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
805 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
806 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
807 /*AllowInlineNamespace*/false);
808 if (!Previous.empty()) {
809 auto *Old = Previous.getRepresentativeDecl();
810 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
811 Diag(Old->getLocation(), diag::note_previous_definition);
812 }
813
814 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
815 PushOnScopeChains(BD, S, true);
816 Bindings.push_back(BD);
817 ParsingInitForAutoVars.insert(BD);
818 }
819
820 // There are no prior lookup results for the variable itself, because it
821 // is unnamed.
822 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
823 Decomp.getLSquareLoc());
824 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
825 ForVisibleRedeclaration);
826
827 // Build the variable that holds the non-decomposed object.
828 bool AddToScope = true;
829 NamedDecl *New =
830 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
831 MultiTemplateParamsArg(), AddToScope, Bindings);
832 if (AddToScope) {
833 S->AddDecl(New);
834 CurContext->addHiddenDecl(New);
835 }
836
837 if (isInOpenMPDeclareTargetContext())
838 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
839
840 return New;
841}
842
843static bool checkSimpleDecomposition(
844 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
845 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
846 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
847 if ((int64_t)Bindings.size() != NumElems) {
848 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
849 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
850 << (NumElems < Bindings.size());
851 return true;
852 }
853
854 unsigned I = 0;
855 for (auto *B : Bindings) {
856 SourceLocation Loc = B->getLocation();
857 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
858 if (E.isInvalid())
859 return true;
860 E = GetInit(Loc, E.get(), I++);
861 if (E.isInvalid())
862 return true;
863 B->setBinding(ElemType, E.get());
864 }
865
866 return false;
867}
868
869static bool checkArrayLikeDecomposition(Sema &S,
870 ArrayRef<BindingDecl *> Bindings,
871 ValueDecl *Src, QualType DecompType,
872 const llvm::APSInt &NumElems,
873 QualType ElemType) {
874 return checkSimpleDecomposition(
875 S, Bindings, Src, DecompType, NumElems, ElemType,
876 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
877 ExprResult E = S.ActOnIntegerConstant(Loc, I);
878 if (E.isInvalid())
879 return ExprError();
880 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
881 });
882}
883
884static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
885 ValueDecl *Src, QualType DecompType,
886 const ConstantArrayType *CAT) {
887 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
888 llvm::APSInt(CAT->getSize()),
889 CAT->getElementType());
890}
891
892static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
893 ValueDecl *Src, QualType DecompType,
894 const VectorType *VT) {
895 return checkArrayLikeDecomposition(
896 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
897 S.Context.getQualifiedType(VT->getElementType(),
898 DecompType.getQualifiers()));
899}
900
901static bool checkComplexDecomposition(Sema &S,
902 ArrayRef<BindingDecl *> Bindings,
903 ValueDecl *Src, QualType DecompType,
904 const ComplexType *CT) {
905 return checkSimpleDecomposition(
906 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
907 S.Context.getQualifiedType(CT->getElementType(),
908 DecompType.getQualifiers()),
909 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
910 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
911 });
912}
913
914static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
915 TemplateArgumentListInfo &Args) {
916 SmallString<128> SS;
917 llvm::raw_svector_ostream OS(SS);
918 bool First = true;
919 for (auto &Arg : Args.arguments()) {
920 if (!First)
921 OS << ", ";
922 Arg.getArgument().print(PrintingPolicy, OS);
923 First = false;
924 }
925 return OS.str();
926}
927
928static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
929 SourceLocation Loc, StringRef Trait,
930 TemplateArgumentListInfo &Args,
931 unsigned DiagID) {
932 auto DiagnoseMissing = [&] {
933 if (DiagID)
934 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
935 Args);
936 return true;
937 };
938
939 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
940 NamespaceDecl *Std = S.getStdNamespace();
941 if (!Std)
942 return DiagnoseMissing();
943
944 // Look up the trait itself, within namespace std. We can diagnose various
945 // problems with this lookup even if we've been asked to not diagnose a
946 // missing specialization, because this can only fail if the user has been
947 // declaring their own names in namespace std or we don't support the
948 // standard library implementation in use.
949 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
950 Loc, Sema::LookupOrdinaryName);
951 if (!S.LookupQualifiedName(Result, Std))
952 return DiagnoseMissing();
953 if (Result.isAmbiguous())
954 return true;
955
956 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
957 if (!TraitTD) {
958 Result.suppressDiagnostics();
959 NamedDecl *Found = *Result.begin();
960 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
961 S.Diag(Found->getLocation(), diag::note_declared_at);
962 return true;
963 }
964
965 // Build the template-id.
966 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
967 if (TraitTy.isNull())
968 return true;
969 if (!S.isCompleteType(Loc, TraitTy)) {
970 if (DiagID)
971 S.RequireCompleteType(
972 Loc, TraitTy, DiagID,
973 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
974 return true;
975 }
976
977 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
978 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 978, __PRETTY_FUNCTION__))
;
979
980 // Look up the member of the trait type.
981 S.LookupQualifiedName(TraitMemberLookup, RD);
982 return TraitMemberLookup.isAmbiguous();
983}
984
985static TemplateArgumentLoc
986getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
987 uint64_t I) {
988 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
989 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
990}
991
992static TemplateArgumentLoc
993getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
994 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
995}
996
997namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
998
999static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1000 llvm::APSInt &Size) {
1001 EnterExpressionEvaluationContext ContextRAII(
1002 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1003
1004 DeclarationName Value = S.PP.getIdentifierInfo("value");
1005 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1006
1007 // Form template argument list for tuple_size<T>.
1008 TemplateArgumentListInfo Args(Loc, Loc);
1009 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1010
1011 // If there's no tuple_size specialization, it's not tuple-like.
1012 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1013 return IsTupleLike::NotTupleLike;
1014
1015 // If we get this far, we've committed to the tuple interpretation, but
1016 // we can still fail if there actually isn't a usable ::value.
1017
1018 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1019 LookupResult &R;
1020 TemplateArgumentListInfo &Args;
1021 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1022 : R(R), Args(Args) {}
1023 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1024 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1025 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1026 }
1027 } Diagnoser(R, Args);
1028
1029 if (R.empty()) {
1030 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1031 return IsTupleLike::Error;
1032 }
1033
1034 ExprResult E =
1035 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1036 if (E.isInvalid())
1037 return IsTupleLike::Error;
1038
1039 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1040 if (E.isInvalid())
1041 return IsTupleLike::Error;
1042
1043 return IsTupleLike::TupleLike;
1044}
1045
1046/// \return std::tuple_element<I, T>::type.
1047static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1048 unsigned I, QualType T) {
1049 // Form template argument list for tuple_element<I, T>.
1050 TemplateArgumentListInfo Args(Loc, Loc);
1051 Args.addArgument(
1052 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054
1055 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1056 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1057 if (lookupStdTypeTraitMember(
1058 S, R, Loc, "tuple_element", Args,
1059 diag::err_decomp_decl_std_tuple_element_not_specialized))
1060 return QualType();
1061
1062 auto *TD = R.getAsSingle<TypeDecl>();
1063 if (!TD) {
1064 R.suppressDiagnostics();
1065 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1066 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1067 if (!R.empty())
1068 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1069 return QualType();
1070 }
1071
1072 return S.Context.getTypeDeclType(TD);
1073}
1074
1075namespace {
1076struct BindingDiagnosticTrap {
1077 Sema &S;
1078 DiagnosticErrorTrap Trap;
1079 BindingDecl *BD;
1080
1081 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1082 : S(S), Trap(S.Diags), BD(BD) {}
1083 ~BindingDiagnosticTrap() {
1084 if (Trap.hasErrorOccurred())
1085 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1086 }
1087};
1088}
1089
1090static bool checkTupleLikeDecomposition(Sema &S,
1091 ArrayRef<BindingDecl *> Bindings,
1092 VarDecl *Src, QualType DecompType,
1093 const llvm::APSInt &TupleSize) {
1094 if ((int64_t)Bindings.size() != TupleSize) {
1095 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1096 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1097 << (TupleSize < Bindings.size());
1098 return true;
1099 }
1100
1101 if (Bindings.empty())
1102 return false;
1103
1104 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1105
1106 // [dcl.decomp]p3:
1107 // The unqualified-id get is looked up in the scope of E by class member
1108 // access lookup ...
1109 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1110 bool UseMemberGet = false;
1111 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1112 if (auto *RD = DecompType->getAsCXXRecordDecl())
1113 S.LookupQualifiedName(MemberGet, RD);
1114 if (MemberGet.isAmbiguous())
1115 return true;
1116 // ... and if that finds at least one declaration that is a function
1117 // template whose first template parameter is a non-type parameter ...
1118 for (NamedDecl *D : MemberGet) {
1119 if (FunctionTemplateDecl *FTD =
1120 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1121 TemplateParameterList *TPL = FTD->getTemplateParameters();
1122 if (TPL->size() != 0 &&
1123 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1124 // ... the initializer is e.get<i>().
1125 UseMemberGet = true;
1126 break;
1127 }
1128 }
1129 }
1130 }
1131
1132 unsigned I = 0;
1133 for (auto *B : Bindings) {
1134 BindingDiagnosticTrap Trap(S, B);
1135 SourceLocation Loc = B->getLocation();
1136
1137 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1138 if (E.isInvalid())
1139 return true;
1140
1141 // e is an lvalue if the type of the entity is an lvalue reference and
1142 // an xvalue otherwise
1143 if (!Src->getType()->isLValueReferenceType())
1144 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1145 E.get(), nullptr, VK_XValue);
1146
1147 TemplateArgumentListInfo Args(Loc, Loc);
1148 Args.addArgument(
1149 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1150
1151 if (UseMemberGet) {
1152 // if [lookup of member get] finds at least one declaration, the
1153 // initializer is e.get<i-1>().
1154 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1155 CXXScopeSpec(), SourceLocation(), nullptr,
1156 MemberGet, &Args, nullptr);
1157 if (E.isInvalid())
1158 return true;
1159
1160 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1161 } else {
1162 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1163 // in the associated namespaces.
1164 Expr *Get = UnresolvedLookupExpr::Create(
1165 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1166 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1167 UnresolvedSetIterator(), UnresolvedSetIterator());
1168
1169 Expr *Arg = E.get();
1170 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1171 }
1172 if (E.isInvalid())
1173 return true;
1174 Expr *Init = E.get();
1175
1176 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1177 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1178 if (T.isNull())
1179 return true;
1180
1181 // each vi is a variable of type "reference to T" initialized with the
1182 // initializer, where the reference is an lvalue reference if the
1183 // initializer is an lvalue and an rvalue reference otherwise
1184 QualType RefType =
1185 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1186 if (RefType.isNull())
1187 return true;
1188 auto *RefVD = VarDecl::Create(
1189 S.Context, Src->getDeclContext(), Loc, Loc,
1190 B->getDeclName().getAsIdentifierInfo(), RefType,
1191 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1192 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1193 RefVD->setTSCSpec(Src->getTSCSpec());
1194 RefVD->setImplicit();
1195 if (Src->isInlineSpecified())
1196 RefVD->setInlineSpecified();
1197 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1198
1199 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1200 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1201 InitializationSequence Seq(S, Entity, Kind, Init);
1202 E = Seq.Perform(S, Entity, Kind, Init);
1203 if (E.isInvalid())
1204 return true;
1205 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1206 if (E.isInvalid())
1207 return true;
1208 RefVD->setInit(E.get());
1209 RefVD->checkInitIsICE();
1210
1211 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1212 DeclarationNameInfo(B->getDeclName(), Loc),
1213 RefVD);
1214 if (E.isInvalid())
1215 return true;
1216
1217 B->setBinding(T, E.get());
1218 I++;
1219 }
1220
1221 return false;
1222}
1223
1224/// Find the base class to decompose in a built-in decomposition of a class type.
1225/// This base class search is, unfortunately, not quite like any other that we
1226/// perform anywhere else in C++.
1227static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1228 const CXXRecordDecl *RD,
1229 CXXCastPath &BasePath) {
1230 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1231 CXXBasePath &Path) {
1232 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1233 };
1234
1235 const CXXRecordDecl *ClassWithFields = nullptr;
1236 AccessSpecifier AS = AS_public;
1237 if (RD->hasDirectFields())
1238 // [dcl.decomp]p4:
1239 // Otherwise, all of E's non-static data members shall be public direct
1240 // members of E ...
1241 ClassWithFields = RD;
1242 else {
1243 // ... or of ...
1244 CXXBasePaths Paths;
1245 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1246 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1247 // If no classes have fields, just decompose RD itself. (This will work
1248 // if and only if zero bindings were provided.)
1249 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1250 }
1251
1252 CXXBasePath *BestPath = nullptr;
1253 for (auto &P : Paths) {
1254 if (!BestPath)
1255 BestPath = &P;
1256 else if (!S.Context.hasSameType(P.back().Base->getType(),
1257 BestPath->back().Base->getType())) {
1258 // ... the same ...
1259 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1260 << false << RD << BestPath->back().Base->getType()
1261 << P.back().Base->getType();
1262 return DeclAccessPair();
1263 } else if (P.Access < BestPath->Access) {
1264 BestPath = &P;
1265 }
1266 }
1267
1268 // ... unambiguous ...
1269 QualType BaseType = BestPath->back().Base->getType();
1270 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1271 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1272 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1273 return DeclAccessPair();
1274 }
1275
1276 // ... [accessible, implied by other rules] base class of E.
1277 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1278 *BestPath, diag::err_decomp_decl_inaccessible_base);
1279 AS = BestPath->Access;
1280
1281 ClassWithFields = BaseType->getAsCXXRecordDecl();
1282 S.BuildBasePathArray(Paths, BasePath);
1283 }
1284
1285 // The above search did not check whether the selected class itself has base
1286 // classes with fields, so check that now.
1287 CXXBasePaths Paths;
1288 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1289 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1290 << (ClassWithFields == RD) << RD << ClassWithFields
1291 << Paths.front().back().Base->getType();
1292 return DeclAccessPair();
1293 }
1294
1295 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1296}
1297
1298static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1299 ValueDecl *Src, QualType DecompType,
1300 const CXXRecordDecl *OrigRD) {
1301 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1302 diag::err_incomplete_type))
1303 return true;
1304
1305 CXXCastPath BasePath;
1306 DeclAccessPair BasePair =
1307 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1308 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1309 if (!RD)
1310 return true;
1311 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1312 DecompType.getQualifiers());
1313
1314 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1315 unsigned NumFields =
1316 std::count_if(RD->field_begin(), RD->field_end(),
1317 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1318 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1318, __PRETTY_FUNCTION__))
;
1319 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1320 << DecompType << (unsigned)Bindings.size() << NumFields
1321 << (NumFields < Bindings.size());
1322 return true;
1323 };
1324
1325 // all of E's non-static data members shall be [...] well-formed
1326 // when named as e.name in the context of the structured binding,
1327 // E shall not have an anonymous union member, ...
1328 unsigned I = 0;
1329 for (auto *FD : RD->fields()) {
1330 if (FD->isUnnamedBitfield())
1331 continue;
1332
1333 if (FD->isAnonymousStructOrUnion()) {
1334 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1335 << DecompType << FD->getType()->isUnionType();
1336 S.Diag(FD->getLocation(), diag::note_declared_at);
1337 return true;
1338 }
1339
1340 // We have a real field to bind.
1341 if (I >= Bindings.size())
1342 return DiagnoseBadNumberOfBindings();
1343 auto *B = Bindings[I++];
1344 SourceLocation Loc = B->getLocation();
1345
1346 // The field must be accessible in the context of the structured binding.
1347 // We already checked that the base class is accessible.
1348 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1349 // const_cast here.
1350 S.CheckStructuredBindingMemberAccess(
1351 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1352 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1353 BasePair.getAccess(), FD->getAccess())));
1354
1355 // Initialize the binding to Src.FD.
1356 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1357 if (E.isInvalid())
1358 return true;
1359 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1360 VK_LValue, &BasePath);
1361 if (E.isInvalid())
1362 return true;
1363 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1364 CXXScopeSpec(), FD,
1365 DeclAccessPair::make(FD, FD->getAccess()),
1366 DeclarationNameInfo(FD->getDeclName(), Loc));
1367 if (E.isInvalid())
1368 return true;
1369
1370 // If the type of the member is T, the referenced type is cv T, where cv is
1371 // the cv-qualification of the decomposition expression.
1372 //
1373 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1374 // 'const' to the type of the field.
1375 Qualifiers Q = DecompType.getQualifiers();
1376 if (FD->isMutable())
1377 Q.removeConst();
1378 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1379 }
1380
1381 if (I != Bindings.size())
1382 return DiagnoseBadNumberOfBindings();
1383
1384 return false;
1385}
1386
1387void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1388 QualType DecompType = DD->getType();
1389
1390 // If the type of the decomposition is dependent, then so is the type of
1391 // each binding.
1392 if (DecompType->isDependentType()) {
1393 for (auto *B : DD->bindings())
1394 B->setType(Context.DependentTy);
1395 return;
1396 }
1397
1398 DecompType = DecompType.getNonReferenceType();
1399 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1400
1401 // C++1z [dcl.decomp]/2:
1402 // If E is an array type [...]
1403 // As an extension, we also support decomposition of built-in complex and
1404 // vector types.
1405 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1406 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1407 DD->setInvalidDecl();
1408 return;
1409 }
1410 if (auto *VT = DecompType->getAs<VectorType>()) {
1411 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1412 DD->setInvalidDecl();
1413 return;
1414 }
1415 if (auto *CT = DecompType->getAs<ComplexType>()) {
1416 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1417 DD->setInvalidDecl();
1418 return;
1419 }
1420
1421 // C++1z [dcl.decomp]/3:
1422 // if the expression std::tuple_size<E>::value is a well-formed integral
1423 // constant expression, [...]
1424 llvm::APSInt TupleSize(32);
1425 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1426 case IsTupleLike::Error:
1427 DD->setInvalidDecl();
1428 return;
1429
1430 case IsTupleLike::TupleLike:
1431 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1432 DD->setInvalidDecl();
1433 return;
1434
1435 case IsTupleLike::NotTupleLike:
1436 break;
1437 }
1438
1439 // C++1z [dcl.dcl]/8:
1440 // [E shall be of array or non-union class type]
1441 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1442 if (!RD || RD->isUnion()) {
1443 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1444 << DD << !RD << DecompType;
1445 DD->setInvalidDecl();
1446 return;
1447 }
1448
1449 // C++1z [dcl.decomp]/4:
1450 // all of E's non-static data members shall be [...] direct members of
1451 // E or of the same unambiguous public base class of E, ...
1452 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1453 DD->setInvalidDecl();
1454}
1455
1456/// Merge the exception specifications of two variable declarations.
1457///
1458/// This is called when there's a redeclaration of a VarDecl. The function
1459/// checks if the redeclaration might have an exception specification and
1460/// validates compatibility and merges the specs if necessary.
1461void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1462 // Shortcut if exceptions are disabled.
1463 if (!getLangOpts().CXXExceptions)
1464 return;
1465
1466 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1467, __PRETTY_FUNCTION__))
1467 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1467, __PRETTY_FUNCTION__))
;
1468
1469 QualType NewType = New->getType();
1470 QualType OldType = Old->getType();
1471
1472 // We're only interested in pointers and references to functions, as well
1473 // as pointers to member functions.
1474 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1475 NewType = R->getPointeeType();
1476 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1477 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1478 NewType = P->getPointeeType();
1479 OldType = OldType->getAs<PointerType>()->getPointeeType();
1480 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1481 NewType = M->getPointeeType();
1482 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1483 }
1484
1485 if (!NewType->isFunctionProtoType())
1486 return;
1487
1488 // There's lots of special cases for functions. For function pointers, system
1489 // libraries are hopefully not as broken so that we don't need these
1490 // workarounds.
1491 if (CheckEquivalentExceptionSpec(
1492 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1493 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1494 New->setInvalidDecl();
1495 }
1496}
1497
1498/// CheckCXXDefaultArguments - Verify that the default arguments for a
1499/// function declaration are well-formed according to C++
1500/// [dcl.fct.default].
1501void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1502 unsigned NumParams = FD->getNumParams();
1503 unsigned p;
1504
1505 // Find first parameter with a default argument
1506 for (p = 0; p < NumParams; ++p) {
1507 ParmVarDecl *Param = FD->getParamDecl(p);
1508 if (Param->hasDefaultArg())
1509 break;
1510 }
1511
1512 // C++11 [dcl.fct.default]p4:
1513 // In a given function declaration, each parameter subsequent to a parameter
1514 // with a default argument shall have a default argument supplied in this or
1515 // a previous declaration or shall be a function parameter pack. A default
1516 // argument shall not be redefined by a later declaration (not even to the
1517 // same value).
1518 unsigned LastMissingDefaultArg = 0;
1519 for (; p < NumParams; ++p) {
1520 ParmVarDecl *Param = FD->getParamDecl(p);
1521 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1522 if (Param->isInvalidDecl())
1523 /* We already complained about this parameter. */;
1524 else if (Param->getIdentifier())
1525 Diag(Param->getLocation(),
1526 diag::err_param_default_argument_missing_name)
1527 << Param->getIdentifier();
1528 else
1529 Diag(Param->getLocation(),
1530 diag::err_param_default_argument_missing);
1531
1532 LastMissingDefaultArg = p;
1533 }
1534 }
1535
1536 if (LastMissingDefaultArg > 0) {
1537 // Some default arguments were missing. Clear out all of the
1538 // default arguments up to (and including) the last missing
1539 // default argument, so that we leave the function parameters
1540 // in a semantically valid state.
1541 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1542 ParmVarDecl *Param = FD->getParamDecl(p);
1543 if (Param->hasDefaultArg()) {
1544 Param->setDefaultArg(nullptr);
1545 }
1546 }
1547 }
1548}
1549
1550// CheckConstexprParameterTypes - Check whether a function's parameter types
1551// are all literal types. If so, return true. If not, produce a suitable
1552// diagnostic and return false.
1553static bool CheckConstexprParameterTypes(Sema &SemaRef,
1554 const FunctionDecl *FD) {
1555 unsigned ArgIndex = 0;
1556 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1557 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1558 e = FT->param_type_end();
1559 i != e; ++i, ++ArgIndex) {
1560 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1561 SourceLocation ParamLoc = PD->getLocation();
1562 if (!(*i)->isDependentType() &&
1563 SemaRef.RequireLiteralType(ParamLoc, *i,
1564 diag::err_constexpr_non_literal_param,
1565 ArgIndex+1, PD->getSourceRange(),
1566 isa<CXXConstructorDecl>(FD)))
1567 return false;
1568 }
1569 return true;
1570}
1571
1572/// Get diagnostic %select index for tag kind for
1573/// record diagnostic message.
1574/// WARNING: Indexes apply to particular diagnostics only!
1575///
1576/// \returns diagnostic %select index.
1577static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1578 switch (Tag) {
1579 case TTK_Struct: return 0;
1580 case TTK_Interface: return 1;
1581 case TTK_Class: return 2;
1582 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1582)
;
1583 }
1584}
1585
1586// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1587// the requirements of a constexpr function definition or a constexpr
1588// constructor definition. If so, return true. If not, produce appropriate
1589// diagnostics and return false.
1590//
1591// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1592bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1593 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1594 if (MD && MD->isInstance()) {
1595 // C++11 [dcl.constexpr]p4:
1596 // The definition of a constexpr constructor shall satisfy the following
1597 // constraints:
1598 // - the class shall not have any virtual base classes;
1599 const CXXRecordDecl *RD = MD->getParent();
1600 if (RD->getNumVBases()) {
1601 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1602 << isa<CXXConstructorDecl>(NewFD)
1603 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1604 for (const auto &I : RD->vbases())
1605 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1606 << I.getSourceRange();
1607 return false;
1608 }
1609 }
1610
1611 if (!isa<CXXConstructorDecl>(NewFD)) {
1612 // C++11 [dcl.constexpr]p3:
1613 // The definition of a constexpr function shall satisfy the following
1614 // constraints:
1615 // - it shall not be virtual;
1616 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1617 if (Method && Method->isVirtual()) {
1618 Method = Method->getCanonicalDecl();
1619 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1620
1621 // If it's not obvious why this function is virtual, find an overridden
1622 // function which uses the 'virtual' keyword.
1623 const CXXMethodDecl *WrittenVirtual = Method;
1624 while (!WrittenVirtual->isVirtualAsWritten())
1625 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1626 if (WrittenVirtual != Method)
1627 Diag(WrittenVirtual->getLocation(),
1628 diag::note_overridden_virtual_function);
1629 return false;
1630 }
1631
1632 // - its return type shall be a literal type;
1633 QualType RT = NewFD->getReturnType();
1634 if (!RT->isDependentType() &&
1635 RequireLiteralType(NewFD->getLocation(), RT,
1636 diag::err_constexpr_non_literal_return))
1637 return false;
1638 }
1639
1640 // - each of its parameter types shall be a literal type;
1641 if (!CheckConstexprParameterTypes(*this, NewFD))
1642 return false;
1643
1644 return true;
1645}
1646
1647/// Check the given declaration statement is legal within a constexpr function
1648/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1649///
1650/// \return true if the body is OK (maybe only as an extension), false if we
1651/// have diagnosed a problem.
1652static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1653 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1654 // C++11 [dcl.constexpr]p3 and p4:
1655 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1656 // contain only
1657 for (const auto *DclIt : DS->decls()) {
1658 switch (DclIt->getKind()) {
1659 case Decl::StaticAssert:
1660 case Decl::Using:
1661 case Decl::UsingShadow:
1662 case Decl::UsingDirective:
1663 case Decl::UnresolvedUsingTypename:
1664 case Decl::UnresolvedUsingValue:
1665 // - static_assert-declarations
1666 // - using-declarations,
1667 // - using-directives,
1668 continue;
1669
1670 case Decl::Typedef:
1671 case Decl::TypeAlias: {
1672 // - typedef declarations and alias-declarations that do not define
1673 // classes or enumerations,
1674 const auto *TN = cast<TypedefNameDecl>(DclIt);
1675 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1676 // Don't allow variably-modified types in constexpr functions.
1677 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1678 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1679 << TL.getSourceRange() << TL.getType()
1680 << isa<CXXConstructorDecl>(Dcl);
1681 return false;
1682 }
1683 continue;
1684 }
1685
1686 case Decl::Enum:
1687 case Decl::CXXRecord:
1688 // C++1y allows types to be defined, not just declared.
1689 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1690 SemaRef.Diag(DS->getBeginLoc(),
1691 SemaRef.getLangOpts().CPlusPlus14
1692 ? diag::warn_cxx11_compat_constexpr_type_definition
1693 : diag::ext_constexpr_type_definition)
1694 << isa<CXXConstructorDecl>(Dcl);
1695 continue;
1696
1697 case Decl::EnumConstant:
1698 case Decl::IndirectField:
1699 case Decl::ParmVar:
1700 // These can only appear with other declarations which are banned in
1701 // C++11 and permitted in C++1y, so ignore them.
1702 continue;
1703
1704 case Decl::Var:
1705 case Decl::Decomposition: {
1706 // C++1y [dcl.constexpr]p3 allows anything except:
1707 // a definition of a variable of non-literal type or of static or
1708 // thread storage duration or for which no initialization is performed.
1709 const auto *VD = cast<VarDecl>(DclIt);
1710 if (VD->isThisDeclarationADefinition()) {
1711 if (VD->isStaticLocal()) {
1712 SemaRef.Diag(VD->getLocation(),
1713 diag::err_constexpr_local_var_static)
1714 << isa<CXXConstructorDecl>(Dcl)
1715 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1716 return false;
1717 }
1718 if (!VD->getType()->isDependentType() &&
1719 SemaRef.RequireLiteralType(
1720 VD->getLocation(), VD->getType(),
1721 diag::err_constexpr_local_var_non_literal_type,
1722 isa<CXXConstructorDecl>(Dcl)))
1723 return false;
1724 if (!VD->getType()->isDependentType() &&
1725 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1726 SemaRef.Diag(VD->getLocation(),
1727 diag::err_constexpr_local_var_no_init)
1728 << isa<CXXConstructorDecl>(Dcl);
1729 return false;
1730 }
1731 }
1732 SemaRef.Diag(VD->getLocation(),
1733 SemaRef.getLangOpts().CPlusPlus14
1734 ? diag::warn_cxx11_compat_constexpr_local_var
1735 : diag::ext_constexpr_local_var)
1736 << isa<CXXConstructorDecl>(Dcl);
1737 continue;
1738 }
1739
1740 case Decl::NamespaceAlias:
1741 case Decl::Function:
1742 // These are disallowed in C++11 and permitted in C++1y. Allow them
1743 // everywhere as an extension.
1744 if (!Cxx1yLoc.isValid())
1745 Cxx1yLoc = DS->getBeginLoc();
1746 continue;
1747
1748 default:
1749 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1750 << isa<CXXConstructorDecl>(Dcl);
1751 return false;
1752 }
1753 }
1754
1755 return true;
1756}
1757
1758/// Check that the given field is initialized within a constexpr constructor.
1759///
1760/// \param Dcl The constexpr constructor being checked.
1761/// \param Field The field being checked. This may be a member of an anonymous
1762/// struct or union nested within the class being checked.
1763/// \param Inits All declarations, including anonymous struct/union members and
1764/// indirect members, for which any initialization was provided.
1765/// \param Diagnosed Set to true if an error is produced.
1766static void CheckConstexprCtorInitializer(Sema &SemaRef,
1767 const FunctionDecl *Dcl,
1768 FieldDecl *Field,
1769 llvm::SmallSet<Decl*, 16> &Inits,
1770 bool &Diagnosed) {
1771 if (Field->isInvalidDecl())
1772 return;
1773
1774 if (Field->isUnnamedBitfield())
1775 return;
1776
1777 // Anonymous unions with no variant members and empty anonymous structs do not
1778 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1779 // indirect fields don't need initializing.
1780 if (Field->isAnonymousStructOrUnion() &&
1781 (Field->getType()->isUnionType()
1782 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1783 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1784 return;
1785
1786 if (!Inits.count(Field)) {
1787 if (!Diagnosed) {
1788 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1789 Diagnosed = true;
1790 }
1791 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1792 } else if (Field->isAnonymousStructOrUnion()) {
1793 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1794 for (auto *I : RD->fields())
1795 // If an anonymous union contains an anonymous struct of which any member
1796 // is initialized, all members must be initialized.
1797 if (!RD->isUnion() || Inits.count(I))
1798 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1799 }
1800}
1801
1802/// Check the provided statement is allowed in a constexpr function
1803/// definition.
1804static bool
1805CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1806 SmallVectorImpl<SourceLocation> &ReturnStmts,
1807 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1808 // - its function-body shall be [...] a compound-statement that contains only
1809 switch (S->getStmtClass()) {
1810 case Stmt::NullStmtClass:
1811 // - null statements,
1812 return true;
1813
1814 case Stmt::DeclStmtClass:
1815 // - static_assert-declarations
1816 // - using-declarations,
1817 // - using-directives,
1818 // - typedef declarations and alias-declarations that do not define
1819 // classes or enumerations,
1820 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1821 return false;
1822 return true;
1823
1824 case Stmt::ReturnStmtClass:
1825 // - and exactly one return statement;
1826 if (isa<CXXConstructorDecl>(Dcl)) {
1827 // C++1y allows return statements in constexpr constructors.
1828 if (!Cxx1yLoc.isValid())
1829 Cxx1yLoc = S->getBeginLoc();
1830 return true;
1831 }
1832
1833 ReturnStmts.push_back(S->getBeginLoc());
1834 return true;
1835
1836 case Stmt::CompoundStmtClass: {
1837 // C++1y allows compound-statements.
1838 if (!Cxx1yLoc.isValid())
1839 Cxx1yLoc = S->getBeginLoc();
1840
1841 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1842 for (auto *BodyIt : CompStmt->body()) {
1843 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1844 Cxx1yLoc, Cxx2aLoc))
1845 return false;
1846 }
1847 return true;
1848 }
1849
1850 case Stmt::AttributedStmtClass:
1851 if (!Cxx1yLoc.isValid())
1852 Cxx1yLoc = S->getBeginLoc();
1853 return true;
1854
1855 case Stmt::IfStmtClass: {
1856 // C++1y allows if-statements.
1857 if (!Cxx1yLoc.isValid())
1858 Cxx1yLoc = S->getBeginLoc();
1859
1860 IfStmt *If = cast<IfStmt>(S);
1861 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1862 Cxx1yLoc, Cxx2aLoc))
1863 return false;
1864 if (If->getElse() &&
1865 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1866 Cxx1yLoc, Cxx2aLoc))
1867 return false;
1868 return true;
1869 }
1870
1871 case Stmt::WhileStmtClass:
1872 case Stmt::DoStmtClass:
1873 case Stmt::ForStmtClass:
1874 case Stmt::CXXForRangeStmtClass:
1875 case Stmt::ContinueStmtClass:
1876 // C++1y allows all of these. We don't allow them as extensions in C++11,
1877 // because they don't make sense without variable mutation.
1878 if (!SemaRef.getLangOpts().CPlusPlus14)
1879 break;
1880 if (!Cxx1yLoc.isValid())
1881 Cxx1yLoc = S->getBeginLoc();
1882 for (Stmt *SubStmt : S->children())
1883 if (SubStmt &&
1884 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1885 Cxx1yLoc, Cxx2aLoc))
1886 return false;
1887 return true;
1888
1889 case Stmt::SwitchStmtClass:
1890 case Stmt::CaseStmtClass:
1891 case Stmt::DefaultStmtClass:
1892 case Stmt::BreakStmtClass:
1893 // C++1y allows switch-statements, and since they don't need variable
1894 // mutation, we can reasonably allow them in C++11 as an extension.
1895 if (!Cxx1yLoc.isValid())
1896 Cxx1yLoc = S->getBeginLoc();
1897 for (Stmt *SubStmt : S->children())
1898 if (SubStmt &&
1899 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1900 Cxx1yLoc, Cxx2aLoc))
1901 return false;
1902 return true;
1903
1904 case Stmt::CXXTryStmtClass:
1905 if (Cxx2aLoc.isInvalid())
1906 Cxx2aLoc = S->getBeginLoc();
1907 for (Stmt *SubStmt : S->children()) {
1908 if (SubStmt &&
1909 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1910 Cxx1yLoc, Cxx2aLoc))
1911 return false;
1912 }
1913 return true;
1914
1915 case Stmt::CXXCatchStmtClass:
1916 // Do not bother checking the language mode (already covered by the
1917 // try block check).
1918 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1919 cast<CXXCatchStmt>(S)->getHandlerBlock(),
1920 ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1921 return false;
1922 return true;
1923
1924 default:
1925 if (!isa<Expr>(S))
1926 break;
1927
1928 // C++1y allows expression-statements.
1929 if (!Cxx1yLoc.isValid())
1930 Cxx1yLoc = S->getBeginLoc();
1931 return true;
1932 }
1933
1934 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1935 << isa<CXXConstructorDecl>(Dcl);
1936 return false;
1937}
1938
1939/// Check the body for the given constexpr function declaration only contains
1940/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1941///
1942/// \return true if the body is OK, false if we have diagnosed a problem.
1943bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1944 SmallVector<SourceLocation, 4> ReturnStmts;
1945
1946 if (isa<CXXTryStmt>(Body)) {
1947 // C++11 [dcl.constexpr]p3:
1948 // The definition of a constexpr function shall satisfy the following
1949 // constraints: [...]
1950 // - its function-body shall be = delete, = default, or a
1951 // compound-statement
1952 //
1953 // C++11 [dcl.constexpr]p4:
1954 // In the definition of a constexpr constructor, [...]
1955 // - its function-body shall not be a function-try-block;
1956 //
1957 // This restriction is lifted in C++2a, as long as inner statements also
1958 // apply the general constexpr rules.
1959 Diag(Body->getBeginLoc(),
1960 !getLangOpts().CPlusPlus2a
1961 ? diag::ext_constexpr_function_try_block_cxx2a
1962 : diag::warn_cxx17_compat_constexpr_function_try_block)
1963 << isa<CXXConstructorDecl>(Dcl);
1964 }
1965
1966 // - its function-body shall be [...] a compound-statement that contains only
1967 // [... list of cases ...]
1968 //
1969 // Note that walking the children here is enough to properly check for
1970 // CompoundStmt and CXXTryStmt body.
1971 SourceLocation Cxx1yLoc, Cxx2aLoc;
1972 for (Stmt *SubStmt : Body->children()) {
1973 if (SubStmt &&
1974 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1975 Cxx1yLoc, Cxx2aLoc))
1976 return false;
1977 }
1978
1979 if (Cxx2aLoc.isValid())
1980 Diag(Cxx2aLoc,
1981 getLangOpts().CPlusPlus2a
1982 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1983 : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1984 << isa<CXXConstructorDecl>(Dcl);
1985 if (Cxx1yLoc.isValid())
1986 Diag(Cxx1yLoc,
1987 getLangOpts().CPlusPlus14
1988 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1989 : diag::ext_constexpr_body_invalid_stmt)
1990 << isa<CXXConstructorDecl>(Dcl);
1991
1992 if (const CXXConstructorDecl *Constructor
1993 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1994 const CXXRecordDecl *RD = Constructor->getParent();
1995 // DR1359:
1996 // - every non-variant non-static data member and base class sub-object
1997 // shall be initialized;
1998 // DR1460:
1999 // - if the class is a union having variant members, exactly one of them
2000 // shall be initialized;
2001 if (RD->isUnion()) {
2002 if (Constructor->getNumCtorInitializers() == 0 &&
2003 RD->hasVariantMembers()) {
2004 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2005 return false;
2006 }
2007 } else if (!Constructor->isDependentContext() &&
2008 !Constructor->isDelegatingConstructor()) {
2009 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2009, __PRETTY_FUNCTION__))
;
2010
2011 // Skip detailed checking if we have enough initializers, and we would
2012 // allow at most one initializer per member.
2013 bool AnyAnonStructUnionMembers = false;
2014 unsigned Fields = 0;
2015 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2016 E = RD->field_end(); I != E; ++I, ++Fields) {
2017 if (I->isAnonymousStructOrUnion()) {
2018 AnyAnonStructUnionMembers = true;
2019 break;
2020 }
2021 }
2022 // DR1460:
2023 // - if the class is a union-like class, but is not a union, for each of
2024 // its anonymous union members having variant members, exactly one of
2025 // them shall be initialized;
2026 if (AnyAnonStructUnionMembers ||
2027 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2028 // Check initialization of non-static data members. Base classes are
2029 // always initialized so do not need to be checked. Dependent bases
2030 // might not have initializers in the member initializer list.
2031 llvm::SmallSet<Decl*, 16> Inits;
2032 for (const auto *I: Constructor->inits()) {
2033 if (FieldDecl *FD = I->getMember())
2034 Inits.insert(FD);
2035 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2036 Inits.insert(ID->chain_begin(), ID->chain_end());
2037 }
2038
2039 bool Diagnosed = false;
2040 for (auto *I : RD->fields())
2041 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2042 if (Diagnosed)
2043 return false;
2044 }
2045 }
2046 } else {
2047 if (ReturnStmts.empty()) {
2048 // C++1y doesn't require constexpr functions to contain a 'return'
2049 // statement. We still do, unless the return type might be void, because
2050 // otherwise if there's no return statement, the function cannot
2051 // be used in a core constant expression.
2052 bool OK = getLangOpts().CPlusPlus14 &&
2053 (Dcl->getReturnType()->isVoidType() ||
2054 Dcl->getReturnType()->isDependentType());
2055 Diag(Dcl->getLocation(),
2056 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2057 : diag::err_constexpr_body_no_return);
2058 if (!OK)
2059 return false;
2060 } else if (ReturnStmts.size() > 1) {
2061 Diag(ReturnStmts.back(),
2062 getLangOpts().CPlusPlus14
2063 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2064 : diag::ext_constexpr_body_multiple_return);
2065 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2066 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2067 }
2068 }
2069
2070 // C++11 [dcl.constexpr]p5:
2071 // if no function argument values exist such that the function invocation
2072 // substitution would produce a constant expression, the program is
2073 // ill-formed; no diagnostic required.
2074 // C++11 [dcl.constexpr]p3:
2075 // - every constructor call and implicit conversion used in initializing the
2076 // return value shall be one of those allowed in a constant expression.
2077 // C++11 [dcl.constexpr]p4:
2078 // - every constructor involved in initializing non-static data members and
2079 // base class sub-objects shall be a constexpr constructor.
2080 SmallVector<PartialDiagnosticAt, 8> Diags;
2081 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2082 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2083 << isa<CXXConstructorDecl>(Dcl);
2084 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2085 Diag(Diags[I].first, Diags[I].second);
2086 // Don't return false here: we allow this for compatibility in
2087 // system headers.
2088 }
2089
2090 return true;
2091}
2092
2093/// Get the class that is directly named by the current context. This is the
2094/// class for which an unqualified-id in this scope could name a constructor
2095/// or destructor.
2096///
2097/// If the scope specifier denotes a class, this will be that class.
2098/// If the scope specifier is empty, this will be the class whose
2099/// member-specification we are currently within. Otherwise, there
2100/// is no such class.
2101CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2102 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2102, __PRETTY_FUNCTION__))
;
2103
2104 if (SS && SS->isInvalid())
2105 return nullptr;
2106
2107 if (SS && SS->isNotEmpty()) {
2108 DeclContext *DC = computeDeclContext(*SS, true);
2109 return dyn_cast_or_null<CXXRecordDecl>(DC);
2110 }
2111
2112 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2113}
2114
2115/// isCurrentClassName - Determine whether the identifier II is the
2116/// name of the class type currently being defined. In the case of
2117/// nested classes, this will only return true if II is the name of
2118/// the innermost class.
2119bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2120 const CXXScopeSpec *SS) {
2121 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2122 return CurDecl && &II == CurDecl->getIdentifier();
2123}
2124
2125/// Determine whether the identifier II is a typo for the name of
2126/// the class type currently being defined. If so, update it to the identifier
2127/// that should have been used.
2128bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2129 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2129, __PRETTY_FUNCTION__))
;
2130
2131 if (!getLangOpts().SpellChecking)
2132 return false;
2133
2134 CXXRecordDecl *CurDecl;
2135 if (SS && SS->isSet() && !SS->isInvalid()) {
2136 DeclContext *DC = computeDeclContext(*SS, true);
2137 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2138 } else
2139 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2140
2141 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2142 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2143 < II->getLength()) {
2144 II = CurDecl->getIdentifier();
2145 return true;
2146 }
2147
2148 return false;
2149}
2150
2151/// Determine whether the given class is a base class of the given
2152/// class, including looking at dependent bases.
2153static bool findCircularInheritance(const CXXRecordDecl *Class,
2154 const CXXRecordDecl *Current) {
2155 SmallVector<const CXXRecordDecl*, 8> Queue;
2156
2157 Class = Class->getCanonicalDecl();
2158 while (true) {
2159 for (const auto &I : Current->bases()) {
2160 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2161 if (!Base)
2162 continue;
2163
2164 Base = Base->getDefinition();
2165 if (!Base)
2166 continue;
2167
2168 if (Base->getCanonicalDecl() == Class)
2169 return true;
2170
2171 Queue.push_back(Base);
2172 }
2173
2174 if (Queue.empty())
2175 return false;
2176
2177 Current = Queue.pop_back_val();
2178 }
2179
2180 return false;
2181}
2182
2183/// Check the validity of a C++ base class specifier.
2184///
2185/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2186/// and returns NULL otherwise.
2187CXXBaseSpecifier *
2188Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2189 SourceRange SpecifierRange,
2190 bool Virtual, AccessSpecifier Access,
2191 TypeSourceInfo *TInfo,
2192 SourceLocation EllipsisLoc) {
2193 QualType BaseType = TInfo->getType();
2194
2195 // C++ [class.union]p1:
2196 // A union shall not have base classes.
2197 if (Class->isUnion()) {
2198 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2199 << SpecifierRange;
2200 return nullptr;
2201 }
2202
2203 if (EllipsisLoc.isValid() &&
2204 !TInfo->getType()->containsUnexpandedParameterPack()) {
2205 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2206 << TInfo->getTypeLoc().getSourceRange();
2207 EllipsisLoc = SourceLocation();
2208 }
2209
2210 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2211
2212 if (BaseType->isDependentType()) {
2213 // Make sure that we don't have circular inheritance among our dependent
2214 // bases. For non-dependent bases, the check for completeness below handles
2215 // this.
2216 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2217 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2218 ((BaseDecl = BaseDecl->getDefinition()) &&
2219 findCircularInheritance(Class, BaseDecl))) {
2220 Diag(BaseLoc, diag::err_circular_inheritance)
2221 << BaseType << Context.getTypeDeclType(Class);
2222
2223 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2224 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2225 << BaseType;
2226
2227 return nullptr;
2228 }
2229 }
2230
2231 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2232 Class->getTagKind() == TTK_Class,
2233 Access, TInfo, EllipsisLoc);
2234 }
2235
2236 // Base specifiers must be record types.
2237 if (!BaseType->isRecordType()) {
2238 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2239 return nullptr;
2240 }
2241
2242 // C++ [class.union]p1:
2243 // A union shall not be used as a base class.
2244 if (BaseType->isUnionType()) {
2245 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2246 return nullptr;
2247 }
2248
2249 // For the MS ABI, propagate DLL attributes to base class templates.
2250 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2251 if (Attr *ClassAttr = getDLLAttr(Class)) {
2252 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2253 BaseType->getAsCXXRecordDecl())) {
2254 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2255 BaseLoc);
2256 }
2257 }
2258 }
2259
2260 // C++ [class.derived]p2:
2261 // The class-name in a base-specifier shall not be an incompletely
2262 // defined class.
2263 if (RequireCompleteType(BaseLoc, BaseType,
2264 diag::err_incomplete_base_class, SpecifierRange)) {
2265 Class->setInvalidDecl();
2266 return nullptr;
2267 }
2268
2269 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2270 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2271 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2271, __PRETTY_FUNCTION__))
;
2272 BaseDecl = BaseDecl->getDefinition();
2273 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2273, __PRETTY_FUNCTION__))
;
2274 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2275 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2275, __PRETTY_FUNCTION__))
;
2276
2277 // Microsoft docs say:
2278 // "If a base-class has a code_seg attribute, derived classes must have the
2279 // same attribute."
2280 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2281 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2282 if ((DerivedCSA || BaseCSA) &&
2283 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2284 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2285 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2286 << CXXBaseDecl;
2287 return nullptr;
2288 }
2289
2290 // A class which contains a flexible array member is not suitable for use as a
2291 // base class:
2292 // - If the layout determines that a base comes before another base,
2293 // the flexible array member would index into the subsequent base.
2294 // - If the layout determines that base comes before the derived class,
2295 // the flexible array member would index into the derived class.
2296 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2297 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2298 << CXXBaseDecl->getDeclName();
2299 return nullptr;
2300 }
2301
2302 // C++ [class]p3:
2303 // If a class is marked final and it appears as a base-type-specifier in
2304 // base-clause, the program is ill-formed.
2305 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2306 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2307 << CXXBaseDecl->getDeclName()
2308 << FA->isSpelledAsSealed();
2309 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2310 << CXXBaseDecl->getDeclName() << FA->getRange();
2311 return nullptr;
2312 }
2313
2314 if (BaseDecl->isInvalidDecl())
2315 Class->setInvalidDecl();
2316
2317 // Create the base specifier.
2318 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2319 Class->getTagKind() == TTK_Class,
2320 Access, TInfo, EllipsisLoc);
2321}
2322
2323/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2324/// one entry in the base class list of a class specifier, for
2325/// example:
2326/// class foo : public bar, virtual private baz {
2327/// 'public bar' and 'virtual private baz' are each base-specifiers.
2328BaseResult
2329Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2330 ParsedAttributes &Attributes,
2331 bool Virtual, AccessSpecifier Access,
2332 ParsedType basetype, SourceLocation BaseLoc,
2333 SourceLocation EllipsisLoc) {
2334 if (!classdecl)
2335 return true;
2336
2337 AdjustDeclIfTemplate(classdecl);
2338 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2339 if (!Class)
2340 return true;
2341
2342 // We haven't yet attached the base specifiers.
2343 Class->setIsParsingBaseSpecifiers();
2344
2345 // We do not support any C++11 attributes on base-specifiers yet.
2346 // Diagnose any attributes we see.
2347 for (const ParsedAttr &AL : Attributes) {
2348 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2349 continue;
2350 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2351 ? (unsigned)diag::warn_unknown_attribute_ignored
2352 : (unsigned)diag::err_base_specifier_attribute)
2353 << AL.getName();
2354 }
2355
2356 TypeSourceInfo *TInfo = nullptr;
2357 GetTypeFromParser(basetype, &TInfo);
2358
2359 if (EllipsisLoc.isInvalid() &&
2360 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2361 UPPC_BaseType))
2362 return true;
2363
2364 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2365 Virtual, Access, TInfo,
2366 EllipsisLoc))
2367 return BaseSpec;
2368 else
2369 Class->setInvalidDecl();
2370
2371 return true;
2372}
2373
2374/// Use small set to collect indirect bases. As this is only used
2375/// locally, there's no need to abstract the small size parameter.
2376typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2377
2378/// Recursively add the bases of Type. Don't add Type itself.
2379static void
2380NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2381 const QualType &Type)
2382{
2383 // Even though the incoming type is a base, it might not be
2384 // a class -- it could be a template parm, for instance.
2385 if (auto Rec = Type->getAs<RecordType>()) {
2386 auto Decl = Rec->getAsCXXRecordDecl();
2387
2388 // Iterate over its bases.
2389 for (const auto &BaseSpec : Decl->bases()) {
2390 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2391 .getUnqualifiedType();
2392 if (Set.insert(Base).second)
2393 // If we've not already seen it, recurse.
2394 NoteIndirectBases(Context, Set, Base);
2395 }
2396 }
2397}
2398
2399/// Performs the actual work of attaching the given base class
2400/// specifiers to a C++ class.
2401bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2402 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2403 if (Bases.empty())
2404 return false;
2405
2406 // Used to keep track of which base types we have already seen, so
2407 // that we can properly diagnose redundant direct base types. Note
2408 // that the key is always the unqualified canonical type of the base
2409 // class.
2410 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2411
2412 // Used to track indirect bases so we can see if a direct base is
2413 // ambiguous.
2414 IndirectBaseSet IndirectBaseTypes;
2415
2416 // Copy non-redundant base specifiers into permanent storage.
2417 unsigned NumGoodBases = 0;
2418 bool Invalid = false;
2419 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2420 QualType NewBaseType
2421 = Context.getCanonicalType(Bases[idx]->getType());
2422 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2423
2424 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2425 if (KnownBase) {
2426 // C++ [class.mi]p3:
2427 // A class shall not be specified as a direct base class of a
2428 // derived class more than once.
2429 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2430 << KnownBase->getType() << Bases[idx]->getSourceRange();
2431
2432 // Delete the duplicate base class specifier; we're going to
2433 // overwrite its pointer later.
2434 Context.Deallocate(Bases[idx]);
2435
2436 Invalid = true;
2437 } else {
2438 // Okay, add this new base class.
2439 KnownBase = Bases[idx];
2440 Bases[NumGoodBases++] = Bases[idx];
2441
2442 // Note this base's direct & indirect bases, if there could be ambiguity.
2443 if (Bases.size() > 1)
2444 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2445
2446 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2447 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2448 if (Class->isInterface() &&
2449 (!RD->isInterfaceLike() ||
2450 KnownBase->getAccessSpecifier() != AS_public)) {
2451 // The Microsoft extension __interface does not permit bases that
2452 // are not themselves public interfaces.
2453 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2454 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2455 << RD->getSourceRange();
2456 Invalid = true;
2457 }
2458 if (RD->hasAttr<WeakAttr>())
2459 Class->addAttr(WeakAttr::CreateImplicit(Context));
2460 }
2461 }
2462 }
2463
2464 // Attach the remaining base class specifiers to the derived class.
2465 Class->setBases(Bases.data(), NumGoodBases);
2466
2467 // Check that the only base classes that are duplicate are virtual.
2468 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2469 // Check whether this direct base is inaccessible due to ambiguity.
2470 QualType BaseType = Bases[idx]->getType();
2471
2472 // Skip all dependent types in templates being used as base specifiers.
2473 // Checks below assume that the base specifier is a CXXRecord.
2474 if (BaseType->isDependentType())
2475 continue;
2476
2477 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2478 .getUnqualifiedType();
2479
2480 if (IndirectBaseTypes.count(CanonicalBase)) {
2481 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2482 /*DetectVirtual=*/true);
2483 bool found
2484 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2485 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2485, __PRETTY_FUNCTION__))
;
2486 (void)found;
2487
2488 if (Paths.isAmbiguous(CanonicalBase))
2489 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2490 << BaseType << getAmbiguousPathsDisplayString(Paths)
2491 << Bases[idx]->getSourceRange();
2492 else
2493 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2493, __PRETTY_FUNCTION__))
;
2494 }
2495
2496 // Delete the base class specifier, since its data has been copied
2497 // into the CXXRecordDecl.
2498 Context.Deallocate(Bases[idx]);
2499 }
2500
2501 return Invalid;
2502}
2503
2504/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2505/// class, after checking whether there are any duplicate base
2506/// classes.
2507void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2508 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2509 if (!ClassDecl || Bases.empty())
2510 return;
2511
2512 AdjustDeclIfTemplate(ClassDecl);
2513 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2514}
2515
2516/// Determine whether the type \p Derived is a C++ class that is
2517/// derived from the type \p Base.
2518bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2519 if (!getLangOpts().CPlusPlus)
2520 return false;
2521
2522 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2523 if (!DerivedRD)
2524 return false;
2525
2526 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2527 if (!BaseRD)
2528 return false;
2529
2530 // If either the base or the derived type is invalid, don't try to
2531 // check whether one is derived from the other.
2532 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2533 return false;
2534
2535 // FIXME: In a modules build, do we need the entire path to be visible for us
2536 // to be able to use the inheritance relationship?
2537 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2538 return false;
2539
2540 return DerivedRD->isDerivedFrom(BaseRD);
2541}
2542
2543/// Determine whether the type \p Derived is a C++ class that is
2544/// derived from the type \p Base.
2545bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2546 CXXBasePaths &Paths) {
2547 if (!getLangOpts().CPlusPlus)
2548 return false;
2549
2550 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2551 if (!DerivedRD)
2552 return false;
2553
2554 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2555 if (!BaseRD)
2556 return false;
2557
2558 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2559 return false;
2560
2561 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2562}
2563
2564static void BuildBasePathArray(const CXXBasePath &Path,
2565 CXXCastPath &BasePathArray) {
2566 // We first go backward and check if we have a virtual base.
2567 // FIXME: It would be better if CXXBasePath had the base specifier for
2568 // the nearest virtual base.
2569 unsigned Start = 0;
2570 for (unsigned I = Path.size(); I != 0; --I) {
2571 if (Path[I - 1].Base->isVirtual()) {
2572 Start = I - 1;
2573 break;
2574 }
2575 }
2576
2577 // Now add all bases.
2578 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2579 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2580}
2581
2582
2583void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2584 CXXCastPath &BasePathArray) {
2585 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2585, __PRETTY_FUNCTION__))
;
2586 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2586, __PRETTY_FUNCTION__))
;
2587 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2588}
2589/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2590/// conversion (where Derived and Base are class types) is
2591/// well-formed, meaning that the conversion is unambiguous (and
2592/// that all of the base classes are accessible). Returns true
2593/// and emits a diagnostic if the code is ill-formed, returns false
2594/// otherwise. Loc is the location where this routine should point to
2595/// if there is an error, and Range is the source range to highlight
2596/// if there is an error.
2597///
2598/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2599/// diagnostic for the respective type of error will be suppressed, but the
2600/// check for ill-formed code will still be performed.
2601bool
2602Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2603 unsigned InaccessibleBaseID,
2604 unsigned AmbigiousBaseConvID,
2605 SourceLocation Loc, SourceRange Range,
2606 DeclarationName Name,
2607 CXXCastPath *BasePath,
2608 bool IgnoreAccess) {
2609 // First, determine whether the path from Derived to Base is
2610 // ambiguous. This is slightly more expensive than checking whether
2611 // the Derived to Base conversion exists, because here we need to
2612 // explore multiple paths to determine if there is an ambiguity.
2613 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2614 /*DetectVirtual=*/false);
2615 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2616 if (!DerivationOkay)
2617 return true;
2618
2619 const CXXBasePath *Path = nullptr;
2620 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2621 Path = &Paths.front();
2622
2623 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2624 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2625 // user to access such bases.
2626 if (!Path && getLangOpts().MSVCCompat) {
2627 for (const CXXBasePath &PossiblePath : Paths) {
2628 if (PossiblePath.size() == 1) {
2629 Path = &PossiblePath;
2630 if (AmbigiousBaseConvID)
2631 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2632 << Base << Derived << Range;
2633 break;
2634 }
2635 }
2636 }
2637
2638 if (Path) {
2639 if (!IgnoreAccess) {
2640 // Check that the base class can be accessed.
2641 switch (
2642 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2643 case AR_inaccessible:
2644 return true;
2645 case AR_accessible:
2646 case AR_dependent:
2647 case AR_delayed:
2648 break;
2649 }
2650 }
2651
2652 // Build a base path if necessary.
2653 if (BasePath)
2654 ::BuildBasePathArray(*Path, *BasePath);
2655 return false;
2656 }
2657
2658 if (AmbigiousBaseConvID) {
2659 // We know that the derived-to-base conversion is ambiguous, and
2660 // we're going to produce a diagnostic. Perform the derived-to-base
2661 // search just one more time to compute all of the possible paths so
2662 // that we can print them out. This is more expensive than any of
2663 // the previous derived-to-base checks we've done, but at this point
2664 // performance isn't as much of an issue.
2665 Paths.clear();
2666 Paths.setRecordingPaths(true);
2667 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2668 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2668, __PRETTY_FUNCTION__))
;
2669 (void)StillOkay;
2670
2671 // Build up a textual representation of the ambiguous paths, e.g.,
2672 // D -> B -> A, that will be used to illustrate the ambiguous
2673 // conversions in the diagnostic. We only print one of the paths
2674 // to each base class subobject.
2675 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2676
2677 Diag(Loc, AmbigiousBaseConvID)
2678 << Derived << Base << PathDisplayStr << Range << Name;
2679 }
2680 return true;
2681}
2682
2683bool
2684Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2685 SourceLocation Loc, SourceRange Range,
2686 CXXCastPath *BasePath,
2687 bool IgnoreAccess) {
2688 return CheckDerivedToBaseConversion(
2689 Derived, Base, diag::err_upcast_to_inaccessible_base,
2690 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2691 BasePath, IgnoreAccess);
2692}
2693
2694
2695/// Builds a string representing ambiguous paths from a
2696/// specific derived class to different subobjects of the same base
2697/// class.
2698///
2699/// This function builds a string that can be used in error messages
2700/// to show the different paths that one can take through the
2701/// inheritance hierarchy to go from the derived class to different
2702/// subobjects of a base class. The result looks something like this:
2703/// @code
2704/// struct D -> struct B -> struct A
2705/// struct D -> struct C -> struct A
2706/// @endcode
2707std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2708 std::string PathDisplayStr;
2709 std::set<unsigned> DisplayedPaths;
2710 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2711 Path != Paths.end(); ++Path) {
2712 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2713 // We haven't displayed a path to this particular base
2714 // class subobject yet.
2715 PathDisplayStr += "\n ";
2716 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2717 for (CXXBasePath::const_iterator Element = Path->begin();
2718 Element != Path->end(); ++Element)
2719 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2720 }
2721 }
2722
2723 return PathDisplayStr;
2724}
2725
2726//===----------------------------------------------------------------------===//
2727// C++ class member Handling
2728//===----------------------------------------------------------------------===//
2729
2730/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2731bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2732 SourceLocation ColonLoc,
2733 const ParsedAttributesView &Attrs) {
2734 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2734, __PRETTY_FUNCTION__))
;
2735 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2736 ASLoc, ColonLoc);
2737 CurContext->addHiddenDecl(ASDecl);
2738 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2739}
2740
2741/// CheckOverrideControl - Check C++11 override control semantics.
2742void Sema::CheckOverrideControl(NamedDecl *D) {
2743 if (D->isInvalidDecl())
2744 return;
2745
2746 // We only care about "override" and "final" declarations.
2747 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2748 return;
2749
2750 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2751
2752 // We can't check dependent instance methods.
2753 if (MD && MD->isInstance() &&
2754 (MD->getParent()->hasAnyDependentBases() ||
2755 MD->getType()->isDependentType()))
2756 return;
2757
2758 if (MD && !MD->isVirtual()) {
2759 // If we have a non-virtual method, check if if hides a virtual method.
2760 // (In that case, it's most likely the method has the wrong type.)
2761 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2762 FindHiddenVirtualMethods(MD, OverloadedMethods);
2763
2764 if (!OverloadedMethods.empty()) {
2765 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2766 Diag(OA->getLocation(),
2767 diag::override_keyword_hides_virtual_member_function)
2768 << "override" << (OverloadedMethods.size() > 1);
2769 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2770 Diag(FA->getLocation(),
2771 diag::override_keyword_hides_virtual_member_function)
2772 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2773 << (OverloadedMethods.size() > 1);
2774 }
2775 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2776 MD->setInvalidDecl();
2777 return;
2778 }
2779 // Fall through into the general case diagnostic.
2780 // FIXME: We might want to attempt typo correction here.
2781 }
2782
2783 if (!MD || !MD->isVirtual()) {
2784 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2785 Diag(OA->getLocation(),
2786 diag::override_keyword_only_allowed_on_virtual_member_functions)
2787 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2788 D->dropAttr<OverrideAttr>();
2789 }
2790 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2791 Diag(FA->getLocation(),
2792 diag::override_keyword_only_allowed_on_virtual_member_functions)
2793 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2794 << FixItHint::CreateRemoval(FA->getLocation());
2795 D->dropAttr<FinalAttr>();
2796 }
2797 return;
2798 }
2799
2800 // C++11 [class.virtual]p5:
2801 // If a function is marked with the virt-specifier override and
2802 // does not override a member function of a base class, the program is
2803 // ill-formed.
2804 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2805 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2806 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2807 << MD->getDeclName();
2808}
2809
2810void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2811 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2812 return;
2813 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2814 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2815 return;
2816
2817 SourceLocation Loc = MD->getLocation();
2818 SourceLocation SpellingLoc = Loc;
2819 if (getSourceManager().isMacroArgExpansion(Loc))
2820 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2821 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2822 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2823 return;
2824
2825 if (MD->size_overridden_methods() > 0) {
2826 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2827 ? diag::warn_destructor_marked_not_override_overriding
2828 : diag::warn_function_marked_not_override_overriding;
2829 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2830 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2831 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2832 }
2833}
2834
2835/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2836/// function overrides a virtual member function marked 'final', according to
2837/// C++11 [class.virtual]p4.
2838bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2839 const CXXMethodDecl *Old) {
2840 FinalAttr *FA = Old->getAttr<FinalAttr>();
2841 if (!FA)
2842 return false;
2843
2844 Diag(New->getLocation(), diag::err_final_function_overridden)
2845 << New->getDeclName()
2846 << FA->isSpelledAsSealed();
2847 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2848 return true;
2849}
2850
2851static bool InitializationHasSideEffects(const FieldDecl &FD) {
2852 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2853 // FIXME: Destruction of ObjC lifetime types has side-effects.
2854 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2855 return !RD->isCompleteDefinition() ||
2856 !RD->hasTrivialDefaultConstructor() ||
2857 !RD->hasTrivialDestructor();
2858 return false;
2859}
2860
2861static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2862 ParsedAttributesView::const_iterator Itr =
2863 llvm::find_if(list, [](const ParsedAttr &AL) {
2864 return AL.isDeclspecPropertyAttribute();
2865 });
2866 if (Itr != list.end())
2867 return &*Itr;
2868 return nullptr;
2869}
2870
2871// Check if there is a field shadowing.
2872void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2873 DeclarationName FieldName,
2874 const CXXRecordDecl *RD,
2875 bool DeclIsField) {
2876 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2877 return;
2878
2879 // To record a shadowed field in a base
2880 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2881 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2882 CXXBasePath &Path) {
2883 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2884 // Record an ambiguous path directly
2885 if (Bases.find(Base) != Bases.end())
2886 return true;
2887 for (const auto Field : Base->lookup(FieldName)) {
2888 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2889 Field->getAccess() != AS_private) {
2890 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2890, __PRETTY_FUNCTION__))
;
2891 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2891, __PRETTY_FUNCTION__))
;
2892 Bases[Base] = Field;
2893 return true;
2894 }
2895 }
2896 return false;
2897 };
2898
2899 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2900 /*DetectVirtual=*/true);
2901 if (!RD->lookupInBases(FieldShadowed, Paths))
2902 return;
2903
2904 for (const auto &P : Paths) {
2905 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2906 auto It = Bases.find(Base);
2907 // Skip duplicated bases
2908 if (It == Bases.end())
2909 continue;
2910 auto BaseField = It->second;
2911 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2911, __PRETTY_FUNCTION__))
;
2912 if (AS_none !=
2913 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2914 Diag(Loc, diag::warn_shadow_field)
2915 << FieldName << RD << Base << DeclIsField;
2916 Diag(BaseField->getLocation(), diag::note_shadow_field);
2917 Bases.erase(It);
2918 }
2919 }
2920}
2921
2922/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2923/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2924/// bitfield width if there is one, 'InitExpr' specifies the initializer if
2925/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2926/// present (but parsing it has been deferred).
2927NamedDecl *
2928Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2929 MultiTemplateParamsArg TemplateParameterLists,
2930 Expr *BW, const VirtSpecifiers &VS,
2931 InClassInitStyle InitStyle) {
2932 const DeclSpec &DS = D.getDeclSpec();
2933 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2934 DeclarationName Name = NameInfo.getName();
2935 SourceLocation Loc = NameInfo.getLoc();
2936
2937 // For anonymous bitfields, the location should point to the type.
2938 if (Loc.isInvalid())
2939 Loc = D.getBeginLoc();
2940
2941 Expr *BitWidth = static_cast<Expr*>(BW);
2942
2943 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2943, __PRETTY_FUNCTION__))
;
2944 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2944, __PRETTY_FUNCTION__))
;
2945
2946 bool isFunc = D.isDeclarationOfFunction();
2947 const ParsedAttr *MSPropertyAttr =
2948 getMSPropertyAttr(D.getDeclSpec().getAttributes());
2949
2950 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2951 // The Microsoft extension __interface only permits public member functions
2952 // and prohibits constructors, destructors, operators, non-public member
2953 // functions, static methods and data members.
2954 unsigned InvalidDecl;
2955 bool ShowDeclName = true;
2956 if (!isFunc &&
2957 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2958 InvalidDecl = 0;
2959 else if (!isFunc)
2960 InvalidDecl = 1;
2961 else if (AS != AS_public)
2962 InvalidDecl = 2;
2963 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2964 InvalidDecl = 3;
2965 else switch (Name.getNameKind()) {
2966 case DeclarationName::CXXConstructorName:
2967 InvalidDecl = 4;
2968 ShowDeclName = false;
2969 break;
2970
2971 case DeclarationName::CXXDestructorName:
2972 InvalidDecl = 5;
2973 ShowDeclName = false;
2974 break;
2975
2976 case DeclarationName::CXXOperatorName:
2977 case DeclarationName::CXXConversionFunctionName:
2978 InvalidDecl = 6;
2979 break;
2980
2981 default:
2982 InvalidDecl = 0;
2983 break;
2984 }
2985
2986 if (InvalidDecl) {
2987 if (ShowDeclName)
2988 Diag(Loc, diag::err_invalid_member_in_interface)
2989 << (InvalidDecl-1) << Name;
2990 else
2991 Diag(Loc, diag::err_invalid_member_in_interface)
2992 << (InvalidDecl-1) << "";
2993 return nullptr;
2994 }
2995 }
2996
2997 // C++ 9.2p6: A member shall not be declared to have automatic storage
2998 // duration (auto, register) or with the extern storage-class-specifier.
2999 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3000 // data members and cannot be applied to names declared const or static,
3001 // and cannot be applied to reference members.
3002 switch (DS.getStorageClassSpec()) {
3003 case DeclSpec::SCS_unspecified:
3004 case DeclSpec::SCS_typedef:
3005 case DeclSpec::SCS_static:
3006 break;
3007 case DeclSpec::SCS_mutable:
3008 if (isFunc) {
3009 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3010
3011 // FIXME: It would be nicer if the keyword was ignored only for this
3012 // declarator. Otherwise we could get follow-up errors.
3013 D.getMutableDeclSpec().ClearStorageClassSpecs();
3014 }
3015 break;
3016 default:
3017 Diag(DS.getStorageClassSpecLoc(),
3018 diag::err_storageclass_invalid_for_member);
3019 D.getMutableDeclSpec().ClearStorageClassSpecs();
3020 break;
3021 }
3022
3023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3025 !isFunc);
3026
3027 if (DS.isConstexprSpecified() && isInstField) {
3028 SemaDiagnosticBuilder B =
3029 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3030 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3031 if (InitStyle == ICIS_NoInit) {
3032 B << 0 << 0;
3033 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3034 B << FixItHint::CreateRemoval(ConstexprLoc);
3035 else {
3036 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3037 D.getMutableDeclSpec().ClearConstexprSpec();
3038 const char *PrevSpec;
3039 unsigned DiagID;
3040 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3041 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3042 (void)Failed;
3043 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3043, __PRETTY_FUNCTION__))
;
3044 }
3045 } else {
3046 B << 1;
3047 const char *PrevSpec;
3048 unsigned DiagID;
3049 if (D.getMutableDeclSpec().SetStorageClassSpec(
3050 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3051 Context.getPrintingPolicy())) {
3052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3053, __PRETTY_FUNCTION__))
3053 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3053, __PRETTY_FUNCTION__))
;
3054 B << 1;
3055 } else {
3056 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3057 isInstField = false;
3058 }
3059 }
3060 }
3061
3062 NamedDecl *Member;
3063 if (isInstField) {
3064 CXXScopeSpec &SS = D.getCXXScopeSpec();
3065
3066 // Data members must have identifiers for names.
3067 if (!Name.isIdentifier()) {
3068 Diag(Loc, diag::err_bad_variable_name)
3069 << Name;
3070 return nullptr;
3071 }
3072
3073 IdentifierInfo *II = Name.getAsIdentifierInfo();
3074
3075 // Member field could not be with "template" keyword.
3076 // So TemplateParameterLists should be empty in this case.
3077 if (TemplateParameterLists.size()) {
3078 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3079 if (TemplateParams->size()) {
3080 // There is no such thing as a member field template.
3081 Diag(D.getIdentifierLoc(), diag::err_template_member)
3082 << II
3083 << SourceRange(TemplateParams->getTemplateLoc(),
3084 TemplateParams->getRAngleLoc());
3085 } else {
3086 // There is an extraneous 'template<>' for this member.
3087 Diag(TemplateParams->getTemplateLoc(),
3088 diag::err_template_member_noparams)
3089 << II
3090 << SourceRange(TemplateParams->getTemplateLoc(),
3091 TemplateParams->getRAngleLoc());
3092 }
3093 return nullptr;
3094 }
3095
3096 if (SS.isSet() && !SS.isInvalid()) {
3097 // The user provided a superfluous scope specifier inside a class
3098 // definition:
3099 //
3100 // class X {
3101 // int X::member;
3102 // };
3103 if (DeclContext *DC = computeDeclContext(SS, false))
3104 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3105 D.getName().getKind() ==
3106 UnqualifiedIdKind::IK_TemplateId);
3107 else
3108 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3109 << Name << SS.getRange();
3110
3111 SS.clear();
3112 }
3113
3114 if (MSPropertyAttr) {
3115 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3116 BitWidth, InitStyle, AS, *MSPropertyAttr);
3117 if (!Member)
3118 return nullptr;
3119 isInstField = false;
3120 } else {
3121 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3122 BitWidth, InitStyle, AS);
3123 if (!Member)
3124 return nullptr;
3125 }
3126
3127 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3128 } else {
3129 Member = HandleDeclarator(S, D, TemplateParameterLists);
3130 if (!Member)
3131 return nullptr;
3132
3133 // Non-instance-fields can't have a bitfield.
3134 if (BitWidth) {
3135 if (Member->isInvalidDecl()) {
3136 // don't emit another diagnostic.
3137 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3138 // C++ 9.6p3: A bit-field shall not be a static member.
3139 // "static member 'A' cannot be a bit-field"
3140 Diag(Loc, diag::err_static_not_bitfield)
3141 << Name << BitWidth->getSourceRange();
3142 } else if (isa<TypedefDecl>(Member)) {
3143 // "typedef member 'x' cannot be a bit-field"
3144 Diag(Loc, diag::err_typedef_not_bitfield)
3145 << Name << BitWidth->getSourceRange();
3146 } else {
3147 // A function typedef ("typedef int f(); f a;").
3148 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3149 Diag(Loc, diag::err_not_integral_type_bitfield)
3150 << Name << cast<ValueDecl>(Member)->getType()
3151 << BitWidth->getSourceRange();
3152 }
3153
3154 BitWidth = nullptr;
3155 Member->setInvalidDecl();
3156 }
3157
3158 NamedDecl *NonTemplateMember = Member;
3159 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3160 NonTemplateMember = FunTmpl->getTemplatedDecl();
3161 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3162 NonTemplateMember = VarTmpl->getTemplatedDecl();
3163
3164 Member->setAccess(AS);
3165
3166 // If we have declared a member function template or static data member
3167 // template, set the access of the templated declaration as well.
3168 if (NonTemplateMember != Member)
3169 NonTemplateMember->setAccess(AS);
3170
3171 // C++ [temp.deduct.guide]p3:
3172 // A deduction guide [...] for a member class template [shall be
3173 // declared] with the same access [as the template].
3174 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3175 auto *TD = DG->getDeducedTemplate();
3176 // Access specifiers are only meaningful if both the template and the
3177 // deduction guide are from the same scope.
3178 if (AS != TD->getAccess() &&
3179 TD->getDeclContext()->getRedeclContext()->Equals(
3180 DG->getDeclContext()->getRedeclContext())) {
3181 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3182 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3183 << TD->getAccess();
3184 const AccessSpecDecl *LastAccessSpec = nullptr;
3185 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3186 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3187 LastAccessSpec = AccessSpec;
3188 }
3189 assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier"
) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3189, __PRETTY_FUNCTION__))
;
3190 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3191 << AS;
3192 }
3193 }
3194 }
3195
3196 if (VS.isOverrideSpecified())
3197 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3198 if (VS.isFinalSpecified())
3199 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3200 VS.isFinalSpelledSealed()));
3201
3202 if (VS.getLastLocation().isValid()) {
3203 // Update the end location of a method that has a virt-specifiers.
3204 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3205 MD->setRangeEnd(VS.getLastLocation());
3206 }
3207
3208 CheckOverrideControl(Member);
3209
3210 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3210, __PRETTY_FUNCTION__))
;
3211
3212 if (isInstField) {
3213 FieldDecl *FD = cast<FieldDecl>(Member);
3214 FieldCollector->Add(FD);
3215
3216 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3217 // Remember all explicit private FieldDecls that have a name, no side
3218 // effects and are not part of a dependent type declaration.
3219 if (!FD->isImplicit() && FD->getDeclName() &&
3220 FD->getAccess() == AS_private &&
3221 !FD->hasAttr<UnusedAttr>() &&
3222 !FD->getParent()->isDependentContext() &&
3223 !InitializationHasSideEffects(*FD))
3224 UnusedPrivateFields.insert(FD);
3225 }
3226 }
3227
3228 return Member;
3229}
3230
3231namespace {
3232 class UninitializedFieldVisitor
3233 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3234 Sema &S;
3235 // List of Decls to generate a warning on. Also remove Decls that become
3236 // initialized.
3237 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3238 // List of base classes of the record. Classes are removed after their
3239 // initializers.
3240 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3241 // Vector of decls to be removed from the Decl set prior to visiting the
3242 // nodes. These Decls may have been initialized in the prior initializer.
3243 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3244 // If non-null, add a note to the warning pointing back to the constructor.
3245 const CXXConstructorDecl *Constructor;
3246 // Variables to hold state when processing an initializer list. When
3247 // InitList is true, special case initialization of FieldDecls matching
3248 // InitListFieldDecl.
3249 bool InitList;
3250 FieldDecl *InitListFieldDecl;
3251 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3252
3253 public:
3254 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3255 UninitializedFieldVisitor(Sema &S,
3256 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3257 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3258 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3259 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3260
3261 // Returns true if the use of ME is not an uninitialized use.
3262 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3263 bool CheckReferenceOnly) {
3264 llvm::SmallVector<FieldDecl*, 4> Fields;
3265 bool ReferenceField = false;
3266 while (ME) {
3267 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3268 if (!FD)
3269 return false;
3270 Fields.push_back(FD);
3271 if (FD->getType()->isReferenceType())
3272 ReferenceField = true;
3273 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3274 }
3275
3276 // Binding a reference to an uninitialized field is not an
3277 // uninitialized use.
3278 if (CheckReferenceOnly && !ReferenceField)
3279 return true;
3280
3281 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3282 // Discard the first field since it is the field decl that is being
3283 // initialized.
3284 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3285 UsedFieldIndex.push_back((*I)->getFieldIndex());
3286 }
3287
3288 for (auto UsedIter = UsedFieldIndex.begin(),
3289 UsedEnd = UsedFieldIndex.end(),
3290 OrigIter = InitFieldIndex.begin(),
3291 OrigEnd = InitFieldIndex.end();
3292 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3293 if (*UsedIter < *OrigIter)
3294 return true;
3295 if (*UsedIter > *OrigIter)
3296 break;
3297 }
3298
3299 return false;
3300 }
3301
3302 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3303 bool AddressOf) {
3304 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3305 return;
3306
3307 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3308 // or union.
3309 MemberExpr *FieldME = ME;
3310
3311 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3312
3313 Expr *Base = ME;
3314 while (MemberExpr *SubME =
3315 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3316
3317 if (isa<VarDecl>(SubME->getMemberDecl()))
3318 return;
3319
3320 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3321 if (!FD->isAnonymousStructOrUnion())
3322 FieldME = SubME;
3323
3324 if (!FieldME->getType().isPODType(S.Context))
3325 AllPODFields = false;
3326
3327 Base = SubME->getBase();
3328 }
3329
3330 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3331 return;
3332
3333 if (AddressOf && AllPODFields)
3334 return;
3335
3336 ValueDecl* FoundVD = FieldME->getMemberDecl();
3337
3338 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3339 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3340 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3341 }
3342
3343 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3344 QualType T = BaseCast->getType();
3345 if (T->isPointerType() &&
3346 BaseClasses.count(T->getPointeeType())) {
3347 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3348 << T->getPointeeType() << FoundVD;
3349 }
3350 }
3351 }
3352
3353 if (!Decls.count(FoundVD))
3354 return;
3355
3356 const bool IsReference = FoundVD->getType()->isReferenceType();
3357
3358 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3359 // Special checking for initializer lists.
3360 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3361 return;
3362 }
3363 } else {
3364 // Prevent double warnings on use of unbounded references.
3365 if (CheckReferenceOnly && !IsReference)
3366 return;
3367 }
3368
3369 unsigned diag = IsReference
3370 ? diag::warn_reference_field_is_uninit
3371 : diag::warn_field_is_uninit;
3372 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3373 if (Constructor)
3374 S.Diag(Constructor->getLocation(),
3375 diag::note_uninit_in_this_constructor)
3376 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3377
3378 }
3379
3380 void HandleValue(Expr *E, bool AddressOf) {
3381 E = E->IgnoreParens();
3382
3383 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3384 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3385 AddressOf /*AddressOf*/);
3386 return;
3387 }
3388
3389 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3390 Visit(CO->getCond());
3391 HandleValue(CO->getTrueExpr(), AddressOf);
3392 HandleValue(CO->getFalseExpr(), AddressOf);
3393 return;
3394 }
3395
3396 if (BinaryConditionalOperator *BCO =
3397 dyn_cast<BinaryConditionalOperator>(E)) {
3398 Visit(BCO->getCond());
3399 HandleValue(BCO->getFalseExpr(), AddressOf);
3400 return;
3401 }
3402
3403 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3404 HandleValue(OVE->getSourceExpr(), AddressOf);
3405 return;
3406 }
3407
3408 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3409 switch (BO->getOpcode()) {
3410 default:
3411 break;
3412 case(BO_PtrMemD):
3413 case(BO_PtrMemI):
3414 HandleValue(BO->getLHS(), AddressOf);
3415 Visit(BO->getRHS());
3416 return;
3417 case(BO_Comma):
3418 Visit(BO->getLHS());
3419 HandleValue(BO->getRHS(), AddressOf);
3420 return;
3421 }
3422 }
3423
3424 Visit(E);
3425 }
3426
3427 void CheckInitListExpr(InitListExpr *ILE) {
3428 InitFieldIndex.push_back(0);
3429 for (auto Child : ILE->children()) {
3430 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3431 CheckInitListExpr(SubList);
3432 } else {
3433 Visit(Child);
3434 }
3435 ++InitFieldIndex.back();
3436 }
3437 InitFieldIndex.pop_back();
3438 }
3439
3440 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3441 FieldDecl *Field, const Type *BaseClass) {
3442 // Remove Decls that may have been initialized in the previous
3443 // initializer.
3444 for (ValueDecl* VD : DeclsToRemove)
3445 Decls.erase(VD);
3446 DeclsToRemove.clear();
3447
3448 Constructor = FieldConstructor;
3449 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3450
3451 if (ILE && Field) {
3452 InitList = true;
3453 InitListFieldDecl = Field;
3454 InitFieldIndex.clear();
3455 CheckInitListExpr(ILE);
3456 } else {
3457 InitList = false;
3458 Visit(E);
3459 }
3460
3461 if (Field)
3462 Decls.erase(Field);
3463 if (BaseClass)
3464 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3465 }
3466
3467 void VisitMemberExpr(MemberExpr *ME) {
3468 // All uses of unbounded reference fields will warn.
3469 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3470 }
3471
3472 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3473 if (E->getCastKind() == CK_LValueToRValue) {
3474 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3475 return;
3476 }
3477
3478 Inherited::VisitImplicitCastExpr(E);
3479 }
3480
3481 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3482 if (E->getConstructor()->isCopyConstructor()) {
3483 Expr *ArgExpr = E->getArg(0);
3484 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3485 if (ILE->getNumInits() == 1)
3486 ArgExpr = ILE->getInit(0);
3487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3488 if (ICE->getCastKind() == CK_NoOp)
3489 ArgExpr = ICE->getSubExpr();
3490 HandleValue(ArgExpr, false /*AddressOf*/);
3491 return;
3492 }
3493 Inherited::VisitCXXConstructExpr(E);
3494 }
3495
3496 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3497 Expr *Callee = E->getCallee();
3498 if (isa<MemberExpr>(Callee)) {
3499 HandleValue(Callee, false /*AddressOf*/);
3500 for (auto Arg : E->arguments())
3501 Visit(Arg);
3502 return;
3503 }
3504
3505 Inherited::VisitCXXMemberCallExpr(E);
3506 }
3507
3508 void VisitCallExpr(CallExpr *E) {
3509 // Treat std::move as a use.
3510 if (E->isCallToStdMove()) {
3511 HandleValue(E->getArg(0), /*AddressOf=*/false);
3512 return;
3513 }
3514
3515 Inherited::VisitCallExpr(E);
3516 }
3517
3518 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3519 Expr *Callee = E->getCallee();
3520
3521 if (isa<UnresolvedLookupExpr>(Callee))
3522 return Inherited::VisitCXXOperatorCallExpr(E);
3523
3524 Visit(Callee);
3525 for (auto Arg : E->arguments())
3526 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3527 }
3528
3529 void VisitBinaryOperator(BinaryOperator *E) {
3530 // If a field assignment is detected, remove the field from the
3531 // uninitiailized field set.
3532 if (E->getOpcode() == BO_Assign)
3533 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3534 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3535 if (!FD->getType()->isReferenceType())
3536 DeclsToRemove.push_back(FD);
3537
3538 if (E->isCompoundAssignmentOp()) {
3539 HandleValue(E->getLHS(), false /*AddressOf*/);
3540 Visit(E->getRHS());
3541 return;
3542 }
3543
3544 Inherited::VisitBinaryOperator(E);
3545 }
3546
3547 void VisitUnaryOperator(UnaryOperator *E) {
3548 if (E->isIncrementDecrementOp()) {
3549 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3550 return;
3551 }
3552 if (E->getOpcode() == UO_AddrOf) {
3553 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3554 HandleValue(ME->getBase(), true /*AddressOf*/);
3555 return;
3556 }
3557 }
3558
3559 Inherited::VisitUnaryOperator(E);
3560 }
3561 };
3562
3563 // Diagnose value-uses of fields to initialize themselves, e.g.
3564 // foo(foo)
3565 // where foo is not also a parameter to the constructor.
3566 // Also diagnose across field uninitialized use such as
3567 // x(y), y(x)
3568 // TODO: implement -Wuninitialized and fold this into that framework.
3569 static void DiagnoseUninitializedFields(
3570 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3571
3572 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3573 Constructor->getLocation())) {
3574 return;
3575 }
3576
3577 if (Constructor->isInvalidDecl())
3578 return;
3579
3580 const CXXRecordDecl *RD = Constructor->getParent();
3581
3582 if (RD->getDescribedClassTemplate())
3583 return;
3584
3585 // Holds fields that are uninitialized.
3586 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3587
3588 // At the beginning, all fields are uninitialized.
3589 for (auto *I : RD->decls()) {
3590 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3591 UninitializedFields.insert(FD);
3592 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3593 UninitializedFields.insert(IFD->getAnonField());
3594 }
3595 }
3596
3597 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3598 for (auto I : RD->bases())
3599 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3600
3601 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3602 return;
3603
3604 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3605 UninitializedFields,
3606 UninitializedBaseClasses);
3607
3608 for (const auto *FieldInit : Constructor->inits()) {
3609 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3610 break;
3611
3612 Expr *InitExpr = FieldInit->getInit();
3613 if (!InitExpr)
3614 continue;
3615
3616 if (CXXDefaultInitExpr *Default =
3617 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3618 InitExpr = Default->getExpr();
3619 if (!InitExpr)
3620 continue;
3621 // In class initializers will point to the constructor.
3622 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3623 FieldInit->getAnyMember(),
3624 FieldInit->getBaseClass());
3625 } else {
3626 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3627 FieldInit->getAnyMember(),
3628 FieldInit->getBaseClass());
3629 }
3630 }
3631 }
3632} // namespace
3633
3634/// Enter a new C++ default initializer scope. After calling this, the
3635/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3636/// parsing or instantiating the initializer failed.
3637void Sema::ActOnStartCXXInClassMemberInitializer() {
3638 // Create a synthetic function scope to represent the call to the constructor
3639 // that notionally surrounds a use of this initializer.
3640 PushFunctionScope();
3641}
3642
3643/// This is invoked after parsing an in-class initializer for a
3644/// non-static C++ class member, and after instantiating an in-class initializer
3645/// in a class template. Such actions are deferred until the class is complete.
3646void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3647 SourceLocation InitLoc,
3648 Expr *InitExpr) {
3649 // Pop the notional constructor scope we created earlier.
3650 PopFunctionScopeInfo(nullptr, D);
3651
3652 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3653 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3654, __PRETTY_FUNCTION__))
3654 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3654, __PRETTY_FUNCTION__))
;
3655
3656 if (!InitExpr) {
3657 D->setInvalidDecl();
3658 if (FD)
3659 FD->removeInClassInitializer();
3660 return;
3661 }
3662
3663 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3664 FD->setInvalidDecl();
3665 FD->removeInClassInitializer();
3666 return;
3667 }
3668
3669 ExprResult Init = InitExpr;
3670 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3671 InitializedEntity Entity =
3672 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3673 InitializationKind Kind =
3674 FD->getInClassInitStyle() == ICIS_ListInit
3675 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3676 InitExpr->getBeginLoc(),
3677 InitExpr->getEndLoc())
3678 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3679 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3680 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3681 if (Init.isInvalid()) {
3682 FD->setInvalidDecl();
3683 return;
3684 }
3685 }
3686
3687 // C++11 [class.base.init]p7:
3688 // The initialization of each base and member constitutes a
3689 // full-expression.
3690 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3691 if (Init.isInvalid()) {
3692 FD->setInvalidDecl();
3693 return;
3694 }
3695
3696 InitExpr = Init.get();
3697
3698 FD->setInClassInitializer(InitExpr);
3699}
3700
3701/// Find the direct and/or virtual base specifiers that
3702/// correspond to the given base type, for use in base initialization
3703/// within a constructor.
3704static bool FindBaseInitializer(Sema &SemaRef,
3705 CXXRecordDecl *ClassDecl,
3706 QualType BaseType,
3707 const CXXBaseSpecifier *&DirectBaseSpec,
3708 const CXXBaseSpecifier *&VirtualBaseSpec) {
3709 // First, check for a direct base class.
3710 DirectBaseSpec = nullptr;
3711 for (const auto &Base : ClassDecl->bases()) {
3712 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3713 // We found a direct base of this type. That's what we're
3714 // initializing.
3715 DirectBaseSpec = &Base;
3716 break;
3717 }
3718 }
3719
3720 // Check for a virtual base class.
3721 // FIXME: We might be able to short-circuit this if we know in advance that
3722 // there are no virtual bases.
3723 VirtualBaseSpec = nullptr;
3724 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3725 // We haven't found a base yet; search the class hierarchy for a
3726 // virtual base class.
3727 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3728 /*DetectVirtual=*/false);
3729 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3730 SemaRef.Context.getTypeDeclType(ClassDecl),
3731 BaseType, Paths)) {
3732 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3733 Path != Paths.end(); ++Path) {
3734 if (Path->back().Base->isVirtual()) {
3735 VirtualBaseSpec = Path->back().Base;
3736 break;
3737 }
3738 }
3739 }
3740 }
3741
3742 return DirectBaseSpec || VirtualBaseSpec;
3743}
3744
3745/// Handle a C++ member initializer using braced-init-list syntax.
3746MemInitResult
3747Sema::ActOnMemInitializer(Decl *ConstructorD,
3748 Scope *S,
3749 CXXScopeSpec &SS,
3750 IdentifierInfo *MemberOrBase,
3751 ParsedType TemplateTypeTy,
3752 const DeclSpec &DS,
3753 SourceLocation IdLoc,
3754 Expr *InitList,
3755 SourceLocation EllipsisLoc) {
3756 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3757 DS, IdLoc, InitList,
3758 EllipsisLoc);
3759}
3760
3761/// Handle a C++ member initializer using parentheses syntax.
3762MemInitResult
3763Sema::ActOnMemInitializer(Decl *ConstructorD,
3764 Scope *S,
3765 CXXScopeSpec &SS,
3766 IdentifierInfo *MemberOrBase,
3767 ParsedType TemplateTypeTy,
3768 const DeclSpec &DS,
3769 SourceLocation IdLoc,
3770 SourceLocation LParenLoc,
3771 ArrayRef<Expr *> Args,
3772 SourceLocation RParenLoc,
3773 SourceLocation EllipsisLoc) {
3774 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3775 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3776 DS, IdLoc, List, EllipsisLoc);
3777}
3778
3779namespace {
3780
3781// Callback to only accept typo corrections that can be a valid C++ member
3782// intializer: either a non-static field member or a base class.
3783class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3784public:
3785 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3786 : ClassDecl(ClassDecl) {}
3787
3788 bool ValidateCandidate(const TypoCorrection &candidate) override {
3789 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3790 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3791 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3792 return isa<TypeDecl>(ND);
3793 }
3794 return false;
3795 }
3796
3797 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3798 return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3799 }
3800
3801private:
3802 CXXRecordDecl *ClassDecl;
3803};
3804
3805}
3806
3807ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3808 CXXScopeSpec &SS,
3809 ParsedType TemplateTypeTy,
3810 IdentifierInfo *MemberOrBase) {
3811 if (SS.getScopeRep() || TemplateTypeTy)
3812 return nullptr;
3813 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3814 if (Result.empty())
3815 return nullptr;
3816 ValueDecl *Member;
3817 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3818 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3819 return Member;
3820 return nullptr;
3821}
3822
3823/// Handle a C++ member initializer.
3824MemInitResult
3825Sema::BuildMemInitializer(Decl *ConstructorD,
3826 Scope *S,
3827 CXXScopeSpec &SS,
3828 IdentifierInfo *MemberOrBase,
3829 ParsedType TemplateTypeTy,
3830 const DeclSpec &DS,
3831 SourceLocation IdLoc,
3832 Expr *Init,
3833 SourceLocation EllipsisLoc) {
3834 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3835 if (!Res.isUsable())
3836 return true;
3837 Init = Res.get();
3838
3839 if (!ConstructorD)
3840 return true;
3841
3842 AdjustDeclIfTemplate(ConstructorD);
3843
3844 CXXConstructorDecl *Constructor
3845 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3846 if (!Constructor) {
3847 // The user wrote a constructor initializer on a function that is
3848 // not a C++ constructor. Ignore the error for now, because we may
3849 // have more member initializers coming; we'll diagnose it just
3850 // once in ActOnMemInitializers.
3851 return true;
3852 }
3853
3854 CXXRecordDecl *ClassDecl = Constructor->getParent();
3855
3856 // C++ [class.base.init]p2:
3857 // Names in a mem-initializer-id are looked up in the scope of the
3858 // constructor's class and, if not found in that scope, are looked
3859 // up in the scope containing the constructor's definition.
3860 // [Note: if the constructor's class contains a member with the
3861 // same name as a direct or virtual base class of the class, a
3862 // mem-initializer-id naming the member or base class and composed
3863 // of a single identifier refers to the class member. A
3864 // mem-initializer-id for the hidden base class may be specified
3865 // using a qualified name. ]
3866
3867 // Look for a member, first.
3868 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3869 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3870 if (EllipsisLoc.isValid())
3871 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3872 << MemberOrBase
3873 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3874
3875 return BuildMemberInitializer(Member, Init, IdLoc);
3876 }
3877 // It didn't name a member, so see if it names a class.
3878 QualType BaseType;
3879 TypeSourceInfo *TInfo = nullptr;
3880
3881 if (TemplateTypeTy) {
3882 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3883 if (BaseType.isNull())
3884 return true;
3885 } else if (DS.getTypeSpecType() == TST_decltype) {
3886 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3887 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3888 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3889 return true;
3890 } else {
3891 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3892 LookupParsedName(R, S, &SS);
3893
3894 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3895 if (!TyD) {
3896 if (R.isAmbiguous()) return true;
3897
3898 // We don't want access-control diagnostics here.
3899 R.suppressDiagnostics();
3900
3901 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3902 bool NotUnknownSpecialization = false;
3903 DeclContext *DC = computeDeclContext(SS, false);
3904 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3905 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3906
3907 if (!NotUnknownSpecialization) {
3908 // When the scope specifier can refer to a member of an unknown
3909 // specialization, we take it as a type name.
3910 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3911 SS.getWithLocInContext(Context),
3912 *MemberOrBase, IdLoc);
3913 if (BaseType.isNull())
3914 return true;
3915
3916 TInfo = Context.CreateTypeSourceInfo(BaseType);
3917 DependentNameTypeLoc TL =
3918 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3919 if (!TL.isNull()) {
3920 TL.setNameLoc(IdLoc);
3921 TL.setElaboratedKeywordLoc(SourceLocation());
3922 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3923 }
3924
3925 R.clear();
3926 R.setLookupName(MemberOrBase);
3927 }
3928 }
3929
3930 // If no results were found, try to correct typos.
3931 TypoCorrection Corr;
3932 MemInitializerValidatorCCC CCC(ClassDecl);
3933 if (R.empty() && BaseType.isNull() &&
3934 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3935 CCC, CTK_ErrorRecovery, ClassDecl))) {
3936 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3937 // We have found a non-static data member with a similar
3938 // name to what was typed; complain and initialize that
3939 // member.
3940 diagnoseTypo(Corr,
3941 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3942 << MemberOrBase << true);
3943 return BuildMemberInitializer(Member, Init, IdLoc);
3944 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3945 const CXXBaseSpecifier *DirectBaseSpec;
3946 const CXXBaseSpecifier *VirtualBaseSpec;
3947 if (FindBaseInitializer(*this, ClassDecl,
3948 Context.getTypeDeclType(Type),
3949 DirectBaseSpec, VirtualBaseSpec)) {
3950 // We have found a direct or virtual base class with a
3951 // similar name to what was typed; complain and initialize
3952 // that base class.
3953 diagnoseTypo(Corr,
3954 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3955 << MemberOrBase << false,
3956 PDiag() /*Suppress note, we provide our own.*/);
3957
3958 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3959 : VirtualBaseSpec;
3960 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3961 << BaseSpec->getType() << BaseSpec->getSourceRange();
3962
3963 TyD = Type;
3964 }
3965 }
3966 }
3967
3968 if (!TyD && BaseType.isNull()) {
3969 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3970 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3971 return true;
3972 }
3973 }
3974
3975 if (BaseType.isNull()) {
3976 BaseType = Context.getTypeDeclType(TyD);
3977 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3978 if (SS.isSet()) {
3979 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3980 BaseType);
3981 TInfo = Context.CreateTypeSourceInfo(BaseType);
3982 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3983 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3984 TL.setElaboratedKeywordLoc(SourceLocation());
3985 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3986 }
3987 }
3988 }
3989
3990 if (!TInfo)
3991 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3992
3993 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3994}
3995
3996MemInitResult
3997Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3998 SourceLocation IdLoc) {
3999 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4000 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4001 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4002, __PRETTY_FUNCTION__))
4002 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4002, __PRETTY_FUNCTION__))
;
4003
4004 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4005 return true;
4006
4007 if (Member->isInvalidDecl())
4008 return true;
4009
4010 MultiExprArg Args;
4011 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4012 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4013 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4014 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4015 } else {
4016 // Template instantiation doesn't reconstruct ParenListExprs for us.
4017 Args = Init;
4018 }
4019
4020 SourceRange InitRange = Init->getSourceRange();
4021
4022 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4023 // Can't check initialization for a member of dependent type or when
4024 // any of the arguments are type-dependent expressions.
4025 DiscardCleanupsInEvaluationContext();
4026 } else {
4027 bool InitList = false;
4028 if (isa<InitListExpr>(Init)) {
4029 InitList = true;
4030 Args = Init;
4031 }
4032
4033 // Initialize the member.
4034 InitializedEntity MemberEntity =
4035 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4036 : InitializedEntity::InitializeMember(IndirectMember,
4037 nullptr);
4038 InitializationKind Kind =
4039 InitList ? InitializationKind::CreateDirectList(
4040 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4041 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4042 InitRange.getEnd());
4043
4044 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4045 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4046 nullptr);
4047 if (MemberInit.isInvalid())
4048 return true;
4049
4050 // C++11 [class.base.init]p7:
4051 // The initialization of each base and member constitutes a
4052 // full-expression.
4053 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4054 /*DiscardedValue*/ false);
4055 if (MemberInit.isInvalid())
4056 return true;
4057
4058 Init = MemberInit.get();
4059 }
4060
4061 if (DirectMember) {
4062 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4063 InitRange.getBegin(), Init,
4064 InitRange.getEnd());
4065 } else {
4066 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4067 InitRange.getBegin(), Init,
4068 InitRange.getEnd());
4069 }
4070}
4071
4072MemInitResult
4073Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4074 CXXRecordDecl *ClassDecl) {
4075 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4076 if (!LangOpts.CPlusPlus11)
4077 return Diag(NameLoc, diag::err_delegating_ctor)
4078 << TInfo->getTypeLoc().getLocalSourceRange();
4079 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4080
4081 bool InitList = true;
4082 MultiExprArg Args = Init;
4083 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4084 InitList = false;
4085 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4086 }
4087
4088 SourceRange InitRange = Init->getSourceRange();
4089 // Initialize the object.
4090 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4091 QualType(ClassDecl->getTypeForDecl(), 0));
4092 InitializationKind Kind =
4093 InitList ? InitializationKind::CreateDirectList(
4094 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4095 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4096 InitRange.getEnd());
4097 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4098 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4099 Args, nullptr);
4100 if (DelegationInit.isInvalid())
4101 return true;
4102
4103 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4104, __PRETTY_FUNCTION__))
4104 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4104, __PRETTY_FUNCTION__))
;
4105
4106 // C++11 [class.base.init]p7:
4107 // The initialization of each base and member constitutes a
4108 // full-expression.
4109 DelegationInit = ActOnFinishFullExpr(
4110 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4111 if (DelegationInit.isInvalid())
4112 return true;
4113
4114 // If we are in a dependent context, template instantiation will
4115 // perform this type-checking again. Just save the arguments that we
4116 // received in a ParenListExpr.
4117 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4118 // of the information that we have about the base
4119 // initializer. However, deconstructing the ASTs is a dicey process,
4120 // and this approach is far more likely to get the corner cases right.
4121 if (CurContext->isDependentContext())
4122 DelegationInit = Init;
4123
4124 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4125 DelegationInit.getAs<Expr>(),
4126 InitRange.getEnd());
4127}
4128
4129MemInitResult
4130Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4131 Expr *Init, CXXRecordDecl *ClassDecl,
4132 SourceLocation EllipsisLoc) {
4133 SourceLocation BaseLoc
4134 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4135
4136 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4137 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4138 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4139
4140 // C++ [class.base.init]p2:
4141 // [...] Unless the mem-initializer-id names a nonstatic data
4142 // member of the constructor's class or a direct or virtual base
4143 // of that class, the mem-initializer is ill-formed. A
4144 // mem-initializer-list can initialize a base class using any
4145 // name that denotes that base class type.
4146 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4147
4148 SourceRange InitRange = Init->getSourceRange();
4149 if (EllipsisLoc.isValid()) {
4150 // This is a pack expansion.
4151 if (!BaseType->containsUnexpandedParameterPack()) {
4152 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4153 << SourceRange(BaseLoc, InitRange.getEnd());
4154
4155 EllipsisLoc = SourceLocation();
4156 }
4157 } else {
4158 // Check for any unexpanded parameter packs.
4159 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4160 return true;
4161
4162 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4163 return true;
4164 }
4165
4166 // Check for direct and virtual base classes.
4167 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4168 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4169 if (!Dependent) {
4170 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4171 BaseType))
4172 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4173
4174 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4175 VirtualBaseSpec);
4176
4177 // C++ [base.class.init]p2:
4178 // Unless the mem-initializer-id names a nonstatic data member of the
4179 // constructor's class or a direct or virtual base of that class, the
4180 // mem-initializer is ill-formed.
4181 if (!DirectBaseSpec && !VirtualBaseSpec) {
4182 // If the class has any dependent bases, then it's possible that
4183 // one of those types will resolve to the same type as
4184 // BaseType. Therefore, just treat this as a dependent base
4185 // class initialization. FIXME: Should we try to check the
4186 // initialization anyway? It seems odd.
4187 if (ClassDecl->hasAnyDependentBases())
4188 Dependent = true;
4189 else
4190 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4191 << BaseType << Context.getTypeDeclType(ClassDecl)
4192 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4193 }
4194 }
4195
4196 if (Dependent) {
4197 DiscardCleanupsInEvaluationContext();
4198
4199 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4200 /*IsVirtual=*/false,
4201 InitRange.getBegin(), Init,
4202 InitRange.getEnd(), EllipsisLoc);
4203 }
4204
4205 // C++ [base.class.init]p2:
4206 // If a mem-initializer-id is ambiguous because it designates both
4207 // a direct non-virtual base class and an inherited virtual base
4208 // class, the mem-initializer is ill-formed.
4209 if (DirectBaseSpec && VirtualBaseSpec)
4210 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4211 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4212
4213 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4214 if (!BaseSpec)
4215 BaseSpec = VirtualBaseSpec;
4216
4217 // Initialize the base.
4218 bool InitList = true;
4219 MultiExprArg Args = Init;
4220 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4221 InitList = false;
4222 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4223 }
4224
4225 InitializedEntity BaseEntity =
4226 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4227 InitializationKind Kind =
4228 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4229 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4230 InitRange.getEnd());
4231 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4232 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4233 if (BaseInit.isInvalid())
4234 return true;
4235
4236 // C++11 [class.base.init]p7:
4237 // The initialization of each base and member constitutes a
4238 // full-expression.
4239 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4240 /*DiscardedValue*/ false);
4241 if (BaseInit.isInvalid())
4242 return true;
4243
4244 // If we are in a dependent context, template instantiation will
4245 // perform this type-checking again. Just save the arguments that we
4246 // received in a ParenListExpr.
4247 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4248 // of the information that we have about the base
4249 // initializer. However, deconstructing the ASTs is a dicey process,
4250 // and this approach is far more likely to get the corner cases right.
4251 if (CurContext->isDependentContext())
4252 BaseInit = Init;
4253
4254 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4255 BaseSpec->isVirtual(),
4256 InitRange.getBegin(),
4257 BaseInit.getAs<Expr>(),
4258 InitRange.getEnd(), EllipsisLoc);
4259}
4260
4261// Create a static_cast\<T&&>(expr).
4262static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4263 if (T.isNull()) T = E->getType();
4264 QualType TargetType = SemaRef.BuildReferenceType(
4265 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4266 SourceLocation ExprLoc = E->getBeginLoc();
4267 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4268 TargetType, ExprLoc);
4269
4270 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4271 SourceRange(ExprLoc, ExprLoc),
4272 E->getSourceRange()).get();
4273}
4274
4275/// ImplicitInitializerKind - How an implicit base or member initializer should
4276/// initialize its base or member.
4277enum ImplicitInitializerKind {
4278 IIK_Default,
4279 IIK_Copy,
4280 IIK_Move,
4281 IIK_Inherit
4282};
4283
4284static bool
4285BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4286 ImplicitInitializerKind ImplicitInitKind,
4287 CXXBaseSpecifier *BaseSpec,
4288 bool IsInheritedVirtualBase,
4289 CXXCtorInitializer *&CXXBaseInit) {
4290 InitializedEntity InitEntity
4291 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4292 IsInheritedVirtualBase);
4293
4294 ExprResult BaseInit;
4295
4296 switch (ImplicitInitKind) {
4297 case IIK_Inherit:
4298 case IIK_Default: {
4299 InitializationKind InitKind
4300 = InitializationKind::CreateDefault(Constructor->getLocation());
4301 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4302 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4303 break;
4304 }
4305
4306 case IIK_Move:
4307 case IIK_Copy: {
4308 bool Moving = ImplicitInitKind == IIK_Move;
4309 ParmVarDecl *Param = Constructor->getParamDecl(0);
4310 QualType ParamType = Param->getType().getNonReferenceType();
4311
4312 Expr *CopyCtorArg =
4313 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4314 SourceLocation(), Param, false,
4315 Constructor->getLocation(), ParamType,
4316 VK_LValue, nullptr);
4317
4318 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4319
4320 // Cast to the base class to avoid ambiguities.
4321 QualType ArgTy =
4322 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4323 ParamType.getQualifiers());
4324
4325 if (Moving) {
4326 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4327 }
4328
4329 CXXCastPath BasePath;
4330 BasePath.push_back(BaseSpec);
4331 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4332 CK_UncheckedDerivedToBase,
4333 Moving ? VK_XValue : VK_LValue,
4334 &BasePath).get();
4335
4336 InitializationKind InitKind
4337 = InitializationKind::CreateDirect(Constructor->getLocation(),
4338 SourceLocation(), SourceLocation());
4339 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4340 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4341 break;
4342 }
4343 }
4344
4345 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4346 if (BaseInit.isInvalid())
4347 return true;
4348
4349 CXXBaseInit =
4350 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4351 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4352 SourceLocation()),
4353 BaseSpec->isVirtual(),
4354 SourceLocation(),
4355 BaseInit.getAs<Expr>(),
4356 SourceLocation(),
4357 SourceLocation());
4358
4359 return false;
4360}
4361
4362static bool RefersToRValueRef(Expr *MemRef) {
4363 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4364 return Referenced->getType()->isRValueReferenceType();
4365}
4366
4367static bool
4368BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4369 ImplicitInitializerKind ImplicitInitKind,
4370 FieldDecl *Field, IndirectFieldDecl *Indirect,
4371 CXXCtorInitializer *&CXXMemberInit) {
4372 if (Field->isInvalidDecl())
4373 return true;
4374
4375 SourceLocation Loc = Constructor->getLocation();
4376
4377 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4378 bool Moving = ImplicitInitKind == IIK_Move;
4379 ParmVarDecl *Param = Constructor->getParamDecl(0);
4380 QualType ParamType = Param->getType().getNonReferenceType();
4381
4382 // Suppress copying zero-width bitfields.
4383 if (Field->isZeroLengthBitField(SemaRef.Context))
4384 return false;
4385
4386 Expr *MemberExprBase =
4387 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4388 SourceLocation(), Param, false,
4389 Loc, ParamType, VK_LValue, nullptr);
4390
4391 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4392
4393 if (Moving) {
4394 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4395 }
4396
4397 // Build a reference to this field within the parameter.
4398 CXXScopeSpec SS;
4399 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4400 Sema::LookupMemberName);
4401 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4402 : cast<ValueDecl>(Field), AS_public);
4403 MemberLookup.resolveKind();
4404 ExprResult CtorArg
4405 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4406 ParamType, Loc,
4407 /*IsArrow=*/false,
4408 SS,
4409 /*TemplateKWLoc=*/SourceLocation(),
4410 /*FirstQualifierInScope=*/nullptr,
4411 MemberLookup,
4412 /*TemplateArgs=*/nullptr,
4413 /*S*/nullptr);
4414 if (CtorArg.isInvalid())
4415 return true;
4416
4417 // C++11 [class.copy]p15:
4418 // - if a member m has rvalue reference type T&&, it is direct-initialized
4419 // with static_cast<T&&>(x.m);
4420 if (RefersToRValueRef(CtorArg.get())) {
4421 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4422 }
4423
4424 InitializedEntity Entity =
4425 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4426 /*Implicit*/ true)
4427 : InitializedEntity::InitializeMember(Field, nullptr,
4428 /*Implicit*/ true);
4429
4430 // Direct-initialize to use the copy constructor.
4431 InitializationKind InitKind =
4432 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4433
4434 Expr *CtorArgE = CtorArg.getAs<Expr>();
4435 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4436 ExprResult MemberInit =
4437 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4438 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4439 if (MemberInit.isInvalid())
4440 return true;
4441
4442 if (Indirect)
4443 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4444 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4445 else
4446 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4447 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4448 return false;
4449 }
4450
4451 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4452, __PRETTY_FUNCTION__))
4452 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4452, __PRETTY_FUNCTION__))
;
4453
4454 QualType FieldBaseElementType =
4455 SemaRef.Context.getBaseElementType(Field->getType());
4456
4457 if (FieldBaseElementType->isRecordType()) {
4458 InitializedEntity InitEntity =
4459 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4460 /*Implicit*/ true)
4461 : InitializedEntity::InitializeMember(Field, nullptr,
4462 /*Implicit*/ true);
4463 InitializationKind InitKind =
4464 InitializationKind::CreateDefault(Loc);
4465
4466 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4467 ExprResult MemberInit =
4468 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4469
4470 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4471 if (MemberInit.isInvalid())
4472 return true;
4473
4474 if (Indirect)
4475 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4476 Indirect, Loc,
4477 Loc,
4478 MemberInit.get(),
4479 Loc);
4480 else
4481 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4482 Field, Loc, Loc,
4483 MemberInit.get(),
4484 Loc);
4485 return false;
4486 }
4487
4488 if (!Field->getParent()->isUnion()) {
4489 if (FieldBaseElementType->isReferenceType()) {
4490 SemaRef.Diag(Constructor->getLocation(),
4491 diag::err_uninitialized_member_in_ctor)
4492 << (int)Constructor->isImplicit()
4493 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4494 << 0 << Field->getDeclName();
4495 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4496 return true;
4497 }
4498
4499 if (FieldBaseElementType.isConstQualified()) {
4500 SemaRef.Diag(Constructor->getLocation(),
4501 diag::err_uninitialized_member_in_ctor)
4502 << (int)Constructor->isImplicit()
4503 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4504 << 1 << Field->getDeclName();
4505 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4506 return true;
4507 }
4508 }
4509
4510 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4511 // ARC and Weak:
4512 // Default-initialize Objective-C pointers to NULL.
4513 CXXMemberInit
4514 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4515 Loc, Loc,
4516 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4517 Loc);
4518 return false;
4519 }
4520
4521 // Nothing to initialize.
4522 CXXMemberInit = nullptr;
4523 return false;
4524}
4525
4526namespace {
4527struct BaseAndFieldInfo {
4528 Sema &S;
4529 CXXConstructorDecl *Ctor;
4530 bool AnyErrorsInInits;
4531 ImplicitInitializerKind IIK;
4532 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4533 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4534 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4535
4536 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4537 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4538 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4539 if (Ctor->getInheritedConstructor())
4540 IIK = IIK_Inherit;
4541 else if (Generated && Ctor->isCopyConstructor())
4542 IIK = IIK_Copy;
4543 else if (Generated && Ctor->isMoveConstructor())
4544 IIK = IIK_Move;
4545 else
4546 IIK = IIK_Default;
4547 }
4548
4549 bool isImplicitCopyOrMove() const {
4550 switch (IIK) {
4551 case IIK_Copy:
4552 case IIK_Move:
4553 return true;
4554
4555 case IIK_Default:
4556 case IIK_Inherit:
4557 return false;
4558 }
4559
4560 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4560)
;
4561 }
4562
4563 bool addFieldInitializer(CXXCtorInitializer *Init) {
4564 AllToInit.push_back(Init);
4565
4566 // Check whether this initializer makes the field "used".
4567 if (Init->getInit()->HasSideEffects(S.Context))
4568 S.UnusedPrivateFields.remove(Init->getAnyMember());
4569
4570 return false;
4571 }
4572
4573 bool isInactiveUnionMember(FieldDecl *Field) {
4574 RecordDecl *Record = Field->getParent();
4575 if (!Record->isUnion())
4576 return false;
4577
4578 if (FieldDecl *Active =
4579 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4580 return Active != Field->getCanonicalDecl();
4581
4582 // In an implicit copy or move constructor, ignore any in-class initializer.
4583 if (isImplicitCopyOrMove())
4584 return true;
4585
4586 // If there's no explicit initialization, the field is active only if it
4587 // has an in-class initializer...
4588 if (Field->hasInClassInitializer())
4589 return false;
4590 // ... or it's an anonymous struct or union whose class has an in-class
4591 // initializer.
4592 if (!Field->isAnonymousStructOrUnion())
4593 return true;
4594 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4595 return !FieldRD->hasInClassInitializer();
4596 }
4597
4598 /// Determine whether the given field is, or is within, a union member
4599 /// that is inactive (because there was an initializer given for a different
4600 /// member of the union, or because the union was not initialized at all).
4601 bool isWithinInactiveUnionMember(FieldDecl *Field,
4602 IndirectFieldDecl *Indirect) {
4603 if (!Indirect)
4604 return isInactiveUnionMember(Field);
4605
4606 for (auto *C : Indirect->chain()) {
4607 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4608 if (Field && isInactiveUnionMember(Field))
4609 return true;
4610 }
4611 return false;
4612 }
4613};
4614}
4615
4616/// Determine whether the given type is an incomplete or zero-lenfgth
4617/// array type.
4618static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4619 if (T->isIncompleteArrayType())
4620 return true;
4621
4622 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4623 if (!ArrayT->getSize())
4624 return true;
4625
4626 T = ArrayT->getElementType();
4627 }
4628
4629 return false;
4630}
4631
4632static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4633 FieldDecl *Field,
4634 IndirectFieldDecl *Indirect = nullptr) {
4635 if (Field->isInvalidDecl())
4636 return false;
4637
4638 // Overwhelmingly common case: we have a direct initializer for this field.
4639 if (CXXCtorInitializer *Init =
4640 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4641 return Info.addFieldInitializer(Init);
4642
4643 // C++11 [class.base.init]p8:
4644 // if the entity is a non-static data member that has a
4645 // brace-or-equal-initializer and either
4646 // -- the constructor's class is a union and no other variant member of that
4647 // union is designated by a mem-initializer-id or
4648 // -- the constructor's class is not a union, and, if the entity is a member
4649 // of an anonymous union, no other member of that union is designated by
4650 // a mem-initializer-id,
4651 // the entity is initialized as specified in [dcl.init].
4652 //
4653 // We also apply the same rules to handle anonymous structs within anonymous
4654 // unions.
4655 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4656 return false;
4657
4658 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4659 ExprResult DIE =
4660 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4661 if (DIE.isInvalid())
4662 return true;
4663
4664 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4665 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4666
4667 CXXCtorInitializer *Init;
4668 if (Indirect)
4669 Init = new (SemaRef.Context)
4670 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4671 SourceLocation(), DIE.get(), SourceLocation());
4672 else
4673 Init = new (SemaRef.Context)
4674 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4675 SourceLocation(), DIE.get(), SourceLocation());
4676 return Info.addFieldInitializer(Init);
4677 }
4678
4679 // Don't initialize incomplete or zero-length arrays.
4680 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4681 return false;
4682
4683 // Don't try to build an implicit initializer if there were semantic
4684 // errors in any of the initializers (and therefore we might be
4685 // missing some that the user actually wrote).
4686 if (Info.AnyErrorsInInits)
4687 return false;
4688
4689 CXXCtorInitializer *Init = nullptr;
4690 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4691 Indirect, Init))
4692 return true;
4693
4694 if (!Init)
4695 return false;
4696
4697 return Info.addFieldInitializer(Init);
4698}
4699
4700bool
4701Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4702 CXXCtorInitializer *Initializer) {
4703 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4703, __PRETTY_FUNCTION__))
;
4704 Constructor->setNumCtorInitializers(1);
4705 CXXCtorInitializer **initializer =
4706 new (Context) CXXCtorInitializer*[1];
4707 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4708 Constructor->setCtorInitializers(initializer);
4709
4710 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4711 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4712 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4713 }
4714
4715 DelegatingCtorDecls.push_back(Constructor);
4716
4717 DiagnoseUninitializedFields(*this, Constructor);
4718
4719 return false;
4720}
4721
4722bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4723 ArrayRef<CXXCtorInitializer *> Initializers) {
4724 if (Constructor->isDependentContext()) {
4725 // Just store the initializers as written, they will be checked during
4726 // instantiation.
4727 if (!Initializers.empty()) {
4728 Constructor->setNumCtorInitializers(Initializers.size());
4729 CXXCtorInitializer **baseOrMemberInitializers =
4730 new (Context) CXXCtorInitializer*[Initializers.size()];
4731 memcpy(baseOrMemberInitializers, Initializers.data(),
4732 Initializers.size() * sizeof(CXXCtorInitializer*));
4733 Constructor->setCtorInitializers(baseOrMemberInitializers);
4734 }
4735
4736 // Let template instantiation know whether we had errors.
4737 if (AnyErrors)
4738 Constructor->setInvalidDecl();
4739
4740 return false;
4741 }
4742
4743 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4744
4745 // We need to build the initializer AST according to order of construction
4746 // and not what user specified in the Initializers list.
4747 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4748 if (!ClassDecl)
4749 return true;
4750
4751 bool HadError = false;
4752
4753 for (unsigned i = 0; i < Initializers.size(); i++) {
4754 CXXCtorInitializer *Member = Initializers[i];
4755
4756 if (Member->isBaseInitializer())
4757 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4758 else {
4759 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4760
4761 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4762 for (auto *C : F->chain()) {
4763 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4764 if (FD && FD->getParent()->isUnion())
4765 Info.ActiveUnionMember.insert(std::make_pair(
4766 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4767 }
4768 } else if (FieldDecl *FD = Member->getMember()) {
4769 if (FD->getParent()->isUnion())
4770 Info.ActiveUnionMember.insert(std::make_pair(
4771 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4772 }
4773 }
4774 }
4775
4776 // Keep track of the direct virtual bases.
4777 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4778 for (auto &I : ClassDecl->bases()) {
4779 if (I.isVirtual())
4780 DirectVBases.insert(&I);
4781 }
4782
4783 // Push virtual bases before others.
4784 for (auto &VBase : ClassDecl->vbases()) {
4785 if (CXXCtorInitializer *Value
4786 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4787 // [class.base.init]p7, per DR257:
4788 // A mem-initializer where the mem-initializer-id names a virtual base
4789 // class is ignored during execution of a constructor of any class that
4790 // is not the most derived class.
4791 if (ClassDecl->isAbstract()) {
4792 // FIXME: Provide a fixit to remove the base specifier. This requires
4793 // tracking the location of the associated comma for a base specifier.
4794 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4795 << VBase.getType() << ClassDecl;
4796 DiagnoseAbstractType(ClassDecl);
4797 }
4798
4799 Info.AllToInit.push_back(Value);
4800 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4801 // [class.base.init]p8, per DR257:
4802 // If a given [...] base class is not named by a mem-initializer-id
4803 // [...] and the entity is not a virtual base class of an abstract
4804 // class, then [...] the entity is default-initialized.
4805 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4806 CXXCtorInitializer *CXXBaseInit;
4807 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4808 &VBase, IsInheritedVirtualBase,
4809 CXXBaseInit)) {
4810 HadError = true;
4811 continue;
4812 }
4813
4814 Info.AllToInit.push_back(CXXBaseInit);
4815 }
4816 }
4817
4818 // Non-virtual bases.
4819 for (auto &Base : ClassDecl->bases()) {
4820 // Virtuals are in the virtual base list and already constructed.
4821 if (Base.isVirtual())
4822 continue;
4823
4824 if (CXXCtorInitializer *Value
4825 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4826 Info.AllToInit.push_back(Value);
4827 } else if (!AnyErrors) {
4828 CXXCtorInitializer *CXXBaseInit;
4829 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4830 &Base, /*IsInheritedVirtualBase=*/false,
4831 CXXBaseInit)) {
4832 HadError = true;
4833 continue;
4834 }
4835
4836 Info.AllToInit.push_back(CXXBaseInit);
4837 }
4838 }
4839
4840 // Fields.
4841 for (auto *Mem : ClassDecl->decls()) {
4842 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4843 // C++ [class.bit]p2:
4844 // A declaration for a bit-field that omits the identifier declares an
4845 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4846 // initialized.
4847 if (F->isUnnamedBitfield())
4848 continue;
4849
4850 // If we're not generating the implicit copy/move constructor, then we'll
4851 // handle anonymous struct/union fields based on their individual
4852 // indirect fields.
4853 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4854 continue;
4855
4856 if (CollectFieldInitializer(*this, Info, F))
4857 HadError = true;
4858 continue;
4859 }
4860
4861 // Beyond this point, we only consider default initialization.
4862 if (Info.isImplicitCopyOrMove())
4863 continue;
4864
4865 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4866 if (F->getType()->isIncompleteArrayType()) {
4867 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4868, __PRETTY_FUNCTION__))
4868 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4868, __PRETTY_FUNCTION__))
;
4869 continue;
4870 }
4871
4872 // Initialize each field of an anonymous struct individually.
4873 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4874 HadError = true;
4875
4876 continue;
4877 }
4878 }
4879
4880 unsigned NumInitializers = Info.AllToInit.size();
4881 if (NumInitializers > 0) {
4882 Constructor->setNumCtorInitializers(NumInitializers);
4883 CXXCtorInitializer **baseOrMemberInitializers =
4884 new (Context) CXXCtorInitializer*[NumInitializers];
4885 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4886 NumInitializers * sizeof(CXXCtorInitializer*));
4887 Constructor->setCtorInitializers(baseOrMemberInitializers);
4888
4889 // Constructors implicitly reference the base and member
4890 // destructors.
4891 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4892 Constructor->getParent());
4893 }
4894
4895 return HadError;
4896}
4897
4898static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4899 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4900 const RecordDecl *RD = RT->getDecl();
4901 if (RD->isAnonymousStructOrUnion()) {
4902 for (auto *Field : RD->fields())
4903 PopulateKeysForFields(Field, IdealInits);
4904 return;
4905 }
4906 }
4907 IdealInits.push_back(Field->getCanonicalDecl());
4908}
4909
4910static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4911 return Context.getCanonicalType(BaseType).getTypePtr();
4912}
4913
4914static const void *GetKeyForMember(ASTContext &Context,
4915 CXXCtorInitializer *Member) {
4916 if (!Member->isAnyMemberInitializer())
4917 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4918
4919 return Member->getAnyMember()->getCanonicalDecl();
4920}
4921
4922static void DiagnoseBaseOrMemInitializerOrder(
4923 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4924 ArrayRef<CXXCtorInitializer *> Inits) {
4925 if (Constructor->getDeclContext()->isDependentContext())
4926 return;
4927
4928 // Don't check initializers order unless the warning is enabled at the
4929 // location of at least one initializer.
4930 bool ShouldCheckOrder = false;
4931 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4932 CXXCtorInitializer *Init = Inits[InitIndex];
4933 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4934 Init->getSourceLocation())) {
4935 ShouldCheckOrder = true;
4936 break;
4937 }
4938 }
4939 if (!ShouldCheckOrder)
4940 return;
4941
4942 // Build the list of bases and members in the order that they'll
4943 // actually be initialized. The explicit initializers should be in
4944 // this same order but may be missing things.
4945 SmallVector<const void*, 32> IdealInitKeys;
4946
4947 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4948
4949 // 1. Virtual bases.
4950 for (const auto &VBase : ClassDecl->vbases())
4951 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4952
4953 // 2. Non-virtual bases.
4954 for (const auto &Base : ClassDecl->bases()) {
4955 if (Base.isVirtual())
4956 continue;
4957 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4958 }
4959
4960 // 3. Direct fields.
4961 for (auto *Field : ClassDecl->fields()) {
4962 if (Field->isUnnamedBitfield())
4963 continue;
4964
4965 PopulateKeysForFields(Field, IdealInitKeys);
4966 }
4967
4968 unsigned NumIdealInits = IdealInitKeys.size();
4969 unsigned IdealIndex = 0;
4970
4971 CXXCtorInitializer *PrevInit = nullptr;
4972 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4973 CXXCtorInitializer *Init = Inits[InitIndex];
4974 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4975
4976 // Scan forward to try to find this initializer in the idealized
4977 // initializers list.
4978 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4979 if (InitKey == IdealInitKeys[IdealIndex])
4980 break;
4981
4982 // If we didn't find this initializer, it must be because we
4983 // scanned past it on a previous iteration. That can only
4984 // happen if we're out of order; emit a warning.
4985 if (IdealIndex == NumIdealInits && PrevInit) {
4986 Sema::SemaDiagnosticBuilder D =
4987 SemaRef.Diag(PrevInit->getSourceLocation(),
4988 diag::warn_initializer_out_of_order);
4989
4990 if (PrevInit->isAnyMemberInitializer())
4991 D << 0 << PrevInit->getAnyMember()->getDeclName();
4992 else
4993 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4994
4995 if (Init->isAnyMemberInitializer())
4996 D << 0 << Init->getAnyMember()->getDeclName();
4997 else
4998 D << 1 << Init->getTypeSourceInfo()->getType();
4999
5000 // Move back to the initializer's location in the ideal list.
5001 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5002 if (InitKey == IdealInitKeys[IdealIndex])
5003 break;
5004
5005 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5006, __PRETTY_FUNCTION__))
5006 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5006, __PRETTY_FUNCTION__))
;
5007 }
5008
5009 PrevInit = Init;
5010 }
5011}
5012
5013namespace {
5014bool CheckRedundantInit(Sema &S,
5015 CXXCtorInitializer *Init,
5016 CXXCtorInitializer *&PrevInit) {
5017 if (!PrevInit) {
5018 PrevInit = Init;
5019 return false;
5020 }
5021
5022 if (FieldDecl *Field = Init->getAnyMember())
5023 S.Diag(Init->getSourceLocation(),
5024 diag::err_multiple_mem_initialization)
5025 << Field->getDeclName()
5026 << Init->getSourceRange();
5027 else {
5028 const Type *BaseClass = Init->getBaseClass();
5029 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5029, __PRETTY_FUNCTION__))
;
5030 S.Diag(Init->getSourceLocation(),
5031 diag::err_multiple_base_initialization)
5032 << QualType(BaseClass, 0)
5033 << Init->getSourceRange();
5034 }
5035 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5036 << 0 << PrevInit->getSourceRange();
5037
5038 return true;
5039}
5040
5041typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5042typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5043
5044bool CheckRedundantUnionInit(Sema &S,
5045 CXXCtorInitializer *Init,
5046 RedundantUnionMap &Unions) {
5047 FieldDecl *Field = Init->getAnyMember();
5048 RecordDecl *Parent = Field->getParent();
5049 NamedDecl *Child = Field;
5050
5051 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5052 if (Parent->isUnion()) {
5053 UnionEntry &En = Unions[Parent];
5054 if (En.first && En.first != Child) {
5055 S.Diag(Init->getSourceLocation(),
5056 diag::err_multiple_mem_union_initialization)
5057 << Field->getDeclName()
5058 << Init->getSourceRange();
5059 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5060 << 0 << En.second->getSourceRange();
5061 return true;
5062 }
5063 if (!En.first) {
5064 En.first = Child;
5065 En.second = Init;
5066 }
5067 if (!Parent->isAnonymousStructOrUnion())
5068 return false;
5069 }
5070
5071 Child = Parent;
5072 Parent = cast<RecordDecl>(Parent->getDeclContext());
5073 }
5074
5075 return false;
5076}
5077}
5078
5079/// ActOnMemInitializers - Handle the member initializers for a constructor.
5080void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5081 SourceLocation ColonLoc,
5082 ArrayRef<CXXCtorInitializer*> MemInits,
5083 bool AnyErrors) {
5084 if (!ConstructorDecl)
5085 return;
5086
5087 AdjustDeclIfTemplate(ConstructorDecl);
5088
5089 CXXConstructorDecl *Constructor
5090 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5091
5092 if (!Constructor) {
5093 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5094 return;
5095 }
5096
5097 // Mapping for the duplicate initializers check.
5098 // For member initializers, this is keyed with a FieldDecl*.
5099 // For base initializers, this is keyed with a Type*.
5100 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5101
5102 // Mapping for the inconsistent anonymous-union initializers check.
5103 RedundantUnionMap MemberUnions;
5104
5105 bool HadError = false;
5106 for (unsigned i = 0; i < MemInits.size(); i++) {
5107 CXXCtorInitializer *Init = MemInits[i];
5108
5109 // Set the source order index.
5110 Init->setSourceOrder(i);
5111
5112 if (Init->isAnyMemberInitializer()) {
5113 const void *Key = GetKeyForMember(Context, Init);
5114 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5115 CheckRedundantUnionInit(*this, Init, MemberUnions))
5116 HadError = true;
5117 } else if (Init->isBaseInitializer()) {
5118 const void *Key = GetKeyForMember(Context, Init);
5119 if (CheckRedundantInit(*this, Init, Members[Key]))
5120 HadError = true;
5121 } else {
5122 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5122, __PRETTY_FUNCTION__))
;
5123 // This must be the only initializer
5124 if (MemInits.size() != 1) {
5125 Diag(Init->getSourceLocation(),
5126 diag::err_delegating_initializer_alone)
5127 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5128 // We will treat this as being the only initializer.
5129 }
5130 SetDelegatingInitializer(Constructor, MemInits[i]);
5131 // Return immediately as the initializer is set.
5132 return;
5133 }
5134 }
5135
5136 if (HadError)
5137 return;
5138
5139 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5140
5141 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5142
5143 DiagnoseUninitializedFields(*this, Constructor);
5144}
5145
5146void
5147Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5148 CXXRecordDecl *ClassDecl) {
5149 // Ignore dependent contexts. Also ignore unions, since their members never
5150 // have destructors implicitly called.
5151 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5152 return;
5153
5154 // FIXME: all the access-control diagnostics are positioned on the
5155 // field/base declaration. That's probably good; that said, the
5156 // user might reasonably want to know why the destructor is being
5157 // emitted, and we currently don't say.
5158
5159 // Non-static data members.
5160 for (auto *Field : ClassDecl->fields()) {
5161 if (Field->isInvalidDecl())
5162 continue;
5163
5164 // Don't destroy incomplete or zero-length arrays.
5165 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5166 continue;
5167
5168 QualType FieldType = Context.getBaseElementType(Field->getType());
5169
5170 const RecordType* RT = FieldType->getAs<RecordType>();
5171 if (!RT)
5172 continue;
5173
5174 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5175 if (FieldClassDecl->isInvalidDecl())
5176 continue;
5177 if (FieldClassDecl->hasIrrelevantDestructor())
5178 continue;
5179 // The destructor for an implicit anonymous union member is never invoked.
5180 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5181 continue;
5182
5183 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5184 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5184, __PRETTY_FUNCTION__))
;
5185 CheckDestructorAccess(Field->getLocation(), Dtor,
5186 PDiag(diag::err_access_dtor_field)
5187 << Field->getDeclName()
5188 << FieldType);
5189
5190 MarkFunctionReferenced(Location, Dtor);
5191 DiagnoseUseOfDecl(Dtor, Location);
5192 }
5193
5194 // We only potentially invoke the destructors of potentially constructed
5195 // subobjects.
5196 bool VisitVirtualBases = !ClassDecl->isAbstract();
5197
5198 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5199
5200 // Bases.
5201 for (const auto &Base : ClassDecl->bases()) {
5202 // Bases are always records in a well-formed non-dependent class.
5203 const RecordType *RT = Base.getType()->getAs<RecordType>();
5204
5205 // Remember direct virtual bases.
5206 if (Base.isVirtual()) {
5207 if (!VisitVirtualBases)
5208 continue;
5209 DirectVirtualBases.insert(RT);
5210 }
5211
5212 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5213 // If our base class is invalid, we probably can't get its dtor anyway.
5214 if (BaseClassDecl->isInvalidDecl())
5215 continue;
5216 if (BaseClassDecl->hasIrrelevantDestructor())
5217 continue;
5218
5219 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5220 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5220, __PRETTY_FUNCTION__))
;
5221
5222 // FIXME: caret should be on the start of the class name
5223 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5224 PDiag(diag::err_access_dtor_base)
5225 << Base.getType() << Base.getSourceRange(),
5226 Context.getTypeDeclType(ClassDecl));
5227
5228 MarkFunctionReferenced(Location, Dtor);
5229 DiagnoseUseOfDecl(Dtor, Location);
5230 }
5231
5232 if (!VisitVirtualBases)
5233 return;
5234
5235 // Virtual bases.
5236 for (const auto &VBase : ClassDecl->vbases()) {
5237 // Bases are always records in a well-formed non-dependent class.
5238 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5239
5240 // Ignore direct virtual bases.
5241 if (DirectVirtualBases.count(RT))
5242 continue;
5243
5244 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5245 // If our base class is invalid, we probably can't get its dtor anyway.
5246 if (BaseClassDecl->isInvalidDecl())
5247 continue;
5248 if (BaseClassDecl->hasIrrelevantDestructor())
5249 continue;
5250
5251 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5252 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5252, __PRETTY_FUNCTION__))
;
5253 if (CheckDestructorAccess(
5254 ClassDecl->getLocation(), Dtor,
5255 PDiag(diag::err_access_dtor_vbase)
5256 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5257 Context.getTypeDeclType(ClassDecl)) ==
5258 AR_accessible) {
5259 CheckDerivedToBaseConversion(
5260 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5261 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5262 SourceRange(), DeclarationName(), nullptr);
5263 }
5264
5265 MarkFunctionReferenced(Location, Dtor);
5266 DiagnoseUseOfDecl(Dtor, Location);
5267 }
5268}
5269
5270void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5271 if (!CDtorDecl)
5272 return;
5273
5274 if (CXXConstructorDecl *Constructor
5275 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5276 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5277 DiagnoseUninitializedFields(*this, Constructor);
5278 }
5279}
5280
5281bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5282 if (!getLangOpts().CPlusPlus)
5283 return false;
5284
5285 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5286 if (!RD)
5287 return false;
5288
5289 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5290 // class template specialization here, but doing so breaks a lot of code.
5291
5292 // We can't answer whether something is abstract until it has a
5293 // definition. If it's currently being defined, we'll walk back
5294 // over all the declarations when we have a full definition.
5295 const CXXRecordDecl *Def = RD->getDefinition();
5296 if (!Def || Def->isBeingDefined())
5297 return false;
5298
5299 return RD->isAbstract();
5300}
5301
5302bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5303 TypeDiagnoser &Diagnoser) {
5304 if (!isAbstractType(Loc, T))
5305 return false;
5306
5307 T = Context.getBaseElementType(T);
5308 Diagnoser.diagnose(*this, Loc, T);
5309 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5310 return true;
5311}
5312
5313void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5314 // Check if we've already emitted the list of pure virtual functions
5315 // for this class.
5316 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5317 return;
5318
5319 // If the diagnostic is suppressed, don't emit the notes. We're only
5320 // going to emit them once, so try to attach them to a diagnostic we're
5321 // actually going to show.
5322 if (Diags.isLastDiagnosticIgnored())
5323 return;
5324
5325 CXXFinalOverriderMap FinalOverriders;
5326 RD->getFinalOverriders(FinalOverriders);
5327
5328 // Keep a set of seen pure methods so we won't diagnose the same method
5329 // more than once.
5330 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5331
5332 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5333 MEnd = FinalOverriders.end();
5334 M != MEnd;
5335 ++M) {
5336 for (OverridingMethods::iterator SO = M->second.begin(),
5337 SOEnd = M->second.end();
5338 SO != SOEnd; ++SO) {
5339 // C++ [class.abstract]p4:
5340 // A class is abstract if it contains or inherits at least one
5341 // pure virtual function for which the final overrider is pure
5342 // virtual.
5343
5344 //
5345 if (SO->second.size() != 1)
5346 continue;
5347
5348 if (!SO->second.front().Method->isPure())
5349 continue;
5350
5351 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5352 continue;
5353
5354 Diag(SO->second.front().Method->getLocation(),
5355 diag::note_pure_virtual_function)
5356 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5357 }
5358 }
5359
5360 if (!PureVirtualClassDiagSet)
5361 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5362 PureVirtualClassDiagSet->insert(RD);
5363}
5364
5365namespace {
5366struct AbstractUsageInfo {
5367 Sema &S;
5368 CXXRecordDecl *Record;
5369 CanQualType AbstractType;
5370 bool Invalid;
5371
5372 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5373 : S(S), Record(Record),
5374 AbstractType(S.Context.getCanonicalType(
5375 S.Context.getTypeDeclType(Record))),
5376 Invalid(false) {}
5377
5378 void DiagnoseAbstractType() {
5379 if (Invalid) return;
5380 S.DiagnoseAbstractType(Record);
5381 Invalid = true;
5382 }
5383
5384 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5385};
5386
5387struct CheckAbstractUsage {
5388 AbstractUsageInfo &Info;
5389 const NamedDecl *Ctx;
5390
5391 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5392 : Info(Info), Ctx(Ctx) {}
5393
5394 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5395 switch (TL.getTypeLocClass()) {
5396#define ABSTRACT_TYPELOC(CLASS, PARENT)
5397#define TYPELOC(CLASS, PARENT) \
5398 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5399#include "clang/AST/TypeLocNodes.def"
5400 }
5401 }
5402
5403 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5404 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5405 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5406 if (!TL.getParam(I))
5407 continue;
5408
5409 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5410 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5411 }
5412 }
5413
5414 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5415 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5416 }
5417
5418 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5419 // Visit the type parameters from a permissive context.
5420 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5421 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5422 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5423 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5424 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5425 // TODO: other template argument types?
5426 }
5427 }
5428
5429 // Visit pointee types from a permissive context.
5430#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5431 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5432 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5433 }
5434 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5435 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5436 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5437 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5438 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5439
5440 /// Handle all the types we haven't given a more specific
5441 /// implementation for above.
5442 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5443 // Every other kind of type that we haven't called out already
5444 // that has an inner type is either (1) sugar or (2) contains that
5445 // inner type in some way as a subobject.
5446 if (TypeLoc Next = TL.getNextTypeLoc())
5447 return Visit(Next, Sel);
5448
5449 // If there's no inner type and we're in a permissive context,
5450 // don't diagnose.
5451 if (Sel == Sema::AbstractNone) return;
5452
5453 // Check whether the type matches the abstract type.
5454 QualType T = TL.getType();
5455 if (T->isArrayType()) {
5456 Sel = Sema::AbstractArrayType;
5457 T = Info.S.Context.getBaseElementType(T);
5458 }
5459 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5460 if (CT != Info.AbstractType) return;
5461
5462 // It matched; do some magic.
5463 if (Sel == Sema::AbstractArrayType) {
5464 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5465 << T << TL.getSourceRange();
5466 } else {
5467 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5468 << Sel << T << TL.getSourceRange();
5469 }
5470 Info.DiagnoseAbstractType();
5471 }
5472};
5473
5474void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5475 Sema::AbstractDiagSelID Sel) {
5476 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5477}
5478
5479}
5480
5481/// Check for invalid uses of an abstract type in a method declaration.
5482static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5483 CXXMethodDecl *MD) {
5484 // No need to do the check on definitions, which require that
5485 // the return/param types be complete.
5486 if (MD->doesThisDeclarationHaveABody())
5487 return;
5488
5489 // For safety's sake, just ignore it if we don't have type source
5490 // information. This should never happen for non-implicit methods,
5491 // but...
5492 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5493 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5494}
5495
5496/// Check for invalid uses of an abstract type within a class definition.
5497static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5498 CXXRecordDecl *RD) {
5499 for (auto *D : RD->decls()) {
5500 if (D->isImplicit()) continue;
5501
5502 // Methods and method templates.
5503 if (isa<CXXMethodDecl>(D)) {
5504 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5505 } else if (isa<FunctionTemplateDecl>(D)) {
5506 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5507 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5508
5509 // Fields and static variables.
5510 } else if (isa<FieldDecl>(D)) {
5511 FieldDecl *FD = cast<FieldDecl>(D);
5512 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5513 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5514 } else if (isa<VarDecl>(D)) {
5515 VarDecl *VD = cast<VarDecl>(D);
5516 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5517 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5518
5519 // Nested classes and class templates.
5520 } else if (isa<CXXRecordDecl>(D)) {
5521 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5522 } else if (isa<ClassTemplateDecl>(D)) {
5523 CheckAbstractClassUsage(Info,
5524 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5525 }
5526 }
5527}
5528
5529static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5530 Attr *ClassAttr = getDLLAttr(Class);
5531 if (!ClassAttr)
5532 return;
5533
5534 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5534, __PRETTY_FUNCTION__))
;
5535
5536 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5537
5538 if (TSK == TSK_ExplicitInstantiationDeclaration)
5539 // Don't go any further if this is just an explicit instantiation
5540 // declaration.
5541 return;
5542
5543 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5544 S.MarkVTableUsed(Class->getLocation(), Class, true);
5545
5546 for (Decl *Member : Class->decls()) {
5547 // Defined static variables that are members of an exported base
5548 // class must be marked export too.
5549 auto *VD = dyn_cast<VarDecl>(Member);
5550 if (VD && Member->getAttr<DLLExportAttr>() &&
5551 VD->getStorageClass() == SC_Static &&
5552 TSK == TSK_ImplicitInstantiation)
5553 S.MarkVariableReferenced(VD->getLocation(), VD);
5554
5555 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5556 if (!MD)
5557 continue;
5558
5559 if (Member->getAttr<DLLExportAttr>()) {
5560 if (MD->isUserProvided()) {
5561 // Instantiate non-default class member functions ...
5562
5563 // .. except for certain kinds of template specializations.
5564 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5565 continue;
5566
5567 S.MarkFunctionReferenced(Class->getLocation(), MD);
5568
5569 // The function will be passed to the consumer when its definition is
5570 // encountered.
5571 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5572 MD->isCopyAssignmentOperator() ||
5573 MD->isMoveAssignmentOperator()) {
5574 // Synthesize and instantiate non-trivial implicit methods, explicitly
5575 // defaulted methods, and the copy and move assignment operators. The
5576 // latter are exported even if they are trivial, because the address of
5577 // an operator can be taken and should compare equal across libraries.
5578 DiagnosticErrorTrap Trap(S.Diags);
5579 S.MarkFunctionReferenced(Class->getLocation(), MD);
5580 if (Trap.hasErrorOccurred()) {
5581 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5582 << Class << !S.getLangOpts().CPlusPlus11;
5583 break;
5584 }
5585
5586 // There is no later point when we will see the definition of this
5587 // function, so pass it to the consumer now.
5588 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5589 }
5590 }
5591 }
5592}
5593
5594static void checkForMultipleExportedDefaultConstructors(Sema &S,
5595 CXXRecordDecl *Class) {
5596 // Only the MS ABI has default constructor closures, so we don't need to do
5597 // this semantic checking anywhere else.
5598 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5599 return;
5600
5601 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5602 for (Decl *Member : Class->decls()) {
5603 // Look for exported default constructors.
5604 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5605 if (!CD || !CD->isDefaultConstructor())
5606 continue;
5607 auto *Attr = CD->getAttr<DLLExportAttr>();
5608 if (!Attr)
5609 continue;
5610
5611 // If the class is non-dependent, mark the default arguments as ODR-used so
5612 // that we can properly codegen the constructor closure.
5613 if (!Class->isDependentContext()) {
5614 for (ParmVarDecl *PD : CD->parameters()) {
5615 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5616 S.DiscardCleanupsInEvaluationContext();
5617 }
5618 }
5619
5620 if (LastExportedDefaultCtor) {
5621 S.Diag(LastExportedDefaultCtor->getLocation(),
5622 diag::err_attribute_dll_ambiguous_default_ctor)
5623 << Class;
5624 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5625 << CD->getDeclName();
5626 return;
5627 }
5628 LastExportedDefaultCtor = CD;
5629 }
5630}
5631
5632void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5633 // Mark any compiler-generated routines with the implicit code_seg attribute.
5634 for (auto *Method : Class->methods()) {
5635 if (Method->isUserProvided())
5636 continue;
5637 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5638 Method->addAttr(A);
5639 }
5640}
5641
5642/// Check class-level dllimport/dllexport attribute.
5643void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5644 Attr *ClassAttr = getDLLAttr(Class);
5645
5646 // MSVC inherits DLL attributes to partial class template specializations.
5647 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5648 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5649 if (Attr *TemplateAttr =
5650 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5651 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5652 A->setInherited(true);
5653 ClassAttr = A;
5654 }
5655 }
5656 }
5657
5658 if (!ClassAttr)
5659 return;
5660
5661 if (!Class->isExternallyVisible()) {
5662 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5663 << Class << ClassAttr;
5664 return;
5665 }
5666
5667 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5668 !ClassAttr->isInherited()) {
5669 // Diagnose dll attributes on members of class with dll attribute.
5670 for (Decl *Member : Class->decls()) {
5671 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5672 continue;
5673 InheritableAttr *MemberAttr = getDLLAttr(Member);
5674 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5675 continue;
5676
5677 Diag(MemberAttr->getLocation(),
5678 diag::err_attribute_dll_member_of_dll_class)
5679 << MemberAttr << ClassAttr;
5680 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5681 Member->setInvalidDecl();
5682 }
5683 }
5684
5685 if (Class->getDescribedClassTemplate())
5686 // Don't inherit dll attribute until the template is instantiated.
5687 return;
5688
5689 // The class is either imported or exported.
5690 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5691
5692 // Check if this was a dllimport attribute propagated from a derived class to
5693 // a base class template specialization. We don't apply these attributes to
5694 // static data members.
5695 const bool PropagatedImport =
5696 !ClassExported &&
5697 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5698
5699 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5700
5701 // Ignore explicit dllexport on explicit class template instantiation
5702 // declarations, except in MinGW mode.
5703 if (ClassExported && !ClassAttr->isInherited() &&
5704 TSK == TSK_ExplicitInstantiationDeclaration &&
5705 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5706 Class->dropAttr<DLLExportAttr>();
5707 return;
5708 }
5709
5710 // Force declaration of implicit members so they can inherit the attribute.
5711 ForceDeclarationOfImplicitMembers(Class);
5712
5713 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5714 // seem to be true in practice?
5715
5716 for (Decl *Member : Class->decls()) {
5717 VarDecl *VD = dyn_cast<VarDecl>(Member);
5718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5719
5720 // Only methods and static fields inherit the attributes.
5721 if (!VD && !MD)
5722 continue;
5723
5724 if (MD) {
5725 // Don't process deleted methods.
5726 if (MD->isDeleted())
5727 continue;
5728
5729 if (MD->isInlined()) {
5730 // MinGW does not import or export inline methods. But do it for
5731 // template instantiations.
5732 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5733 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5734 TSK != TSK_ExplicitInstantiationDeclaration &&
5735 TSK != TSK_ExplicitInstantiationDefinition)
5736 continue;
5737
5738 // MSVC versions before 2015 don't export the move assignment operators
5739 // and move constructor, so don't attempt to import/export them if
5740 // we have a definition.
5741 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5742 if ((MD->isMoveAssignmentOperator() ||
5743 (Ctor && Ctor->isMoveConstructor())) &&
5744 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5745 continue;
5746
5747 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5748 // operator is exported anyway.
5749 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5750 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5751 continue;
5752 }
5753 }
5754
5755 // Don't apply dllimport attributes to static data members of class template
5756 // instantiations when the attribute is propagated from a derived class.
5757 if (VD && PropagatedImport)
5758 continue;
5759
5760 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5761 continue;
5762
5763 if (!getDLLAttr(Member)) {
5764 InheritableAttr *NewAttr = nullptr;
5765
5766 // Do not export/import inline function when -fno-dllexport-inlines is
5767 // passed. But add attribute for later local static var check.
5768 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5769 TSK != TSK_ExplicitInstantiationDeclaration &&
5770 TSK != TSK_ExplicitInstantiationDefinition) {
5771 if (ClassExported) {
5772 NewAttr = ::new (getASTContext())
5773 DLLExportStaticLocalAttr(ClassAttr->getRange(),
5774 getASTContext(),
5775 ClassAttr->getSpellingListIndex());
5776 } else {
5777 NewAttr = ::new (getASTContext())
5778 DLLImportStaticLocalAttr(ClassAttr->getRange(),
5779 getASTContext(),
5780 ClassAttr->getSpellingListIndex());
5781 }
5782 } else {
5783 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5784 }
5785
5786 NewAttr->setInherited(true);
5787 Member->addAttr(NewAttr);
5788
5789 if (MD) {
5790 // Propagate DLLAttr to friend re-declarations of MD that have already
5791 // been constructed.
5792 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5793 FD = FD->getPreviousDecl()) {
5794 if (FD->getFriendObjectKind() == Decl::FOK_None)
5795 continue;
5796 assert(!getDLLAttr(FD) &&((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5797, __PRETTY_FUNCTION__))
5797 "friend re-decl should not already have a DLLAttr")((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5797, __PRETTY_FUNCTION__))
;
5798 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5799 NewAttr->setInherited(true);
5800 FD->addAttr(NewAttr);
5801 }
5802 }
5803 }
5804 }
5805
5806 if (ClassExported)
5807 DelayedDllExportClasses.push_back(Class);
5808}
5809
5810/// Perform propagation of DLL attributes from a derived class to a
5811/// templated base class for MS compatibility.
5812void Sema::propagateDLLAttrToBaseClassTemplate(
5813 CXXRecordDecl *Class, Attr *ClassAttr,
5814 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5815 if (getDLLAttr(
5816 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5817 // If the base class template has a DLL attribute, don't try to change it.
5818 return;
5819 }
5820
5821 auto TSK = BaseTemplateSpec->getSpecializationKind();
5822 if (!getDLLAttr(BaseTemplateSpec) &&
5823 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5824 TSK == TSK_ImplicitInstantiation)) {
5825 // The template hasn't been instantiated yet (or it has, but only as an
5826 // explicit instantiation declaration or implicit instantiation, which means
5827 // we haven't codegenned any members yet), so propagate the attribute.
5828 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5829 NewAttr->setInherited(true);
5830 BaseTemplateSpec->addAttr(NewAttr);
5831
5832 // If this was an import, mark that we propagated it from a derived class to
5833 // a base class template specialization.
5834 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5835 ImportAttr->setPropagatedToBaseTemplate();
5836
5837 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5838 // needs to be run again to work see the new attribute. Otherwise this will
5839 // get run whenever the template is instantiated.
5840 if (TSK != TSK_Undeclared)
5841 checkClassLevelDLLAttribute(BaseTemplateSpec);
5842
5843 return;
5844 }
5845
5846 if (getDLLAttr(BaseTemplateSpec)) {
5847 // The template has already been specialized or instantiated with an
5848 // attribute, explicitly or through propagation. We should not try to change
5849 // it.
5850 return;
5851 }
5852
5853 // The template was previously instantiated or explicitly specialized without
5854 // a dll attribute, It's too late for us to add an attribute, so warn that
5855 // this is unsupported.
5856 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5857 << BaseTemplateSpec->isExplicitSpecialization();
5858 Diag(ClassAttr->getLocation(), diag::note_attribute);
5859 if (BaseTemplateSpec->isExplicitSpecialization()) {
5860 Diag(BaseTemplateSpec->getLocation(),
5861 diag::note_template_class_explicit_specialization_was_here)
5862 << BaseTemplateSpec;
5863 } else {
5864 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5865 diag::note_template_class_instantiation_was_here)
5866 << BaseTemplateSpec;
5867 }
5868}
5869
5870static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5871 SourceLocation DefaultLoc) {
5872 switch (S.getSpecialMember(MD)) {
5873 case Sema::CXXDefaultConstructor:
5874 S.DefineImplicitDefaultConstructor(DefaultLoc,
5875 cast<CXXConstructorDecl>(MD));
5876 break;
5877 case Sema::CXXCopyConstructor:
5878 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5879 break;
5880 case Sema::CXXCopyAssignment:
5881 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5882 break;
5883 case Sema::CXXDestructor:
5884 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5885 break;
5886 case Sema::CXXMoveConstructor:
5887 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5888 break;
5889 case Sema::CXXMoveAssignment:
5890 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5891 break;
5892 case Sema::CXXInvalid:
5893 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5893)
;
5894 }
5895}
5896
5897/// Determine whether a type is permitted to be passed or returned in
5898/// registers, per C++ [class.temporary]p3.
5899static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5900 TargetInfo::CallingConvKind CCK) {
5901 if (D->isDependentType() || D->isInvalidDecl())
5902 return false;
5903
5904 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5905 // The PS4 platform ABI follows the behavior of Clang 3.2.
5906 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5907 return !D->hasNonTrivialDestructorForCall() &&
5908 !D->hasNonTrivialCopyConstructorForCall();
5909
5910 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5911 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5912 bool DtorIsTrivialForCall = false;
5913
5914 // If a class has at least one non-deleted, trivial copy constructor, it
5915 // is passed according to the C ABI. Otherwise, it is passed indirectly.
5916 //
5917 // Note: This permits classes with non-trivial copy or move ctors to be
5918 // passed in registers, so long as they *also* have a trivial copy ctor,
5919 // which is non-conforming.
5920 if (D->needsImplicitCopyConstructor()) {
5921 if (!D->defaultedCopyConstructorIsDeleted()) {
5922 if (D->hasTrivialCopyConstructor())
5923 CopyCtorIsTrivial = true;
5924 if (D->hasTrivialCopyConstructorForCall())
5925 CopyCtorIsTrivialForCall = true;
5926 }
5927 } else {
5928 for (const CXXConstructorDecl *CD : D->ctors()) {
5929 if (CD->isCopyConstructor() && !CD->isDeleted()) {
5930 if (CD->isTrivial())
5931 CopyCtorIsTrivial = true;
5932 if (CD->isTrivialForCall())
5933 CopyCtorIsTrivialForCall = true;
5934 }
5935 }
5936 }
5937
5938 if (D->needsImplicitDestructor()) {
5939 if (!D->defaultedDestructorIsDeleted() &&
5940 D->hasTrivialDestructorForCall())
5941 DtorIsTrivialForCall = true;
5942 } else if (const auto *DD = D->getDestructor()) {
5943 if (!DD->isDeleted() && DD->isTrivialForCall())
5944 DtorIsTrivialForCall = true;
5945 }
5946
5947 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5948 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5949 return true;
5950
5951 // If a class has a destructor, we'd really like to pass it indirectly
5952 // because it allows us to elide copies. Unfortunately, MSVC makes that
5953 // impossible for small types, which it will pass in a single register or
5954 // stack slot. Most objects with dtors are large-ish, so handle that early.
5955 // We can't call out all large objects as being indirect because there are
5956 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5957 // how we pass large POD types.
5958
5959 // Note: This permits small classes with nontrivial destructors to be
5960 // passed in registers, which is non-conforming.
5961 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5962 uint64_t TypeSize = isAArch64 ? 128 : 64;
5963
5964 if (CopyCtorIsTrivial &&
5965 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
5966 return true;
5967 return false;
5968 }
5969
5970 // Per C++ [class.temporary]p3, the relevant condition is:
5971 // each copy constructor, move constructor, and destructor of X is
5972 // either trivial or deleted, and X has at least one non-deleted copy
5973 // or move constructor
5974 bool HasNonDeletedCopyOrMove = false;
5975
5976 if (D->needsImplicitCopyConstructor() &&
5977 !D->defaultedCopyConstructorIsDeleted()) {
5978 if (!D->hasTrivialCopyConstructorForCall())
5979 return false;
5980 HasNonDeletedCopyOrMove = true;
5981 }
5982
5983 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5984 !D->defaultedMoveConstructorIsDeleted()) {
5985 if (!D->hasTrivialMoveConstructorForCall())
5986 return false;
5987 HasNonDeletedCopyOrMove = true;
5988 }
5989
5990 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5991 !D->hasTrivialDestructorForCall())
5992 return false;
5993
5994 for (const CXXMethodDecl *MD : D->methods()) {
5995 if (MD->isDeleted())
5996 continue;
5997
5998 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5999 if (CD && CD->isCopyOrMoveConstructor())
6000 HasNonDeletedCopyOrMove = true;
6001 else if (!isa<CXXDestructorDecl>(MD))
6002 continue;
6003
6004 if (!MD->isTrivialForCall())
6005 return false;
6006 }
6007
6008 return HasNonDeletedCopyOrMove;
6009}
6010
6011/// Perform semantic checks on a class definition that has been
6012/// completing, introducing implicitly-declared members, checking for
6013/// abstract types, etc.
6014void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6015 if (!Record)
6016 return;
6017
6018 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6019 AbstractUsageInfo Info(*this, Record);
6020 CheckAbstractClassUsage(Info, Record);
6021 }
6022
6023 // If this is not an aggregate type and has no user-declared constructor,
6024 // complain about any non-static data members of reference or const scalar
6025 // type, since they will never get initializers.
6026 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6027 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6028 !Record->isLambda()) {
6029 bool Complained = false;
6030 for (const auto *F : Record->fields()) {
6031 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6032 continue;
6033
6034 if (F->getType()->isReferenceType() ||
6035 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6036 if (!Complained) {
6037 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6038 << Record->getTagKind() << Record;
6039 Complained = true;
6040 }
6041
6042 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6043 << F->getType()->isReferenceType()
6044 << F->getDeclName();
6045 }
6046 }
6047 }
6048
6049 if (Record->getIdentifier()) {
6050 // C++ [class.mem]p13:
6051 // If T is the name of a class, then each of the following shall have a
6052 // name different from T:
6053 // - every member of every anonymous union that is a member of class T.
6054 //
6055 // C++ [class.mem]p14:
6056 // In addition, if class T has a user-declared constructor (12.1), every
6057 // non-static data member of class T shall have a name different from T.
6058 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6059 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6060 ++I) {
6061 NamedDecl *D = (*I)->getUnderlyingDecl();
6062 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6063 Record->hasUserDeclaredConstructor()) ||
6064 isa<IndirectFieldDecl>(D)) {
6065 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6066 << D->getDeclName();
6067 break;
6068 }
6069 }
6070 }
6071
6072 // Warn if the class has virtual methods but non-virtual public destructor.
6073 if (Record->isPolymorphic() && !Record->isDependentType()) {
6074 CXXDestructorDecl *dtor = Record->getDestructor();
6075 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6076 !Record->hasAttr<FinalAttr>())
6077 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6078 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6079 }
6080
6081 if (Record->isAbstract()) {
6082 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6083 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6084 << FA->isSpelledAsSealed();
6085 DiagnoseAbstractType(Record);
6086 }
6087 }
6088
6089 // See if trivial_abi has to be dropped.
6090 if (Record->hasAttr<TrivialABIAttr>())
6091 checkIllFormedTrivialABIStruct(*Record);
6092
6093 // Set HasTrivialSpecialMemberForCall if the record has attribute
6094 // "trivial_abi".
6095 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6096
6097 if (HasTrivialABI)
6098 Record->setHasTrivialSpecialMemberForCall();
6099
6100 bool HasMethodWithOverrideControl = false,
6101 HasOverridingMethodWithoutOverrideControl = false;
6102 if (!Record->isDependentType()) {
6103 for (auto *M : Record->methods()) {
6104 // See if a method overloads virtual methods in a base
6105 // class without overriding any.
6106 if (!M->isStatic())
6107 DiagnoseHiddenVirtualMethods(M);
6108 if (M->hasAttr<OverrideAttr>())
6109 HasMethodWithOverrideControl = true;
6110 else if (M->size_overridden_methods() > 0)
6111 HasOverridingMethodWithoutOverrideControl = true;
6112 // Check whether the explicitly-defaulted special members are valid.
6113 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6114 CheckExplicitlyDefaultedSpecialMember(M);
6115
6116 // For an explicitly defaulted or deleted special member, we defer
6117 // determining triviality until the class is complete. That time is now!
6118 CXXSpecialMember CSM = getSpecialMember(M);
6119 if (!M->isImplicit() && !M->isUserProvided()) {
6120 if (CSM != CXXInvalid) {
6121 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6122 // Inform the class that we've finished declaring this member.
6123 Record->finishedDefaultedOrDeletedMember(M);
6124 M->setTrivialForCall(
6125 HasTrivialABI ||
6126 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6127 Record->setTrivialForCallFlags(M);
6128 }
6129 }
6130
6131 // Set triviality for the purpose of calls if this is a user-provided
6132 // copy/move constructor or destructor.
6133 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6134 CSM == CXXDestructor) && M->isUserProvided()) {
6135 M->setTrivialForCall(HasTrivialABI);
6136 Record->setTrivialForCallFlags(M);
6137 }
6138
6139 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6140 M->hasAttr<DLLExportAttr>()) {
6141 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6142 M->isTrivial() &&
6143 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6144 CSM == CXXDestructor))
6145 M->dropAttr<DLLExportAttr>();
6146
6147 if (M->hasAttr<DLLExportAttr>()) {
6148 DefineImplicitSpecialMember(*this, M, M->getLocation());
6149 ActOnFinishInlineFunctionDef(M);
6150 }
6151 }
6152 }
6153 }
6154
6155 if (HasMethodWithOverrideControl &&
6156 HasOverridingMethodWithoutOverrideControl) {
6157 // At least one method has the 'override' control declared.
6158 // Diagnose all other overridden methods which do not have 'override' specified on them.
6159 for (auto *M : Record->methods())
6160 DiagnoseAbsenceOfOverrideControl(M);
6161 }
6162
6163 // ms_struct is a request to use the same ABI rules as MSVC. Check
6164 // whether this class uses any C++ features that are implemented
6165 // completely differently in MSVC, and if so, emit a diagnostic.
6166 // That diagnostic defaults to an error, but we allow projects to
6167 // map it down to a warning (or ignore it). It's a fairly common
6168 // practice among users of the ms_struct pragma to mass-annotate
6169 // headers, sweeping up a bunch of types that the project doesn't
6170 // really rely on MSVC-compatible layout for. We must therefore
6171 // support "ms_struct except for C++ stuff" as a secondary ABI.
6172 if (Record->isMsStruct(Context) &&
6173 (Record->isPolymorphic() || Record->getNumBases())) {
6174 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6175 }
6176
6177 checkClassLevelDLLAttribute(Record);
6178 checkClassLevelCodeSegAttribute(Record);
6179
6180 bool ClangABICompat4 =
6181 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6182 TargetInfo::CallingConvKind CCK =
6183 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6184 bool CanPass = canPassInRegisters(*this, Record, CCK);
6185
6186 // Do not change ArgPassingRestrictions if it has already been set to
6187 // APK_CanNeverPassInRegs.
6188 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6189 Record->setArgPassingRestrictions(CanPass
6190 ? RecordDecl::APK_CanPassInRegs
6191 : RecordDecl::APK_CannotPassInRegs);
6192
6193 // If canPassInRegisters returns true despite the record having a non-trivial
6194 // destructor, the record is destructed in the callee. This happens only when
6195 // the record or one of its subobjects has a field annotated with trivial_abi
6196 // or a field qualified with ObjC __strong/__weak.
6197 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6198 Record->setParamDestroyedInCallee(true);
6199 else if (Record->hasNonTrivialDestructor())
6200 Record->setParamDestroyedInCallee(CanPass);
6201
6202 if (getLangOpts().ForceEmitVTables) {
6203 // If we want to emit all the vtables, we need to mark it as used. This
6204 // is especially required for cases like vtable assumption loads.
6205 MarkVTableUsed(Record->getInnerLocStart(), Record);
6206 }
6207}
6208
6209/// Look up the special member function that would be called by a special
6210/// member function for a subobject of class type.
6211///
6212/// \param Class The class type of the subobject.
6213/// \param CSM The kind of special member function.
6214/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6215/// \param ConstRHS True if this is a copy operation with a const object
6216/// on its RHS, that is, if the argument to the outer special member
6217/// function is 'const' and this is not a field marked 'mutable'.
6218static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6219 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6220 unsigned FieldQuals, bool ConstRHS) {
6221 unsigned LHSQuals = 0;
6222 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6223 LHSQuals = FieldQuals;
6224
6225 unsigned RHSQuals = FieldQuals;
6226 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6227 RHSQuals = 0;
6228 else if (ConstRHS)
6229 RHSQuals |= Qualifiers::Const;
6230
6231 return S.LookupSpecialMember(Class, CSM,
6232 RHSQuals & Qualifiers::Const,
6233 RHSQuals & Qualifiers::Volatile,
6234 false,
6235 LHSQuals & Qualifiers::Const,
6236 LHSQuals & Qualifiers::Volatile);
6237}
6238
6239class Sema::InheritedConstructorInfo {
6240 Sema &S;
6241 SourceLocation UseLoc;
6242
6243 /// A mapping from the base classes through which the constructor was
6244 /// inherited to the using shadow declaration in that base class (or a null
6245 /// pointer if the constructor was declared in that base class).
6246 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6247 InheritedFromBases;
6248
6249public:
6250 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6251 ConstructorUsingShadowDecl *Shadow)
6252 : S(S), UseLoc(UseLoc) {
6253 bool DiagnosedMultipleConstructedBases = false;
6254 CXXRecordDecl *ConstructedBase = nullptr;
6255 UsingDecl *ConstructedBaseUsing = nullptr;
6256
6257 // Find the set of such base class subobjects and check that there's a
6258 // unique constructed subobject.
6259 for (auto *D : Shadow->redecls()) {
6260 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6261 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6262 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6263
6264 InheritedFromBases.insert(
6265 std::make_pair(DNominatedBase->getCanonicalDecl(),
6266 DShadow->getNominatedBaseClassShadowDecl()));
6267 if (DShadow->constructsVirtualBase())
6268 InheritedFromBases.insert(
6269 std::make_pair(DConstructedBase->getCanonicalDecl(),
6270 DShadow->getConstructedBaseClassShadowDecl()));
6271 else
6272 assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void>
(0) : __assert_fail ("DNominatedBase == DConstructedBase", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6272, __PRETTY_FUNCTION__))
;
6273
6274 // [class.inhctor.init]p2:
6275 // If the constructor was inherited from multiple base class subobjects
6276 // of type B, the program is ill-formed.
6277 if (!ConstructedBase) {
6278 ConstructedBase = DConstructedBase;
6279 ConstructedBaseUsing = D->getUsingDecl();
6280 } else if (ConstructedBase != DConstructedBase &&
6281 !Shadow->isInvalidDecl()) {
6282 if (!DiagnosedMultipleConstructedBases) {
6283 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6284 << Shadow->getTargetDecl();
6285 S.Diag(ConstructedBaseUsing->getLocation(),
6286 diag::note_ambiguous_inherited_constructor_using)
6287 << ConstructedBase;
6288 DiagnosedMultipleConstructedBases = true;
6289 }
6290 S.Diag(D->getUsingDecl()->getLocation(),
6291 diag::note_ambiguous_inherited_constructor_using)
6292 << DConstructedBase;
6293 }
6294 }
6295
6296 if (DiagnosedMultipleConstructedBases)
6297 Shadow->setInvalidDecl();
6298 }
6299
6300 /// Find the constructor to use for inherited construction of a base class,
6301 /// and whether that base class constructor inherits the constructor from a
6302 /// virtual base class (in which case it won't actually invoke it).
6303 std::pair<CXXConstructorDecl *, bool>
6304 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6305 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6306 if (It == InheritedFromBases.end())
6307 return std::make_pair(nullptr, false);
6308
6309 // This is an intermediary class.
6310 if (It->second)
6311 return std::make_pair(
6312 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6313 It->second->constructsVirtualBase());
6314
6315 // This is the base class from which the constructor was inherited.
6316 return std::make_pair(Ctor, false);
6317 }
6318};
6319
6320/// Is the special member function which would be selected to perform the
6321/// specified operation on the specified class type a constexpr constructor?
6322static bool
6323specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6324 Sema::CXXSpecialMember CSM, unsigned Quals,
6325 bool ConstRHS,
6326 CXXConstructorDecl *InheritedCtor = nullptr,
6327 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6328 // If we're inheriting a constructor, see if we need to call it for this base
6329 // class.
6330 if (InheritedCtor) {
6331 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6331, __PRETTY_FUNCTION__))
;
6332 auto BaseCtor =
6333 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6334 if (BaseCtor)
6335 return BaseCtor->isConstexpr();
6336 }
6337
6338 if (CSM == Sema::CXXDefaultConstructor)
6339 return ClassDecl->hasConstexprDefaultConstructor();
6340
6341 Sema::SpecialMemberOverloadResult SMOR =
6342 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6343 if (!SMOR.getMethod())
6344 // A constructor we wouldn't select can't be "involved in initializing"
6345 // anything.
6346 return true;
6347 return SMOR.getMethod()->isConstexpr();
6348}
6349
6350/// Determine whether the specified special member function would be constexpr
6351/// if it were implicitly defined.
6352static bool defaultedSpecialMemberIsConstexpr(
6353 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6354 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6355 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6356 if (!S.getLangOpts().CPlusPlus11)
6357 return false;
6358
6359 // C++11 [dcl.constexpr]p4:
6360 // In the definition of a constexpr constructor [...]
6361 bool Ctor = true;
6362 switch (CSM) {
6363 case Sema::CXXDefaultConstructor:
6364 if (Inherited)
6365 break;
6366 // Since default constructor lookup is essentially trivial (and cannot
6367 // involve, for instance, template instantiation), we compute whether a
6368 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6369 //
6370 // This is important for performance; we need to know whether the default
6371 // constructor is constexpr to determine whether the type is a literal type.
6372 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6373
6374 case Sema::CXXCopyConstructor:
6375 case Sema::CXXMoveConstructor:
6376 // For copy or move constructors, we need to perform overload resolution.
6377 break;
6378
6379 case Sema::CXXCopyAssignment:
6380 case Sema::CXXMoveAssignment:
6381 if (!S.getLangOpts().CPlusPlus14)
6382 return false;
6383 // In C++1y, we need to perform overload resolution.
6384 Ctor = false;
6385 break;
6386
6387 case Sema::CXXDestructor:
6388 case Sema::CXXInvalid:
6389 return false;
6390 }
6391
6392 // -- if the class is a non-empty union, or for each non-empty anonymous
6393 // union member of a non-union class, exactly one non-static data member
6394 // shall be initialized; [DR1359]
6395 //
6396 // If we squint, this is guaranteed, since exactly one non-static data member
6397 // will be initialized (if the constructor isn't deleted), we just don't know
6398 // which one.
6399 if (Ctor && ClassDecl->isUnion())
6400 return CSM == Sema::CXXDefaultConstructor
6401 ? ClassDecl->hasInClassInitializer() ||
6402 !ClassDecl->hasVariantMembers()
6403 : true;
6404
6405 // -- the class shall not have any virtual base classes;
6406 if (Ctor && ClassDecl->getNumVBases())
6407 return false;
6408
6409 // C++1y [class.copy]p26:
6410 // -- [the class] is a literal type, and
6411 if (!Ctor && !ClassDecl->isLiteral())
6412 return false;
6413
6414 // -- every constructor involved in initializing [...] base class
6415 // sub-objects shall be a constexpr constructor;
6416 // -- the assignment operator selected to copy/move each direct base
6417 // class is a constexpr function, and
6418 for (const auto &B : ClassDecl->bases()) {
6419 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6420 if (!BaseType) continue;
6421
6422 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6423 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6424 InheritedCtor, Inherited))
6425 return false;
6426 }
6427
6428 // -- every constructor involved in initializing non-static data members
6429 // [...] shall be a constexpr constructor;
6430 // -- every non-static data member and base class sub-object shall be
6431 // initialized
6432 // -- for each non-static data member of X that is of class type (or array
6433 // thereof), the assignment operator selected to copy/move that member is
6434 // a constexpr function
6435 for (const auto *F : ClassDecl->fields()) {
6436 if (F->isInvalidDecl())
6437 continue;
6438 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6439 continue;
6440 QualType BaseType = S.Context.getBaseElementType(F->getType());
6441 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6442 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6443 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6444 BaseType.getCVRQualifiers(),
6445 ConstArg && !F->isMutable()))
6446 return false;
6447 } else if (CSM == Sema::CXXDefaultConstructor) {
6448 return false;
6449 }
6450 }
6451
6452 // All OK, it's constexpr!
6453 return true;
6454}
6455
6456static Sema::ImplicitExceptionSpecification
6457ComputeDefaultedSpecialMemberExceptionSpec(
6458 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6459 Sema::InheritedConstructorInfo *ICI);
6460
6461static Sema::ImplicitExceptionSpecification
6462computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6463 auto CSM = S.getSpecialMember(MD);
6464 if (CSM != Sema::CXXInvalid)
6465 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6466
6467 auto *CD = cast<CXXConstructorDecl>(MD);
6468 assert(CD->getInheritedConstructor() &&((CD->getInheritedConstructor() && "only special members have implicit exception specs"
) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6469, __PRETTY_FUNCTION__))
6469 "only special members have implicit exception specs")((CD->getInheritedConstructor() && "only special members have implicit exception specs"
) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6469, __PRETTY_FUNCTION__))
;
6470 Sema::InheritedConstructorInfo ICI(
6471 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6472 return ComputeDefaultedSpecialMemberExceptionSpec(
6473 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6474}
6475
6476static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6477 CXXMethodDecl *MD) {
6478 FunctionProtoType::ExtProtoInfo EPI;
6479
6480 // Build an exception specification pointing back at this member.
6481 EPI.ExceptionSpec.Type = EST_Unevaluated;
6482 EPI.ExceptionSpec.SourceDecl = MD;
6483
6484 // Set the calling convention to the default for C++ instance methods.
6485 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6486 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6487 /*IsCXXMethod=*/true));
6488 return EPI;
6489}
6490
6491void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6492 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6493 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6494 return;
6495
6496 // Evaluate the exception specification.
6497 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6498 auto ESI = IES.getExceptionSpec();
6499
6500 // Update the type of the special member to use it.
6501 UpdateExceptionSpec(MD, ESI);
6502
6503 // A user-provided destructor can be defined outside the class. When that
6504 // happens, be sure to update the exception specification on both
6505 // declarations.
6506 const FunctionProtoType *CanonicalFPT =
6507 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6508 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6509 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6510}
6511
6512void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6513 CXXRecordDecl *RD = MD->getParent();
6514 CXXSpecialMember CSM = getSpecialMember(MD);
6515
6516 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6517, __PRETTY_FUNCTION__))
6517 "not an explicitly-defaulted special member")((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6517, __PRETTY_FUNCTION__))
;
6518
6519 // Whether this was the first-declared instance of the constructor.
6520 // This affects whether we implicitly add an exception spec and constexpr.
6521 bool First = MD == MD->getCanonicalDecl();
6522
6523 bool HadError = false;
6524
6525 // C++11 [dcl.fct.def.default]p1:
6526 // A function that is explicitly defaulted shall
6527 // -- be a special member function (checked elsewhere),
6528 // -- have the same type (except for ref-qualifiers, and except that a
6529 // copy operation can take a non-const reference) as an implicit
6530 // declaration, and
6531 // -- not have default arguments.
6532 // C++2a changes the second bullet to instead delete the function if it's
6533 // defaulted on its first declaration, unless it's "an assignment operator,
6534 // and its return type differs or its parameter type is not a reference".
6535 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6536 bool ShouldDeleteForTypeMismatch = false;
6537 unsigned ExpectedParams = 1;
6538 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6539 ExpectedParams = 0;
6540 if (MD->getNumParams() != ExpectedParams) {
6541 // This checks for default arguments: a copy or move constructor with a
6542 // default argument is classified as a default constructor, and assignment
6543 // operations and destructors can't have default arguments.
6544 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6545 << CSM << MD->getSourceRange();
6546 HadError = true;
6547 } else if (MD->isVariadic()) {
6548 if (DeleteOnTypeMismatch)
6549 ShouldDeleteForTypeMismatch = true;
6550 else {
6551 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6552 << CSM << MD->getSourceRange();
6553 HadError = true;
6554 }
6555 }
6556
6557 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6558
6559 bool CanHaveConstParam = false;
6560 if (CSM == CXXCopyConstructor)
6561 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6562 else if (CSM == CXXCopyAssignment)
6563 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6564
6565 QualType ReturnType = Context.VoidTy;
6566 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6567 // Check for return type matching.
6568 ReturnType = Type->getReturnType();
6569
6570 QualType DeclType = Context.getTypeDeclType(RD);
6571 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6572 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6573
6574 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6575 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6576 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6577 HadError = true;
6578 }
6579
6580 // A defaulted special member cannot have cv-qualifiers.
6581 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6582 if (DeleteOnTypeMismatch)
6583 ShouldDeleteForTypeMismatch = true;
6584 else {
6585 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6586 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6587 HadError = true;
6588 }
6589 }
6590 }
6591
6592 // Check for parameter type matching.
6593 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6594 bool HasConstParam = false;
6595 if (ExpectedParams && ArgType->isReferenceType()) {
6596 // Argument must be reference to possibly-const T.
6597 QualType ReferentType = ArgType->getPointeeType();
6598 HasConstParam = ReferentType.isConstQualified();
6599
6600 if (ReferentType.isVolatileQualified()) {
6601 if (DeleteOnTypeMismatch)
6602 ShouldDeleteForTypeMismatch = true;
6603 else {
6604 Diag(MD->getLocation(),
6605 diag::err_defaulted_special_member_volatile_param) << CSM;
6606 HadError = true;
6607 }
6608 }
6609
6610 if (HasConstParam && !CanHaveConstParam) {
6611 if (DeleteOnTypeMismatch)
6612 ShouldDeleteForTypeMismatch = true;
6613 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6614 Diag(MD->getLocation(),
6615 diag::err_defaulted_special_member_copy_const_param)
6616 << (CSM == CXXCopyAssignment);
6617 // FIXME: Explain why this special member can't be const.
6618 HadError = true;
6619 } else {
6620 Diag(MD->getLocation(),
6621 diag::err_defaulted_special_member_move_const_param)
6622 << (CSM == CXXMoveAssignment);
6623 HadError = true;
6624 }
6625 }
6626 } else if (ExpectedParams) {
6627 // A copy assignment operator can take its argument by value, but a
6628 // defaulted one cannot.
6629 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")((CSM == CXXCopyAssignment && "unexpected non-ref argument"
) ? static_cast<void> (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6629, __PRETTY_FUNCTION__))
;
6630 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6631 HadError = true;
6632 }
6633
6634 // C++11 [dcl.fct.def.default]p2:
6635 // An explicitly-defaulted function may be declared constexpr only if it
6636 // would have been implicitly declared as constexpr,
6637 // Do not apply this rule to members of class templates, since core issue 1358
6638 // makes such functions always instantiate to constexpr functions. For
6639 // functions which cannot be constexpr (for non-constructors in C++11 and for
6640 // destructors in C++1y), this is checked elsewhere.
6641 //
6642 // FIXME: This should not apply if the member is deleted.
6643 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6644 HasConstParam);
6645 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6646 : isa<CXXConstructorDecl>(MD)) &&
6647 MD->isConstexpr() && !Constexpr &&
6648 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6649 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6650 // FIXME: Explain why the special member can't be constexpr.
6651 HadError = true;
6652 }
6653
6654 if (First) {
6655 // C++2a [dcl.fct.def.default]p3:
6656 // If a function is explicitly defaulted on its first declaration, it is
6657 // implicitly considered to be constexpr if the implicit declaration
6658 // would be.
6659 MD->setConstexpr(Constexpr);
6660
6661 if (!Type->hasExceptionSpec()) {
6662 // C++2a [except.spec]p3:
6663 // If a declaration of a function does not have a noexcept-specifier
6664 // [and] is defaulted on its first declaration, [...] the exception
6665 // specification is as specified below
6666 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6667 EPI.ExceptionSpec.Type = EST_Unevaluated;
6668 EPI.ExceptionSpec.SourceDecl = MD;
6669 MD->setType(Context.getFunctionType(ReturnType,
6670 llvm::makeArrayRef(&ArgType,
6671 ExpectedParams),
6672 EPI));
6673 }
6674 }
6675
6676 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6677 if (First) {
6678 SetDeclDeleted(MD, MD->getLocation());
6679 if (!inTemplateInstantiation() && !HadError) {
6680 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6681 if (ShouldDeleteForTypeMismatch) {
6682 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6683 } else {
6684 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6685 }
6686 }
6687 if (ShouldDeleteForTypeMismatch && !HadError) {
6688 Diag(MD->getLocation(),
6689 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6690 }
6691 } else {
6692 // C++11 [dcl.fct.def.default]p4:
6693 // [For a] user-provided explicitly-defaulted function [...] if such a
6694 // function is implicitly defined as deleted, the program is ill-formed.
6695 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6696 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")((!ShouldDeleteForTypeMismatch && "deleted non-first decl"
) ? static_cast<void> (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6696, __PRETTY_FUNCTION__))
;
6697 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6698 HadError = true;
6699 }
6700 }
6701
6702 if (HadError)
6703 MD->setInvalidDecl();
6704}
6705
6706void Sema::CheckDelayedMemberExceptionSpecs() {
6707 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6708 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6709
6710 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6711 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6712
6713 // Perform any deferred checking of exception specifications for virtual
6714 // destructors.
6715 for (auto &Check : Overriding)
6716 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6717
6718 // Perform any deferred checking of exception specifications for befriended
6719 // special members.
6720 for (auto &Check : Equivalent)
6721 CheckEquivalentExceptionSpec(Check.second, Check.first);
6722}
6723
6724namespace {
6725/// CRTP base class for visiting operations performed by a special member
6726/// function (or inherited constructor).
6727template<typename Derived>
6728struct SpecialMemberVisitor {
6729 Sema &S;
6730 CXXMethodDecl *MD;
6731 Sema::CXXSpecialMember CSM;
6732 Sema::InheritedConstructorInfo *ICI;
6733
6734 // Properties of the special member, computed for convenience.
6735 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6736
6737 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6738 Sema::InheritedConstructorInfo *ICI)
6739 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6740 switch (CSM) {
6741 case Sema::CXXDefaultConstructor:
6742 case Sema::CXXCopyConstructor:
6743 case Sema::CXXMoveConstructor:
6744 IsConstructor = true;
6745 break;
6746 case Sema::CXXCopyAssignment:
6747 case Sema::CXXMoveAssignment:
6748 IsAssignment = true;
6749 break;
6750 case Sema::CXXDestructor:
6751 break;
6752 case Sema::CXXInvalid:
6753 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6753)
;
6754 }
6755
6756 if (MD->getNumParams()) {
6757 if (const ReferenceType *RT =
6758 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6759 ConstArg = RT->getPointeeType().isConstQualified();
6760 }
6761 }
6762
6763 Derived &getDerived() { return static_cast<Derived&>(*this); }
6764
6765 /// Is this a "move" special member?
6766 bool isMove() const {
6767 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6768 }
6769
6770 /// Look up the corresponding special member in the given class.
6771 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6772 unsigned Quals, bool IsMutable) {
6773 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6774 ConstArg && !IsMutable);
6775 }
6776
6777 /// Look up the constructor for the specified base class to see if it's
6778 /// overridden due to this being an inherited constructor.
6779 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6780 if (!ICI)
6781 return {};
6782 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6782, __PRETTY_FUNCTION__))
;
6783 auto *BaseCtor =
6784 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6785 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6786 return MD;
6787 return {};
6788 }
6789
6790 /// A base or member subobject.
6791 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6792
6793 /// Get the location to use for a subobject in diagnostics.
6794 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6795 // FIXME: For an indirect virtual base, the direct base leading to
6796 // the indirect virtual base would be a more useful choice.
6797 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6798 return B->getBaseTypeLoc();
6799 else
6800 return Subobj.get<FieldDecl*>()->getLocation();
6801 }
6802
6803 enum BasesToVisit {
6804 /// Visit all non-virtual (direct) bases.
6805 VisitNonVirtualBases,
6806 /// Visit all direct bases, virtual or not.
6807 VisitDirectBases,
6808 /// Visit all non-virtual bases, and all virtual bases if the class
6809 /// is not abstract.
6810 VisitPotentiallyConstructedBases,
6811 /// Visit all direct or virtual bases.
6812 VisitAllBases
6813 };
6814
6815 // Visit the bases and members of the class.
6816 bool visit(BasesToVisit Bases) {
6817 CXXRecordDecl *RD = MD->getParent();
6818
6819 if (Bases == VisitPotentiallyConstructedBases)
6820 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6821
6822 for (auto &B : RD->bases())
6823 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6824 getDerived().visitBase(&B))
6825 return true;
6826
6827 if (Bases == VisitAllBases)
6828 for (auto &B : RD->vbases())
6829 if (getDerived().visitBase(&B))
6830 return true;
6831
6832 for (auto *F : RD->fields())
6833 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6834 getDerived().visitField(F))
6835 return true;
6836
6837 return false;
6838 }
6839};
6840}
6841
6842namespace {
6843struct SpecialMemberDeletionInfo
6844 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6845 bool Diagnose;
6846
6847 SourceLocation Loc;
6848
6849 bool AllFieldsAreConst;
6850
6851 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6852 Sema::CXXSpecialMember CSM,
6853 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6854 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6855 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6856
6857 bool inUnion() const { return MD->getParent()->isUnion(); }
6858
6859 Sema::CXXSpecialMember getEffectiveCSM() {
6860 return ICI ? Sema::CXXInvalid : CSM;
6861 }
6862
6863 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6864
6865 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6866 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6867
6868 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6869 bool shouldDeleteForField(FieldDecl *FD);
6870 bool shouldDeleteForAllConstMembers();
6871
6872 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6873 unsigned Quals);
6874 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6875 Sema::SpecialMemberOverloadResult SMOR,
6876 bool IsDtorCallInCtor);
6877
6878 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6879};
6880}
6881
6882/// Is the given special member inaccessible when used on the given
6883/// sub-object.
6884bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6885 CXXMethodDecl *target) {
6886 /// If we're operating on a base class, the object type is the
6887 /// type of this special member.
6888 QualType objectTy;
6889 AccessSpecifier access = target->getAccess();
6890 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6891 objectTy = S.Context.getTypeDeclType(MD->getParent());
6892 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6893
6894 // If we're operating on a field, the object type is the type of the field.
6895 } else {
6896 objectTy = S.Context.getTypeDeclType(target->getParent());
6897 }
6898
6899 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6900}
6901
6902/// Check whether we should delete a special member due to the implicit
6903/// definition containing a call to a special member of a subobject.
6904bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6905 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6906 bool IsDtorCallInCtor) {
6907 CXXMethodDecl *Decl = SMOR.getMethod();
6908 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6909
6910 int DiagKind = -1;
6911
6912 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6913 DiagKind = !Decl ? 0 : 1;
6914 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6915 DiagKind = 2;
6916 else if (!isAccessible(Subobj, Decl))
6917 DiagKind = 3;
6918 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6919 !Decl->isTrivial()) {
6920 // A member of a union must have a trivial corresponding special member.
6921 // As a weird special case, a destructor call from a union's constructor
6922 // must be accessible and non-deleted, but need not be trivial. Such a
6923 // destructor is never actually called, but is semantically checked as
6924 // if it were.
6925 DiagKind = 4;
6926 }
6927
6928 if (DiagKind == -1)
6929 return false;
6930
6931 if (Diagnose) {
6932 if (Field) {
6933 S.Diag(Field->getLocation(),
6934 diag::note_deleted_special_member_class_subobject)
6935 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6936 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6937 } else {
6938 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6939 S.Diag(Base->getBeginLoc(),
6940 diag::note_deleted_special_member_class_subobject)
6941 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6942 << Base->getType() << DiagKind << IsDtorCallInCtor
6943 << /*IsObjCPtr*/false;
6944 }
6945
6946 if (DiagKind == 1)
6947 S.NoteDeletedFunction(Decl);
6948 // FIXME: Explain inaccessibility if DiagKind == 3.
6949 }
6950
6951 return true;
6952}
6953
6954/// Check whether we should delete a special member function due to having a
6955/// direct or virtual base class or non-static data member of class type M.
6956bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6957 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6958 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6959 bool IsMutable = Field && Field->isMutable();
6960
6961 // C++11 [class.ctor]p5:
6962 // -- any direct or virtual base class, or non-static data member with no
6963 // brace-or-equal-initializer, has class type M (or array thereof) and
6964 // either M has no default constructor or overload resolution as applied
6965 // to M's default constructor results in an ambiguity or in a function
6966 // that is deleted or inaccessible
6967 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6968 // -- a direct or virtual base class B that cannot be copied/moved because
6969 // overload resolution, as applied to B's corresponding special member,
6970 // results in an ambiguity or a function that is deleted or inaccessible
6971 // from the defaulted special member
6972 // C++11 [class.dtor]p5:
6973 // -- any direct or virtual base class [...] has a type with a destructor
6974 // that is deleted or inaccessible
6975 if (!(CSM == Sema::CXXDefaultConstructor &&
6976 Field && Field->hasInClassInitializer()) &&
6977 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6978 false))
6979 return true;
6980
6981 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6982 // -- any direct or virtual base class or non-static data member has a
6983 // type with a destructor that is deleted or inaccessible
6984 if (IsConstructor) {
6985 Sema::SpecialMemberOverloadResult SMOR =
6986 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6987 false, false, false, false, false);
6988 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6989 return true;
6990 }
6991
6992 return false;
6993}
6994
6995bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
6996 FieldDecl *FD, QualType FieldType) {
6997 // The defaulted special functions are defined as deleted if this is a variant
6998 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
6999 // type under ARC.
7000 if (!FieldType.hasNonTrivialObjCLifetime())
7001 return false;
7002
7003 // Don't make the defaulted default constructor defined as deleted if the
7004 // member has an in-class initializer.
7005 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7006 return false;
7007
7008 if (Diagnose) {
7009 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7010 S.Diag(FD->getLocation(),
7011 diag::note_deleted_special_member_class_subobject)
7012 << getEffectiveCSM() << ParentClass << /*IsField*/true
7013 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7014 }
7015
7016 return true;
7017}
7018
7019/// Check whether we should delete a special member function due to the class
7020/// having a particular direct or virtual base class.
7021bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7022 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7023 // If program is correct, BaseClass cannot be null, but if it is, the error
7024 // must be reported elsewhere.
7025 if (!BaseClass)
7026 return false;
7027 // If we have an inheriting constructor, check whether we're calling an
7028 // inherited constructor instead of a default constructor.
7029 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7030 if (auto *BaseCtor = SMOR.getMethod()) {
7031 // Note that we do not check access along this path; other than that,
7032 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7033 // FIXME: Check that the base has a usable destructor! Sink this into
7034 // shouldDeleteForClassSubobject.
7035 if (BaseCtor->isDeleted() && Diagnose) {
7036 S.Diag(Base->getBeginLoc(),
7037 diag::note_deleted_special_member_class_subobject)
7038 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7039 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7040 << /*IsObjCPtr*/false;
7041 S.NoteDeletedFunction(BaseCtor);
7042 }
7043 return BaseCtor->isDeleted();
7044 }
7045 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7046}
7047
7048/// Check whether we should delete a special member function due to the class
7049/// having a particular non-static data member.
7050bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7051 QualType FieldType = S.Context.getBaseElementType(FD->getType());
7052 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7053
7054 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7055 return true;
7056
7057 if (CSM == Sema::CXXDefaultConstructor) {
7058 // For a default constructor, all references must be initialized in-class
7059 // and, if a union, it must have a non-const member.
7060 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7061 if (Diagnose)
7062 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7063 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7064 return true;
7065 }
7066 // C++11 [class.ctor]p5: any non-variant non-static data member of
7067 // const-qualified type (or array thereof) with no
7068 // brace-or-equal-initializer does not have a user-provided default
7069 // constructor.
7070 if (!inUnion() && FieldType.isConstQualified() &&
7071 !FD->hasInClassInitializer() &&
7072 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7073 if (Diagnose)
7074 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7075 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7076 return true;
7077 }
7078
7079 if (inUnion() && !FieldType.isConstQualified())
7080 AllFieldsAreConst = false;
7081 } else if (CSM == Sema::CXXCopyConstructor) {
7082 // For a copy constructor, data members must not be of rvalue reference
7083 // type.
7084 if (FieldType->isRValueReferenceType()) {
7085 if (Diagnose)
7086 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7087 << MD->getParent() << FD << FieldType;
7088 return true;
7089 }
7090 } else if (IsAssignment) {
7091 // For an assignment operator, data members must not be of reference type.
7092 if (FieldType->isReferenceType()) {
7093 if (Diagnose)
7094 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7095 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7096 return true;
7097 }
7098 if (!FieldRecord && FieldType.isConstQualified()) {
7099 // C++11 [class.copy]p23:
7100 // -- a non-static data member of const non-class type (or array thereof)
7101 if (Diagnose)
7102 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7103 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7104 return true;
7105 }
7106 }
7107
7108 if (FieldRecord) {
7109 // Some additional restrictions exist on the variant members.
7110 if (!inUnion() && FieldRecord->isUnion() &&
7111 FieldRecord->isAnonymousStructOrUnion()) {
7112 bool AllVariantFieldsAreConst = true;
7113
7114 // FIXME: Handle anonymous unions declared within anonymous unions.
7115 for (auto *UI : FieldRecord->fields()) {
7116 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7117
7118 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7119 return true;
7120
7121 if (!UnionFieldType.isConstQualified())
7122 AllVariantFieldsAreConst = false;
7123
7124 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7125 if (UnionFieldRecord &&
7126 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7127 UnionFieldType.getCVRQualifiers()))
7128 return true;
7129 }
7130
7131 // At least one member in each anonymous union must be non-const
7132 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7133 !FieldRecord->field_empty()) {
7134 if (Diagnose)
7135 S.Diag(FieldRecord->getLocation(),
7136 diag::note_deleted_default_ctor_all_const)
7137 << !!ICI << MD->getParent() << /*anonymous union*/1;
7138 return true;
7139 }
7140
7141 // Don't check the implicit member of the anonymous union type.
7142 // This is technically non-conformant, but sanity demands it.
7143 return false;
7144 }
7145
7146 if (shouldDeleteForClassSubobject(FieldRecord, FD,
7147 FieldType.getCVRQualifiers()))
7148 return true;
7149 }
7150
7151 return false;
7152}
7153
7154/// C++11 [class.ctor] p5:
7155/// A defaulted default constructor for a class X is defined as deleted if
7156/// X is a union and all of its variant members are of const-qualified type.
7157bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7158 // This is a silly definition, because it gives an empty union a deleted
7159 // default constructor. Don't do that.
7160 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7161 bool AnyFields = false;
7162 for (auto *F : MD->getParent()->fields())
7163 if ((AnyFields = !F->isUnnamedBitfield()))
7164 break;
7165 if (!AnyFields)
7166 return false;
7167 if (Diagnose)
7168 S.Diag(MD->getParent()->getLocation(),
7169 diag::note_deleted_default_ctor_all_const)
7170 << !!ICI << MD->getParent() << /*not anonymous union*/0;
7171 return true;
7172 }
7173 return false;
7174}
7175
7176/// Determine whether a defaulted special member function should be defined as
7177/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7178/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7179bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7180 InheritedConstructorInfo *ICI,
7181 bool Diagnose) {
7182 if (MD->isInvalidDecl())
7183 return false;
7184 CXXRecordDecl *RD = MD->getParent();
7185 assert(!RD->isDependentType() && "do deletion after instantiation")((!RD->isDependentType() && "do deletion after instantiation"
) ? static_cast<void> (0) : __assert_fail ("!RD->isDependentType() && \"do deletion after instantiation\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7185, __PRETTY_FUNCTION__))
;
7186 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7187 return false;
7188
7189 // C++11 [expr.lambda.prim]p19:
7190 // The closure type associated with a lambda-expression has a
7191 // deleted (8.4.3) default constructor and a deleted copy
7192 // assignment operator.
7193 // C++2a adds back these operators if the lambda has no capture-default.
7194 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7195 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7196 if (Diagnose)
7197 Diag(RD->getLocation(), diag::note_lambda_decl);
7198 return true;
7199 }
7200
7201 // For an anonymous struct or union, the copy and assignment special members
7202 // will never be used, so skip the check. For an anonymous union declared at
7203 // namespace scope, the constructor and destructor are used.
7204 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7205 RD->isAnonymousStructOrUnion())
7206 return false;
7207
7208 // C++11 [class.copy]p7, p18:
7209 // If the class definition declares a move constructor or move assignment
7210 // operator, an implicitly declared copy constructor or copy assignment
7211 // operator is defined as deleted.
7212 if (MD->isImplicit() &&
7213 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7214 CXXMethodDecl *UserDeclaredMove = nullptr;
7215
7216 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7217 // deletion of the corresponding copy operation, not both copy operations.
7218 // MSVC 2015 has adopted the standards conforming behavior.
7219 bool DeletesOnlyMatchingCopy =
7220 getLangOpts().MSVCCompat &&
7221 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7222
7223 if (RD->hasUserDeclaredMoveConstructor() &&
7224 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7225 if (!Diagnose) return true;
7226
7227 // Find any user-declared move constructor.
7228 for (auto *I : RD->ctors()) {
7229 if (I->isMoveConstructor()) {
7230 UserDeclaredMove = I;
7231 break;
7232 }
7233 }
7234 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7234, __PRETTY_FUNCTION__))
;
7235 } else if (RD->hasUserDeclaredMoveAssignment() &&
7236 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7237 if (!Diagnose) return true;
7238
7239 // Find any user-declared move assignment operator.
7240 for (auto *I : RD->methods()) {
7241 if (I->isMoveAssignmentOperator()) {
7242 UserDeclaredMove = I;
7243 break;
7244 }
7245 }
7246 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7246, __PRETTY_FUNCTION__))
;
7247 }
7248
7249 if (UserDeclaredMove) {
7250 Diag(UserDeclaredMove->getLocation(),
7251 diag::note_deleted_copy_user_declared_move)
7252 << (CSM == CXXCopyAssignment) << RD
7253 << UserDeclaredMove->isMoveAssignmentOperator();
7254 return true;
7255 }
7256 }
7257
7258 // Do access control from the special member function
7259 ContextRAII MethodContext(*this, MD);
7260
7261 // C++11 [class.dtor]p5:
7262 // -- for a virtual destructor, lookup of the non-array deallocation function
7263 // results in an ambiguity or in a function that is deleted or inaccessible
7264 if (CSM == CXXDestructor && MD->isVirtual()) {
7265 FunctionDecl *OperatorDelete = nullptr;
7266 DeclarationName Name =
7267 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7268 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7269 OperatorDelete, /*Diagnose*/false)) {
7270 if (Diagnose)
7271 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7272 return true;
7273 }
7274 }
7275
7276 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7277
7278 // Per DR1611, do not consider virtual bases of constructors of abstract
7279 // classes, since we are not going to construct them.
7280 // Per DR1658, do not consider virtual bases of destructors of abstract
7281 // classes either.
7282 // Per DR2180, for assignment operators we only assign (and thus only
7283 // consider) direct bases.
7284 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7285 : SMI.VisitPotentiallyConstructedBases))
7286 return true;
7287
7288 if (SMI.shouldDeleteForAllConstMembers())
7289 return true;
7290
7291 if (getLangOpts().CUDA) {
7292 // We should delete the special member in CUDA mode if target inference
7293 // failed.
7294 // For inherited constructors (non-null ICI), CSM may be passed so that MD
7295 // is treated as certain special member, which may not reflect what special
7296 // member MD really is. However inferCUDATargetForImplicitSpecialMember
7297 // expects CSM to match MD, therefore recalculate CSM.
7298 assert(ICI || CSM == getSpecialMember(MD))((ICI || CSM == getSpecialMember(MD)) ? static_cast<void>
(0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7298, __PRETTY_FUNCTION__))
;
7299 auto RealCSM = CSM;
7300 if (ICI)
7301 RealCSM = getSpecialMember(MD);
7302
7303 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7304 SMI.ConstArg, Diagnose);
7305 }
7306
7307 return false;
7308}
7309
7310/// Perform lookup for a special member of the specified kind, and determine
7311/// whether it is trivial. If the triviality can be determined without the
7312/// lookup, skip it. This is intended for use when determining whether a
7313/// special member of a containing object is trivial, and thus does not ever
7314/// perform overload resolution for default constructors.
7315///
7316/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7317/// member that was most likely to be intended to be trivial, if any.
7318///
7319/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7320/// determine whether the special member is trivial.
7321static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7322 Sema::CXXSpecialMember CSM, unsigned Quals,
7323 bool ConstRHS,
7324 Sema::TrivialABIHandling TAH,
7325 CXXMethodDecl **Selected) {
7326 if (Selected)
7327 *Selected = nullptr;
7328
7329 switch (CSM) {
7330 case Sema::CXXInvalid:
7331 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7331)
;
7332
7333 case Sema::CXXDefaultConstructor:
7334 // C++11 [class.ctor]p5:
7335 // A default constructor is trivial if:
7336 // - all the [direct subobjects] have trivial default constructors
7337 //
7338 // Note, no overload resolution is performed in this case.
7339 if (RD->hasTrivialDefaultConstructor())
7340 return true;
7341
7342 if (Selected) {
7343 // If there's a default constructor which could have been trivial, dig it
7344 // out. Otherwise, if there's any user-provided default constructor, point
7345 // to that as an example of why there's not a trivial one.
7346 CXXConstructorDecl *DefCtor = nullptr;
7347 if (RD->needsImplicitDefaultConstructor())
7348 S.DeclareImplicitDefaultConstructor(RD);
7349 for (auto *CI : RD->ctors()) {
7350 if (!CI->isDefaultConstructor())
7351 continue;
7352 DefCtor = CI;
7353 if (!DefCtor->isUserProvided())
7354 break;
7355 }
7356
7357 *Selected = DefCtor;
7358 }
7359
7360 return false;
7361
7362 case Sema::CXXDestructor:
7363 // C++11 [class.dtor]p5:
7364 // A destructor is trivial if:
7365 // - all the direct [subobjects] have trivial destructors
7366 if (RD->hasTrivialDestructor() ||
7367 (TAH == Sema::TAH_ConsiderTrivialABI &&
7368 RD->hasTrivialDestructorForCall()))
7369 return true;
7370
7371 if (Selected) {
7372 if (RD->needsImplicitDestructor())
7373 S.DeclareImplicitDestructor(RD);
7374 *Selected = RD->getDestructor();
7375 }
7376
7377 return false;
7378
7379 case Sema::CXXCopyConstructor:
7380 // C++11 [class.copy]p12:
7381 // A copy constructor is trivial if:
7382 // - the constructor selected to copy each direct [subobject] is trivial
7383 if (RD->hasTrivialCopyConstructor() ||
7384 (TAH == Sema::TAH_ConsiderTrivialABI &&
7385 RD->hasTrivialCopyConstructorForCall())) {
7386 if (Quals == Qualifiers::Const)
7387 // We must either select the trivial copy constructor or reach an
7388 // ambiguity; no need to actually perform overload resolution.
7389 return true;
7390 } else if (!Selected) {
7391 return false;
7392 }
7393 // In C++98, we are not supposed to perform overload resolution here, but we
7394 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7395 // cases like B as having a non-trivial copy constructor:
7396 // struct A { template<typename T> A(T&); };
7397 // struct B { mutable A a; };
7398 goto NeedOverloadResolution;
7399
7400 case Sema::CXXCopyAssignment:
7401 // C++11 [class.copy]p25:
7402 // A copy assignment operator is trivial if:
7403 // - the assignment operator selected to copy each direct [subobject] is
7404 // trivial
7405 if (RD->hasTrivialCopyAssignment()) {
7406 if (Quals == Qualifiers::Const)
7407 return true;
7408 } else if (!Selected) {
7409 return false;
7410 }
7411 // In C++98, we are not supposed to perform overload resolution here, but we
7412 // treat that as a language defect.
7413 goto NeedOverloadResolution;
7414
7415 case Sema::CXXMoveConstructor:
7416 case Sema::CXXMoveAssignment:
7417 NeedOverloadResolution:
7418 Sema::SpecialMemberOverloadResult SMOR =
7419 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7420
7421 // The standard doesn't describe how to behave if the lookup is ambiguous.
7422 // We treat it as not making the member non-trivial, just like the standard
7423 // mandates for the default constructor. This should rarely matter, because
7424 // the member will also be deleted.
7425 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7426 return true;
7427
7428 if (!SMOR.getMethod()) {
7429 assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7430, __PRETTY_FUNCTION__))
7430 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7430, __PRETTY_FUNCTION__))
;
7431 return false;
7432 }
7433
7434 // We deliberately don't check if we found a deleted special member. We're
7435 // not supposed to!
7436 if (Selected)
7437 *Selected = SMOR.getMethod();
7438
7439 if (TAH == Sema::TAH_ConsiderTrivialABI &&
7440 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7441 return SMOR.getMethod()->isTrivialForCall();
7442 return SMOR.getMethod()->isTrivial();
7443 }
7444
7445 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7445)
;
7446}
7447
7448static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7449 for (auto *CI : RD->ctors())
7450 if (!CI->isImplicit())
7451 return CI;
7452
7453 // Look for constructor templates.
7454 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7455 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7456 if (CXXConstructorDecl *CD =
7457 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7458 return CD;
7459 }
7460
7461 return nullptr;
7462}
7463
7464/// The kind of subobject we are checking for triviality. The values of this
7465/// enumeration are used in diagnostics.
7466enum TrivialSubobjectKind {
7467 /// The subobject is a base class.
7468 TSK_BaseClass,
7469 /// The subobject is a non-static data member.
7470 TSK_Field,
7471 /// The object is actually the complete object.
7472 TSK_CompleteObject
7473};
7474
7475/// Check whether the special member selected for a given type would be trivial.
7476static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7477 QualType SubType, bool ConstRHS,
7478 Sema::CXXSpecialMember CSM,
7479 TrivialSubobjectKind Kind,
7480 Sema::TrivialABIHandling TAH, bool Diagnose) {
7481 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7482 if (!SubRD)
7483 return true;
7484
7485 CXXMethodDecl *Selected;
7486 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7487 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7488 return true;
7489
7490 if (Diagnose) {
7491 if (ConstRHS)
7492 SubType.addConst();
7493
7494 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7495 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7496 << Kind << SubType.getUnqualifiedType();
7497 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7498 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7499 } else if (!Selected)
7500 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7501 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7502 else if (Selected->isUserProvided()) {
7503 if (Kind == TSK_CompleteObject)
7504 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7505 << Kind << SubType.getUnqualifiedType() << CSM;
7506 else {
7507 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7508 << Kind << SubType.getUnqualifiedType() << CSM;
7509 S.Diag(Selected->getLocation(), diag::note_declared_at);
7510 }
7511 } else {
7512 if (Kind != TSK_CompleteObject)
7513 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7514 << Kind << SubType.getUnqualifiedType() << CSM;
7515
7516 // Explain why the defaulted or deleted special member isn't trivial.
7517 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7518 Diagnose);
7519 }
7520 }
7521
7522 return false;
7523}
7524
7525/// Check whether the members of a class type allow a special member to be
7526/// trivial.
7527static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7528 Sema::CXXSpecialMember CSM,
7529 bool ConstArg,
7530 Sema::TrivialABIHandling TAH,
7531 bool Diagnose) {
7532 for (const auto *FI : RD->fields()) {
7533 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7534 continue;
7535
7536 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7537
7538 // Pretend anonymous struct or union members are members of this class.
7539 if (FI->isAnonymousStructOrUnion()) {
7540 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7541 CSM, ConstArg, TAH, Diagnose))
7542 return false;
7543 continue;
7544 }
7545
7546 // C++11 [class.ctor]p5:
7547 // A default constructor is trivial if [...]
7548 // -- no non-static data member of its class has a
7549 // brace-or-equal-initializer
7550 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7551 if (Diagnose)
7552 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7553 return false;
7554 }
7555
7556 // Objective C ARC 4.3.5:
7557 // [...] nontrivally ownership-qualified types are [...] not trivially
7558 // default constructible, copy constructible, move constructible, copy
7559 // assignable, move assignable, or destructible [...]
7560 if (FieldType.hasNonTrivialObjCLifetime()) {
7561 if (Diagnose)
7562 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7563 << RD << FieldType.getObjCLifetime();
7564 return false;
7565 }
7566
7567 bool ConstRHS = ConstArg && !FI->isMutable();
7568 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7569 CSM, TSK_Field, TAH, Diagnose))
7570 return false;
7571 }
7572
7573 return true;
7574}
7575
7576/// Diagnose why the specified class does not have a trivial special member of
7577/// the given kind.
7578void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7579 QualType Ty = Context.getRecordType(RD);
7580
7581 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7582 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7583 TSK_CompleteObject, TAH_IgnoreTrivialABI,
7584 /*Diagnose*/true);
7585}
7586
7587/// Determine whether a defaulted or deleted special member function is trivial,
7588/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7589/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7590bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7591 TrivialABIHandling TAH, bool Diagnose) {
7592 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")((!MD->isUserProvided() && CSM != CXXInvalid &&
"not special enough") ? static_cast<void> (0) : __assert_fail
("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7592, __PRETTY_FUNCTION__))
;
7593
7594 CXXRecordDecl *RD = MD->getParent();
7595
7596 bool ConstArg = false;
7597
7598 // C++11 [class.copy]p12, p25: [DR1593]
7599 // A [special member] is trivial if [...] its parameter-type-list is
7600 // equivalent to the parameter-type-list of an implicit declaration [...]
7601 switch (CSM) {
7602 case CXXDefaultConstructor:
7603 case CXXDestructor:
7604 // Trivial default constructors and destructors cannot have parameters.
7605 break;
7606
7607 case CXXCopyConstructor:
7608 case CXXCopyAssignment: {
7609 // Trivial copy operations always have const, non-volatile parameter types.
7610 ConstArg = true;
7611 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7612 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7613 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7614 if (Diagnose)
7615 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7616 << Param0->getSourceRange() << Param0->getType()
7617 << Context.getLValueReferenceType(
7618 Context.getRecordType(RD).withConst());
7619 return false;
7620 }
7621 break;
7622 }
7623
7624 case CXXMoveConstructor:
7625 case CXXMoveAssignment: {
7626 // Trivial move operations always have non-cv-qualified parameters.
7627 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7628 const RValueReferenceType *RT =
7629 Param0->getType()->getAs<RValueReferenceType>();
7630 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7631 if (Diagnose)
7632 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7633 << Param0->getSourceRange() << Param0->getType()
7634 << Context.getRValueReferenceType(Context.getRecordType(RD));
7635 return false;
7636 }
7637 break;
7638 }
7639
7640 case CXXInvalid:
7641 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7641)
;
7642 }
7643
7644 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7645 if (Diagnose)
7646 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7647 diag::note_nontrivial_default_arg)
7648 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7649 return false;
7650 }
7651 if (MD->isVariadic()) {
7652 if (Diagnose)
7653 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7654 return false;
7655 }
7656
7657 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7658 // A copy/move [constructor or assignment operator] is trivial if
7659 // -- the [member] selected to copy/move each direct base class subobject
7660 // is trivial
7661 //
7662 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7663 // A [default constructor or destructor] is trivial if
7664 // -- all the direct base classes have trivial [default constructors or
7665 // destructors]
7666 for (const auto &BI : RD->bases())
7667 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7668 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7669 return false;
7670
7671 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7672 // A copy/move [constructor or assignment operator] for a class X is
7673 // trivial if
7674 // -- for each non-static data member of X that is of class type (or array
7675 // thereof), the constructor selected to copy/move that member is
7676 // trivial
7677 //
7678 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7679 // A [default constructor or destructor] is trivial if
7680 // -- for all of the non-static data members of its class that are of class
7681 // type (or array thereof), each such class has a trivial [default
7682 // constructor or destructor]
7683 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7684 return false;
7685
7686 // C++11 [class.dtor]p5:
7687 // A destructor is trivial if [...]
7688 // -- the destructor is not virtual
7689 if (CSM == CXXDestructor && MD->isVirtual()) {
7690 if (Diagnose)
7691 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7692 return false;
7693 }
7694
7695 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7696 // A [special member] for class X is trivial if [...]
7697 // -- class X has no virtual functions and no virtual base classes
7698 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7699 if (!Diagnose)
7700 return false;
7701
7702 if (RD->getNumVBases()) {
7703 // Check for virtual bases. We already know that the corresponding
7704 // member in all bases is trivial, so vbases must all be direct.
7705 CXXBaseSpecifier &BS = *RD->vbases_begin();
7706 assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail
("BS.isVirtual()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7706, __PRETTY_FUNCTION__))
;
7707 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7708 return false;
7709 }
7710
7711 // Must have a virtual method.
7712 for (const auto *MI : RD->methods()) {
7713 if (MI->isVirtual()) {
7714 SourceLocation MLoc = MI->getBeginLoc();
7715 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7716 return false;
7717 }
7718 }
7719
7720 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7720)
;
7721 }
7722
7723 // Looks like it's trivial!
7724 return true;
7725}
7726
7727namespace {
7728struct FindHiddenVirtualMethod {
7729 Sema *S;
7730 CXXMethodDecl *Method;
7731 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7732 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7733
7734private:
7735 /// Check whether any most overridden method from MD in Methods
7736 static bool CheckMostOverridenMethods(
7737 const CXXMethodDecl *MD,
7738 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7739 if (MD->size_overridden_methods() == 0)
7740 return Methods.count(MD->getCanonicalDecl());
7741 for (const CXXMethodDecl *O : MD->overridden_methods())
7742 if (CheckMostOverridenMethods(O, Methods))
7743 return true;
7744 return false;
7745 }
7746
7747public:
7748 /// Member lookup function that determines whether a given C++
7749 /// method overloads virtual methods in a base class without overriding any,
7750 /// to be used with CXXRecordDecl::lookupInBases().
7751 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7752 RecordDecl *BaseRecord =
7753 Specifier->getType()->getAs<RecordType>()->getDecl();
7754
7755 DeclarationName Name = Method->getDeclName();
7756 assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast
<void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7756, __PRETTY_FUNCTION__))
;
7757
7758 bool foundSameNameMethod = false;
7759 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7760 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7761 Path.Decls = Path.Decls.slice(1)) {
7762 NamedDecl *D = Path.Decls.front();
7763 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7764 MD = MD->getCanonicalDecl();
7765 foundSameNameMethod = true;
7766 // Interested only in hidden virtual methods.
7767 if (!MD->isVirtual())
7768 continue;
7769 // If the method we are checking overrides a method from its base
7770 // don't warn about the other overloaded methods. Clang deviates from
7771 // GCC by only diagnosing overloads of inherited virtual functions that
7772 // do not override any other virtual functions in the base. GCC's
7773 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7774 // function from a base class. These cases may be better served by a
7775 // warning (not specific to virtual functions) on call sites when the
7776 // call would select a different function from the base class, were it
7777 // visible.
7778 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7779 if (!S->IsOverload(Method, MD, false))
7780 return true;
7781 // Collect the overload only if its hidden.
7782 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7783 overloadedMethods.push_back(MD);
7784 }
7785 }
7786
7787 if (foundSameNameMethod)
7788 OverloadedMethods.append(overloadedMethods.begin(),
7789 overloadedMethods.end());
7790 return foundSameNameMethod;
7791 }
7792};
7793} // end anonymous namespace
7794
7795/// Add the most overriden methods from MD to Methods
7796static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7797 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7798 if (MD->size_overridden_methods() == 0)
7799 Methods.insert(MD->getCanonicalDecl());
7800 else
7801 for (const CXXMethodDecl *O : MD->overridden_methods())
7802 AddMostOverridenMethods(O, Methods);
7803}
7804
7805/// Check if a method overloads virtual methods in a base class without
7806/// overriding any.
7807void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7808 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7809 if (!MD->getDeclName().isIdentifier())
7810 return;
7811
7812 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7813 /*bool RecordPaths=*/false,
7814 /*bool DetectVirtual=*/false);
7815 FindHiddenVirtualMethod FHVM;
7816 FHVM.Method = MD;
7817 FHVM.S = this;
7818
7819 // Keep the base methods that were overridden or introduced in the subclass
7820 // by 'using' in a set. A base method not in this set is hidden.
7821 CXXRecordDecl *DC = MD->getParent();
7822 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7823 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7824 NamedDecl *ND = *I;
7825 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7826 ND = shad->getTargetDecl();
7827 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7828 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7829 }
7830
7831 if (DC->lookupInBases(FHVM, Paths))
7832 OverloadedMethods = FHVM.OverloadedMethods;
7833}
7834
7835void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7836 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7837 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7838 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7839 PartialDiagnostic PD = PDiag(
7840 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7841 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7842 Diag(overloadedMD->getLocation(), PD);
7843 }
7844}
7845
7846/// Diagnose methods which overload virtual methods in a base class
7847/// without overriding any.
7848void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7849 if (MD->isInvalidDecl())
7850 return;
7851
7852 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7853 return;
7854
7855 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7856 FindHiddenVirtualMethods(MD, OverloadedMethods);
7857 if (!OverloadedMethods.empty()) {
7858 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7859 << MD << (OverloadedMethods.size() > 1);
7860
7861 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7862 }
7863}
7864
7865void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7866 auto PrintDiagAndRemoveAttr = [&]() {
7867 // No diagnostics if this is a template instantiation.
7868 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7869 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7870 diag::ext_cannot_use_trivial_abi) << &RD;
7871 RD.dropAttr<TrivialABIAttr>();
7872 };
7873
7874 // Ill-formed if the struct has virtual functions.
7875 if (RD.isPolymorphic()) {
7876 PrintDiagAndRemoveAttr();
7877 return;
7878 }
7879
7880 for (const auto &B : RD.bases()) {
7881 // Ill-formed if the base class is non-trivial for the purpose of calls or a
7882 // virtual base.
7883 if ((!B.getType()->isDependentType() &&
7884 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7885 B.isVirtual()) {
7886 PrintDiagAndRemoveAttr();
7887 return;
7888 }
7889 }
7890
7891 for (const auto *FD : RD.fields()) {
7892 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7893 // non-trivial for the purpose of calls.
7894 QualType FT = FD->getType();
7895 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7896 PrintDiagAndRemoveAttr();
7897 return;
7898 }
7899
7900 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7901 if (!RT->isDependentType() &&
7902 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7903 PrintDiagAndRemoveAttr();
7904 return;
7905 }
7906 }
7907}
7908
7909void Sema::ActOnFinishCXXMemberSpecification(
7910 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7911 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7912 if (!TagDecl)
7913 return;
7914
7915 AdjustDeclIfTemplate(TagDecl);
7916
7917 for (const ParsedAttr &AL : AttrList) {
7918 if (AL.getKind() != ParsedAttr::AT_Visibility)
7919 continue;
7920 AL.setInvalid();
7921 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7922 << AL.getName();
7923 }
7924
7925 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7926 // strict aliasing violation!
7927 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7928 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7929
7930 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7931}
7932
7933/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7934/// special functions, such as the default constructor, copy
7935/// constructor, or destructor, to the given C++ class (C++
7936/// [special]p1). This routine can only be executed just before the
7937/// definition of the class is complete.
7938void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7939 if (ClassDecl->needsImplicitDefaultConstructor()) {
7940 ++getASTContext().NumImplicitDefaultConstructors;
7941
7942 if (ClassDecl->hasInheritedConstructor())
7943 DeclareImplicitDefaultConstructor(ClassDecl);
7944 }
7945
7946 if (ClassDecl->needsImplicitCopyConstructor()) {
7947 ++getASTContext().NumImplicitCopyConstructors;
7948
7949 // If the properties or semantics of the copy constructor couldn't be
7950 // determined while the class was being declared, force a declaration
7951 // of it now.
7952 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7953 ClassDecl->hasInheritedConstructor())
7954 DeclareImplicitCopyConstructor(ClassDecl);
7955 // For the MS ABI we need to know whether the copy ctor is deleted. A
7956 // prerequisite for deleting the implicit copy ctor is that the class has a
7957 // move ctor or move assignment that is either user-declared or whose
7958 // semantics are inherited from a subobject. FIXME: We should provide a more
7959 // direct way for CodeGen to ask whether the constructor was deleted.
7960 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7961 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7962 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7963 ClassDecl->hasUserDeclaredMoveAssignment() ||
7964 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7965 DeclareImplicitCopyConstructor(ClassDecl);
7966 }
7967
7968 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7969 ++getASTContext().NumImplicitMoveConstructors;
7970
7971 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7972 ClassDecl->hasInheritedConstructor())
7973 DeclareImplicitMoveConstructor(ClassDecl);
7974 }
7975
7976 if (ClassDecl->needsImplicitCopyAssignment()) {
7977 ++getASTContext().NumImplicitCopyAssignmentOperators;
7978
7979 // If we have a dynamic class, then the copy assignment operator may be
7980 // virtual, so we have to declare it immediately. This ensures that, e.g.,
7981 // it shows up in the right place in the vtable and that we diagnose
7982 // problems with the implicit exception specification.
7983 if (ClassDecl->isDynamicClass() ||
7984 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7985 ClassDecl->hasInheritedAssignment())
7986 DeclareImplicitCopyAssignment(ClassDecl);
7987 }
7988
7989 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7990 ++getASTContext().NumImplicitMoveAssignmentOperators;
7991
7992 // Likewise for the move assignment operator.
7993 if (ClassDecl->isDynamicClass() ||
7994 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7995 ClassDecl->hasInheritedAssignment())
7996 DeclareImplicitMoveAssignment(ClassDecl);
7997 }
7998
7999 if (ClassDecl->needsImplicitDestructor()) {
8000 ++getASTContext().NumImplicitDestructors;
8001
8002 // If we have a dynamic class, then the destructor may be virtual, so we
8003 // have to declare the destructor immediately. This ensures that, e.g., it
8004 // shows up in the right place in the vtable and that we diagnose problems
8005 // with the implicit exception specification.
8006 if (ClassDecl->isDynamicClass() ||
8007 ClassDecl->needsOverloadResolutionForDestructor())
8008 DeclareImplicitDestructor(ClassDecl);
8009 }
8010}
8011
8012unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8013 if (!D)
8014 return 0;
8015
8016 // The order of template parameters is not important here. All names
8017 // get added to the same scope.
8018 SmallVector<TemplateParameterList *, 4> ParameterLists;
8019
8020 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8021 D = TD->getTemplatedDecl();
8022
8023 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8024 ParameterLists.push_back(PSD->getTemplateParameters());
8025
8026 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8027 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8028 ParameterLists.push_back(DD->getTemplateParameterList(i));
8029
8030 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8031 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8032 ParameterLists.push_back(FTD->getTemplateParameters());
8033 }
8034 }
8035
8036 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8037 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8038 ParameterLists.push_back(TD->getTemplateParameterList(i));
8039
8040 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8041 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8042 ParameterLists.push_back(CTD->getTemplateParameters());
8043 }
8044 }
8045
8046 unsigned Count = 0;
8047 for (TemplateParameterList *Params : ParameterLists) {
8048 if (Params->size() > 0)
8049 // Ignore explicit specializations; they don't contribute to the template
8050 // depth.
8051 ++Count;
8052 for (NamedDecl *Param : *Params) {
8053 if (Param->getDeclName()) {
8054 S->AddDecl(Param);
8055 IdResolver.AddDecl(Param);
8056 }
8057 }
8058 }
8059
8060 return Count;
8061}
8062
8063void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8064 if (!RecordD) return;
8065 AdjustDeclIfTemplate(RecordD);
8066 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8067 PushDeclContext(S, Record);
8068}
8069
8070void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8071 if (!RecordD) return;
8072 PopDeclContext();
8073}
8074
8075/// This is used to implement the constant expression evaluation part of the
8076/// attribute enable_if extension. There is nothing in standard C++ which would
8077/// require reentering parameters.
8078void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8079 if (!Param)
8080 return;
8081
8082 S->AddDecl(Param);
8083 if (Param->getDeclName())
8084 IdResolver.AddDecl(Param);
8085}
8086
8087/// ActOnStartDelayedCXXMethodDeclaration - We have completed
8088/// parsing a top-level (non-nested) C++ class, and we are now
8089/// parsing those parts of the given Method declaration that could
8090/// not be parsed earlier (C++ [class.mem]p2), such as default
8091/// arguments. This action should enter the scope of the given
8092/// Method declaration as if we had just parsed the qualified method
8093/// name. However, it should not bring the parameters into scope;
8094/// that will be performed by ActOnDelayedCXXMethodParameter.
8095void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8096}
8097
8098/// ActOnDelayedCXXMethodParameter - We've already started a delayed
8099/// C++ method declaration. We're (re-)introducing the given
8100/// function parameter into scope for use in parsing later parts of
8101/// the method declaration. For example, we could see an
8102/// ActOnParamDefaultArgument event for this parameter.
8103void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8104 if (!ParamD)
8105 return;
8106
8107 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8108
8109 // If this parameter has an unparsed default argument, clear it out
8110 // to make way for the parsed default argument.
8111 if (Param->hasUnparsedDefaultArg())
8112 Param->setDefaultArg(nullptr);
8113
8114 S->AddDecl(Param);
8115 if (Param->getDeclName())
8116 IdResolver.AddDecl(Param);
8117}
8118
8119/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8120/// processing the delayed method declaration for Method. The method
8121/// declaration is now considered finished. There may be a separate
8122/// ActOnStartOfFunctionDef action later (not necessarily
8123/// immediately!) for this method, if it was also defined inside the
8124/// class body.
8125void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8126 if (!MethodD)
8127 return;
8128
8129 AdjustDeclIfTemplate(MethodD);
8130
8131 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8132
8133 // Now that we have our default arguments, check the constructor
8134 // again. It could produce additional diagnostics or affect whether
8135 // the class has implicitly-declared destructors, among other
8136 // things.
8137 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8138 CheckConstructor(Constructor);
8139
8140 // Check the default arguments, which we may have added.
8141 if (!Method->isInvalidDecl())
8142 CheckCXXDefaultArguments(Method);
8143}
8144
8145/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8146/// the well-formedness of the constructor declarator @p D with type @p
8147/// R. If there are any errors in the declarator, this routine will
8148/// emit diagnostics and set the invalid bit to true. In any case, the type
8149/// will be updated to reflect a well-formed type for the constructor and
8150/// returned.
8151QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8152 StorageClass &SC) {
8153 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8154
8155 // C++ [class.ctor]p3:
8156 // A constructor shall not be virtual (10.3) or static (9.4). A
8157 // constructor can be invoked for a const, volatile or const
8158 // volatile object. A constructor shall not be declared const,
8159 // volatile, or const volatile (9.3.2).
8160 if (isVirtual) {
8161 if (!D.isInvalidType())
8162 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8163 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8164 << SourceRange(D.getIdentifierLoc());
8165 D.setInvalidType();
8166 }
8167 if (SC == SC_Static) {
8168 if (!D.isInvalidType())
8169 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8170 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8171 << SourceRange(D.getIdentifierLoc());
8172 D.setInvalidType();
8173 SC = SC_None;
8174 }
8175
8176 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8177 diagnoseIgnoredQualifiers(
8178 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8179 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8180 D.getDeclSpec().getRestrictSpecLoc(),
8181 D.getDeclSpec().getAtomicSpecLoc());
8182 D.setInvalidType();
8183 }
8184
8185 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8186 if (FTI.hasMethodTypeQualifiers()) {
8187 FTI.MethodQualifiers->forEachQualifier(
8188 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8189 Diag(SL, diag::err_invalid_qualified_constructor)
8190 << QualName << SourceRange(SL);
8191 });
8192 D.setInvalidType();
8193 }
8194
8195 // C++0x [class.ctor]p4:
8196 // A constructor shall not be declared with a ref-qualifier.
8197 if (FTI.hasRefQualifier()) {
8198 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8199 << FTI.RefQualifierIsLValueRef
8200 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8201 D.setInvalidType();
8202 }
8203
8204 // Rebuild the function type "R" without any type qualifiers (in
8205 // case any of the errors above fired) and with "void" as the
8206 // return type, since constructors don't have return types.
8207 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8208 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8209 return R;
8210
8211 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8212 EPI.TypeQuals = Qualifiers();
8213 EPI.RefQualifier = RQ_None;
8214
8215 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8216}
8217
8218/// CheckConstructor - Checks a fully-formed constructor for
8219/// well-formedness, issuing any diagnostics required. Returns true if
8220/// the constructor declarator is invalid.
8221void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8222 CXXRecordDecl *ClassDecl
8223 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8224 if (!ClassDecl)
8225 return Constructor->setInvalidDecl();
8226
8227 // C++ [class.copy]p3:
8228 // A declaration of a constructor for a class X is ill-formed if
8229 // its first parameter is of type (optionally cv-qualified) X and
8230 // either there are no other parameters or else all other
8231 // parameters have default arguments.
8232 if (!Constructor->isInvalidDecl() &&
8233 ((Constructor->getNumParams() == 1) ||
8234 (Constructor->getNumParams() > 1 &&
8235 Constructor->getParamDecl(1)->hasDefaultArg())) &&
8236 Constructor->getTemplateSpecializationKind()
8237 != TSK_ImplicitInstantiation) {
8238 QualType ParamType = Constructor->getParamDecl(0)->getType();
8239 QualType ClassTy = Context.getTagDeclType(ClassDecl);
8240 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8241 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8242 const char *ConstRef
8243 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8244 : " const &";
8245 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8246 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8247
8248 // FIXME: Rather that making the constructor invalid, we should endeavor
8249 // to fix the type.
8250 Constructor->setInvalidDecl();
8251 }
8252 }
8253}
8254
8255/// CheckDestructor - Checks a fully-formed destructor definition for
8256/// well-formedness, issuing any diagnostics required. Returns true
8257/// on error.
8258bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8259 CXXRecordDecl *RD = Destructor->getParent();
8260
8261 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8262 SourceLocation Loc;
8263
8264 if (!Destructor->isImplicit())
8265 Loc = Destructor->getLocation();
8266 else
8267 Loc = RD->getLocation();
8268
8269 // If we have a virtual destructor, look up the deallocation function
8270 if (FunctionDecl *OperatorDelete =
8271 FindDeallocationFunctionForDestructor(Loc, RD)) {
8272 Expr *ThisArg = nullptr;
8273
8274 // If the notional 'delete this' expression requires a non-trivial
8275 // conversion from 'this' to the type of a destroying operator delete's
8276 // first parameter, perform that conversion now.
8277 if (OperatorDelete->isDestroyingOperatorDelete()) {
8278 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8279 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8280 // C++ [class.dtor]p13:
8281 // ... as if for the expression 'delete this' appearing in a
8282 // non-virtual destructor of the destructor's class.
8283 ContextRAII SwitchContext(*this, Destructor);
8284 ExprResult This =
8285 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8286 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")((!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? static_cast<void> (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8286, __PRETTY_FUNCTION__))
;
8287 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8288 if (This.isInvalid()) {
8289 // FIXME: Register this as a context note so that it comes out
8290 // in the right order.
8291 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8292 return true;
8293 }
8294 ThisArg = This.get();
8295 }
8296 }
8297
8298 DiagnoseUseOfDecl(OperatorDelete, Loc);
8299 MarkFunctionReferenced(Loc, OperatorDelete);
8300 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8301 }
8302 }
8303
8304 return false;
8305}
8306
8307/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8308/// the well-formednes of the destructor declarator @p D with type @p
8309/// R. If there are any errors in the declarator, this routine will
8310/// emit diagnostics and set the declarator to invalid. Even if this happens,
8311/// will be updated to reflect a well-formed type for the destructor and
8312/// returned.
8313QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8314 StorageClass& SC) {
8315 // C++ [class.dtor]p1:
8316 // [...] A typedef-name that names a class is a class-name
8317 // (7.1.3); however, a typedef-name that names a class shall not
8318 // be used as the identifier in the declarator for a destructor
8319 // declaration.
8320 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8321 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8322 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8323 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8324 else if (const TemplateSpecializationType *TST =
8325 DeclaratorType->getAs<TemplateSpecializationType>())
8326 if (TST->isTypeAlias())
8327 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8328 << DeclaratorType << 1;
8329
8330 // C++ [class.dtor]p2:
8331 // A destructor is used to destroy objects of its class type. A
8332 // destructor takes no parameters, and no return type can be
8333 // specified for it (not even void). The address of a destructor
8334 // shall not be taken. A destructor shall not be static. A
8335 // destructor can be invoked for a const, volatile or const
8336 // volatile object. A destructor shall not be declared const,
8337 // volatile or const volatile (9.3.2).
8338 if (SC == SC_Static) {
8339 if (!D.isInvalidType())
8340 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8341 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8342 << SourceRange(D.getIdentifierLoc())
8343 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8344
8345 SC = SC_None;
8346 }
8347 if (!D.isInvalidType()) {
8348 // Destructors don't have return types, but the parser will
8349 // happily parse something like:
8350 //
8351 // class X {
8352 // float ~X();
8353 // };
8354 //
8355 // The return type will be eliminated later.
8356 if (D.getDeclSpec().hasTypeSpecifier())
8357 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8358 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8359 << SourceRange(D.getIdentifierLoc());
8360 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8361 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8362 SourceLocation(),
8363 D.getDeclSpec().getConstSpecLoc(),
8364 D.getDeclSpec().getVolatileSpecLoc(),
8365 D.getDeclSpec().getRestrictSpecLoc(),
8366 D.getDeclSpec().getAtomicSpecLoc());
8367 D.setInvalidType();
8368 }
8369 }
8370
8371 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8372 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8373 FTI.MethodQualifiers->forEachQualifier(
8374 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8375 Diag(SL, diag::err_invalid_qualified_destructor)
8376 << QualName << SourceRange(SL);
8377 });
8378 D.setInvalidType();
8379 }
8380
8381 // C++0x [class.dtor]p2:
8382 // A destructor shall not be declared with a ref-qualifier.
8383 if (FTI.hasRefQualifier()) {
8384 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8385 << FTI.RefQualifierIsLValueRef
8386 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8387 D.setInvalidType();
8388 }
8389
8390 // Make sure we don't have any parameters.
8391 if (FTIHasNonVoidParameters(FTI)) {
8392 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8393
8394 // Delete the parameters.
8395 FTI.freeParams();
8396 D.setInvalidType();
8397 }
8398
8399 // Make sure the destructor isn't variadic.
8400 if (FTI.isVariadic) {
8401 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8402 D.setInvalidType();
8403 }
8404
8405 // Rebuild the function type "R" without any type qualifiers or
8406 // parameters (in case any of the errors above fired) and with
8407 // "void" as the return type, since destructors don't have return
8408 // types.
8409 if (!D.isInvalidType())
8410 return R;
8411
8412 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8413 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8414 EPI.Variadic = false;
8415 EPI.TypeQuals = Qualifiers();
8416 EPI.RefQualifier = RQ_None;
8417 return Context.getFunctionType(Context.VoidTy, None, EPI);
8418}
8419
8420static void extendLeft(SourceRange &R, SourceRange Before) {
8421 if (Before.isInvalid())
8422 return;
8423 R.setBegin(Before.getBegin());
8424 if (R.getEnd().isInvalid())
8425 R.setEnd(Before.getEnd());
8426}
8427
8428static void extendRight(SourceRange &R, SourceRange After) {
8429 if (After.isInvalid())
8430 return;
8431 if (R.getBegin().isInvalid())
8432 R.setBegin(After.getBegin());
8433 R.setEnd(After.getEnd());
8434}
8435
8436/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8437/// well-formednes of the conversion function declarator @p D with
8438/// type @p R. If there are any errors in the declarator, this routine
8439/// will emit diagnostics and return true. Otherwise, it will return
8440/// false. Either way, the type @p R will be updated to reflect a
8441/// well-formed type for the conversion operator.
8442void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8443 StorageClass& SC) {
8444 // C++ [class.conv.fct]p1:
8445 // Neither parameter types nor return type can be specified. The
8446 // type of a conversion function (8.3.5) is "function taking no
8447 // parameter returning conversion-type-id."
8448 if (SC == SC_Static) {
8449 if (!D.isInvalidType())
8450 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8451 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8452 << D.getName().getSourceRange();
8453 D.setInvalidType();
8454 SC = SC_None;
8455 }
8456
8457 TypeSourceInfo *ConvTSI = nullptr;
8458 QualType ConvType =
8459 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8460
8461 const DeclSpec &DS = D.getDeclSpec();
8462 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8463 // Conversion functions don't have return types, but the parser will
8464 // happily parse something like:
8465 //
8466 // class X {
8467 // float operator bool();
8468 // };
8469 //
8470 // The return type will be changed later anyway.
8471 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8472 << SourceRange(DS.getTypeSpecTypeLoc())
8473 << SourceRange(D.getIdentifierLoc());
8474 D.setInvalidType();
8475 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8476 // It's also plausible that the user writes type qualifiers in the wrong
8477 // place, such as:
8478 // struct S { const operator int(); };
8479 // FIXME: we could provide a fixit to move the qualifiers onto the
8480 // conversion type.
8481 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8482 << SourceRange(D.getIdentifierLoc()) << 0;
8483 D.setInvalidType();
8484 }
8485
8486 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8487
8488 // Make sure we don't have any parameters.
8489 if (Proto->getNumParams() > 0) {
8490 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8491
8492 // Delete the parameters.
8493 D.getFunctionTypeInfo().freeParams();
8494 D.setInvalidType();
8495 } else if (Proto->isVariadic()) {
8496 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8497 D.setInvalidType();
8498 }
8499
8500 // Diagnose "&operator bool()" and other such nonsense. This
8501 // is actually a gcc extension which we don't support.
8502 if (Proto->getReturnType() != ConvType) {
8503 bool NeedsTypedef = false;
8504 SourceRange Before, After;
8505
8506 // Walk the chunks and extract information on them for our diagnostic.
8507 bool PastFunctionChunk = false;
8508 for (auto &Chunk : D.type_objects()) {
8509 switch (Chunk.Kind) {
8510 case DeclaratorChunk::Function:
8511 if (!PastFunctionChunk) {
8512 if (Chunk.Fun.HasTrailingReturnType) {
8513 TypeSourceInfo *TRT = nullptr;
8514 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8515 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8516 }
8517 PastFunctionChunk = true;
8518 break;
8519 }
8520 LLVM_FALLTHROUGH[[clang::fallthrough]];
8521 case DeclaratorChunk::Array:
8522 NeedsTypedef = true;
8523 extendRight(After, Chunk.getSourceRange());
8524 break;
8525
8526 case DeclaratorChunk::Pointer:
8527 case DeclaratorChunk::BlockPointer:
8528 case DeclaratorChunk::Reference:
8529 case DeclaratorChunk::MemberPointer:
8530 case DeclaratorChunk::Pipe:
8531 extendLeft(Before, Chunk.getSourceRange());
8532 break;
8533
8534 case DeclaratorChunk::Paren:
8535 extendLeft(Before, Chunk.Loc);
8536 extendRight(After, Chunk.EndLoc);
8537 break;
8538 }
8539 }
8540
8541 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8542 After.isValid() ? After.getBegin() :
8543 D.getIdentifierLoc();
8544 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8545 DB << Before << After;
8546
8547 if (!NeedsTypedef) {
8548 DB << /*don't need a typedef*/0;
8549
8550 // If we can provide a correct fix-it hint, do so.
8551 if (After.isInvalid() && ConvTSI) {
8552 SourceLocation InsertLoc =
8553 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8554 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8555 << FixItHint::CreateInsertionFromRange(
8556 InsertLoc, CharSourceRange::getTokenRange(Before))
8557 << FixItHint::CreateRemoval(Before);
8558 }
8559 } else if (!Proto->getReturnType()->isDependentType()) {
8560 DB << /*typedef*/1 << Proto->getReturnType();
8561 } else if (getLangOpts().CPlusPlus11) {
8562 DB << /*alias template*/2 << Proto->getReturnType();
8563 } else {
8564 DB << /*might not be fixable*/3;
8565 }
8566
8567 // Recover by incorporating the other type chunks into the result type.
8568 // Note, this does *not* change the name of the function. This is compatible
8569 // with the GCC extension:
8570 // struct S { &operator int(); } s;
8571 // int &r = s.operator int(); // ok in GCC
8572 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8573 ConvType = Proto->getReturnType();
8574 }
8575
8576 // C++ [class.conv.fct]p4:
8577 // The conversion-type-id shall not represent a function type nor
8578 // an array type.
8579 if (ConvType->isArrayType()) {
8580 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8581 ConvType = Context.getPointerType(ConvType);
8582 D.setInvalidType();
8583 } else if (ConvType->isFunctionType()) {
8584 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8585 ConvType = Context.getPointerType(ConvType);
8586 D.setInvalidType();
8587 }
8588
8589 // Rebuild the function type "R" without any parameters (in case any
8590 // of the errors above fired) and with the conversion type as the
8591 // return type.
8592 if (D.isInvalidType())
8593 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8594
8595 // C++0x explicit conversion operators.
8596 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8597 Diag(DS.getExplicitSpecLoc(),
8598 getLangOpts().CPlusPlus11
8599 ? diag::warn_cxx98_compat_explicit_conversion_functions
8600 : diag::ext_explicit_conversion_functions)
8601 << SourceRange(DS.getExplicitSpecRange());
8602}
8603
8604/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8605/// the declaration of the given C++ conversion function. This routine
8606/// is responsible for recording the conversion function in the C++
8607/// class, if possible.
8608Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8609 assert(Conversion && "Expected to receive a conversion function declaration")((Conversion && "Expected to receive a conversion function declaration"
) ? static_cast<void> (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8609, __PRETTY_FUNCTION__))
;
8610
8611 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8612
8613 // Make sure we aren't redeclaring the conversion function.
8614 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8615
8616 // C++ [class.conv.fct]p1:
8617 // [...] A conversion function is never used to convert a
8618 // (possibly cv-qualified) object to the (possibly cv-qualified)
8619 // same object type (or a reference to it), to a (possibly
8620 // cv-qualified) base class of that type (or a reference to it),
8621 // or to (possibly cv-qualified) void.
8622 // FIXME: Suppress this warning if the conversion function ends up being a
8623 // virtual function that overrides a virtual function in a base class.
8624 QualType ClassType
8625 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8626 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8627 ConvType = ConvTypeRef->getPointeeType();
8628 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8629 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8630 /* Suppress diagnostics for instantiations. */;
8631 else if (ConvType->isRecordType()) {
8632 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8633 if (ConvType == ClassType)
8634 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8635 << ClassType;
8636 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8637 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8638 << ClassType << ConvType;
8639 } else if (ConvType->isVoidType()) {
8640 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8641 << ClassType << ConvType;
8642 }
8643
8644 if (FunctionTemplateDecl *ConversionTemplate
8645 = Conversion->getDescribedFunctionTemplate())
8646 return ConversionTemplate;
8647
8648 return Conversion;
8649}
8650
8651namespace {
8652/// Utility class to accumulate and print a diagnostic listing the invalid
8653/// specifier(s) on a declaration.
8654struct BadSpecifierDiagnoser {
8655 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8656 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8657 ~BadSpecifierDiagnoser() {
8658 Diagnostic << Specifiers;
8659 }
8660
8661 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8662 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8663 }
8664 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8665 return check(SpecLoc,
8666 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8667 }
8668 void check(SourceLocation SpecLoc, const char *Spec) {
8669 if (SpecLoc.isInvalid()) return;
8670 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8671 if (!Specifiers.empty()) Specifiers += " ";
8672 Specifiers += Spec;
8673 }
8674
8675 Sema &S;
8676 Sema::SemaDiagnosticBuilder Diagnostic;
8677 std::string Specifiers;
8678};
8679}
8680
8681/// Check the validity of a declarator that we parsed for a deduction-guide.
8682/// These aren't actually declarators in the grammar, so we need to check that
8683/// the user didn't specify any pieces that are not part of the deduction-guide
8684/// grammar.
8685void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8686 StorageClass &SC) {
8687 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8688 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8689 assert(GuidedTemplateDecl && "missing template decl for deduction guide")((GuidedTemplateDecl && "missing template decl for deduction guide"
) ? static_cast<void> (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8689, __PRETTY_FUNCTION__))
;
8690
8691 // C++ [temp.deduct.guide]p3:
8692 // A deduction-gide shall be declared in the same scope as the
8693 // corresponding class template.
8694 if (!CurContext->getRedeclContext()->Equals(
8695 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8696 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8697 << GuidedTemplateDecl;
8698 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8699 }
8700
8701 auto &DS = D.getMutableDeclSpec();
8702 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8703 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8704 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8705 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8706 BadSpecifierDiagnoser Diagnoser(
8707 *this, D.getIdentifierLoc(),
8708 diag::err_deduction_guide_invalid_specifier);
8709
8710 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8711 DS.ClearStorageClassSpecs();
8712 SC = SC_None;
8713
8714 // 'explicit' is permitted.
8715 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8716 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8717 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8718 DS.ClearConstexprSpec();
8719
8720 Diagnoser.check(DS.getConstSpecLoc(), "const");
8721 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8722 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8723 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8724 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8725 DS.ClearTypeQualifiers();
8726
8727 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8728 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8729 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8730 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8731 DS.ClearTypeSpecType();
8732 }
8733
8734 if (D.isInvalidType())
8735 return;
8736
8737 // Check the declarator is simple enough.
8738 bool FoundFunction = false;
8739 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8740 if (Chunk.Kind == DeclaratorChunk::Paren)
8741 continue;
8742 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8743 Diag(D.getDeclSpec().getBeginLoc(),
8744 diag::err_deduction_guide_with_complex_decl)
8745 << D.getSourceRange();
8746 break;
8747 }
8748 if (!Chunk.Fun.hasTrailingReturnType()) {
8749 Diag(D.getName().getBeginLoc(),
8750 diag::err_deduction_guide_no_trailing_return_type);
8751 break;
8752 }
8753
8754 // Check that the return type is written as a specialization of
8755 // the template specified as the deduction-guide's name.
8756 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8757 TypeSourceInfo *TSI = nullptr;
8758 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8759 assert(TSI && "deduction guide has valid type but invalid return type?")((TSI && "deduction guide has valid type but invalid return type?"
) ? static_cast<void> (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8759, __PRETTY_FUNCTION__))
;
8760 bool AcceptableReturnType = false;
8761 bool MightInstantiateToSpecialization = false;
8762 if (auto RetTST =
8763 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8764 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8765 bool TemplateMatches =
8766 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8767 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8768 AcceptableReturnType = true;
8769 else {
8770 // This could still instantiate to the right type, unless we know it
8771 // names the wrong class template.
8772 auto *TD = SpecifiedName.getAsTemplateDecl();
8773 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8774 !TemplateMatches);
8775 }
8776 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8777 MightInstantiateToSpecialization = true;
8778 }
8779
8780 if (!AcceptableReturnType) {
8781 Diag(TSI->getTypeLoc().getBeginLoc(),
8782 diag::err_deduction_guide_bad_trailing_return_type)
8783 << GuidedTemplate << TSI->getType()
8784 << MightInstantiateToSpecialization
8785 << TSI->getTypeLoc().getSourceRange();
8786 }
8787
8788 // Keep going to check that we don't have any inner declarator pieces (we
8789 // could still have a function returning a pointer to a function).
8790 FoundFunction = true;
8791 }
8792
8793 if (D.isFunctionDefinition())
8794 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8795}
8796
8797//===----------------------------------------------------------------------===//
8798// Namespace Handling
8799//===----------------------------------------------------------------------===//
8800
8801/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8802/// reopened.
8803static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8804 SourceLocation Loc,
8805 IdentifierInfo *II, bool *IsInline,
8806 NamespaceDecl *PrevNS) {
8807 assert(*IsInline != PrevNS->isInline())((*IsInline != PrevNS->isInline()) ? static_cast<void>
(0) : __assert_fail ("*IsInline != PrevNS->isInline()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8807, __PRETTY_FUNCTION__))
;
8808
8809 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8810 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8811 // inline namespaces, with the intention of bringing names into namespace std.
8812 //
8813 // We support this just well enough to get that case working; this is not
8814 // sufficient to support reopening namespaces as inline in general.
8815 if (*IsInline && II && II->getName().startswith("__atomic") &&
8816 S.getSourceManager().isInSystemHeader(Loc)) {
8817 // Mark all prior declarations of the namespace as inline.
8818 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8819 NS = NS->getPreviousDecl())
8820 NS->setInline(*IsInline);
8821 // Patch up the lookup table for the containing namespace. This isn't really
8822 // correct, but it's good enough for this particular case.
8823 for (auto *I : PrevNS->decls())
8824 if (auto *ND = dyn_cast<NamedDecl>(I))
8825 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8826 return;
8827 }
8828
8829 if (PrevNS->isInline())
8830 // The user probably just forgot the 'inline', so suggest that it
8831 // be added back.
8832 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8833 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8834 else
8835 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8836
8837 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8838 *IsInline = PrevNS->isInline();
8839}
8840
8841/// ActOnStartNamespaceDef - This is called at the start of a namespace
8842/// definition.
8843Decl *Sema::ActOnStartNamespaceDef(
8844 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8845 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8846 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8847 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8848 // For anonymous namespace, take the location of the left brace.
8849 SourceLocation Loc = II ? IdentLoc : LBrace;
8850 bool IsInline = InlineLoc.isValid();
8851 bool IsInvalid = false;
8852 bool IsStd = false;
8853 bool AddToKnown = false;
8854 Scope *DeclRegionScope = NamespcScope->getParent();
8855
8856 NamespaceDecl *PrevNS = nullptr;
8857 if (II) {
8858 // C++ [namespace.def]p2:
8859 // The identifier in an original-namespace-definition shall not
8860 // have been previously defined in the declarative region in
8861 // which the original-namespace-definition appears. The
8862 // identifier in an original-namespace-definition is the name of
8863 // the namespace. Subsequently in that declarative region, it is
8864 // treated as an original-namespace-name.
8865 //
8866 // Since namespace names are unique in their scope, and we don't
8867 // look through using directives, just look for any ordinary names
8868 // as if by qualified name lookup.
8869 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8870 ForExternalRedeclaration);
8871 LookupQualifiedName(R, CurContext->getRedeclContext());
8872 NamedDecl *PrevDecl =
8873 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8874 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8875
8876 if (PrevNS) {
8877 // This is an extended namespace definition.
8878 if (IsInline != PrevNS->isInline())
8879 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8880 &IsInline, PrevNS);
8881 } else if (PrevDecl) {
8882 // This is an invalid name redefinition.
8883 Diag(Loc, diag::err_redefinition_different_kind)
8884 << II;
8885 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8886 IsInvalid = true;
8887 // Continue on to push Namespc as current DeclContext and return it.
8888 } else if (II->isStr("std") &&
8889 CurContext->getRedeclContext()->isTranslationUnit()) {
8890 // This is the first "real" definition of the namespace "std", so update
8891 // our cache of the "std" namespace to point at this definition.
8892 PrevNS = getStdNamespace();
8893 IsStd = true;
8894 AddToKnown = !IsInline;
8895 } else {
8896 // We've seen this namespace for the first time.
8897 AddToKnown = !IsInline;
8898 }
8899 } else {
8900 // Anonymous namespaces.
8901
8902 // Determine whether the parent already has an anonymous namespace.
8903 DeclContext *Parent = CurContext->getRedeclContext();
8904 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8905 PrevNS = TU->getAnonymousNamespace();
8906 } else {
8907 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8908 PrevNS = ND->getAnonymousNamespace();
8909 }
8910
8911 if (PrevNS && IsInline != PrevNS->isInline())
8912 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8913 &IsInline, PrevNS);
8914 }
8915
8916 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8917 StartLoc, Loc, II, PrevNS);
8918 if (IsInvalid)
8919 Namespc->setInvalidDecl();
8920
8921 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8922 AddPragmaAttributes(DeclRegionScope, Namespc);
8923
8924 // FIXME: Should we be merging attributes?
8925 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8926 PushNamespaceVisibilityAttr(Attr, Loc);
8927
8928 if (IsStd)
8929 StdNamespace = Namespc;
8930 if (AddToKnown)
8931 KnownNamespaces[Namespc] = false;
8932
8933 if (II) {
8934 PushOnScopeChains(Namespc, DeclRegionScope);
8935 } else {
8936 // Link the anonymous namespace into its parent.
8937 DeclContext *Parent = CurContext->getRedeclContext();
8938 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8939 TU->setAnonymousNamespace(Namespc);
8940 } else {
8941 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8942 }
8943
8944 CurContext->addDecl(Namespc);
8945
8946 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8947 // behaves as if it were replaced by
8948 // namespace unique { /* empty body */ }
8949 // using namespace unique;
8950 // namespace unique { namespace-body }
8951 // where all occurrences of 'unique' in a translation unit are
8952 // replaced by the same identifier and this identifier differs
8953 // from all other identifiers in the entire program.
8954
8955 // We just create the namespace with an empty name and then add an
8956 // implicit using declaration, just like the standard suggests.
8957 //
8958 // CodeGen enforces the "universally unique" aspect by giving all
8959 // declarations semantically contained within an anonymous
8960 // namespace internal linkage.
8961
8962 if (!PrevNS) {
8963 UD = UsingDirectiveDecl::Create(Context, Parent,
8964 /* 'using' */ LBrace,
8965 /* 'namespace' */ SourceLocation(),
8966 /* qualifier */ NestedNameSpecifierLoc(),
8967 /* identifier */ SourceLocation(),
8968 Namespc,
8969 /* Ancestor */ Parent);
8970 UD->setImplicit();
8971 Parent->addDecl(UD);
8972 }
8973 }
8974
8975 ActOnDocumentableDecl(Namespc);
8976
8977 // Although we could have an invalid decl (i.e. the namespace name is a
8978 // redefinition), push it as current DeclContext and try to continue parsing.
8979 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8980 // for the namespace has the declarations that showed up in that particular
8981 // namespace definition.
8982 PushDeclContext(NamespcScope, Namespc);
8983 return Namespc;
8984}
8985
8986/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8987/// is a namespace alias, returns the namespace it points to.
8988static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8989 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8990 return AD->getNamespace();
8991 return dyn_cast_or_null<NamespaceDecl>(D);
8992}
8993
8994/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8995/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8996void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8997 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8998 assert(Namespc && "Invalid parameter, expected NamespaceDecl")((Namespc && "Invalid parameter, expected NamespaceDecl"
) ? static_cast<void> (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8998, __PRETTY_FUNCTION__))
;
8999 Namespc->setRBraceLoc(RBrace);
9000 PopDeclContext();
9001 if (Namespc->hasAttr<VisibilityAttr>())
9002 PopPragmaVisibility(true, RBrace);
9003 // If this namespace contains an export-declaration, export it now.
9004 if (DeferredExportedNamespaces.erase(Namespc))
9005 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9006}
9007
9008CXXRecordDecl *Sema::getStdBadAlloc() const {
9009 return cast_or_null<CXXRecordDecl>(
9010 StdBadAlloc.get(Context.getExternalSource()));
9011}
9012
9013EnumDecl *Sema::getStdAlignValT() const {
9014 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9015}
9016
9017NamespaceDecl *Sema::getStdNamespace() const {
9018 return cast_or_null<NamespaceDecl>(
9019 StdNamespace.get(Context.getExternalSource()));
9020}
9021
9022NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9023 if (!StdExperimentalNamespaceCache) {
9024 if (auto Std = getStdNamespace()) {
9025 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9026 SourceLocation(), LookupNamespaceName);
9027 if (!LookupQualifiedName(Result, Std) ||
9028 !(StdExperimentalNamespaceCache =
9029 Result.getAsSingle<NamespaceDecl>()))
9030 Result.suppressDiagnostics();
9031 }
9032 }
9033 return StdExperimentalNamespaceCache;
9034}
9035
9036namespace {
9037
9038enum UnsupportedSTLSelect {
9039 USS_InvalidMember,
9040 USS_MissingMember,
9041 USS_NonTrivial,
9042 USS_Other
9043};
9044
9045struct InvalidSTLDiagnoser {
9046 Sema &S;
9047 SourceLocation Loc;
9048 QualType TyForDiags;
9049
9050 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9051 const VarDecl *VD = nullptr) {
9052 {
9053 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9054 << TyForDiags << ((int)Sel);
9055 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9056 assert(!Name.empty())((!Name.empty()) ? static_cast<void> (0) : __assert_fail
("!Name.empty()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9056, __PRETTY_FUNCTION__))
;
9057 D << Name;
9058 }
9059 }
9060 if (Sel == USS_InvalidMember) {
9061 S.Diag(VD->getLocation(), diag::note_var_declared_here)
9062 << VD << VD->getSourceRange();
9063 }
9064 return QualType();
9065 }
9066};
9067} // namespace
9068
9069QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9070 SourceLocation Loc) {
9071 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9072, __PRETTY_FUNCTION__))
9072 "Looking for comparison category type outside of C++.")((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9072, __PRETTY_FUNCTION__))
;
9073
9074 // Check if we've already successfully checked the comparison category type
9075 // before. If so, skip checking it again.
9076 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9077 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9078 return Info->getType();
9079
9080 // If lookup failed
9081 if (!Info) {
9082 std::string NameForDiags = "std::";
9083 NameForDiags += ComparisonCategories::getCategoryString(Kind);
9084 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9085 << NameForDiags;
9086 return QualType();
9087 }
9088
9089 assert(Info->Kind == Kind)((Info->Kind == Kind) ? static_cast<void> (0) : __assert_fail
("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9089, __PRETTY_FUNCTION__))
;
9090 assert(Info->Record)((Info->Record) ? static_cast<void> (0) : __assert_fail
("Info->Record", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9090, __PRETTY_FUNCTION__))
;
9091
9092 // Update the Record decl in case we encountered a forward declaration on our
9093 // first pass. FIXME: This is a bit of a hack.
9094 if (Info->Record->hasDefinition())
9095 Info->Record = Info->Record->getDefinition();
9096
9097 // Use an elaborated type for diagnostics which has a name containing the
9098 // prepended 'std' namespace but not any inline namespace names.
9099 QualType TyForDiags = [&]() {
9100 auto *NNS =
9101 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9102 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9103 }();
9104
9105 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9106 return QualType();
9107
9108 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9109
9110 if (!Info->Record->isTriviallyCopyable())
9111 return UnsupportedSTLError(USS_NonTrivial);
9112
9113 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9114 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9115 // Tolerate empty base classes.
9116 if (Base->isEmpty())
9117 continue;
9118 // Reject STL implementations which have at least one non-empty base.
9119 return UnsupportedSTLError();
9120 }
9121
9122 // Check that the STL has implemented the types using a single integer field.
9123 // This expectation allows better codegen for builtin operators. We require:
9124 // (1) The class has exactly one field.
9125 // (2) The field is an integral or enumeration type.
9126 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9127 if (std::distance(FIt, FEnd) != 1 ||
9128 !FIt->getType()->isIntegralOrEnumerationType()) {
9129 return UnsupportedSTLError();
9130 }
9131
9132 // Build each of the require values and store them in Info.
9133 for (ComparisonCategoryResult CCR :
9134 ComparisonCategories::getPossibleResultsForType(Kind)) {
9135 StringRef MemName = ComparisonCategories::getResultString(CCR);
9136 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9137
9138 if (!ValInfo)
9139 return UnsupportedSTLError(USS_MissingMember, MemName);
9140
9141 VarDecl *VD = ValInfo->VD;
9142 assert(VD && "should not be null!")((VD && "should not be null!") ? static_cast<void>
(0) : __assert_fail ("VD && \"should not be null!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9142, __PRETTY_FUNCTION__))
;
9143
9144 // Attempt to diagnose reasons why the STL definition of this type
9145 // might be foobar, including it failing to be a constant expression.
9146 // TODO Handle more ways the lookup or result can be invalid.
9147 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9148 !VD->checkInitIsICE())
9149 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9150
9151 // Attempt to evaluate the var decl as a constant expression and extract
9152 // the value of its first field as a ICE. If this fails, the STL
9153 // implementation is not supported.
9154 if (!ValInfo->hasValidIntValue())
9155 return UnsupportedSTLError();
9156
9157 MarkVariableReferenced(Loc, VD);
9158 }
9159
9160 // We've successfully built the required types and expressions. Update
9161 // the cache and return the newly cached value.
9162 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9163 return Info->getType();
9164}
9165
9166/// Retrieve the special "std" namespace, which may require us to
9167/// implicitly define the namespace.
9168NamespaceDecl *Sema::getOrCreateStdNamespace() {
9169 if (!StdNamespace) {
9170 // The "std" namespace has not yet been defined, so build one implicitly.
9171 StdNamespace = NamespaceDecl::Create(Context,
9172 Context.getTranslationUnitDecl(),
9173 /*Inline=*/false,
9174 SourceLocation(), SourceLocation(),
9175 &PP.getIdentifierTable().get("std"),
9176 /*PrevDecl=*/nullptr);
9177 getStdNamespace()->setImplicit(true);
9178 }
9179
9180 return getStdNamespace();
9181}
9182
9183bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9184 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9185, __PRETTY_FUNCTION__))
9185 "Looking for std::initializer_list outside of C++.")((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9185, __PRETTY_FUNCTION__))
;
9186
9187 // We're looking for implicit instantiations of
9188 // template <typename E> class std::initializer_list.
9189
9190 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9191 return false;
9192
9193 ClassTemplateDecl *Template = nullptr;
9194 const TemplateArgument *Arguments = nullptr;
9195
9196 if (const RecordType *RT = Ty->getAs<RecordType>()) {
9197
9198 ClassTemplateSpecializationDecl *Specialization =
9199 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9200 if (!Specialization)
9201 return false;
9202
9203 Template = Specialization->getSpecializedTemplate();
9204 Arguments = Specialization->getTemplateArgs().data();
9205 } else if (const TemplateSpecializationType *TST =
9206 Ty->getAs<TemplateSpecializationType>()) {
9207 Template = dyn_cast_or_null<ClassTemplateDecl>(
9208 TST->getTemplateName().getAsTemplateDecl());
9209 Arguments = TST->getArgs();
9210 }
9211 if (!Template)
9212 return false;
9213
9214 if (!StdInitializerList) {
9215 // Haven't recognized std::initializer_list yet, maybe this is it.
9216 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9217 if (TemplateClass->getIdentifier() !=
9218 &PP.getIdentifierTable().get("initializer_list") ||
9219 !getStdNamespace()->InEnclosingNamespaceSetOf(
9220 TemplateClass->getDeclContext()))
9221 return false;
9222 // This is a template called std::initializer_list, but is it the right
9223 // template?
9224 TemplateParameterList *Params = Template->getTemplateParameters();
9225 if (Params->getMinRequiredArguments() != 1)
9226 return false;
9227 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9228 return false;
9229
9230 // It's the right template.
9231 StdInitializerList = Template;
9232 }
9233
9234 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9235 return false;
9236
9237 // This is an instance of std::initializer_list. Find the argument type.
9238 if (Element)
9239 *Element = Arguments[0].getAsType();
9240 return true;
9241}
9242
9243static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9244 NamespaceDecl *Std = S.getStdNamespace();
9245 if (!Std) {
9246 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9247 return nullptr;
9248 }
9249
9250 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9251 Loc, Sema::LookupOrdinaryName);
9252 if (!S.LookupQualifiedName(Result, Std)) {
9253 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9254 return nullptr;
9255 }
9256 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9257 if (!Template) {
9258 Result.suppressDiagnostics();
9259 // We found something weird. Complain about the first thing we found.
9260 NamedDecl *Found = *Result.begin();
9261 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9262 return nullptr;
9263 }
9264
9265 // We found some template called std::initializer_list. Now verify that it's
9266 // correct.
9267 TemplateParameterList *Params = Template->getTemplateParameters();
9268 if (Params->getMinRequiredArguments() != 1 ||
9269 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9270 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9271 return nullptr;
9272 }
9273
9274 return Template;
9275}
9276
9277QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9278 if (!StdInitializerList) {
9279 StdInitializerList = LookupStdInitializerList(*this, Loc);
9280 if (!StdInitializerList)
9281 return QualType();
9282 }
9283
9284 TemplateArgumentListInfo Args(Loc, Loc);
9285 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9286 Context.getTrivialTypeSourceInfo(Element,
9287 Loc)));
9288 return Context.getCanonicalType(
9289 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9290}
9291
9292bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9293 // C++ [dcl.init.list]p2:
9294 // A constructor is an initializer-list constructor if its first parameter
9295 // is of type std::initializer_list<E> or reference to possibly cv-qualified
9296 // std::initializer_list<E> for some type E, and either there are no other
9297 // parameters or else all other parameters have default arguments.
9298 if (Ctor->getNumParams() < 1 ||
9299 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9300 return false;
9301
9302 QualType ArgType = Ctor->getParamDecl(0)->getType();
9303 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9304 ArgType = RT->getPointeeType().getUnqualifiedType();
9305
9306 return isStdInitializerList(ArgType, nullptr);
9307}
9308
9309/// Determine whether a using statement is in a context where it will be
9310/// apply in all contexts.
9311static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9312 switch (CurContext->getDeclKind()) {
9313 case Decl::TranslationUnit:
9314 return true;
9315 case Decl::LinkageSpec:
9316 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9317 default:
9318 return false;
9319 }
9320}
9321
9322namespace {
9323
9324// Callback to only accept typo corrections that are namespaces.
9325class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9326public:
9327 bool ValidateCandidate(const TypoCorrection &candidate) override {
9328 if (NamedDecl *ND = candidate.getCorrectionDecl())
9329 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9330 return false;
9331 }
9332
9333 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9334 return llvm::make_unique<NamespaceValidatorCCC>(*this);
9335 }
9336};
9337
9338}
9339
9340static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9341 CXXScopeSpec &SS,
9342 SourceLocation IdentLoc,
9343 IdentifierInfo *Ident) {
9344 R.clear();
9345 NamespaceValidatorCCC CCC{};
9346 if (TypoCorrection Corrected =
9347 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9348 Sema::CTK_ErrorRecovery)) {
9349 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9350 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9351 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9352 Ident->getName().equals(CorrectedStr);
9353 S.diagnoseTypo(Corrected,
9354 S.PDiag(diag::err_using_directive_member_suggest)
9355 << Ident << DC << DroppedSpecifier << SS.getRange(),
9356 S.PDiag(diag::note_namespace_defined_here));
9357 } else {
9358 S.diagnoseTypo(Corrected,
9359 S.PDiag(diag::err_using_directive_suggest) << Ident,
9360 S.PDiag(diag::note_namespace_defined_here));
9361 }
9362 R.addDecl(Corrected.getFoundDecl());
9363 return true;
9364 }
9365 return false;
9366}
9367
9368Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9369 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9370 SourceLocation IdentLoc,
9371 IdentifierInfo *NamespcName,
9372 const ParsedAttributesView &AttrList) {
9373 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast
<void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9373, __PRETTY_FUNCTION__))
;
9374 assert(NamespcName && "Invalid NamespcName.")((NamespcName && "Invalid NamespcName.") ? static_cast
<void> (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9374, __PRETTY_FUNCTION__))
;
9375 assert(IdentLoc.isValid() && "Invalid NamespceName location.")((IdentLoc.isValid() && "Invalid NamespceName location."
) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9375, __PRETTY_FUNCTION__))
;
9376
9377 // This can only happen along a recovery path.
9378 while (S->isTemplateParamScope())
9379 S = S->getParent();
9380 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope."
) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9380, __PRETTY_FUNCTION__))
;
9381
9382 UsingDirectiveDecl *UDir = nullptr;
9383 NestedNameSpecifier *Qualifier = nullptr;
9384 if (SS.isSet())
9385 Qualifier = SS.getScopeRep();
9386
9387 // Lookup namespace name.
9388 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9389 LookupParsedName(R, S, &SS);
9390 if (R.isAmbiguous())
9391 return nullptr;
9392
9393 if (R.empty()) {
9394 R.clear();
9395 // Allow "using namespace std;" or "using namespace ::std;" even if
9396 // "std" hasn't been defined yet, for GCC compatibility.
9397 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9398 NamespcName->isStr("std")) {
9399 Diag(IdentLoc, diag::ext_using_undefined_std);
9400 R.addDecl(getOrCreateStdNamespace());
9401 R.resolveKind();
9402 }
9403 // Otherwise, attempt typo correction.
9404 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9405 }
9406
9407 if (!R.empty()) {
9408 NamedDecl *Named = R.getRepresentativeDecl();
9409 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9410 assert(NS && "expected namespace decl")((NS && "expected namespace decl") ? static_cast<void
> (0) : __assert_fail ("NS && \"expected namespace decl\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9410, __PRETTY_FUNCTION__))
;
9411
9412 // The use of a nested name specifier may trigger deprecation warnings.
9413 DiagnoseUseOfDecl(Named, IdentLoc);
9414
9415 // C++ [namespace.udir]p1:
9416 // A using-directive specifies that the names in the nominated
9417 // namespace can be used in the scope in which the
9418 // using-directive appears after the using-directive. During
9419 // unqualified name lookup (3.4.1), the names appear as if they
9420 // were declared in the nearest enclosing namespace which
9421 // contains both the using-directive and the nominated
9422 // namespace. [Note: in this context, "contains" means "contains
9423 // directly or indirectly". ]
9424
9425 // Find enclosing context containing both using-directive and
9426 // nominated namespace.
9427 DeclContext *CommonAncestor = NS;
9428 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9429 CommonAncestor = CommonAncestor->getParent();
9430
9431 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9432 SS.getWithLocInContext(Context),
9433 IdentLoc, Named, CommonAncestor);
9434
9435 if (IsUsingDirectiveInToplevelContext(CurContext) &&
9436 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9437 Diag(IdentLoc, diag::warn_using_directive_in_header);
9438 }
9439
9440 PushUsingDirective(S, UDir);
9441 } else {
9442 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9443 }
9444
9445 if (UDir)
9446 ProcessDeclAttributeList(S, UDir, AttrList);
9447
9448 return UDir;
9449}
9450
9451void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9452 // If the scope has an associated entity and the using directive is at
9453 // namespace or translation unit scope, add the UsingDirectiveDecl into
9454 // its lookup structure so qualified name lookup can find it.
9455 DeclContext *Ctx = S->getEntity();
9456 if (Ctx && !Ctx->isFunctionOrMethod())
9457 Ctx->addDecl(UDir);
9458 else
9459 // Otherwise, it is at block scope. The using-directives will affect lookup
9460 // only to the end of the scope.
9461 S->PushUsingDirective(UDir);
9462}
9463
9464Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9465 SourceLocation UsingLoc,
9466 SourceLocation TypenameLoc, CXXScopeSpec &SS,
9467 UnqualifiedId &Name,
9468 SourceLocation EllipsisLoc,
9469 const ParsedAttributesView &AttrList) {
9470 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope."
) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9470, __PRETTY_FUNCTION__))
;
9471
9472 if (SS.isEmpty()) {
9473 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9474 return nullptr;
9475 }
9476
9477 switch (Name.getKind()) {
9478 case UnqualifiedIdKind::IK_ImplicitSelfParam:
9479 case UnqualifiedIdKind::IK_Identifier:
9480 case UnqualifiedIdKind::IK_OperatorFunctionId:
9481 case UnqualifiedIdKind::IK_LiteralOperatorId:
9482 case UnqualifiedIdKind::IK_ConversionFunctionId:
9483 break;
9484
9485 case UnqualifiedIdKind::IK_ConstructorName:
9486 case UnqualifiedIdKind::IK_ConstructorTemplateId:
9487 // C++11 inheriting constructors.
9488 Diag(Name.getBeginLoc(),
9489 getLangOpts().CPlusPlus11
9490 ? diag::warn_cxx98_compat_using_decl_constructor
9491 : diag::err_using_decl_constructor)
9492 << SS.getRange();
9493
9494 if (getLangOpts().CPlusPlus11) break;
9495
9496 return nullptr;
9497
9498 case UnqualifiedIdKind::IK_DestructorName:
9499 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9500 return nullptr;
9501
9502 case UnqualifiedIdKind::IK_TemplateId:
9503 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9504 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9505 return nullptr;
9506
9507 case UnqualifiedIdKind::IK_DeductionGuideName:
9508 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9508)
;
9509 }
9510
9511 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9512 DeclarationName TargetName = TargetNameInfo.getName();
9513 if (!TargetName)
9514 return nullptr;
9515
9516 // Warn about access declarations.
9517 if (UsingLoc.isInvalid()) {
9518 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9519 ? diag::err_access_decl
9520 : diag::warn_access_decl_deprecated)
9521 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9522 }
9523
9524 if (EllipsisLoc.isInvalid()) {
9525 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9526 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9527 return nullptr;
9528 } else {
9529 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9530 !TargetNameInfo.containsUnexpandedParameterPack()) {
9531 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9532 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9533 EllipsisLoc = SourceLocation();
9534 }
9535 }
9536
9537 NamedDecl *UD =
9538 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9539 SS, TargetNameInfo, EllipsisLoc, AttrList,
9540 /*IsInstantiation*/false);
9541 if (UD)
9542 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9543
9544 return UD;
9545}
9546
9547/// Determine whether a using declaration considers the given
9548/// declarations as "equivalent", e.g., if they are redeclarations of
9549/// the same entity or are both typedefs of the same type.
9550static bool
9551IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9552 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9553 return true;
9554
9555 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9556 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9557 return Context.hasSameType(TD1->getUnderlyingType(),
9558 TD2->getUnderlyingType());
9559
9560 return false;
9561}
9562
9563
9564/// Determines whether to create a using shadow decl for a particular
9565/// decl, given the set of decls existing prior to this using lookup.
9566bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9567 const LookupResult &Previous,
9568 UsingShadowDecl *&PrevShadow) {
9569 // Diagnose finding a decl which is not from a base class of the
9570 // current class. We do this now because there are cases where this
9571 // function will silently decide not to build a shadow decl, which
9572 // will pre-empt further diagnostics.
9573 //
9574 // We don't need to do this in C++11 because we do the check once on
9575 // the qualifier.
9576 //
9577 // FIXME: diagnose the following if we care enough:
9578 // struct A { int foo; };
9579 // struct B : A { using A::foo; };
9580 // template <class T> struct C : A {};
9581 // template <class T> struct D : C<T> { using B::foo; } // <---
9582 // This is invalid (during instantiation) in C++03 because B::foo
9583 // resolves to the using decl in B, which is not a base class of D<T>.
9584 // We can't diagnose it immediately because C<T> is an unknown
9585 // specialization. The UsingShadowDecl in D<T> then points directly
9586 // to A::foo, which will look well-formed when we instantiate.
9587 // The right solution is to not collapse the shadow-decl chain.
9588 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9589 DeclContext *OrigDC = Orig->getDeclContext();
9590
9591 // Handle enums and anonymous structs.
9592 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9593 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9594 while (OrigRec->isAnonymousStructOrUnion())
9595 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9596
9597 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9598 if (OrigDC == CurContext) {
9599 Diag(Using->getLocation(),
9600 diag::err_using_decl_nested_name_specifier_is_current_class)
9601 << Using->getQualifierLoc().getSourceRange();
9602 Diag(Orig->getLocation(), diag::note_using_decl_target);
9603 Using->setInvalidDecl();
9604 return true;
9605 }
9606
9607 Diag(Using->getQualifierLoc().getBeginLoc(),
9608 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9609 << Using->getQualifier()
9610 << cast<CXXRecordDecl>(CurContext)
9611 << Using->getQualifierLoc().getSourceRange();
9612 Diag(Orig->getLocation(), diag::note_using_decl_target);
9613 Using->setInvalidDecl();
9614 return true;
9615 }
9616 }
9617
9618 if (Previous.empty()) return false;
9619
9620 NamedDecl *Target = Orig;
9621 if (isa<UsingShadowDecl>(Target))
9622 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9623
9624 // If the target happens to be one of the previous declarations, we
9625 // don't have a conflict.
9626 //
9627 // FIXME: but we might be increasing its access, in which case we
9628 // should redeclare it.
9629 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9630 bool FoundEquivalentDecl = false;
9631 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9632 I != E; ++I) {
9633 NamedDecl *D = (*I)->getUnderlyingDecl();
9634 // We can have UsingDecls in our Previous results because we use the same
9635 // LookupResult for checking whether the UsingDecl itself is a valid
9636 // redeclaration.
9637 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9638 continue;
9639
9640 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9641 // C++ [class.mem]p19:
9642 // If T is the name of a class, then [every named member other than
9643 // a non-static data member] shall have a name different from T
9644 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9645 !isa<IndirectFieldDecl>(Target) &&
9646 !isa<UnresolvedUsingValueDecl>(Target) &&
9647 DiagnoseClassNameShadow(
9648 CurContext,
9649 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9650 return true;
9651 }
9652
9653 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9654 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9655 PrevShadow = Shadow;
9656 FoundEquivalentDecl = true;
9657 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9658 // We don't conflict with an existing using shadow decl of an equivalent
9659 // declaration, but we're not a redeclaration of it.
9660 FoundEquivalentDecl = true;
9661 }
9662
9663 if (isVisible(D))
9664 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9665 }
9666
9667 if (FoundEquivalentDecl)
9668 return false;
9669
9670 if (FunctionDecl *FD = Target->getAsFunction()) {
9671 NamedDecl *OldDecl = nullptr;
9672 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9673 /*IsForUsingDecl*/ true)) {
9674 case Ovl_Overload:
9675 return false;
9676
9677 case Ovl_NonFunction:
9678 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9679 break;
9680
9681 // We found a decl with the exact signature.
9682 case Ovl_Match:
9683 // If we're in a record, we want to hide the target, so we
9684 // return true (without a diagnostic) to tell the caller not to
9685 // build a shadow decl.
9686 if (CurContext->isRecord())
9687 return true;
9688
9689 // If we're not in a record, this is an error.
9690 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9691 break;
9692 }
9693
9694 Diag(Target->getLocation(), diag::note_using_decl_target);
9695 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9696 Using->setInvalidDecl();
9697 return true;
9698 }
9699
9700 // Target is not a function.
9701
9702 if (isa<TagDecl>(Target)) {
9703 // No conflict between a tag and a non-tag.
9704 if (!Tag) return false;
9705
9706 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9707 Diag(Target->getLocation(), diag::note_using_decl_target);
9708 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9709 Using->setInvalidDecl();
9710 return true;
9711 }
9712
9713 // No conflict between a tag and a non-tag.
9714 if (!NonTag) return false;
9715
9716 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9717 Diag(Target->getLocation(), diag::note_using_decl_target);
9718 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9719 Using->setInvalidDecl();
9720 return true;
9721}
9722
9723/// Determine whether a direct base class is a virtual base class.
9724static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9725 if (!Derived->getNumVBases())
9726 return false;
9727 for (auto &B : Derived->bases())
9728 if (B.getType()->getAsCXXRecordDecl() == Base)
9729 return B.isVirtual();
9730 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9730)
;
9731}
9732
9733/// Builds a shadow declaration corresponding to a 'using' declaration.
9734UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9735 UsingDecl *UD,
9736 NamedDecl *Orig,
9737 UsingShadowDecl *PrevDecl) {
9738 // If we resolved to another shadow declaration, just coalesce them.
9739 NamedDecl *Target = Orig;
9740 if (isa<UsingShadowDecl>(Target)) {
9741 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9742 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")((!isa<UsingShadowDecl>(Target) && "nested shadow declaration"
) ? static_cast<void> (0) : __assert_fail ("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9742, __PRETTY_FUNCTION__))
;
9743 }
9744
9745 NamedDecl *NonTemplateTarget = Target;
9746 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9747 NonTemplateTarget = TargetTD->getTemplatedDecl();
9748
9749 UsingShadowDecl *Shadow;
9750 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9751 bool IsVirtualBase =
9752 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9753 UD->getQualifier()->getAsRecordDecl());
9754 Shadow = ConstructorUsingShadowDecl::Create(
9755 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9756 } else {
9757 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9758 Target);
9759 }
9760 UD->addShadowDecl(Shadow);
9761
9762 Shadow->setAccess(UD->getAccess());
9763 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9764 Shadow->setInvalidDecl();
9765
9766 Shadow->setPreviousDecl(PrevDecl);
9767
9768 if (S)
9769 PushOnScopeChains(Shadow, S);
9770 else
9771 CurContext->addDecl(Shadow);
9772
9773
9774 return Shadow;
9775}
9776
9777/// Hides a using shadow declaration. This is required by the current
9778/// using-decl implementation when a resolvable using declaration in a
9779/// class is followed by a declaration which would hide or override
9780/// one or more of the using decl's targets; for example:
9781///
9782/// struct Base { void foo(int); };
9783/// struct Derived : Base {
9784/// using Base::foo;
9785/// void foo(int);
9786/// };
9787///
9788/// The governing language is C++03 [namespace.udecl]p12:
9789///
9790/// When a using-declaration brings names from a base class into a
9791/// derived class scope, member functions in the derived class
9792/// override and/or hide member functions with the same name and
9793/// parameter types in a base class (rather than conflicting).
9794///
9795/// There are two ways to implement this:
9796/// (1) optimistically create shadow decls when they're not hidden
9797/// by existing declarations, or
9798/// (2) don't create any shadow decls (or at least don't make them
9799/// visible) until we've fully parsed/instantiated the class.
9800/// The problem with (1) is that we might have to retroactively remove
9801/// a shadow decl, which requires several O(n) operations because the
9802/// decl structures are (very reasonably) not designed for removal.
9803/// (2) avoids this but is very fiddly and phase-dependent.
9804void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9805 if (Shadow->getDeclName().getNameKind() ==
9806 DeclarationName::CXXConversionFunctionName)
9807 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9808
9809 // Remove it from the DeclContext...
9810 Shadow->getDeclContext()->removeDecl(Shadow);
9811
9812 // ...and the scope, if applicable...
9813 if (S) {
9814 S->RemoveDecl(Shadow);
9815 IdResolver.RemoveDecl(Shadow);
9816 }
9817
9818 // ...and the using decl.
9819 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9820
9821 // TODO: complain somehow if Shadow was used. It shouldn't
9822 // be possible for this to happen, because...?
9823}
9824
9825/// Find the base specifier for a base class with the given type.
9826static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9827 QualType DesiredBase,
9828 bool &AnyDependentBases) {
9829 // Check whether the named type is a direct base class.
9830 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9831 for (auto &Base : Derived->bases()) {
9832 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9833 if (CanonicalDesiredBase == BaseType)
9834 return &Base;
9835 if (BaseType->isDependentType())
9836 AnyDependentBases = true;
9837 }
9838 return nullptr;
9839}
9840
9841namespace {
9842class UsingValidatorCCC final : public CorrectionCandidateCallback {
9843public:
9844 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9845 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9846 : HasTypenameKeyword(HasTypenameKeyword),
9847 IsInstantiation(IsInstantiation), OldNNS(NNS),
9848 RequireMemberOf(RequireMemberOf) {}
9849
9850 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9851 NamedDecl *ND = Candidate.getCorrectionDecl();
9852
9853 // Keywords are not valid here.
9854 if (!ND || isa<NamespaceDecl>(ND))
9855 return false;
9856
9857 // Completely unqualified names are invalid for a 'using' declaration.
9858 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9859 return false;
9860
9861 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9862 // reject.
9863
9864 if (RequireMemberOf) {
9865 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9866 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9867 // No-one ever wants a using-declaration to name an injected-class-name
9868 // of a base class, unless they're declaring an inheriting constructor.
9869 ASTContext &Ctx = ND->getASTContext();
9870 if (!Ctx.getLangOpts().CPlusPlus11)
9871 return false;
9872 QualType FoundType = Ctx.getRecordType(FoundRecord);
9873
9874 // Check that the injected-class-name is named as a member of its own
9875 // type; we don't want to suggest 'using Derived::Base;', since that
9876 // means something else.
9877 NestedNameSpecifier *Specifier =
9878 Candidate.WillReplaceSpecifier()
9879 ? Candidate.getCorrectionSpecifier()
9880 : OldNNS;
9881 if (!Specifier->getAsType() ||
9882 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9883 return false;
9884
9885 // Check that this inheriting constructor declaration actually names a
9886 // direct base class of the current class.
9887 bool AnyDependentBases = false;
9888 if (!findDirectBaseWithType(RequireMemberOf,
9889 Ctx.getRecordType(FoundRecord),
9890 AnyDependentBases) &&
9891 !AnyDependentBases)
9892 return false;
9893 } else {
9894 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9895 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9896 return false;
9897
9898 // FIXME: Check that the base class member is accessible?
9899 }
9900 } else {
9901 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9902 if (FoundRecord && FoundRecord->isInjectedClassName())
9903 return false;
9904 }
9905
9906 if (isa<TypeDecl>(ND))
9907 return HasTypenameKeyword || !IsInstantiation;
9908
9909 return !HasTypenameKeyword;
9910 }
9911
9912 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9913 return llvm::make_unique<UsingValidatorCCC>(*this);
9914 }
9915
9916private:
9917 bool HasTypenameKeyword;
9918 bool IsInstantiation;
9919 NestedNameSpecifier *OldNNS;
9920 CXXRecordDecl *RequireMemberOf;
9921};
9922} // end anonymous namespace
9923
9924/// Builds a using declaration.
9925///
9926/// \param IsInstantiation - Whether this call arises from an
9927/// instantiation of an unresolved using declaration. We treat
9928/// the lookup differently for these declarations.
9929NamedDecl *Sema::BuildUsingDeclaration(
9930 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9931 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9932 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9933 const ParsedAttributesView &AttrList, bool IsInstantiation) {
9934 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast
<void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9934, __PRETTY_FUNCTION__))
;
9935 SourceLocation IdentLoc = NameInfo.getLoc();
9936 assert(IdentLoc.isValid() && "Invalid TargetName location.")((IdentLoc.isValid() && "Invalid TargetName location."
) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9936, __PRETTY_FUNCTION__))
;
9937
9938 // FIXME: We ignore attributes for now.
9939
9940 // For an inheriting constructor declaration, the name of the using
9941 // declaration is the name of a constructor in this class, not in the
9942 // base class.
9943 DeclarationNameInfo UsingName = NameInfo;
9944 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9945 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9946 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9947 Context.getCanonicalType(Context.getRecordType(RD))));
9948
9949 // Do the redeclaration lookup in the current scope.
9950 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9951 ForVisibleRedeclaration);
9952 Previous.setHideTags(false);
9953 if (S) {
9954 LookupName(Previous, S);
9955
9956 // It is really dumb that we have to do this.
9957 LookupResult::Filter F = Previous.makeFilter();
9958 while (F.hasNext()) {
9959 NamedDecl *D = F.next();
9960 if (!isDeclInScope(D, CurContext, S))
9961 F.erase();
9962 // If we found a local extern declaration that's not ordinarily visible,
9963 // and this declaration is being added to a non-block scope, ignore it.
9964 // We're only checking for scope conflicts here, not also for violations
9965 // of the linkage rules.
9966 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9967 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9968 F.erase();
9969 }
9970 F.done();
9971 } else {
9972 assert(IsInstantiation && "no scope in non-instantiation")((IsInstantiation && "no scope in non-instantiation")
? static_cast<void> (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9972, __PRETTY_FUNCTION__))
;
9973 if (CurContext->isRecord())
9974 LookupQualifiedName(Previous, CurContext);
9975 else {
9976 // No redeclaration check is needed here; in non-member contexts we
9977 // diagnosed all possible conflicts with other using-declarations when
9978 // building the template:
9979 //
9980 // For a dependent non-type using declaration, the only valid case is
9981 // if we instantiate to a single enumerator. We check for conflicts
9982 // between shadow declarations we introduce, and we check in the template
9983 // definition for conflicts between a non-type using declaration and any
9984 // other declaration, which together covers all cases.
9985 //
9986 // A dependent typename using declaration will never successfully
9987 // instantiate, since it will always name a class member, so we reject
9988 // that in the template definition.
9989 }
9990 }
9991
9992 // Check for invalid redeclarations.
9993 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9994 SS, IdentLoc, Previous))
9995 return nullptr;
9996
9997 // Check for bad qualifiers.
9998 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9999 IdentLoc))
10000 return nullptr;
10001
10002 DeclContext *LookupContext = computeDeclContext(SS);
10003 NamedDecl *D;
10004 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10005 if (!LookupContext || EllipsisLoc.isValid()) {
10006 if (HasTypenameKeyword) {
10007 // FIXME: not all declaration name kinds are legal here
10008 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10009 UsingLoc, TypenameLoc,
10010 QualifierLoc,
10011 IdentLoc, NameInfo.getName(),
10012 EllipsisLoc);
10013 } else {
10014 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10015 QualifierLoc, NameInfo, EllipsisLoc);
10016 }
10017 D->setAccess(AS);
10018 CurContext->addDecl(D);
10019 return D;
10020 }
10021
10022 auto Build = [&](bool Invalid) {
10023 UsingDecl *UD =
10024 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10025 UsingName, HasTypenameKeyword);
10026 UD->setAccess(AS);
10027 CurContext->addDecl(UD);
10028 UD->setInvalidDecl(Invalid);
10029 return UD;
10030 };
10031 auto BuildInvalid = [&]{ return Build(true); };
10032 auto BuildValid = [&]{ return Build(false); };
10033
10034 if (RequireCompleteDeclContext(SS, LookupContext))
10035 return BuildInvalid();
10036
10037 // Look up the target name.
10038 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10039
10040 // Unlike most lookups, we don't always want to hide tag
10041 // declarations: tag names are visible through the using declaration
10042 // even if hidden by ordinary names, *except* in a dependent context
10043 // where it's important for the sanity of two-phase lookup.
10044 if (!IsInstantiation)
10045 R.setHideTags(false);
10046
10047 // For the purposes of this lookup, we have a base object type
10048 // equal to that of the current context.
10049 if (CurContext->isRecord()) {
10050 R.setBaseObjectType(
10051 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10052 }
10053
10054 LookupQualifiedName(R, LookupContext);
10055
10056 // Try to correct typos if possible. If constructor name lookup finds no
10057 // results, that means the named class has no explicit constructors, and we
10058 // suppressed declaring implicit ones (probably because it's dependent or
10059 // invalid).
10060 if (R.empty() &&
10061 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10062 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10063 // it will believe that glibc provides a ::gets in cases where it does not,
10064 // and will try to pull it into namespace std with a using-declaration.
10065 // Just ignore the using-declaration in that case.
10066 auto *II = NameInfo.getName().getAsIdentifierInfo();
10067 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10068 CurContext->isStdNamespace() &&
10069 isa<TranslationUnitDecl>(LookupContext) &&
10070 getSourceManager().isInSystemHeader(UsingLoc))
10071 return nullptr;
10072 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10073 dyn_cast<CXXRecordDecl>(CurContext));
10074 if (TypoCorrection Corrected =
10075 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10076 CTK_ErrorRecovery)) {
10077 // We reject candidates where DroppedSpecifier == true, hence the
10078 // literal '0' below.
10079 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10080 << NameInfo.getName() << LookupContext << 0
10081 << SS.getRange());
10082
10083 // If we picked a correction with no attached Decl we can't do anything
10084 // useful with it, bail out.
10085 NamedDecl *ND = Corrected.getCorrectionDecl();
10086 if (!ND)
10087 return BuildInvalid();
10088
10089 // If we corrected to an inheriting constructor, handle it as one.
10090 auto *RD = dyn_cast<CXXRecordDecl>(ND);
10091 if (RD && RD->isInjectedClassName()) {
10092 // The parent of the injected class name is the class itself.
10093 RD = cast<CXXRecordDecl>(RD->getParent());
10094
10095 // Fix up the information we'll use to build the using declaration.
10096 if (Corrected.WillReplaceSpecifier()) {
10097 NestedNameSpecifierLocBuilder Builder;
10098 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10099 QualifierLoc.getSourceRange());
10100 QualifierLoc = Builder.getWithLocInContext(Context);
10101 }
10102
10103 // In this case, the name we introduce is the name of a derived class
10104 // constructor.
10105 auto *CurClass = cast<CXXRecordDecl>(CurContext);
10106 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10107 Context.getCanonicalType(Context.getRecordType(CurClass))));
10108 UsingName.setNamedTypeInfo(nullptr);
10109 for (auto *Ctor : LookupConstructors(RD))
10110 R.addDecl(Ctor);
10111 R.resolveKind();
10112 } else {
10113 // FIXME: Pick up all the declarations if we found an overloaded
10114 // function.
10115 UsingName.setName(ND->getDeclName());
10116 R.addDecl(ND);
10117 }
10118 } else {
10119 Diag(IdentLoc, diag::err_no_member)
10120 << NameInfo.getName() << LookupContext << SS.getRange();
10121 return BuildInvalid();
10122 }
10123 }
10124
10125 if (R.isAmbiguous())
10126 return BuildInvalid();
10127
10128 if (HasTypenameKeyword) {
10129 // If we asked for a typename and got a non-type decl, error out.
10130 if (!R.getAsSingle<TypeDecl>()) {
10131 Diag(IdentLoc, diag::err_using_typename_non_type);
10132 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10133 Diag((*I)->getUnderlyingDecl()->getLocation(),
10134 diag::note_using_decl_target);
10135 return BuildInvalid();
10136 }
10137 } else {
10138 // If we asked for a non-typename and we got a type, error out,
10139 // but only if this is an instantiation of an unresolved using
10140 // decl. Otherwise just silently find the type name.
10141 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10142 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10143 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10144 return BuildInvalid();
10145 }
10146 }
10147
10148 // C++14 [namespace.udecl]p6:
10149 // A using-declaration shall not name a namespace.
10150 if (R.getAsSingle<NamespaceDecl>()) {
10151 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10152 << SS.getRange();
10153 return BuildInvalid();
10154 }
10155
10156 // C++14 [namespace.udecl]p7:
10157 // A using-declaration shall not name a scoped enumerator.
10158 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10159 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10160 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10161 << SS.getRange();
10162 return BuildInvalid();
10163 }
10164 }
10165
10166 UsingDecl *UD = BuildValid();
10167
10168 // Some additional rules apply to inheriting constructors.
10169 if (UsingName.getName().getNameKind() ==
10170 DeclarationName::CXXConstructorName) {
10171 // Suppress access diagnostics; the access check is instead performed at the
10172 // point of use for an inheriting constructor.
10173 R.suppressDiagnostics();
10174 if (CheckInheritingConstructorUsingDecl(UD))
10175 return UD;
10176 }
10177
10178 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10179 UsingShadowDecl *PrevDecl = nullptr;
10180 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10181 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10182 }
10183
10184 return UD;
10185}
10186
10187NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10188 ArrayRef<NamedDecl *> Expansions) {
10189 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10191, __PRETTY_FUNCTION__))
10190 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10191, __PRETTY_FUNCTION__))
10191 isa<UsingPackDecl>(InstantiatedFrom))((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10191, __PRETTY_FUNCTION__))
;
10192
10193 auto *UPD =
10194 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10195 UPD->setAccess(InstantiatedFrom->getAccess());
10196 CurContext->addDecl(UPD);
10197 return UPD;
10198}
10199
10200/// Additional checks for a using declaration referring to a constructor name.
10201bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10202 assert(!UD->hasTypename() && "expecting a constructor name")((!UD->hasTypename() && "expecting a constructor name"
) ? static_cast<void> (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10202, __PRETTY_FUNCTION__))
;
10203
10204 const Type *SourceType = UD->getQualifier()->getAsType();
10205 assert(SourceType &&((SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10206, __PRETTY_FUNCTION__))
10206 "Using decl naming constructor doesn't have type in scope spec.")((SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10206, __PRETTY_FUNCTION__))
;
10207 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10208
10209 // Check whether the named type is a direct base class.
10210 bool AnyDependentBases = false;
10211 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10212 AnyDependentBases);
10213 if (!Base && !AnyDependentBases) {
10214 Diag(UD->getUsingLoc(),
10215 diag::err_using_decl_constructor_not_in_direct_base)
10216 << UD->getNameInfo().getSourceRange()
10217 << QualType(SourceType, 0) << TargetClass;
10218 UD->setInvalidDecl();
10219 return true;
10220 }
10221
10222 if (Base)
10223 Base->setInheritConstructors();
10224
10225 return false;
10226}
10227
10228/// Checks that the given using declaration is not an invalid
10229/// redeclaration. Note that this is checking only for the using decl
10230/// itself, not for any ill-formedness among the UsingShadowDecls.
10231bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10232 bool HasTypenameKeyword,
10233 const CXXScopeSpec &SS,
10234 SourceLocation NameLoc,
10235 const LookupResult &Prev) {
10236 NestedNameSpecifier *Qual = SS.getScopeRep();
10237
10238 // C++03 [namespace.udecl]p8:
10239 // C++0x [namespace.udecl]p10:
10240 // A using-declaration is a declaration and can therefore be used
10241 // repeatedly where (and only where) multiple declarations are
10242 // allowed.
10243 //
10244 // That's in non-member contexts.
10245 if (!CurContext->getRedeclContext()->isRecord()) {
10246 // A dependent qualifier outside a class can only ever resolve to an
10247 // enumeration type. Therefore it conflicts with any other non-type
10248 // declaration in the same scope.
10249 // FIXME: How should we check for dependent type-type conflicts at block
10250 // scope?
10251 if (Qual->isDependent() && !HasTypenameKeyword) {
10252 for (auto *D : Prev) {
10253 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10254 bool OldCouldBeEnumerator =
10255 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10256 Diag(NameLoc,
10257 OldCouldBeEnumerator ? diag::err_redefinition
10258 : diag::err_redefinition_different_kind)
10259 << Prev.getLookupName();
10260 Diag(D->getLocation(), diag::note_previous_definition);
10261 return true;
10262 }
10263 }
10264 }
10265 return false;
10266 }
10267
10268 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10269 NamedDecl *D = *I;
10270
10271 bool DTypename;
10272 NestedNameSpecifier *DQual;
10273 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10274 DTypename = UD->hasTypename();
10275 DQual = UD->getQualifier();
10276 } else if (UnresolvedUsingValueDecl *UD
10277 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10278 DTypename = false;
10279 DQual = UD->getQualifier();
10280 } else if (UnresolvedUsingTypenameDecl *UD
10281 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10282 DTypename = true;
10283 DQual = UD->getQualifier();
10284 } else continue;
10285
10286 // using decls differ if one says 'typename' and the other doesn't.
10287 // FIXME: non-dependent using decls?
10288 if (HasTypenameKeyword != DTypename) continue;
10289
10290 // using decls differ if they name different scopes (but note that
10291 // template instantiation can cause this check to trigger when it
10292 // didn't before instantiation).
10293 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10294 Context.getCanonicalNestedNameSpecifier(DQual))
10295 continue;
10296
10297 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10298 Diag(D->getLocation(), diag::note_using_decl) << 1;
10299 return true;
10300 }
10301
10302 return false;
10303}
10304
10305
10306/// Checks that the given nested-name qualifier used in a using decl
10307/// in the current context is appropriately related to the current
10308/// scope. If an error is found, diagnoses it and returns true.
10309bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10310 bool HasTypename,
10311 const CXXScopeSpec &SS,
10312 const DeclarationNameInfo &NameInfo,
10313 SourceLocation NameLoc) {
10314 DeclContext *NamedContext = computeDeclContext(SS);
10315
10316 if (!CurContext->isRecord()) {
10317 // C++03 [namespace.udecl]p3:
10318 // C++0x [namespace.udecl]p8:
10319 // A using-declaration for a class member shall be a member-declaration.
10320
10321 // If we weren't able to compute a valid scope, it might validly be a
10322 // dependent class scope or a dependent enumeration unscoped scope. If
10323 // we have a 'typename' keyword, the scope must resolve to a class type.
10324 if ((HasTypename && !NamedContext) ||
10325 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10326 auto *RD = NamedContext
10327 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10328 : nullptr;
10329 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10330 RD = nullptr;
10331
10332 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10333 << SS.getRange();
10334
10335 // If we have a complete, non-dependent source type, try to suggest a
10336 // way to get the same effect.
10337 if (!RD)
10338 return true;
10339
10340 // Find what this using-declaration was referring to.
10341 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10342 R.setHideTags(false);
10343 R.suppressDiagnostics();
10344 LookupQualifiedName(R, RD);
10345
10346 if (R.getAsSingle<TypeDecl>()) {
10347 if (getLangOpts().CPlusPlus11) {
10348 // Convert 'using X::Y;' to 'using Y = X::Y;'.
10349 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10350 << 0 // alias declaration
10351 << FixItHint::CreateInsertion(SS.getBeginLoc(),
10352 NameInfo.getName().getAsString() +
10353 " = ");
10354 } else {
10355 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10356 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10357 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10358 << 1 // typedef declaration
10359 << FixItHint::CreateReplacement(UsingLoc, "typedef")
10360 << FixItHint::CreateInsertion(
10361 InsertLoc, " " + NameInfo.getName().getAsString());
10362 }
10363 } else if (R.getAsSingle<VarDecl>()) {
10364 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10365 // repeating the type of the static data member here.
10366 FixItHint FixIt;
10367 if (getLangOpts().CPlusPlus11) {
10368 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10369 FixIt = FixItHint::CreateReplacement(
10370 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10371 }
10372
10373 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10374 << 2 // reference declaration
10375 << FixIt;
10376 } else if (R.getAsSingle<EnumConstantDecl>()) {
10377 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10378 // repeating the type of the enumeration here, and we can't do so if
10379 // the type is anonymous.
10380 FixItHint FixIt;
10381 if (getLangOpts().CPlusPlus11) {
10382 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10383 FixIt = FixItHint::CreateReplacement(
10384 UsingLoc,
10385 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10386 }
10387
10388 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10389 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10390 << FixIt;
10391 }
10392 return true;
10393 }
10394
10395 // Otherwise, this might be valid.
10396 return false;
10397 }
10398
10399 // The current scope is a record.
10400
10401 // If the named context is dependent, we can't decide much.
10402 if (!NamedContext) {
10403 // FIXME: in C++0x, we can diagnose if we can prove that the
10404 // nested-name-specifier does not refer to a base class, which is
10405 // still possible in some cases.
10406
10407 // Otherwise we have to conservatively report that things might be
10408 // okay.
10409 return false;
10410 }
10411
10412 if (!NamedContext->isRecord()) {
10413 // Ideally this would point at the last name in the specifier,
10414 // but we don't have that level of source info.
10415 Diag(SS.getRange().getBegin(),
10416 diag::err_using_decl_nested_name_specifier_is_not_class)
10417 << SS.getScopeRep() << SS.getRange();
10418 return true;
10419 }
10420
10421 if (!NamedContext->isDependentContext() &&
10422 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10423 return true;
10424
10425 if (getLangOpts().CPlusPlus11) {
10426 // C++11 [namespace.udecl]p3:
10427 // In a using-declaration used as a member-declaration, the
10428 // nested-name-specifier shall name a base class of the class
10429 // being defined.
10430
10431 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10432 cast<CXXRecordDecl>(NamedContext))) {
10433 if (CurContext == NamedContext) {
10434 Diag(NameLoc,
10435 diag::err_using_decl_nested_name_specifier_is_current_class)
10436 << SS.getRange();
10437 return true;
10438 }
10439
10440 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10441 Diag(SS.getRange().getBegin(),
10442 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10443 << SS.getScopeRep()
10444 << cast<CXXRecordDecl>(CurContext)
10445 << SS.getRange();
10446 }
10447 return true;
10448 }
10449
10450 return false;
10451 }
10452
10453 // C++03 [namespace.udecl]p4:
10454 // A using-declaration used as a member-declaration shall refer
10455 // to a member of a base class of the class being defined [etc.].
10456
10457 // Salient point: SS doesn't have to name a base class as long as
10458 // lookup only finds members from base classes. Therefore we can
10459 // diagnose here only if we can prove that that can't happen,
10460 // i.e. if the class hierarchies provably don't intersect.
10461
10462 // TODO: it would be nice if "definitely valid" results were cached
10463 // in the UsingDecl and UsingShadowDecl so that these checks didn't
10464 // need to be repeated.
10465
10466 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10467 auto Collect = [&Bases](const CXXRecordDecl *Base) {
10468 Bases.insert(Base);
10469 return true;
10470 };
10471
10472 // Collect all bases. Return false if we find a dependent base.
10473 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10474 return false;
10475
10476 // Returns true if the base is dependent or is one of the accumulated base
10477 // classes.
10478 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10479 return !Bases.count(Base);
10480 };
10481
10482 // Return false if the class has a dependent base or if it or one
10483 // of its bases is present in the base set of the current context.
10484 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10485 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10486 return false;
10487
10488 Diag(SS.getRange().getBegin(),
10489 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10490 << SS.getScopeRep()
10491 << cast<CXXRecordDecl>(CurContext)
10492 << SS.getRange();
10493
10494 return true;
10495}
10496
10497Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10498 MultiTemplateParamsArg TemplateParamLists,
10499 SourceLocation UsingLoc, UnqualifiedId &Name,
10500 const ParsedAttributesView &AttrList,
10501 TypeResult Type, Decl *DeclFromDeclSpec) {
10502 // Skip up to the relevant declaration scope.
10503 while (S->isTemplateParamScope())
10504 S = S->getParent();
10505 assert((S->getFlags() & Scope::DeclScope) &&(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope"
) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10506, __PRETTY_FUNCTION__))
10506 "got alias-declaration outside of declaration scope")(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope"
) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10506, __PRETTY_FUNCTION__))
;
10507
10508 if (Type.isInvalid())
10509 return nullptr;
10510
10511 bool Invalid = false;
10512 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10513 TypeSourceInfo *TInfo = nullptr;
10514 GetTypeFromParser(Type.get(), &TInfo);
10515
10516 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10517 return nullptr;
10518
10519 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10520 UPPC_DeclarationType)) {
10521 Invalid = true;
10522 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10523 TInfo->getTypeLoc().getBeginLoc());
10524 }
10525
10526 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10527 TemplateParamLists.size()
10528 ? forRedeclarationInCurContext()
10529 : ForVisibleRedeclaration);
10530 LookupName(Previous, S);
10531
10532 // Warn about shadowing the name of a template parameter.
10533 if (Previous.isSingleResult() &&
10534 Previous.getFoundDecl()->isTemplateParameter()) {
10535 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10536 Previous.clear();
10537 }
10538
10539 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10540, __PRETTY_FUNCTION__))
10540 "name in alias declaration must be an identifier")((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10540, __PRETTY_FUNCTION__))
;
10541 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10542 Name.StartLocation,
10543 Name.Identifier, TInfo);
10544
10545 NewTD->setAccess(AS);
10546
10547 if (Invalid)
10548 NewTD->setInvalidDecl();
10549
10550 ProcessDeclAttributeList(S, NewTD, AttrList);
10551 AddPragmaAttributes(S, NewTD);
10552
10553 CheckTypedefForVariablyModifiedType(S, NewTD);
10554 Invalid |= NewTD->isInvalidDecl();
10555
10556 bool Redeclaration = false;
10557
10558 NamedDecl *NewND;
10559 if (TemplateParamLists.size()) {
10560 TypeAliasTemplateDecl *OldDecl = nullptr;
10561 TemplateParameterList *OldTemplateParams = nullptr;
10562
10563 if (TemplateParamLists.size() != 1) {
10564 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10565 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10566 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10567 }
10568 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10569
10570 // Check that we can declare a template here.
10571 if (CheckTemplateDeclScope(S, TemplateParams))
10572 return nullptr;
10573
10574 // Only consider previous declarations in the same scope.
10575 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10576 /*ExplicitInstantiationOrSpecialization*/false);
10577 if (!Previous.empty()) {
10578 Redeclaration = true;
10579
10580 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10581 if (!OldDecl && !Invalid) {
10582 Diag(UsingLoc, diag::err_redefinition_different_kind)
10583 << Name.Identifier;
10584
10585 NamedDecl *OldD = Previous.getRepresentativeDecl();
10586 if (OldD->getLocation().isValid())
10587 Diag(OldD->getLocation(), diag::note_previous_definition);
10588
10589 Invalid = true;
10590 }
10591
10592 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10593 if (TemplateParameterListsAreEqual(TemplateParams,
10594 OldDecl->getTemplateParameters(),
10595 /*Complain=*/true,
10596 TPL_TemplateMatch))
10597 OldTemplateParams =
10598 OldDecl->getMostRecentDecl()->getTemplateParameters();
10599 else
10600 Invalid = true;
10601
10602 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10603 if (!Invalid &&
10604 !Context.hasSameType(OldTD->getUnderlyingType(),
10605 NewTD->getUnderlyingType())) {
10606 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10607 // but we can't reasonably accept it.
10608 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10609 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10610 if (OldTD->getLocation().isValid())
10611 Diag(OldTD->getLocation(), diag::note_previous_definition);
10612 Invalid = true;
10613 }
10614 }
10615 }
10616
10617 // Merge any previous default template arguments into our parameters,
10618 // and check the parameter list.
10619 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10620 TPC_TypeAliasTemplate))
10621 return nullptr;
10622
10623 TypeAliasTemplateDecl *NewDecl =
10624 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10625 Name.Identifier, TemplateParams,
10626 NewTD);
10627 NewTD->setDescribedAliasTemplate(NewDecl);
10628
10629 NewDecl->setAccess(AS);
10630
10631 if (Invalid)
10632 NewDecl->setInvalidDecl();
10633 else if (OldDecl) {
10634 NewDecl->setPreviousDecl(OldDecl);
10635 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10636 }
10637
10638 NewND = NewDecl;
10639 } else {
10640 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10641 setTagNameForLinkagePurposes(TD, NewTD);
10642 handleTagNumbering(TD, S);
10643 }
10644 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10645 NewND = NewTD;
10646 }
10647
10648 PushOnScopeChains(NewND, S);
10649 ActOnDocumentableDecl(NewND);
10650 return NewND;
10651}
10652
10653Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10654 SourceLocation AliasLoc,
10655 IdentifierInfo *Alias, CXXScopeSpec &SS,
10656 SourceLocation IdentLoc,
10657 IdentifierInfo *Ident) {
10658
10659 // Lookup the namespace name.
10660 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10661 LookupParsedName(R, S, &SS);
10662
10663 if (R.isAmbiguous())
10664 return nullptr;
10665
10666 if (R.empty()) {
10667 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10668 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10669 return nullptr;
10670 }
10671 }
10672 assert(!R.isAmbiguous() && !R.empty())((!R.isAmbiguous() && !R.empty()) ? static_cast<void
> (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10672, __PRETTY_FUNCTION__))
;
10673 NamedDecl *ND = R.getRepresentativeDecl();
10674
10675 // Check if we have a previous declaration with the same name.
10676 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10677 ForVisibleRedeclaration);
10678 LookupName(PrevR, S);
10679
10680 // Check we're not shadowing a template parameter.
10681 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10682 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10683 PrevR.clear();
10684 }
10685
10686 // Filter out any other lookup result from an enclosing scope.
10687 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10688 /*AllowInlineNamespace*/false);
10689
10690 // Find the previous declaration and check that we can redeclare it.
10691 NamespaceAliasDecl *Prev = nullptr;
10692 if (PrevR.isSingleResult()) {
10693 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10694 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10695 // We already have an alias with the same name that points to the same
10696 // namespace; check that it matches.
10697 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10698 Prev = AD;
10699 } else if (isVisible(PrevDecl)) {
10700 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10701 << Alias;
10702 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10703 << AD->getNamespace();
10704 return nullptr;
10705 }
10706 } else if (isVisible(PrevDecl)) {
10707 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10708 ? diag::err_redefinition
10709 : diag::err_redefinition_different_kind;
10710 Diag(AliasLoc, DiagID) << Alias;
10711 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10712 return nullptr;
10713 }
10714 }
10715
10716 // The use of a nested name specifier may trigger deprecation warnings.
10717 DiagnoseUseOfDecl(ND, IdentLoc);
10718
10719 NamespaceAliasDecl *AliasDecl =
10720 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10721 Alias, SS.getWithLocInContext(Context),
10722 IdentLoc, ND);
10723 if (Prev)
10724 AliasDecl->setPreviousDecl(Prev);
10725
10726 PushOnScopeChains(AliasDecl, S);
10727 return AliasDecl;
10728}
10729
10730namespace {
10731struct SpecialMemberExceptionSpecInfo
10732 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10733 SourceLocation Loc;
10734 Sema::ImplicitExceptionSpecification ExceptSpec;
10735
10736 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10737 Sema::CXXSpecialMember CSM,
10738 Sema::InheritedConstructorInfo *ICI,
10739 SourceLocation Loc)
10740 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10741
10742 bool visitBase(CXXBaseSpecifier *Base);
10743 bool visitField(FieldDecl *FD);
10744
10745 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10746 unsigned Quals);
10747
10748 void visitSubobjectCall(Subobject Subobj,
10749 Sema::SpecialMemberOverloadResult SMOR);
10750};
10751}
10752
10753bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10754 auto *RT = Base->getType()->getAs<RecordType>();
10755 if (!RT)
10756 return false;
10757
10758 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10759 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10760 if (auto *BaseCtor = SMOR.getMethod()) {
10761 visitSubobjectCall(Base, BaseCtor);
10762 return false;
10763 }
10764
10765 visitClassSubobject(BaseClass, Base, 0);
10766 return false;
10767}
10768
10769bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10770 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10771 Expr *E = FD->getInClassInitializer();
10772 if (!E)
10773 // FIXME: It's a little wasteful to build and throw away a
10774 // CXXDefaultInitExpr here.
10775 // FIXME: We should have a single context note pointing at Loc, and
10776 // this location should be MD->getLocation() instead, since that's
10777 // the location where we actually use the default init expression.
10778 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10779 if (E)
10780 ExceptSpec.CalledExpr(E);
10781 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10782 ->getAs<RecordType>()) {
10783 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10784 FD->getType().getCVRQualifiers());
10785 }
10786 return false;
10787}
10788
10789void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10790 Subobject Subobj,
10791 unsigned Quals) {
10792 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10793 bool IsMutable = Field && Field->isMutable();
10794 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10795}
10796
10797void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10798 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10799 // Note, if lookup fails, it doesn't matter what exception specification we
10800 // choose because the special member will be deleted.
10801 if (CXXMethodDecl *MD = SMOR.getMethod())
10802 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10803}
10804
10805namespace {
10806/// RAII object to register a special member as being currently declared.
10807struct ComputingExceptionSpec {
10808 Sema &S;
10809
10810 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10811 : S(S) {
10812 Sema::CodeSynthesisContext Ctx;
10813 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10814 Ctx.PointOfInstantiation = Loc;
10815 Ctx.Entity = MD;
10816 S.pushCodeSynthesisContext(Ctx);
Passed-by-value struct argument contains uninitialized data (e.g., field: 'SavedInNonInstantiationSFINAEContext')
10817 }
10818 ~ComputingExceptionSpec() {
10819 S.popCodeSynthesisContext();
10820 }
10821};
10822}
10823
10824bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
10825 llvm::APSInt Result;
10826 ExprResult Converted = CheckConvertedConstantExpression(
10827 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
10828 ExplicitSpec.setExpr(Converted.get());
10829 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
10830 ExplicitSpec.setKind(Result.getBoolValue()
10831 ? ExplicitSpecKind::ResolvedTrue
10832 : ExplicitSpecKind::ResolvedFalse);
10833 return true;
10834 }
10835 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
10836 return false;
10837}
10838
10839ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
10840 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
10841 if (!ExplicitExpr->isTypeDependent())
10842 tryResolveExplicitSpecifier(ES);
10843 return ES;
10844}
10845
10846static Sema::ImplicitExceptionSpecification
10847ComputeDefaultedSpecialMemberExceptionSpec(
10848 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10849 Sema::InheritedConstructorInfo *ICI) {
10850 ComputingExceptionSpec CES(S, MD, Loc);
10851
10852 CXXRecordDecl *ClassDecl = MD->getParent();
10853
10854 // C++ [except.spec]p14:
10855 // An implicitly declared special member function (Clause 12) shall have an
10856 // exception-specification. [...]
10857 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10858 if (ClassDecl->isInvalidDecl())
10859 return Info.ExceptSpec;
10860
10861 // FIXME: If this diagnostic fires, we're probably missing a check for
10862 // attempting to resolve an exception specification before it's known
10863 // at a higher level.
10864 if (S.RequireCompleteType(MD->getLocation(),
10865 S.Context.getRecordType(ClassDecl),
10866 diag::err_exception_spec_incomplete_type))
10867 return Info.ExceptSpec;
10868
10869 // C++1z [except.spec]p7:
10870 // [Look for exceptions thrown by] a constructor selected [...] to
10871 // initialize a potentially constructed subobject,
10872 // C++1z [except.spec]p8:
10873 // The exception specification for an implicitly-declared destructor, or a
10874 // destructor without a noexcept-specifier, is potentially-throwing if and
10875 // only if any of the destructors for any of its potentially constructed
10876 // subojects is potentially throwing.
10877 // FIXME: We respect the first rule but ignore the "potentially constructed"
10878 // in the second rule to resolve a core issue (no number yet) that would have
10879 // us reject:
10880 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10881 // struct B : A {};
10882 // struct C : B { void f(); };
10883 // ... due to giving B::~B() a non-throwing exception specification.
10884 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10885 : Info.VisitAllBases);
10886
10887 return Info.ExceptSpec;
10888}
10889
10890namespace {
10891/// RAII object to register a special member as being currently declared.
10892struct DeclaringSpecialMember {
10893 Sema &S;
10894 Sema::SpecialMemberDecl D;
10895 Sema::ContextRAII SavedContext;
10896 bool WasAlreadyBeingDeclared;
10897
10898 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10899 : S(S), D(RD, CSM), SavedContext(S, RD) {
10900 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10901 if (WasAlreadyBeingDeclared)
10902 // This almost never happens, but if it does, ensure that our cache
10903 // doesn't contain a stale result.
10904 S.SpecialMemberCache.clear();
10905 else {
10906 // Register a note to be produced if we encounter an error while
10907 // declaring the special member.
10908 Sema::CodeSynthesisContext Ctx;
10909 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10910 // FIXME: We don't have a location to use here. Using the class's
10911 // location maintains the fiction that we declare all special members
10912 // with the class, but (1) it's not clear that lying about that helps our
10913 // users understand what's going on, and (2) there may be outer contexts
10914 // on the stack (some of which are relevant) and printing them exposes
10915 // our lies.
10916 Ctx.PointOfInstantiation = RD->getLocation();
10917 Ctx.Entity = RD;
10918 Ctx.SpecialMember = CSM;
10919 S.pushCodeSynthesisContext(Ctx);
10920 }
10921 }
10922 ~DeclaringSpecialMember() {
10923 if (!WasAlreadyBeingDeclared) {
10924 S.SpecialMembersBeingDeclared.erase(D);
10925 S.popCodeSynthesisContext();
10926 }
10927 }
10928
10929 /// Are we already trying to declare this special member?
10930 bool isAlreadyBeingDeclared() const {
10931 return WasAlreadyBeingDeclared;
10932 }
10933};
10934}
10935
10936void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10937 // Look up any existing declarations, but don't trigger declaration of all
10938 // implicit special members with this name.
10939 DeclarationName Name = FD->getDeclName();
10940 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10941 ForExternalRedeclaration);
10942 for (auto *D : FD->getParent()->lookup(Name))
10943 if (auto *Acceptable = R.getAcceptableDecl(D))
10944 R.addDecl(Acceptable);
10945 R.resolveKind();
10946 R.suppressDiagnostics();
10947
10948 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10949}
10950
10951void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10952 QualType ResultTy,
10953 ArrayRef<QualType> Args) {
10954 // Build an exception specification pointing back at this constructor.
10955 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10956
10957 if (getLangOpts().OpenCLCPlusPlus) {
10958 // OpenCL: Implicitly defaulted special member are of the generic address
10959 // space.
10960 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
10961 }
10962
10963 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10964 SpecialMem->setType(QT);
10965}
10966
10967CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10968 CXXRecordDecl *ClassDecl) {
10969 // C++ [class.ctor]p5:
10970 // A default constructor for a class X is a constructor of class X
10971 // that can be called without an argument. If there is no
10972 // user-declared constructor for class X, a default constructor is
10973 // implicitly declared. An implicitly-declared default constructor
10974 // is an inline public member of its class.
10975 assert(ClassDecl->needsImplicitDefaultConstructor() &&((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10976, __PRETTY_FUNCTION__))
10976 "Should not build implicit default constructor!")((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10976, __PRETTY_FUNCTION__))
;
10977
10978 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10979 if (DSM.isAlreadyBeingDeclared())
10980 return nullptr;
10981
10982 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10983 CXXDefaultConstructor,
10984 false);
10985
10986 // Create the actual constructor declaration.
10987 CanQualType ClassType
10988 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10989 SourceLocation ClassLoc = ClassDecl->getLocation();
10990 DeclarationName Name
10991 = Context.DeclarationNames.getCXXConstructorName(ClassType);
10992 DeclarationNameInfo NameInfo(Name, ClassLoc);
10993 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10994 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
10995 /*TInfo=*/nullptr, ExplicitSpecifier(),
10996 /*isInline=*/true, /*isImplicitlyDeclared=*/true, Constexpr);
10997 DefaultCon->setAccess(AS_public);
10998 DefaultCon->setDefaulted();
10999
11000 if (getLangOpts().CUDA) {
11001 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11002 DefaultCon,
11003 /* ConstRHS */ false,
11004 /* Diagnose */ false);
11005 }
11006
11007 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11008
11009 // We don't need to use SpecialMemberIsTrivial here; triviality for default
11010 // constructors is easy to compute.
11011 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11012
11013 // Note that we have declared this constructor.
11014 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11015
11016 Scope *S = getScopeForContext(ClassDecl);
11017 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11018
11019 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11020 SetDeclDeleted(DefaultCon, ClassLoc);
11021
11022 if (S)
11023 PushOnScopeChains(DefaultCon, S, false);
11024 ClassDecl->addDecl(DefaultCon);
11025
11026 return DefaultCon;
11027}
11028
11029void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11030 CXXConstructorDecl *Constructor) {
11031 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11034, __PRETTY_FUNCTION__))
11032 !Constructor->doesThisDeclarationHaveABody() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11034, __PRETTY_FUNCTION__))
11033 !Constructor->isDeleted()) &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11034, __PRETTY_FUNCTION__))
11034 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11034, __PRETTY_FUNCTION__))
;
11035 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11036 return;
11037
11038 CXXRecordDecl *ClassDecl = Constructor->getParent();
11039 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")((ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11039, __PRETTY_FUNCTION__))
;
11040
11041 SynthesizedFunctionScope Scope(*this, Constructor);
11042
11043 // The exception specification is needed because we are defining the
11044 // function.
11045 ResolveExceptionSpec(CurrentLocation,
11046 Constructor->getType()->castAs<FunctionProtoType>());
11047 MarkVTableUsed(CurrentLocation, ClassDecl);
11048
11049 // Add a context note for diagnostics produced after this point.
11050 Scope.addContextNote(CurrentLocation);
11051
11052 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11053 Constructor->setInvalidDecl();
11054 return;
11055 }
11056
11057 SourceLocation Loc = Constructor->getEndLoc().isValid()
11058 ? Constructor->getEndLoc()
11059 : Constructor->getLocation();
11060 Constructor->setBody(new (Context) CompoundStmt(Loc));
11061 Constructor->markUsed(Context);
11062
11063 if (ASTMutationListener *L = getASTMutationListener()) {
11064 L->CompletedImplicitDefinition(Constructor);
11065 }
11066
11067 DiagnoseUninitializedFields(*this, Constructor);
11068}
11069
11070void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11071 // Perform any delayed checks on exception specifications.
11072 CheckDelayedMemberExceptionSpecs();
11073}
11074
11075/// Find or create the fake constructor we synthesize to model constructing an
11076/// object of a derived class via a constructor of a base class.
11077CXXConstructorDecl *
11078Sema::findInheritingConstructor(SourceLocation Loc,
11079 CXXConstructorDecl *BaseCtor,
11080 ConstructorUsingShadowDecl *Shadow) {
11081 CXXRecordDecl *Derived = Shadow->getParent();
11082 SourceLocation UsingLoc = Shadow->getLocation();
11083
11084 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11085 // For now we use the name of the base class constructor as a member of the
11086 // derived class to indicate a (fake) inherited constructor name.
11087 DeclarationName Name = BaseCtor->getDeclName();
11088
11089 // Check to see if we already have a fake constructor for this inherited
11090 // constructor call.
11091 for (NamedDecl *Ctor : Derived->lookup(Name))
11092 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11093 ->getInheritedConstructor()
11094 .getConstructor(),
11095 BaseCtor))
11096 return cast<CXXConstructorDecl>(Ctor);
11097
11098 DeclarationNameInfo NameInfo(Name, UsingLoc);
11099 TypeSourceInfo *TInfo =
11100 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11101 FunctionProtoTypeLoc ProtoLoc =
11102 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11103
11104 // Check the inherited constructor is valid and find the list of base classes
11105 // from which it was inherited.
11106 InheritedConstructorInfo ICI(*this, Loc, Shadow);
11107
11108 bool Constexpr =
11109 BaseCtor->isConstexpr() &&
11110 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11111 false, BaseCtor, &ICI);
11112
11113 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11114 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11115 BaseCtor->getExplicitSpecifier(), /*Inline=*/true,
11116 /*ImplicitlyDeclared=*/true, Constexpr,
11117 InheritedConstructor(Shadow, BaseCtor));
11118 if (Shadow->isInvalidDecl())
11119 DerivedCtor->setInvalidDecl();
11120
11121 // Build an unevaluated exception specification for this fake constructor.
11122 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11123 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11124 EPI.ExceptionSpec.Type = EST_Unevaluated;
11125 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11126 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11127 FPT->getParamTypes(), EPI));
11128
11129 // Build the parameter declarations.
11130 SmallVector<ParmVarDecl *, 16> ParamDecls;
11131 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11132 TypeSourceInfo *TInfo =
11133 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11134 ParmVarDecl *PD = ParmVarDecl::Create(
11135 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11136 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11137 PD->setScopeInfo(0, I);
11138 PD->setImplicit();
11139 // Ensure attributes are propagated onto parameters (this matters for
11140 // format, pass_object_size, ...).
11141 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11142 ParamDecls.push_back(PD);
11143 ProtoLoc.setParam(I, PD);
11144 }
11145
11146 // Set up the new constructor.
11147 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")((!BaseCtor->isDeleted() && "should not use deleted constructor"
) ? static_cast<void> (0) : __assert_fail ("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11147, __PRETTY_FUNCTION__))
;
11148 DerivedCtor->setAccess(BaseCtor->getAccess());
11149 DerivedCtor->setParams(ParamDecls);
11150 Derived->addDecl(DerivedCtor);
11151
11152 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11153 SetDeclDeleted(DerivedCtor, UsingLoc);
11154
11155 return DerivedCtor;
11156}
11157
11158void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11159 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11160 Ctor->getInheritedConstructor().getShadowDecl());
11161 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11162 /*Diagnose*/true);
11163}
11164
11165void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11166 CXXConstructorDecl *Constructor) {
11167 CXXRecordDecl *ClassDecl = Constructor->getParent();
11168 assert(Constructor->getInheritedConstructor() &&((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11170, __PRETTY_FUNCTION__))
11169 !Constructor->doesThisDeclarationHaveABody() &&((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11170, __PRETTY_FUNCTION__))
11170 !Constructor->isDeleted())((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11170, __PRETTY_FUNCTION__))
;
11171 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11172 return;
11173
11174 // Initializations are performed "as if by a defaulted default constructor",
11175 // so enter the appropriate scope.
11176 SynthesizedFunctionScope Scope(*this, Constructor);
11177
11178 // The exception specification is needed because we are defining the
11179 // function.
11180 ResolveExceptionSpec(CurrentLocation,
11181 Constructor->getType()->castAs<FunctionProtoType>());
11182 MarkVTableUsed(CurrentLocation, ClassDecl);
11183
11184 // Add a context note for diagnostics produced after this point.
11185 Scope.addContextNote(CurrentLocation);
11186
11187 ConstructorUsingShadowDecl *Shadow =
11188 Constructor->getInheritedConstructor().getShadowDecl();
11189 CXXConstructorDecl *InheritedCtor =
11190 Constructor->getInheritedConstructor().getConstructor();
11191
11192 // [class.inhctor.init]p1:
11193 // initialization proceeds as if a defaulted default constructor is used to
11194 // initialize the D object and each base class subobject from which the
11195 // constructor was inherited
11196
11197 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11198 CXXRecordDecl *RD = Shadow->getParent();
11199 SourceLocation InitLoc = Shadow->getLocation();
11200
11201 // Build explicit initializers for all base classes from which the
11202 // constructor was inherited.
11203 SmallVector<CXXCtorInitializer*, 8> Inits;
11204 for (bool VBase : {false, true}) {
11205 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11206 if (B.isVirtual() != VBase)
11207 continue;
11208
11209 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11210 if (!BaseRD)
11211 continue;
11212
11213 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11214 if (!BaseCtor.first)
11215 continue;
11216
11217 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11218 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11219 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11220
11221 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11222 Inits.push_back(new (Context) CXXCtorInitializer(
11223 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11224 SourceLocation()));
11225 }
11226 }
11227
11228 // We now proceed as if for a defaulted default constructor, with the relevant
11229 // initializers replaced.
11230
11231 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11232 Constructor->setInvalidDecl();
11233 return;
11234 }
11235
11236 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11237 Constructor->markUsed(Context);
11238
11239 if (ASTMutationListener *L = getASTMutationListener()) {
11240 L->CompletedImplicitDefinition(Constructor);
11241 }
11242
11243 DiagnoseUninitializedFields(*this, Constructor);
11244}
11245
11246CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11247 // C++ [class.dtor]p2:
11248 // If a class has no user-declared destructor, a destructor is
11249 // declared implicitly. An implicitly-declared destructor is an
11250 // inline public member of its class.
11251 assert(ClassDecl->needsImplicitDestructor())((ClassDecl->needsImplicitDestructor()) ? static_cast<void
> (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11251, __PRETTY_FUNCTION__))
;
11252
11253 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11254 if (DSM.isAlreadyBeingDeclared())
11255 return nullptr;
11256
11257 // Create the actual destructor declaration.
11258 CanQualType ClassType
11259 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11260 SourceLocation ClassLoc = ClassDecl->getLocation();
11261 DeclarationName Name
11262 = Context.DeclarationNames.getCXXDestructorName(ClassType);
11263 DeclarationNameInfo NameInfo(Name, ClassLoc);
11264 CXXDestructorDecl *Destructor
11265 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11266 QualType(), nullptr, /*isInline=*/true,
11267 /*isImplicitlyDeclared=*/true);
11268 Destructor->setAccess(AS_public);
11269 Destructor->setDefaulted();
11270
11271 if (getLangOpts().CUDA) {
11272 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11273 Destructor,
11274 /* ConstRHS */ false,
11275 /* Diagnose */ false);
11276 }
11277
11278 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11279
11280 // We don't need to use SpecialMemberIsTrivial here; triviality for
11281 // destructors is easy to compute.
11282 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11283 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11284 ClassDecl->hasTrivialDestructorForCall());
11285
11286 // Note that we have declared this destructor.
11287 ++getASTContext().NumImplicitDestructorsDeclared;
11288
11289 Scope *S = getScopeForContext(ClassDecl);
11290 CheckImplicitSpecialMemberDeclaration(S, Destructor);
11291
11292 // We can't check whether an implicit destructor is deleted before we complete
11293 // the definition of the class, because its validity depends on the alignment
11294 // of the class. We'll check this from ActOnFields once the class is complete.
11295 if (ClassDecl->isCompleteDefinition() &&
11296 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11297 SetDeclDeleted(Destructor, ClassLoc);
11298
11299 // Introduce this destructor into its scope.
11300 if (S)
11301 PushOnScopeChains(Destructor, S, false);
11302 ClassDecl->addDecl(Destructor);
11303
11304 return Destructor;
11305}
11306
11307void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11308 CXXDestructorDecl *Destructor) {
11309 assert((Destructor->isDefaulted() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11312, __PRETTY_FUNCTION__))
11310 !Destructor->doesThisDeclarationHaveABody() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11312, __PRETTY_FUNCTION__))
11311 !Destructor->isDeleted()) &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11312, __PRETTY_FUNCTION__))
11312 "DefineImplicitDestructor - call it for implicit default dtor")(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11312, __PRETTY_FUNCTION__))
;
11313 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11314 return;
11315
11316 CXXRecordDecl *ClassDecl = Destructor->getParent();
11317 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")((ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11317, __PRETTY_FUNCTION__))
;
11318
11319 SynthesizedFunctionScope Scope(*this, Destructor);
11320
11321 // The exception specification is needed because we are defining the
11322 // function.
11323 ResolveExceptionSpec(CurrentLocation,
11324 Destructor->getType()->castAs<FunctionProtoType>());
11325 MarkVTableUsed(CurrentLocation, ClassDecl);
11326
11327 // Add a context note for diagnostics produced after this point.
11328 Scope.addContextNote(CurrentLocation);
11329
11330 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11331 Destructor->getParent());
11332
11333 if (CheckDestructor(Destructor)) {
11334 Destructor->setInvalidDecl();
11335 return;
11336 }
11337
11338 SourceLocation Loc = Destructor->getEndLoc().isValid()
11339 ? Destructor->getEndLoc()
11340 : Destructor->getLocation();
11341 Destructor->setBody(new (Context) CompoundStmt(Loc));
11342 Destructor->markUsed(Context);
11343
11344 if (ASTMutationListener *L = getASTMutationListener()) {
11345 L->CompletedImplicitDefinition(Destructor);
11346 }
11347}
11348
11349/// Perform any semantic analysis which needs to be delayed until all
11350/// pending class member declarations have been parsed.
11351void Sema::ActOnFinishCXXMemberDecls() {
11352 // If the context is an invalid C++ class, just suppress these checks.
11353 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11354 if (Record->isInvalidDecl()) {
11355 DelayedOverridingExceptionSpecChecks.clear();
11356 DelayedEquivalentExceptionSpecChecks.clear();
11357 return;
11358 }
11359 checkForMultipleExportedDefaultConstructors(*this, Record);
11360 }
11361}
11362
11363void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11364 referenceDLLExportedClassMethods();
11365}
11366
11367void Sema::referenceDLLExportedClassMethods() {
11368 if (!DelayedDllExportClasses.empty()) {
11369 // Calling ReferenceDllExportedMembers might cause the current function to
11370 // be called again, so use a local copy of DelayedDllExportClasses.
11371 SmallVector<CXXRecordDecl *, 4> WorkList;
11372 std::swap(DelayedDllExportClasses, WorkList);
11373 for (CXXRecordDecl *Class : WorkList)
11374 ReferenceDllExportedMembers(*this, Class);
11375 }
11376}
11377
11378void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11379 assert(getLangOpts().CPlusPlus11 &&((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11380, __PRETTY_FUNCTION__))
11380 "adjusting dtor exception specs was introduced in c++11")((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11380, __PRETTY_FUNCTION__))
;
11381
11382 if (Destructor->isDependentContext())
11383 return;
11384
11385 // C++11 [class.dtor]p3:
11386 // A declaration of a destructor that does not have an exception-
11387 // specification is implicitly considered to have the same exception-
11388 // specification as an implicit declaration.
11389 const FunctionProtoType *DtorType = Destructor->getType()->
11390 getAs<FunctionProtoType>();
11391 if (DtorType->hasExceptionSpec())
11392 return;
11393
11394 // Replace the destructor's type, building off the existing one. Fortunately,
11395 // the only thing of interest in the destructor type is its extended info.
11396 // The return and arguments are fixed.
11397 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11398 EPI.ExceptionSpec.Type = EST_Unevaluated;
11399 EPI.ExceptionSpec.SourceDecl = Destructor;
11400 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11401
11402 // FIXME: If the destructor has a body that could throw, and the newly created
11403 // spec doesn't allow exceptions, we should emit a warning, because this
11404 // change in behavior can break conforming C++03 programs at runtime.
11405 // However, we don't have a body or an exception specification yet, so it
11406 // needs to be done somewhere else.
11407}
11408
11409namespace {
11410/// An abstract base class for all helper classes used in building the
11411// copy/move operators. These classes serve as factory functions and help us
11412// avoid using the same Expr* in the AST twice.
11413class ExprBuilder {
11414 ExprBuilder(const ExprBuilder&) = delete;
11415 ExprBuilder &operator=(const ExprBuilder&) = delete;
11416
11417protected:
11418 static Expr *assertNotNull(Expr *E) {
11419 assert(E && "Expression construction must not fail.")((E && "Expression construction must not fail.") ? static_cast
<void> (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11419, __PRETTY_FUNCTION__))
;
11420 return E;
11421 }
11422
11423public:
11424 ExprBuilder() {}
11425 virtual ~ExprBuilder() {}
11426
11427 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11428};
11429
11430class RefBuilder: public ExprBuilder {
11431 VarDecl *Var;
11432 QualType VarType;
11433
11434public:
11435 Expr *build(Sema &S, SourceLocation Loc) const override {
11436 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11437 }
11438
11439 RefBuilder(VarDecl *Var, QualType VarType)
11440 : Var(Var), VarType(VarType) {}
11441};
11442
11443class ThisBuilder: public ExprBuilder {
11444public:
11445 Expr *build(Sema &S, SourceLocation Loc) const override {
11446 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11447 }
11448};
11449
11450class CastBuilder: public ExprBuilder {
11451 const ExprBuilder &Builder;
11452 QualType Type;
11453 ExprValueKind Kind;
11454 const CXXCastPath &Path;
11455
11456public:
11457 Expr *build(Sema &S, SourceLocation Loc) const override {
11458 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11459 CK_UncheckedDerivedToBase, Kind,
11460 &Path).get());
11461 }
11462
11463 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11464 const CXXCastPath &Path)
11465 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11466};
11467
11468class DerefBuilder: public ExprBuilder {
11469 const ExprBuilder &Builder;
11470
11471public:
11472 Expr *build(Sema &S, SourceLocation Loc) const override {
11473 return assertNotNull(
11474 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11475 }
11476
11477 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11478};
11479
11480class MemberBuilder: public ExprBuilder {
11481 const ExprBuilder &Builder;
11482 QualType Type;
11483 CXXScopeSpec SS;
11484 bool IsArrow;
11485 LookupResult &MemberLookup;
11486
11487public:
11488 Expr *build(Sema &S, SourceLocation Loc) const override {
11489 return assertNotNull(S.BuildMemberReferenceExpr(
11490 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11491 nullptr, MemberLookup, nullptr, nullptr).get());
11492 }
11493
11494 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11495 LookupResult &MemberLookup)
11496 : Builder(Builder), Type(Type), IsArrow(IsArrow),
11497 MemberLookup(MemberLookup) {}
11498};
11499
11500class MoveCastBuilder: public ExprBuilder {
11501 const ExprBuilder &Builder;
11502
11503public:
11504 Expr *build(Sema &S, SourceLocation Loc) const override {
11505 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11506 }
11507
11508 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11509};
11510
11511class LvalueConvBuilder: public ExprBuilder {
11512 const ExprBuilder &Builder;
11513
11514public:
11515 Expr *build(Sema &S, SourceLocation Loc) const override {
11516 return assertNotNull(
11517 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11518 }
11519
11520 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11521};
11522
11523class SubscriptBuilder: public ExprBuilder {
11524 const ExprBuilder &Base;
11525 const ExprBuilder &Index;
11526
11527public:
11528 Expr *build(Sema &S, SourceLocation Loc) const override {
11529 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11530 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11531 }
11532
11533 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11534 : Base(Base), Index(Index) {}
11535};
11536
11537} // end anonymous namespace
11538
11539/// When generating a defaulted copy or move assignment operator, if a field
11540/// should be copied with __builtin_memcpy rather than via explicit assignments,
11541/// do so. This optimization only applies for arrays of scalars, and for arrays
11542/// of class type where the selected copy/move-assignment operator is trivial.
11543static StmtResult
11544buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11545 const ExprBuilder &ToB, const ExprBuilder &FromB) {
11546 // Compute the size of the memory buffer to be copied.
11547 QualType SizeType = S.Context.getSizeType();
11548 llvm::APInt Size(S.Context.getTypeSize(SizeType),
11549 S.Context.getTypeSizeInChars(T).getQuantity());
11550
11551 // Take the address of the field references for "from" and "to". We
11552 // directly construct UnaryOperators here because semantic analysis
11553 // does not permit us to take the address of an xvalue.
11554 Expr *From = FromB.build(S, Loc);
11555 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11556 S.Context.getPointerType(From->getType()),
11557 VK_RValue, OK_Ordinary, Loc, false);
11558 Expr *To = ToB.build(S, Loc);
11559 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11560 S.Context.getPointerType(To->getType()),
11561 VK_RValue, OK_Ordinary, Loc, false);
11562
11563 const Type *E = T->getBaseElementTypeUnsafe();
11564 bool NeedsCollectableMemCpy =
11565 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11566
11567 // Create a reference to the __builtin_objc_memmove_collectable function
11568 StringRef MemCpyName = NeedsCollectableMemCpy ?
11569 "__builtin_objc_memmove_collectable" :
11570 "__builtin_memcpy";
11571 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11572 Sema::LookupOrdinaryName);
11573 S.LookupName(R, S.TUScope, true);
11574
11575 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11576 if (!MemCpy)
11577 // Something went horribly wrong earlier, and we will have complained
11578 // about it.
11579 return StmtError();
11580
11581 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11582 VK_RValue, Loc, nullptr);
11583 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")((MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? static_cast<void> (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11583, __PRETTY_FUNCTION__))
;
11584
11585 Expr *CallArgs[] = {
11586 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11587 };
11588 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11589 Loc, CallArgs, Loc);
11590
11591 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")((!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? static_cast<void> (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11591, __PRETTY_FUNCTION__))
;
11592 return Call.getAs<Stmt>();
11593}
11594
11595/// Builds a statement that copies/moves the given entity from \p From to
11596/// \c To.
11597///
11598/// This routine is used to copy/move the members of a class with an
11599/// implicitly-declared copy/move assignment operator. When the entities being
11600/// copied are arrays, this routine builds for loops to copy them.
11601///
11602/// \param S The Sema object used for type-checking.
11603///
11604/// \param Loc The location where the implicit copy/move is being generated.
11605///
11606/// \param T The type of the expressions being copied/moved. Both expressions
11607/// must have this type.
11608///
11609/// \param To The expression we are copying/moving to.
11610///
11611/// \param From The expression we are copying/moving from.
11612///
11613/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11614/// Otherwise, it's a non-static member subobject.
11615///
11616/// \param Copying Whether we're copying or moving.
11617///
11618/// \param Depth Internal parameter recording the depth of the recursion.
11619///
11620/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11621/// if a memcpy should be used instead.
11622static StmtResult
11623buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11624 const ExprBuilder &To, const ExprBuilder &From,
11625 bool CopyingBaseSubobject, bool Copying,
11626 unsigned Depth = 0) {
11627 // C++11 [class.copy]p28:
11628 // Each subobject is assigned in the manner appropriate to its type:
11629 //
11630 // - if the subobject is of class type, as if by a call to operator= with
11631 // the subobject as the object expression and the corresponding
11632 // subobject of x as a single function argument (as if by explicit
11633 // qualification; that is, ignoring any possible virtual overriding
11634 // functions in more derived classes);
11635 //
11636 // C++03 [class.copy]p13:
11637 // - if the subobject is of class type, the copy assignment operator for
11638 // the class is used (as if by explicit qualification; that is,
11639 // ignoring any possible virtual overriding functions in more derived
11640 // classes);
11641 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11642 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11643
11644 // Look for operator=.
11645 DeclarationName Name
11646 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11647 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11648 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11649
11650 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11651 // operator.
11652 if (!S.getLangOpts().CPlusPlus11) {
11653 LookupResult::Filter F = OpLookup.makeFilter();
11654 while (F.hasNext()) {
11655 NamedDecl *D = F.next();
11656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11657 if (Method->isCopyAssignmentOperator() ||
11658 (!Copying && Method->isMoveAssignmentOperator()))
11659 continue;
11660
11661 F.erase();
11662 }
11663 F.done();
11664 }
11665
11666 // Suppress the protected check (C++ [class.protected]) for each of the
11667 // assignment operators we found. This strange dance is required when
11668 // we're assigning via a base classes's copy-assignment operator. To
11669 // ensure that we're getting the right base class subobject (without
11670 // ambiguities), we need to cast "this" to that subobject type; to
11671 // ensure that we don't go through the virtual call mechanism, we need
11672 // to qualify the operator= name with the base class (see below). However,
11673 // this means that if the base class has a protected copy assignment
11674 // operator, the protected member access check will fail. So, we
11675 // rewrite "protected" access to "public" access in this case, since we
11676 // know by construction that we're calling from a derived class.
11677 if (CopyingBaseSubobject) {
11678 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11679 L != LEnd; ++L) {
11680 if (L.getAccess() == AS_protected)
11681 L.setAccess(AS_public);
11682 }
11683 }
11684
11685 // Create the nested-name-specifier that will be used to qualify the
11686 // reference to operator=; this is required to suppress the virtual
11687 // call mechanism.
11688 CXXScopeSpec SS;
11689 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11690 SS.MakeTrivial(S.Context,
11691 NestedNameSpecifier::Create(S.Context, nullptr, false,
11692 CanonicalT),
11693 Loc);
11694
11695 // Create the reference to operator=.
11696 ExprResult OpEqualRef
11697 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11698 SS, /*TemplateKWLoc=*/SourceLocation(),
11699 /*FirstQualifierInScope=*/nullptr,
11700 OpLookup,
11701 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11702 /*SuppressQualifierCheck=*/true);
11703 if (OpEqualRef.isInvalid())
11704 return StmtError();
11705
11706 // Build the call to the assignment operator.
11707
11708 Expr *FromInst = From.build(S, Loc);
11709 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11710 OpEqualRef.getAs<Expr>(),
11711 Loc, FromInst, Loc);
11712 if (Call.isInvalid())
11713 return StmtError();
11714
11715 // If we built a call to a trivial 'operator=' while copying an array,
11716 // bail out. We'll replace the whole shebang with a memcpy.
11717 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11718 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11719 return StmtResult((Stmt*)nullptr);
11720
11721 // Convert to an expression-statement, and clean up any produced
11722 // temporaries.
11723 return S.ActOnExprStmt(Call);
11724 }
11725
11726 // - if the subobject is of scalar type, the built-in assignment
11727 // operator is used.
11728 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11729 if (!ArrayTy) {
11730 ExprResult Assignment = S.CreateBuiltinBinOp(
11731 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11732 if (Assignment.isInvalid())
11733 return StmtError();
11734 return S.ActOnExprStmt(Assignment);
11735 }
11736
11737 // - if the subobject is an array, each element is assigned, in the
11738 // manner appropriate to the element type;
11739
11740 // Construct a loop over the array bounds, e.g.,
11741 //
11742 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11743 //
11744 // that will copy each of the array elements.
11745 QualType SizeType = S.Context.getSizeType();
11746
11747 // Create the iteration variable.
11748 IdentifierInfo *IterationVarName = nullptr;
11749 {
11750 SmallString<8> Str;
11751 llvm::raw_svector_ostream OS(Str);
11752 OS << "__i" << Depth;
11753 IterationVarName = &S.Context.Idents.get(OS.str());
11754 }
11755 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11756 IterationVarName, SizeType,
11757 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11758 SC_None);
11759
11760 // Initialize the iteration variable to zero.
11761 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11762 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11763
11764 // Creates a reference to the iteration variable.
11765 RefBuilder IterationVarRef(IterationVar, SizeType);
11766 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11767
11768 // Create the DeclStmt that holds the iteration variable.
11769 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11770
11771 // Subscript the "from" and "to" expressions with the iteration variable.
11772 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11773 MoveCastBuilder FromIndexMove(FromIndexCopy);
11774 const ExprBuilder *FromIndex;
11775 if (Copying)
11776 FromIndex = &FromIndexCopy;
11777 else
11778 FromIndex = &FromIndexMove;
11779
11780 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11781
11782 // Build the copy/move for an individual element of the array.
11783 StmtResult Copy =
11784 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11785 ToIndex, *FromIndex, CopyingBaseSubobject,
11786 Copying, Depth + 1);
11787 // Bail out if copying fails or if we determined that we should use memcpy.
11788 if (Copy.isInvalid() || !Copy.get())
11789 return Copy;
11790
11791 // Create the comparison against the array bound.
11792 llvm::APInt Upper
11793 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11794 Expr *Comparison
11795 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11796 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11797 BO_NE, S.Context.BoolTy,
11798 VK_RValue, OK_Ordinary, Loc, FPOptions());
11799
11800 // Create the pre-increment of the iteration variable. We can determine
11801 // whether the increment will overflow based on the value of the array
11802 // bound.
11803 Expr *Increment = new (S.Context)
11804 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11805 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11806
11807 // Construct the loop that copies all elements of this array.
11808 return S.ActOnForStmt(
11809 Loc, Loc, InitStmt,
11810 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11811 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11812}
11813
11814static StmtResult
11815buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11816 const ExprBuilder &To, const ExprBuilder &From,
11817 bool CopyingBaseSubobject, bool Copying) {
11818 // Maybe we should use a memcpy?
11819 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11820 T.isTriviallyCopyableType(S.Context))
11821 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11822
11823 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11824 CopyingBaseSubobject,
11825 Copying, 0));
11826
11827 // If we ended up picking a trivial assignment operator for an array of a
11828 // non-trivially-copyable class type, just emit a memcpy.
11829 if (!Result.isInvalid() && !Result.get())
11830 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11831
11832 return Result;
11833}
11834
11835CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11836 // Note: The following rules are largely analoguous to the copy
11837 // constructor rules. Note that virtual bases are not taken into account
11838 // for determining the argument type of the operator. Note also that
11839 // operators taking an object instead of a reference are allowed.
11840 assert(ClassDecl->needsImplicitCopyAssignment())((ClassDecl->needsImplicitCopyAssignment()) ? static_cast<
void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11840, __PRETTY_FUNCTION__))
;
11841
11842 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11843 if (DSM.isAlreadyBeingDeclared())
11844 return nullptr;
11845
11846 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11847 if (Context.getLangOpts().OpenCLCPlusPlus)
11848 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11849 QualType RetType = Context.getLValueReferenceType(ArgType);
11850 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11851 if (Const)
11852 ArgType = ArgType.withConst();
11853
11854 ArgType = Context.getLValueReferenceType(ArgType);
11855
11856 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11857 CXXCopyAssignment,
11858 Const);
11859
11860 // An implicitly-declared copy assignment operator is an inline public
11861 // member of its class.
11862 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11863 SourceLocation ClassLoc = ClassDecl->getLocation();
11864 DeclarationNameInfo NameInfo(Name, ClassLoc);
11865 CXXMethodDecl *CopyAssignment =
11866 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11867 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11868 /*isInline=*/true, Constexpr, SourceLocation());
11869 CopyAssignment->setAccess(AS_public);
11870 CopyAssignment->setDefaulted();
11871 CopyAssignment->setImplicit();
11872
11873 if (getLangOpts().CUDA) {
11874 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11875 CopyAssignment,
11876 /* ConstRHS */ Const,
11877 /* Diagnose */ false);
11878 }
11879
11880 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11881
11882 // Add the parameter to the operator.
11883 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11884 ClassLoc, ClassLoc,
11885 /*Id=*/nullptr, ArgType,
11886 /*TInfo=*/nullptr, SC_None,
11887 nullptr);
11888 CopyAssignment->setParams(FromParam);
11889
11890 CopyAssignment->setTrivial(
11891 ClassDecl->needsOverloadResolutionForCopyAssignment()
11892 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11893 : ClassDecl->hasTrivialCopyAssignment());
11894
11895 // Note that we have added this copy-assignment operator.
11896 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11897
11898 Scope *S = getScopeForContext(ClassDecl);
11899 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11900
11901 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11902 SetDeclDeleted(CopyAssignment, ClassLoc);
11903
11904 if (S)
11905 PushOnScopeChains(CopyAssignment, S, false);
11906 ClassDecl->addDecl(CopyAssignment);
11907
11908 return CopyAssignment;
11909}
11910
11911/// Diagnose an implicit copy operation for a class which is odr-used, but
11912/// which is deprecated because the class has a user-declared copy constructor,
11913/// copy assignment operator, or destructor.
11914static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11915 assert(CopyOp->isImplicit())((CopyOp->isImplicit()) ? static_cast<void> (0) : __assert_fail
("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11915, __PRETTY_FUNCTION__))
;
11916
11917 CXXRecordDecl *RD = CopyOp->getParent();
11918 CXXMethodDecl *UserDeclaredOperation = nullptr;
11919
11920 // In Microsoft mode, assignment operations don't affect constructors and
11921 // vice versa.
11922 if (RD->hasUserDeclaredDestructor()) {
11923 UserDeclaredOperation = RD->getDestructor();
11924 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11925 RD->hasUserDeclaredCopyConstructor() &&
11926 !S.getLangOpts().MSVCCompat) {
11927 // Find any user-declared copy constructor.
11928 for (auto *I : RD->ctors()) {
11929 if (I->isCopyConstructor()) {
11930 UserDeclaredOperation = I;
11931 break;
11932 }
11933 }
11934 assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail
("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11934, __PRETTY_FUNCTION__))
;
11935 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11936 RD->hasUserDeclaredCopyAssignment() &&
11937 !S.getLangOpts().MSVCCompat) {
11938 // Find any user-declared move assignment operator.
11939 for (auto *I : RD->methods()) {
11940 if (I->isCopyAssignmentOperator()) {
11941 UserDeclaredOperation = I;
11942 break;
11943 }
11944 }
11945 assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail
("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11945, __PRETTY_FUNCTION__))
;
11946 }
11947
11948 if (UserDeclaredOperation) {
11949 S.Diag(UserDeclaredOperation->getLocation(),
11950 diag::warn_deprecated_copy_operation)
11951 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11952 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11953 }
11954}
11955
11956void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11957 CXXMethodDecl *CopyAssignOperator) {
11958 assert((CopyAssignOperator->isDefaulted() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11963, __PRETTY_FUNCTION__))
11959 CopyAssignOperator->isOverloadedOperator() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11963, __PRETTY_FUNCTION__))
11960 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11963, __PRETTY_FUNCTION__))
11961 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11963, __PRETTY_FUNCTION__))
11962 !CopyAssignOperator->isDeleted()) &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11963, __PRETTY_FUNCTION__))
11963 "DefineImplicitCopyAssignment called for wrong function")(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11963, __PRETTY_FUNCTION__))
;
11964 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11965 return;
11966
11967 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11968 if (ClassDecl->isInvalidDecl()) {
11969 CopyAssignOperator->setInvalidDecl();
11970 return;
11971 }
11972
11973 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11974
11975 // The exception specification is needed because we are defining the
11976 // function.
11977 ResolveExceptionSpec(CurrentLocation,
11978 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11979
11980 // Add a context note for diagnostics produced after this point.
11981 Scope.addContextNote(CurrentLocation);
11982
11983 // C++11 [class.copy]p18:
11984 // The [definition of an implicitly declared copy assignment operator] is
11985 // deprecated if the class has a user-declared copy constructor or a
11986 // user-declared destructor.
11987 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11988 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11989
11990 // C++0x [class.copy]p30:
11991 // The implicitly-defined or explicitly-defaulted copy assignment operator
11992 // for a non-union class X performs memberwise copy assignment of its
11993 // subobjects. The direct base classes of X are assigned first, in the
11994 // order of their declaration in the base-specifier-list, and then the
11995 // immediate non-static data members of X are assigned, in the order in
11996 // which they were declared in the class definition.
11997
11998 // The statements that form the synthesized function body.
11999 SmallVector<Stmt*, 8> Statements;
12000
12001 // The parameter for the "other" object, which we are copying from.
12002 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12003 Qualifiers OtherQuals = Other->getType().getQualifiers();
12004 QualType OtherRefType = Other->getType();
12005 if (const LValueReferenceType *OtherRef
12006 = OtherRefType->getAs<LValueReferenceType>()) {
12007 OtherRefType = OtherRef->getPointeeType();
12008 OtherQuals = OtherRefType.getQualifiers();
12009 }
12010
12011 // Our location for everything implicitly-generated.
12012 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12013 ? CopyAssignOperator->getEndLoc()
12014 : CopyAssignOperator->getLocation();
12015
12016 // Builds a DeclRefExpr for the "other" object.
12017 RefBuilder OtherRef(Other, OtherRefType);
12018
12019 // Builds the "this" pointer.
12020 ThisBuilder This;
12021
12022 // Assign base classes.
12023 bool Invalid = false;
12024 for (auto &Base : ClassDecl->bases()) {
12025 // Form the assignment:
12026 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12027 QualType BaseType = Base.getType().getUnqualifiedType();
12028 if (!BaseType->isRecordType()) {
12029 Invalid = true;
12030 continue;
12031 }
12032
12033 CXXCastPath BasePath;
12034 BasePath.push_back(&Base);
12035
12036 // Construct the "from" expression, which is an implicit cast to the
12037 // appropriately-qualified base type.
12038 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12039 VK_LValue, BasePath);
12040
12041 // Dereference "this".
12042 DerefBuilder DerefThis(This);
12043 CastBuilder To(DerefThis,
12044 Context.getQualifiedType(
12045 BaseType, CopyAssignOperator->getMethodQualifiers()),
12046 VK_LValue, BasePath);
12047
12048 // Build the copy.
12049 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12050 To, From,
12051 /*CopyingBaseSubobject=*/true,
12052 /*Copying=*/true);
12053 if (Copy.isInvalid()) {
12054 CopyAssignOperator->setInvalidDecl();
12055 return;
12056 }
12057
12058 // Success! Record the copy.
12059 Statements.push_back(Copy.getAs<Expr>());
12060 }
12061
12062 // Assign non-static members.
12063 for (auto *Field : ClassDecl->fields()) {
12064 // FIXME: We should form some kind of AST representation for the implied
12065 // memcpy in a union copy operation.
12066 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12067 continue;
12068
12069 if (Field->isInvalidDecl()) {
12070 Invalid = true;
12071 continue;
12072 }
12073
12074 // Check for members of reference type; we can't copy those.
12075 if (Field->getType()->isReferenceType()) {
12076 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12077 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12078 Diag(Field->getLocation(), diag::note_declared_at);
12079 Invalid = true;
12080 continue;
12081 }
12082
12083 // Check for members of const-qualified, non-class type.
12084 QualType BaseType = Context.getBaseElementType(Field->getType());
12085 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12086 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12087 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12088 Diag(Field->getLocation(), diag::note_declared_at);
12089 Invalid = true;
12090 continue;
12091 }
12092
12093 // Suppress assigning zero-width bitfields.
12094 if (Field->isZeroLengthBitField(Context))
12095 continue;
12096
12097 QualType FieldType = Field->getType().getNonReferenceType();
12098 if (FieldType->isIncompleteArrayType()) {
12099 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12100, __PRETTY_FUNCTION__))
12100 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12100, __PRETTY_FUNCTION__))
;
12101 continue;
12102 }
12103
12104 // Build references to the field in the object we're copying from and to.
12105 CXXScopeSpec SS; // Intentionally empty
12106 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12107 LookupMemberName);
12108 MemberLookup.addDecl(Field);
12109 MemberLookup.resolveKind();
12110
12111 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12112
12113 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12114
12115 // Build the copy of this field.
12116 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12117 To, From,
12118 /*CopyingBaseSubobject=*/false,
12119 /*Copying=*/true);
12120 if (Copy.isInvalid()) {
12121 CopyAssignOperator->setInvalidDecl();
12122 return;
12123 }
12124
12125 // Success! Record the copy.
12126 Statements.push_back(Copy.getAs<Stmt>());
12127 }
12128
12129 if (!Invalid) {
12130 // Add a "return *this;"
12131 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12132
12133 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12134 if (Return.isInvalid())
12135 Invalid = true;
12136 else
12137 Statements.push_back(Return.getAs<Stmt>());
12138 }
12139
12140 if (Invalid) {
12141 CopyAssignOperator->setInvalidDecl();
12142 return;
12143 }
12144
12145 StmtResult Body;
12146 {
12147 CompoundScopeRAII CompoundScope(*this);
12148 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12149 /*isStmtExpr=*/false);
12150 assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail"
) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12150, __PRETTY_FUNCTION__))
;
12151 }
12152 CopyAssignOperator->setBody(Body.getAs<Stmt>());
12153 CopyAssignOperator->markUsed(Context);
12154
12155 if (ASTMutationListener *L = getASTMutationListener()) {
12156 L->CompletedImplicitDefinition(CopyAssignOperator);
12157 }
12158}
12159
12160CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12161 assert(ClassDecl->needsImplicitMoveAssignment())((ClassDecl->needsImplicitMoveAssignment()) ? static_cast<
void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12161, __PRETTY_FUNCTION__))
;
12162
12163 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12164 if (DSM.isAlreadyBeingDeclared())
12165 return nullptr;
12166
12167 // Note: The following rules are largely analoguous to the move
12168 // constructor rules.
12169
12170 QualType ArgType = Context.getTypeDeclType(ClassDecl);
12171 if (Context.getLangOpts().OpenCLCPlusPlus)
12172 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12173 QualType RetType = Context.getLValueReferenceType(ArgType);
12174 ArgType = Context.getRValueReferenceType(ArgType);
12175
12176 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12177 CXXMoveAssignment,
12178 false);
12179
12180 // An implicitly-declared move assignment operator is an inline public
12181 // member of its class.
12182 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12183 SourceLocation ClassLoc = ClassDecl->getLocation();
12184 DeclarationNameInfo NameInfo(Name, ClassLoc);
12185 CXXMethodDecl *MoveAssignment =
12186 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12187 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12188 /*isInline=*/true, Constexpr, SourceLocation());
12189 MoveAssignment->setAccess(AS_public);
12190 MoveAssignment->setDefaulted();
12191 MoveAssignment->setImplicit();
12192
12193 if (getLangOpts().CUDA) {
12194 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12195 MoveAssignment,
12196 /* ConstRHS */ false,
12197 /* Diagnose */ false);
12198 }
12199
12200 // Build an exception specification pointing back at this member.
12201 FunctionProtoType::ExtProtoInfo EPI =
12202 getImplicitMethodEPI(*this, MoveAssignment);
12203 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12204
12205 // Add the parameter to the operator.
12206 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12207 ClassLoc, ClassLoc,
12208 /*Id=*/nullptr, ArgType,
12209 /*TInfo=*/nullptr, SC_None,
12210 nullptr);
12211 MoveAssignment->setParams(FromParam);
12212
12213 MoveAssignment->setTrivial(
12214 ClassDecl->needsOverloadResolutionForMoveAssignment()
12215 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12216 : ClassDecl->hasTrivialMoveAssignment());
12217
12218 // Note that we have added this copy-assignment operator.
12219 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12220
12221 Scope *S = getScopeForContext(ClassDecl);
12222 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12223
12224 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12225 ClassDecl->setImplicitMoveAssignmentIsDeleted();
12226 SetDeclDeleted(MoveAssignment, ClassLoc);
12227 }
12228
12229 if (S)
12230 PushOnScopeChains(MoveAssignment, S, false);
12231 ClassDecl->addDecl(MoveAssignment);
12232
12233 return MoveAssignment;
12234}
12235
12236/// Check if we're implicitly defining a move assignment operator for a class
12237/// with virtual bases. Such a move assignment might move-assign the virtual
12238/// base multiple times.
12239static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12240 SourceLocation CurrentLocation) {
12241 assert(!Class->isDependentContext() && "should not define dependent move")((!Class->isDependentContext() && "should not define dependent move"
) ? static_cast<void> (0) : __assert_fail ("!Class->isDependentContext() && \"should not define dependent move\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12241, __PRETTY_FUNCTION__))
;
12242
12243 // Only a virtual base could get implicitly move-assigned multiple times.
12244 // Only a non-trivial move assignment can observe this. We only want to
12245 // diagnose if we implicitly define an assignment operator that assigns
12246 // two base classes, both of which move-assign the same virtual base.
12247 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12248 Class->getNumBases() < 2)
12249 return;
12250
12251 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12252 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12253 VBaseMap VBases;
12254
12255 for (auto &BI : Class->bases()) {
12256 Worklist.push_back(&BI);
12257 while (!Worklist.empty()) {
12258 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12259 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12260
12261 // If the base has no non-trivial move assignment operators,
12262 // we don't care about moves from it.
12263 if (!Base->hasNonTrivialMoveAssignment())
12264 continue;
12265
12266 // If there's nothing virtual here, skip it.
12267 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12268 continue;
12269
12270 // If we're not actually going to call a move assignment for this base,
12271 // or the selected move assignment is trivial, skip it.
12272 Sema::SpecialMemberOverloadResult SMOR =
12273 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12274 /*ConstArg*/false, /*VolatileArg*/false,
12275 /*RValueThis*/true, /*ConstThis*/false,
12276 /*VolatileThis*/false);
12277 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12278 !SMOR.getMethod()->isMoveAssignmentOperator())
12279 continue;
12280
12281 if (BaseSpec->isVirtual()) {
12282 // We're going to move-assign this virtual base, and its move
12283 // assignment operator is not trivial. If this can happen for
12284 // multiple distinct direct bases of Class, diagnose it. (If it
12285 // only happens in one base, we'll diagnose it when synthesizing
12286 // that base class's move assignment operator.)
12287 CXXBaseSpecifier *&Existing =
12288 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12289 .first->second;
12290 if (Existing && Existing != &BI) {
12291 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12292 << Class << Base;
12293 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12294 << (Base->getCanonicalDecl() ==
12295 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12296 << Base << Existing->getType() << Existing->getSourceRange();
12297 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12298 << (Base->getCanonicalDecl() ==
12299 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12300 << Base << BI.getType() << BaseSpec->getSourceRange();
12301
12302 // Only diagnose each vbase once.
12303 Existing = nullptr;
12304 }
12305 } else {
12306 // Only walk over bases that have defaulted move assignment operators.
12307 // We assume that any user-provided move assignment operator handles
12308 // the multiple-moves-of-vbase case itself somehow.
12309 if (!SMOR.getMethod()->isDefaulted())
12310 continue;
12311
12312 // We're going to move the base classes of Base. Add them to the list.
12313 for (auto &BI : Base->bases())
12314 Worklist.push_back(&BI);
12315 }
12316 }
12317 }
12318}
12319
12320void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12321 CXXMethodDecl *MoveAssignOperator) {
12322 assert((MoveAssignOperator->isDefaulted() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12327, __PRETTY_FUNCTION__))
12323 MoveAssignOperator->isOverloadedOperator() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12327, __PRETTY_FUNCTION__))
12324 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12327, __PRETTY_FUNCTION__))
12325 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12327, __PRETTY_FUNCTION__))
12326 !MoveAssignOperator->isDeleted()) &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12327, __PRETTY_FUNCTION__))
12327 "DefineImplicitMoveAssignment called for wrong function")(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12327, __PRETTY_FUNCTION__))
;
12328 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12329 return;
12330
12331 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12332 if (ClassDecl->isInvalidDecl()) {
12333 MoveAssignOperator->setInvalidDecl();
12334 return;
12335 }
12336
12337 // C++0x [class.copy]p28:
12338 // The implicitly-defined or move assignment operator for a non-union class
12339 // X performs memberwise move assignment of its subobjects. The direct base
12340 // classes of X are assigned first, in the order of their declaration in the
12341 // base-specifier-list, and then the immediate non-static data members of X
12342 // are assigned, in the order in which they were declared in the class
12343 // definition.
12344
12345 // Issue a warning if our implicit move assignment operator will move
12346 // from a virtual base more than once.
12347 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12348
12349 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12350
12351 // The exception specification is needed because we are defining the
12352 // function.
12353 ResolveExceptionSpec(CurrentLocation,
12354 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12355
12356 // Add a context note for diagnostics produced after this point.
12357 Scope.addContextNote(CurrentLocation);
12358
12359 // The statements that form the synthesized function body.
12360 SmallVector<Stmt*, 8> Statements;
12361
12362 // The parameter for the "other" object, which we are move from.
12363 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12364 QualType OtherRefType = Other->getType()->
12365 getAs<RValueReferenceType>()->getPointeeType();
12366
12367 // Our location for everything implicitly-generated.
12368 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12369 ? MoveAssignOperator->getEndLoc()
12370 : MoveAssignOperator->getLocation();
12371
12372 // Builds a reference to the "other" object.
12373 RefBuilder OtherRef(Other, OtherRefType);
12374 // Cast to rvalue.
12375 MoveCastBuilder MoveOther(OtherRef);
12376
12377 // Builds the "this" pointer.
12378 ThisBuilder This;
12379
12380 // Assign base classes.
12381 bool Invalid = false;
12382 for (auto &Base : ClassDecl->bases()) {
12383 // C++11 [class.copy]p28:
12384 // It is unspecified whether subobjects representing virtual base classes
12385 // are assigned more than once by the implicitly-defined copy assignment
12386 // operator.
12387 // FIXME: Do not assign to a vbase that will be assigned by some other base
12388 // class. For a move-assignment, this can result in the vbase being moved
12389 // multiple times.
12390
12391 // Form the assignment:
12392 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12393 QualType BaseType = Base.getType().getUnqualifiedType();
12394 if (!BaseType->isRecordType()) {
12395 Invalid = true;
12396 continue;
12397 }
12398
12399 CXXCastPath BasePath;
12400 BasePath.push_back(&Base);
12401
12402 // Construct the "from" expression, which is an implicit cast to the
12403 // appropriately-qualified base type.
12404 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12405
12406 // Dereference "this".
12407 DerefBuilder DerefThis(This);
12408
12409 // Implicitly cast "this" to the appropriately-qualified base type.
12410 CastBuilder To(DerefThis,
12411 Context.getQualifiedType(
12412 BaseType, MoveAssignOperator->getMethodQualifiers()),
12413 VK_LValue, BasePath);
12414
12415 // Build the move.
12416 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12417 To, From,
12418 /*CopyingBaseSubobject=*/true,
12419 /*Copying=*/false);
12420 if (Move.isInvalid()) {
12421 MoveAssignOperator->setInvalidDecl();
12422 return;
12423 }
12424
12425 // Success! Record the move.
12426 Statements.push_back(Move.getAs<Expr>());
12427 }
12428
12429 // Assign non-static members.
12430 for (auto *Field : ClassDecl->fields()) {
12431 // FIXME: We should form some kind of AST representation for the implied
12432 // memcpy in a union copy operation.
12433 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12434 continue;
12435
12436 if (Field->isInvalidDecl()) {
12437 Invalid = true;
12438 continue;
12439 }
12440
12441 // Check for members of reference type; we can't move those.
12442 if (Field->getType()->isReferenceType()) {
12443 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12444 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12445 Diag(Field->getLocation(), diag::note_declared_at);
12446 Invalid = true;
12447 continue;
12448 }
12449
12450 // Check for members of const-qualified, non-class type.
12451 QualType BaseType = Context.getBaseElementType(Field->getType());
12452 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12453 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12454 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12455 Diag(Field->getLocation(), diag::note_declared_at);
12456 Invalid = true;
12457 continue;
12458 }
12459
12460 // Suppress assigning zero-width bitfields.
12461 if (Field->isZeroLengthBitField(Context))
12462 continue;
12463
12464 QualType FieldType = Field->getType().getNonReferenceType();
12465 if (FieldType->isIncompleteArrayType()) {
12466 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12467, __PRETTY_FUNCTION__))
12467 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12467, __PRETTY_FUNCTION__))
;
12468 continue;
12469 }
12470
12471 // Build references to the field in the object we're copying from and to.
12472 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12473 LookupMemberName);
12474 MemberLookup.addDecl(Field);
12475 MemberLookup.resolveKind();
12476 MemberBuilder From(MoveOther, OtherRefType,
12477 /*IsArrow=*/false, MemberLookup);
12478 MemberBuilder To(This, getCurrentThisType(),
12479 /*IsArrow=*/true, MemberLookup);
12480
12481 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12483, __PRETTY_FUNCTION__))
12482 "Member reference with rvalue base must be rvalue except for reference "((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12483, __PRETTY_FUNCTION__))
12483 "members, which aren't allowed for move assignment.")((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12483, __PRETTY_FUNCTION__))
;
12484
12485 // Build the move of this field.
12486 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12487 To, From,
12488 /*CopyingBaseSubobject=*/false,
12489 /*Copying=*/false);
12490 if (Move.isInvalid()) {
12491 MoveAssignOperator->setInvalidDecl();
12492 return;
12493 }
12494
12495 // Success! Record the copy.
12496 Statements.push_back(Move.getAs<Stmt>());
12497 }
12498
12499 if (!Invalid) {
12500 // Add a "return *this;"
12501 ExprResult ThisObj =
12502 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12503
12504 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12505 if (Return.isInvalid())
12506 Invalid = true;
12507 else
12508 Statements.push_back(Return.getAs<Stmt>());
12509 }
12510
12511 if (Invalid) {
12512 MoveAssignOperator->setInvalidDecl();
12513 return;
12514 }
12515
12516 StmtResult Body;
12517 {
12518 CompoundScopeRAII CompoundScope(*this);
12519 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12520 /*isStmtExpr=*/false);
12521 assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail"
) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12521, __PRETTY_FUNCTION__))
;
12522 }
12523 MoveAssignOperator->setBody(Body.getAs<Stmt>());
12524 MoveAssignOperator->markUsed(Context);
12525
12526 if (ASTMutationListener *L = getASTMutationListener()) {
12527 L->CompletedImplicitDefinition(MoveAssignOperator);
12528 }
12529}
12530
12531CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12532 CXXRecordDecl *ClassDecl) {
12533 // C++ [class.copy]p4:
12534 // If the class definition does not explicitly declare a copy
12535 // constructor, one is declared implicitly.
12536 assert(ClassDecl->needsImplicitCopyConstructor())((ClassDecl->needsImplicitCopyConstructor()) ? static_cast
<void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12536, __PRETTY_FUNCTION__))
;
12537
12538 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12539 if (DSM.isAlreadyBeingDeclared())
12540 return nullptr;
12541
12542 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12543 QualType ArgType = ClassType;
12544 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12545 if (Const)
12546 ArgType = ArgType.withConst();
12547
12548 if (Context.getLangOpts().OpenCLCPlusPlus)
12549 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12550
12551 ArgType = Context.getLValueReferenceType(ArgType);
12552
12553 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12554 CXXCopyConstructor,
12555 Const);
12556
12557 DeclarationName Name
12558 = Context.DeclarationNames.getCXXConstructorName(
12559 Context.getCanonicalType(ClassType));
12560 SourceLocation ClassLoc = ClassDecl->getLocation();
12561 DeclarationNameInfo NameInfo(Name, ClassLoc);
12562
12563 // An implicitly-declared copy constructor is an inline public
12564 // member of its class.
12565 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12566 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12567 ExplicitSpecifier(),
12568 /*isInline=*/true,
12569 /*isImplicitlyDeclared=*/true, Constexpr);
12570 CopyConstructor->setAccess(AS_public);
12571 CopyConstructor->setDefaulted();
12572
12573 if (getLangOpts().CUDA) {
12574 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12575 CopyConstructor,
12576 /* ConstRHS */ Const,
12577 /* Diagnose */ false);
12578 }
12579
12580 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12581
12582 // Add the parameter to the constructor.
12583 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12584 ClassLoc, ClassLoc,
12585 /*IdentifierInfo=*/nullptr,
12586 ArgType, /*TInfo=*/nullptr,
12587 SC_None, nullptr);
12588 CopyConstructor->setParams(FromParam);
12589
12590 CopyConstructor->setTrivial(
12591 ClassDecl->needsOverloadResolutionForCopyConstructor()
12592 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12593 : ClassDecl->hasTrivialCopyConstructor());
12594
12595 CopyConstructor->setTrivialForCall(
12596 ClassDecl->hasAttr<TrivialABIAttr>() ||
12597 (ClassDecl->needsOverloadResolutionForCopyConstructor()
12598 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12599 TAH_ConsiderTrivialABI)
12600 : ClassDecl->hasTrivialCopyConstructorForCall()));
12601
12602 // Note that we have declared this constructor.
12603 ++getASTContext().NumImplicitCopyConstructorsDeclared;
12604
12605 Scope *S = getScopeForContext(ClassDecl);
12606 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12607
12608 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12609 ClassDecl->setImplicitCopyConstructorIsDeleted();
12610 SetDeclDeleted(CopyConstructor, ClassLoc);
12611 }
12612
12613 if (S)
12614 PushOnScopeChains(CopyConstructor, S, false);
12615 ClassDecl->addDecl(CopyConstructor);
12616
12617 return CopyConstructor;
12618}
12619
12620void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12621 CXXConstructorDecl *CopyConstructor) {
12622 assert((CopyConstructor->isDefaulted() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12626, __PRETTY_FUNCTION__))
12623 CopyConstructor->isCopyConstructor() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12626, __PRETTY_FUNCTION__))
12624 !CopyConstructor->doesThisDeclarationHaveABody() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12626, __PRETTY_FUNCTION__))
12625 !CopyConstructor->isDeleted()) &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12626, __PRETTY_FUNCTION__))
12626 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12626, __PRETTY_FUNCTION__))
;
12627 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12628 return;
12629
12630 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12631 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")((ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12631, __PRETTY_FUNCTION__))
;
12632
12633 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12634
12635 // The exception specification is needed because we are defining the
12636 // function.
12637 ResolveExceptionSpec(CurrentLocation,
12638 CopyConstructor->getType()->castAs<FunctionProtoType>());
12639 MarkVTableUsed(CurrentLocation, ClassDecl);
12640
12641 // Add a context note for diagnostics produced after this point.
12642 Scope.addContextNote(CurrentLocation);
12643
12644 // C++11 [class.copy]p7:
12645 // The [definition of an implicitly declared copy constructor] is
12646 // deprecated if the class has a user-declared copy assignment operator
12647 // or a user-declared destructor.
12648 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12649 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12650
12651 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12652 CopyConstructor->setInvalidDecl();
12653 } else {
12654 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12655 ? CopyConstructor->getEndLoc()
12656 : CopyConstructor->getLocation();
12657 Sema::CompoundScopeRAII CompoundScope(*this);
12658 CopyConstructor->setBody(
12659 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12660 CopyConstructor->markUsed(Context);
12661 }
12662
12663 if (ASTMutationListener *L = getASTMutationListener()) {
12664 L->CompletedImplicitDefinition(CopyConstructor);
12665 }
12666}
12667
12668CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12669 CXXRecordDecl *ClassDecl) {
12670 assert(ClassDecl->needsImplicitMoveConstructor())((ClassDecl->needsImplicitMoveConstructor()) ? static_cast
<void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12670, __PRETTY_FUNCTION__))
;
12671
12672 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12673 if (DSM.isAlreadyBeingDeclared())
12674 return nullptr;
12675
12676 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12677
12678 QualType ArgType = ClassType;
12679 if (Context.getLangOpts().OpenCLCPlusPlus)
12680 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12681 ArgType = Context.getRValueReferenceType(ArgType);
12682
12683 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12684 CXXMoveConstructor,
12685 false);
12686
12687 DeclarationName Name
12688 = Context.DeclarationNames.getCXXConstructorName(
12689 Context.getCanonicalType(ClassType));
12690 SourceLocation ClassLoc = ClassDecl->getLocation();
12691 DeclarationNameInfo NameInfo(Name, ClassLoc);
12692
12693 // C++11 [class.copy]p11:
12694 // An implicitly-declared copy/move constructor is an inline public
12695 // member of its class.
12696 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12697 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12698 ExplicitSpecifier(),
12699 /*isInline=*/true,
12700 /*isImplicitlyDeclared=*/true, Constexpr);
12701 MoveConstructor->setAccess(AS_public);
12702 MoveConstructor->setDefaulted();
12703
12704 if (getLangOpts().CUDA) {
12705 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12706 MoveConstructor,
12707 /* ConstRHS */ false,
12708 /* Diagnose */ false);
12709 }
12710
12711 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12712
12713 // Add the parameter to the constructor.
12714 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12715 ClassLoc, ClassLoc,
12716 /*IdentifierInfo=*/nullptr,
12717 ArgType, /*TInfo=*/nullptr,
12718 SC_None, nullptr);
12719 MoveConstructor->setParams(FromParam);
12720
12721 MoveConstructor->setTrivial(
12722 ClassDecl->needsOverloadResolutionForMoveConstructor()
12723 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12724 : ClassDecl->hasTrivialMoveConstructor());
12725
12726 MoveConstructor->setTrivialForCall(
12727 ClassDecl->hasAttr<TrivialABIAttr>() ||
12728 (ClassDecl->needsOverloadResolutionForMoveConstructor()
12729 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12730 TAH_ConsiderTrivialABI)
12731 : ClassDecl->hasTrivialMoveConstructorForCall()));
12732
12733 // Note that we have declared this constructor.
12734 ++getASTContext().NumImplicitMoveConstructorsDeclared;
12735
12736 Scope *S = getScopeForContext(ClassDecl);
12737 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12738
12739 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12740 ClassDecl->setImplicitMoveConstructorIsDeleted();
12741 SetDeclDeleted(MoveConstructor, ClassLoc);
12742 }
12743
12744 if (S)
12745 PushOnScopeChains(MoveConstructor, S, false);
12746 ClassDecl->addDecl(MoveConstructor);
12747
12748 return MoveConstructor;
12749}
12750
12751void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12752 CXXConstructorDecl *MoveConstructor) {
12753 assert((MoveConstructor->isDefaulted() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __PRETTY_FUNCTION__))
12754 MoveConstructor->isMoveConstructor() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __PRETTY_FUNCTION__))
12755 !MoveConstructor->doesThisDeclarationHaveABody() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __PRETTY_FUNCTION__))
12756 !MoveConstructor->isDeleted()) &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __PRETTY_FUNCTION__))
12757 "DefineImplicitMoveConstructor - call it for implicit move ctor")(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __PRETTY_FUNCTION__))
;
12758 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12759 return;
12760
12761 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12762 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")((ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12762, __PRETTY_FUNCTION__))
;
12763
12764 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12765
12766 // The exception specification is needed because we are defining the
12767 // function.
12768 ResolveExceptionSpec(CurrentLocation,
12769 MoveConstructor->getType()->castAs<FunctionProtoType>());
12770 MarkVTableUsed(CurrentLocation, ClassDecl);
12771
12772 // Add a context note for diagnostics produced after this point.
12773 Scope.addContextNote(CurrentLocation);
12774
12775 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12776 MoveConstructor->setInvalidDecl();
12777 } else {
12778 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12779 ? MoveConstructor->getEndLoc()
12780 : MoveConstructor->getLocation();
12781 Sema::CompoundScopeRAII CompoundScope(*this);
12782 MoveConstructor->setBody(ActOnCompoundStmt(
12783 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12784 MoveConstructor->markUsed(Context);
12785 }
12786
12787 if (ASTMutationListener *L = getASTMutationListener()) {
12788 L->CompletedImplicitDefinition(MoveConstructor);
12789 }
12790}
12791
12792bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12793 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12794}
12795
12796void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12797 SourceLocation CurrentLocation,
12798 CXXConversionDecl *Conv) {
12799 SynthesizedFunctionScope Scope(*this, Conv);
12800 assert(!Conv->getReturnType()->isUndeducedType())((!Conv->getReturnType()->isUndeducedType()) ? static_cast
<void> (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12800, __PRETTY_FUNCTION__))
;
12801
12802 CXXRecordDecl *Lambda = Conv->getParent();
12803 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12804 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12805
12806 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12807 CallOp = InstantiateFunctionDeclaration(
12808 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12809 if (!CallOp)
12810 return;
12811
12812 Invoker = InstantiateFunctionDeclaration(
12813 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12814 if (!Invoker)
12815 return;
12816 }
12817
12818 if (CallOp->isInvalidDecl())
12819 return;
12820
12821 // Mark the call operator referenced (and add to pending instantiations
12822 // if necessary).
12823 // For both the conversion and static-invoker template specializations
12824 // we construct their body's in this function, so no need to add them
12825 // to the PendingInstantiations.
12826 MarkFunctionReferenced(CurrentLocation, CallOp);
12827
12828 // Fill in the __invoke function with a dummy implementation. IR generation
12829 // will fill in the actual details. Update its type in case it contained
12830 // an 'auto'.
12831 Invoker->markUsed(Context);
12832 Invoker->setReferenced();
12833 Invoker->setType(Conv->getReturnType()->getPointeeType());
12834 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12835
12836 // Construct the body of the conversion function { return __invoke; }.
12837 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12838 VK_LValue, Conv->getLocation()).get();
12839 assert(FunctionRef && "Can't refer to __invoke function?")((FunctionRef && "Can't refer to __invoke function?")
? static_cast<void> (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12839, __PRETTY_FUNCTION__))
;
12840 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12841 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12842 Conv->getLocation()));
12843 Conv->markUsed(Context);
12844 Conv->setReferenced();
12845
12846 if (ASTMutationListener *L = getASTMutationListener()) {
12847 L->CompletedImplicitDefinition(Conv);
12848 L->CompletedImplicitDefinition(Invoker);
12849 }
12850}
12851
12852
12853
12854void Sema::DefineImplicitLambdaToBlockPointerConversion(
12855 SourceLocation CurrentLocation,
12856 CXXConversionDecl *Conv)
12857{
12858 assert(!Conv->getParent()->isGenericLambda())((!Conv->getParent()->isGenericLambda()) ? static_cast<
void> (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12858, __PRETTY_FUNCTION__))
;
12859
12860 SynthesizedFunctionScope Scope(*this, Conv);
12861
12862 // Copy-initialize the lambda object as needed to capture it.
12863 Expr *This = ActOnCXXThis(CurrentLocation).get();
12864 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12865
12866 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12867 Conv->getLocation(),
12868 Conv, DerefThis);
12869
12870 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12871 // behavior. Note that only the general conversion function does this
12872 // (since it's unusable otherwise); in the case where we inline the
12873 // block literal, it has block literal lifetime semantics.
12874 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12875 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12876 CK_CopyAndAutoreleaseBlockObject,
12877 BuildBlock.get(), nullptr, VK_RValue);
12878
12879 if (BuildBlock.isInvalid()) {
12880 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12881 Conv->setInvalidDecl();
12882 return;
12883 }
12884
12885 // Create the return statement that returns the block from the conversion
12886 // function.
12887 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12888 if (Return.isInvalid()) {
12889 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12890 Conv->setInvalidDecl();
12891 return;
12892 }
12893
12894 // Set the body of the conversion function.
12895 Stmt *ReturnS = Return.get();
12896 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12897 Conv->getLocation()));
12898 Conv->markUsed(Context);
12899
12900 // We're done; notify the mutation listener, if any.
12901 if (ASTMutationListener *L = getASTMutationListener()) {
12902 L->CompletedImplicitDefinition(Conv);
12903 }
12904}
12905
12906/// Determine whether the given list arguments contains exactly one
12907/// "real" (non-default) argument.
12908static bool hasOneRealArgument(MultiExprArg Args) {
12909 switch (Args.size()) {
12910 case 0:
12911 return false;
12912
12913 default:
12914 if (!Args[1]->isDefaultArgument())
12915 return false;
12916
12917 LLVM_FALLTHROUGH[[clang::fallthrough]];
12918 case 1:
12919 return !Args[0]->isDefaultArgument();
12920 }
12921
12922 return false;
12923}
12924
12925ExprResult
12926Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12927 NamedDecl *FoundDecl,
12928 CXXConstructorDecl *Constructor,
12929 MultiExprArg ExprArgs,
12930 bool HadMultipleCandidates,
12931 bool IsListInitialization,
12932 bool IsStdInitListInitialization,
12933 bool RequiresZeroInit,
12934 unsigned ConstructKind,
12935 SourceRange ParenRange) {
12936 bool Elidable = false;
12937
12938 // C++0x [class.copy]p34:
12939 // When certain criteria are met, an implementation is allowed to
12940 // omit the copy/move construction of a class object, even if the
12941 // copy/move constructor and/or destructor for the object have
12942 // side effects. [...]
12943 // - when a temporary class object that has not been bound to a
12944 // reference (12.2) would be copied/moved to a class object
12945 // with the same cv-unqualified type, the copy/move operation
12946 // can be omitted by constructing the temporary object
12947 // directly into the target of the omitted copy/move
12948 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12949 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12950 Expr *SubExpr = ExprArgs[0];
12951 Elidable = SubExpr->isTemporaryObject(
12952 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12953 }
12954
12955 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12956 FoundDecl, Constructor,
12957 Elidable, ExprArgs, HadMultipleCandidates,
12958 IsListInitialization,
12959 IsStdInitListInitialization, RequiresZeroInit,
12960 ConstructKind, ParenRange);
12961}
12962
12963ExprResult
12964Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12965 NamedDecl *FoundDecl,
12966 CXXConstructorDecl *Constructor,
12967 bool Elidable,
12968 MultiExprArg ExprArgs,
12969 bool HadMultipleCandidates,
12970 bool IsListInitialization,
12971 bool IsStdInitListInitialization,
12972 bool RequiresZeroInit,
12973 unsigned ConstructKind,
12974 SourceRange ParenRange) {
12975 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12976 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12977 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12978 return ExprError();
12979 }
12980
12981 return BuildCXXConstructExpr(
12982 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12983 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12984 RequiresZeroInit, ConstructKind, ParenRange);
12985}
12986
12987/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12988/// including handling of its default argument expressions.
12989ExprResult
12990Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12991 CXXConstructorDecl *Constructor,
12992 bool Elidable,
12993 MultiExprArg ExprArgs,
12994 bool HadMultipleCandidates,
12995 bool IsListInitialization,
12996 bool IsStdInitListInitialization,
12997 bool RequiresZeroInit,
12998 unsigned ConstructKind,
12999 SourceRange ParenRange) {
13000 assert(declaresSameEntity(((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13003, __PRETTY_FUNCTION__))
13001 Constructor->getParent(),((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13003, __PRETTY_FUNCTION__))
13002 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13003, __PRETTY_FUNCTION__))
13003 "given constructor for wrong type")((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13003, __PRETTY_FUNCTION__))
;
13004 MarkFunctionReferenced(ConstructLoc, Constructor);
13005 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13006 return ExprError();
13007
13008 return CXXConstructExpr::Create(
13009 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13010 ExprArgs, HadMultipleCandidates, IsListInitialization,
13011 IsStdInitListInitialization, RequiresZeroInit,
13012 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13013 ParenRange);
13014}
13015
13016ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13017 assert(Field->hasInClassInitializer())((Field->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Field->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13017, __PRETTY_FUNCTION__))
;
13018
13019 // If we already have the in-class initializer nothing needs to be done.
13020 if (Field->getInClassInitializer())
13021 return CXXDefaultInitExpr::Create(Context, Loc, Field);
13022
13023 // If we might have already tried and failed to instantiate, don't try again.
13024 if (Field->isInvalidDecl())
13025 return ExprError();
13026
13027 // Maybe we haven't instantiated the in-class initializer. Go check the
13028 // pattern FieldDecl to see if it has one.
13029 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13030
13031 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13032 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13033 DeclContext::lookup_result Lookup =
13034 ClassPattern->lookup(Field->getDeclName());
13035
13036 // Lookup can return at most two results: the pattern for the field, or the
13037 // injected class name of the parent record. No other member can have the
13038 // same name as the field.
13039 // In modules mode, lookup can return multiple results (coming from
13040 // different modules).
13041 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&(((getLangOpts().Modules || (!Lookup.empty() && Lookup
.size() <= 2)) && "more than two lookup results for field name"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13042, __PRETTY_FUNCTION__))
13042 "more than two lookup results for field name")(((getLangOpts().Modules || (!Lookup.empty() && Lookup
.size() <= 2)) && "more than two lookup results for field name"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13042, __PRETTY_FUNCTION__))
;
13043 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13044 if (!Pattern) {
13045 assert(isa<CXXRecordDecl>(Lookup[0]) &&((isa<CXXRecordDecl>(Lookup[0]) && "cannot have other non-field member with same name"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13046, __PRETTY_FUNCTION__))
13046 "cannot have other non-field member with same name")((isa<CXXRecordDecl>(Lookup[0]) && "cannot have other non-field member with same name"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13046, __PRETTY_FUNCTION__))
;
13047 for (auto L : Lookup)
13048 if (isa<FieldDecl>(L)) {
13049 Pattern = cast<FieldDecl>(L);
13050 break;
13051 }
13052 assert(Pattern && "We must have set the Pattern!")((Pattern && "We must have set the Pattern!") ? static_cast
<void> (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13052, __PRETTY_FUNCTION__))
;
13053 }
13054
13055 if (!Pattern->hasInClassInitializer() ||
13056 InstantiateInClassInitializer(Loc, Field, Pattern,
13057 getTemplateInstantiationArgs(Field))) {
13058 // Don't diagnose this again.
13059 Field->setInvalidDecl();
13060 return ExprError();
13061 }
13062 return CXXDefaultInitExpr::Create(Context, Loc, Field);
13063 }
13064
13065 // DR1351:
13066 // If the brace-or-equal-initializer of a non-static data member
13067 // invokes a defaulted default constructor of its class or of an
13068 // enclosing class in a potentially evaluated subexpression, the
13069 // program is ill-formed.
13070 //
13071 // This resolution is unworkable: the exception specification of the
13072 // default constructor can be needed in an unevaluated context, in
13073 // particular, in the operand of a noexcept-expression, and we can be
13074 // unable to compute an exception specification for an enclosed class.
13075 //
13076 // Any attempt to resolve the exception specification of a defaulted default
13077 // constructor before the initializer is lexically complete will ultimately
13078 // come here at which point we can diagnose it.
13079 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13080 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13081 << OutermostClass << Field;
13082 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13083 // Recover by marking the field invalid, unless we're in a SFINAE context.
13084 if (!isSFINAEContext())
13085 Field->setInvalidDecl();
13086 return ExprError();
13087}
13088
13089void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13090 if (VD->isInvalidDecl()) return;
13091
13092 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13093 if (ClassDecl->isInvalidDecl()) return;
13094 if (ClassDecl->hasIrrelevantDestructor()) return;
13095 if (ClassDecl->isDependentContext()) return;
13096
13097 if (VD->isNoDestroy(getASTContext()))
13098 return;
13099
13100 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13101 MarkFunctionReferenced(VD->getLocation(), Destructor);
13102 CheckDestructorAccess(VD->getLocation(), Destructor,
13103 PDiag(diag::err_access_dtor_var)
13104 << VD->getDeclName()
13105 << VD->getType());
13106 DiagnoseUseOfDecl(Destructor, VD->getLocation());
13107
13108 if (Destructor->isTrivial()) return;
13109 if (!VD->hasGlobalStorage()) return;
13110
13111 // Emit warning for non-trivial dtor in global scope (a real global,
13112 // class-static, function-static).
13113 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13114
13115 // TODO: this should be re-enabled for static locals by !CXAAtExit
13116 if (!VD->isStaticLocal())
13117 Diag(VD->getLocation(), diag::warn_global_destructor);
13118}
13119
13120/// Given a constructor and the set of arguments provided for the
13121/// constructor, convert the arguments and add any required default arguments
13122/// to form a proper call to this constructor.
13123///
13124/// \returns true if an error occurred, false otherwise.
13125bool
13126Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13127 MultiExprArg ArgsPtr,
13128 SourceLocation Loc,
13129 SmallVectorImpl<Expr*> &ConvertedArgs,
13130 bool AllowExplicit,
13131 bool IsListInitialization) {
13132 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13133 unsigned NumArgs = ArgsPtr.size();
13134 Expr **Args = ArgsPtr.data();
13135
13136 const FunctionProtoType *Proto
13137 = Constructor->getType()->getAs<FunctionProtoType>();
13138 assert(Proto && "Constructor without a prototype?")((Proto && "Constructor without a prototype?") ? static_cast
<void> (0) : __assert_fail ("Proto && \"Constructor without a prototype?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13138, __PRETTY_FUNCTION__))
;
13139 unsigned NumParams = Proto->getNumParams();
13140
13141 // If too few arguments are available, we'll fill in the rest with defaults.
13142 if (NumArgs < NumParams)
13143 ConvertedArgs.reserve(NumParams);
13144 else
13145 ConvertedArgs.reserve(NumArgs);
13146
13147 VariadicCallType CallType =
13148 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13149 SmallVector<Expr *, 8> AllArgs;
13150 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13151 Proto, 0,
13152 llvm::makeArrayRef(Args, NumArgs),
13153 AllArgs,
13154 CallType, AllowExplicit,
13155 IsListInitialization);
13156 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13157
13158 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13159
13160 CheckConstructorCall(Constructor,
13161 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13162 Proto, Loc);
13163
13164 return Invalid;
13165}
13166
13167static inline bool
13168CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13169 const FunctionDecl *FnDecl) {
13170 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13171 if (isa<NamespaceDecl>(DC)) {
13172 return SemaRef.Diag(FnDecl->getLocation(),
13173 diag::err_operator_new_delete_declared_in_namespace)
13174 << FnDecl->getDeclName();
13175 }
13176
13177 if (isa<TranslationUnitDecl>(DC) &&
13178 FnDecl->getStorageClass() == SC_Static) {
13179 return SemaRef.Diag(FnDecl->getLocation(),
13180 diag::err_operator_new_delete_declared_static)
13181 << FnDecl->getDeclName();
13182 }
13183
13184 return false;
13185}
13186
13187static QualType
13188RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13189 QualType QTy = PtrTy->getPointeeType();
13190 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13191 return SemaRef.Context.getPointerType(QTy);
13192}
13193
13194static inline bool
13195CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13196 CanQualType ExpectedResultType,
13197 CanQualType ExpectedFirstParamType,
13198 unsigned DependentParamTypeDiag,
13199 unsigned InvalidParamTypeDiag) {
13200 QualType ResultType =
13201 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13202
13203 // Check that the result type is not dependent.
13204 if (ResultType->isDependentType())
13205 return SemaRef.Diag(FnDecl->getLocation(),
13206 diag::err_operator_new_delete_dependent_result_type)
13207 << FnDecl->getDeclName() << ExpectedResultType;
13208
13209 // OpenCL C++: the operator is valid on any address space.
13210 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13211 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13212 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13213 }
13214 }
13215
13216 // Check that the result type is what we expect.
13217 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13218 return SemaRef.Diag(FnDecl->getLocation(),
13219 diag::err_operator_new_delete_invalid_result_type)
13220 << FnDecl->getDeclName() << ExpectedResultType;
13221
13222 // A function template must have at least 2 parameters.
13223 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13224 return SemaRef.Diag(FnDecl->getLocation(),
13225 diag::err_operator_new_delete_template_too_few_parameters)
13226 << FnDecl->getDeclName();
13227
13228 // The function decl must have at least 1 parameter.
13229 if (FnDecl->getNumParams() == 0)
13230 return SemaRef.Diag(FnDecl->getLocation(),
13231 diag::err_operator_new_delete_too_few_parameters)
13232 << FnDecl->getDeclName();
13233
13234 // Check the first parameter type is not dependent.
13235 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13236 if (FirstParamType->isDependentType())
13237 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13238 << FnDecl->getDeclName() << ExpectedFirstParamType;
13239
13240 // Check that the first parameter type is what we expect.
13241 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13242 // OpenCL C++: the operator is valid on any address space.
13243 if (auto *PtrTy =
13244 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13245 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13246 }
13247 }
13248 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13249 ExpectedFirstParamType)
13250 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13251 << FnDecl->getDeclName() << ExpectedFirstParamType;
13252
13253 return false;
13254}
13255
13256static bool
13257CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13258 // C++ [basic.stc.dynamic.allocation]p1:
13259 // A program is ill-formed if an allocation function is declared in a
13260 // namespace scope other than global scope or declared static in global
13261 // scope.
13262 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13263 return true;
13264
13265 CanQualType SizeTy =
13266 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13267
13268 // C++ [basic.stc.dynamic.allocation]p1:
13269 // The return type shall be void*. The first parameter shall have type
13270 // std::size_t.
13271 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13272 SizeTy,
13273 diag::err_operator_new_dependent_param_type,
13274 diag::err_operator_new_param_type))
13275 return true;
13276
13277 // C++ [basic.stc.dynamic.allocation]p1:
13278 // The first parameter shall not have an associated default argument.
13279 if (FnDecl->getParamDecl(0)->hasDefaultArg())
13280 return SemaRef.Diag(FnDecl->getLocation(),
13281 diag::err_operator_new_default_arg)
13282 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13283
13284 return false;
13285}
13286
13287static bool
13288CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13289 // C++ [basic.stc.dynamic.deallocation]p1:
13290 // A program is ill-formed if deallocation functions are declared in a
13291 // namespace scope other than global scope or declared static in global
13292 // scope.
13293 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13294 return true;
13295
13296 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13297
13298 // C++ P0722:
13299 // Within a class C, the first parameter of a destroying operator delete
13300 // shall be of type C *. The first parameter of any other deallocation
13301 // function shall be of type void *.
13302 CanQualType ExpectedFirstParamType =
13303 MD && MD->isDestroyingOperatorDelete()
13304 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13305 SemaRef.Context.getRecordType(MD->getParent())))
13306 : SemaRef.Context.VoidPtrTy;
13307
13308 // C++ [basic.stc.dynamic.deallocation]p2:
13309 // Each deallocation function shall return void
13310 if (CheckOperatorNewDeleteTypes(
13311 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13312 diag::err_operator_delete_dependent_param_type,
13313 diag::err_operator_delete_param_type))
13314 return true;
13315
13316 // C++ P0722:
13317 // A destroying operator delete shall be a usual deallocation function.
13318 if (MD && !MD->getParent()->isDependentContext() &&
13319 MD->isDestroyingOperatorDelete() &&
13320 !SemaRef.isUsualDeallocationFunction(MD)) {
13321 SemaRef.Diag(MD->getLocation(),
13322 diag::err_destroying_operator_delete_not_usual);
13323 return true;
13324 }
13325
13326 return false;
13327}
13328
13329/// CheckOverloadedOperatorDeclaration - Check whether the declaration
13330/// of this overloaded operator is well-formed. If so, returns false;
13331/// otherwise, emits appropriate diagnostics and returns true.
13332bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13333 assert(FnDecl && FnDecl->isOverloadedOperator() &&((FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration") ? static_cast
<void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13334, __PRETTY_FUNCTION__))
13334 "Expected an overloaded operator declaration")((FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration") ? static_cast
<void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13334, __PRETTY_FUNCTION__))
;
13335
13336 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13337
13338 // C++ [over.oper]p5:
13339 // The allocation and deallocation functions, operator new,
13340 // operator new[], operator delete and operator delete[], are
13341 // described completely in 3.7.3. The attributes and restrictions
13342 // found in the rest of this subclause do not apply to them unless
13343 // explicitly stated in 3.7.3.
13344 if (Op == OO_Delete || Op == OO_Array_Delete)
13345 return CheckOperatorDeleteDeclaration(*this, FnDecl);
13346
13347 if (Op == OO_New || Op == OO_Array_New)
13348 return CheckOperatorNewDeclaration(*this, FnDecl);
13349
13350 // C++ [over.oper]p6:
13351 // An operator function shall either be a non-static member
13352 // function or be a non-member function and have at least one
13353 // parameter whose type is a class, a reference to a class, an
13354 // enumeration, or a reference to an enumeration.
13355 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13356 if (MethodDecl->isStatic())
13357 return Diag(FnDecl->getLocation(),
13358 diag::err_operator_overload_static) << FnDecl->getDeclName();
13359 } else {
13360 bool ClassOrEnumParam = false;
13361 for (auto Param : FnDecl->parameters()) {
13362 QualType ParamType = Param->getType().getNonReferenceType();
13363 if (ParamType->isDependentType() || ParamType->isRecordType() ||
13364 ParamType->isEnumeralType()) {
13365 ClassOrEnumParam = true;
13366 break;
13367 }
13368 }
13369
13370 if (!ClassOrEnumParam)
13371 return Diag(FnDecl->getLocation(),
13372 diag::err_operator_overload_needs_class_or_enum)
13373 << FnDecl->getDeclName();
13374 }
13375
13376 // C++ [over.oper]p8:
13377 // An operator function cannot have default arguments (8.3.6),
13378 // except where explicitly stated below.
13379 //
13380 // Only the function-call operator allows default arguments
13381 // (C++ [over.call]p1).
13382 if (Op != OO_Call) {
13383 for (auto Param : FnDecl->parameters()) {
13384 if (Param->hasDefaultArg())
13385 return Diag(Param->getLocation(),
13386 diag::err_operator_overload_default_arg)
13387 << FnDecl->getDeclName() << Param->getDefaultArgRange();
13388 }
13389 }
13390
13391 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13392 { false, false, false }
13393#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13394 , { Unary, Binary, MemberOnly }
13395#include "clang/Basic/OperatorKinds.def"
13396 };
13397
13398 bool CanBeUnaryOperator = OperatorUses[Op][0];
13399 bool CanBeBinaryOperator = OperatorUses[Op][1];
13400 bool MustBeMemberOperator = OperatorUses[Op][2];
13401
13402 // C++ [over.oper]p8:
13403 // [...] Operator functions cannot have more or fewer parameters
13404 // than the number required for the corresponding operator, as
13405 // described in the rest of this subclause.
13406 unsigned NumParams = FnDecl->getNumParams()
13407 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13408 if (Op != OO_Call &&
13409 ((NumParams == 1 && !CanBeUnaryOperator) ||
13410 (NumParams == 2 && !CanBeBinaryOperator) ||
13411 (NumParams < 1) || (NumParams > 2))) {
13412 // We have the wrong number of parameters.
13413 unsigned ErrorKind;
13414 if (CanBeUnaryOperator && CanBeBinaryOperator) {
13415 ErrorKind = 2; // 2 -> unary or binary.
13416 } else if (CanBeUnaryOperator) {
13417 ErrorKind = 0; // 0 -> unary
13418 } else {
13419 assert(CanBeBinaryOperator &&((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13420, __PRETTY_FUNCTION__))
13420 "All non-call overloaded operators are unary or binary!")((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13420, __PRETTY_FUNCTION__))
;
13421 ErrorKind = 1; // 1 -> binary
13422 }
13423
13424 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13425 << FnDecl->getDeclName() << NumParams << ErrorKind;
13426 }
13427
13428 // Overloaded operators other than operator() cannot be variadic.
13429 if (Op != OO_Call &&
13430 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13431 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13432 << FnDecl->getDeclName();
13433 }
13434
13435 // Some operators must be non-static member functions.
13436 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13437 return Diag(FnDecl->getLocation(),
13438 diag::err_operator_overload_must_be_member)
13439 << FnDecl->getDeclName();
13440 }
13441
13442 // C++ [over.inc]p1:
13443 // The user-defined function called operator++ implements the
13444 // prefix and postfix ++ operator. If this function is a member
13445 // function with no parameters, or a non-member function with one
13446 // parameter of class or enumeration type, it defines the prefix
13447 // increment operator ++ for objects of that type. If the function
13448 // is a member function with one parameter (which shall be of type
13449 // int) or a non-member function with two parameters (the second
13450 // of which shall be of type int), it defines the postfix
13451 // increment operator ++ for objects of that type.
13452 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13453 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13454 QualType ParamType = LastParam->getType();
13455
13456 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13457 !ParamType->isDependentType())
13458 return Diag(LastParam->getLocation(),
13459 diag::err_operator_overload_post_incdec_must_be_int)
13460 << LastParam->getType() << (Op == OO_MinusMinus);
13461 }
13462
13463 return false;
13464}
13465
13466static bool
13467checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13468 FunctionTemplateDecl *TpDecl) {
13469 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13470
13471 // Must have one or two template parameters.
13472 if (TemplateParams->size() == 1) {
13473 NonTypeTemplateParmDecl *PmDecl =
13474 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13475
13476 // The template parameter must be a char parameter pack.
13477 if (PmDecl && PmDecl->isTemplateParameterPack() &&
13478 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13479 return false;
13480
13481 } else if (TemplateParams->size() == 2) {
13482 TemplateTypeParmDecl *PmType =
13483 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13484 NonTypeTemplateParmDecl *PmArgs =
13485 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13486
13487 // The second template parameter must be a parameter pack with the
13488 // first template parameter as its type.
13489 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13490 PmArgs->isTemplateParameterPack()) {
13491 const TemplateTypeParmType *TArgs =
13492 PmArgs->getType()->getAs<TemplateTypeParmType>();
13493 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13494 TArgs->getIndex() == PmType->getIndex()) {
13495 if (!SemaRef.inTemplateInstantiation())
13496 SemaRef.Diag(TpDecl->getLocation(),
13497 diag::ext_string_literal_operator_template);
13498 return false;
13499 }
13500 }
13501 }
13502
13503 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13504 diag::err_literal_operator_template)
13505 << TpDecl->getTemplateParameters()->getSourceRange();
13506 return true;
13507}
13508
13509/// CheckLiteralOperatorDeclaration - Check whether the declaration
13510/// of this literal operator function is well-formed. If so, returns
13511/// false; otherwise, emits appropriate diagnostics and returns true.
13512bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13513 if (isa<CXXMethodDecl>(FnDecl)) {
13514 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13515 << FnDecl->getDeclName();
13516 return true;
13517 }
13518
13519 if (FnDecl->isExternC()) {
13520 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13521 if (const LinkageSpecDecl *LSD =
13522 FnDecl->getDeclContext()->getExternCContext())
13523 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13524 return true;
13525 }
13526
13527 // This might be the definition of a literal operator template.
13528 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13529
13530 // This might be a specialization of a literal operator template.
13531 if (!TpDecl)
13532 TpDecl = FnDecl->getPrimaryTemplate();
13533
13534 // template <char...> type operator "" name() and
13535 // template <class T, T...> type operator "" name() are the only valid
13536 // template signatures, and the only valid signatures with no parameters.
13537 if (TpDecl) {
13538 if (FnDecl->param_size() != 0) {
13539 Diag(FnDecl->getLocation(),
13540 diag::err_literal_operator_template_with_params);
13541 return true;
13542 }
13543
13544 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13545 return true;
13546
13547 } else if (FnDecl->param_size() == 1) {
13548 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13549
13550 QualType ParamType = Param->getType().getUnqualifiedType();
13551
13552 // Only unsigned long long int, long double, any character type, and const
13553 // char * are allowed as the only parameters.
13554 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13555 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13556 Context.hasSameType(ParamType, Context.CharTy) ||
13557 Context.hasSameType(ParamType, Context.WideCharTy) ||
13558 Context.hasSameType(ParamType, Context.Char8Ty) ||
13559 Context.hasSameType(ParamType, Context.Char16Ty) ||
13560 Context.hasSameType(ParamType, Context.Char32Ty)) {
13561 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13562 QualType InnerType = Ptr->getPointeeType();
13563
13564 // Pointer parameter must be a const char *.
13565 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13566 Context.CharTy) &&
13567 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13568 Diag(Param->getSourceRange().getBegin(),
13569 diag::err_literal_operator_param)
13570 << ParamType << "'const char *'" << Param->getSourceRange();
13571 return true;
13572 }
13573
13574 } else if (ParamType->isRealFloatingType()) {
13575 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13576 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13577 return true;
13578
13579 } else if (ParamType->isIntegerType()) {
13580 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13581 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13582 return true;
13583
13584 } else {
13585 Diag(Param->getSourceRange().getBegin(),
13586 diag::err_literal_operator_invalid_param)
13587 << ParamType << Param->getSourceRange();
13588 return true;
13589 }
13590
13591 } else if (FnDecl->param_size() == 2) {
13592 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13593
13594 // First, verify that the first parameter is correct.
13595
13596 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13597
13598 // Two parameter function must have a pointer to const as a
13599 // first parameter; let's strip those qualifiers.
13600 const PointerType *PT = FirstParamType->getAs<PointerType>();
13601
13602 if (!PT) {
13603 Diag((*Param)->getSourceRange().getBegin(),
13604 diag::err_literal_operator_param)
13605 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13606 return true;
13607 }
13608
13609 QualType PointeeType = PT->getPointeeType();
13610 // First parameter must be const
13611 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13612 Diag((*Param)->getSourceRange().getBegin(),
13613 diag::err_literal_operator_param)
13614 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13615 return true;
13616 }
13617
13618 QualType InnerType = PointeeType.getUnqualifiedType();
13619 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13620 // const char32_t* are allowed as the first parameter to a two-parameter
13621 // function
13622 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13623 Context.hasSameType(InnerType, Context.WideCharTy) ||
13624 Context.hasSameType(InnerType, Context.Char8Ty) ||
13625 Context.hasSameType(InnerType, Context.Char16Ty) ||
13626 Context.hasSameType(InnerType, Context.Char32Ty))) {
13627 Diag((*Param)->getSourceRange().getBegin(),
13628 diag::err_literal_operator_param)
13629 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13630 return true;
13631 }
13632
13633 // Move on to the second and final parameter.
13634 ++Param;
13635
13636 // The second parameter must be a std::size_t.
13637 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13638 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13639 Diag((*Param)->getSourceRange().getBegin(),
13640 diag::err_literal_operator_param)
13641 << SecondParamType << Context.getSizeType()
13642 << (*Param)->getSourceRange();
13643 return true;
13644 }
13645 } else {
13646 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13647 return true;
13648 }
13649
13650 // Parameters are good.
13651
13652 // A parameter-declaration-clause containing a default argument is not
13653 // equivalent to any of the permitted forms.
13654 for (auto Param : FnDecl->parameters()) {
13655 if (Param->hasDefaultArg()) {
13656 Diag(Param->getDefaultArgRange().getBegin(),
13657 diag::err_literal_operator_default_argument)
13658 << Param->getDefaultArgRange();
13659 break;
13660 }
13661 }
13662
13663 StringRef LiteralName
13664 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13665 if (LiteralName[0] != '_' &&
13666 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13667 // C++11 [usrlit.suffix]p1:
13668 // Literal suffix identifiers that do not start with an underscore
13669 // are reserved for future standardization.
13670 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13671 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13672 }
13673
13674 return false;
13675}
13676
13677/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13678/// linkage specification, including the language and (if present)
13679/// the '{'. ExternLoc is the location of the 'extern', Lang is the
13680/// language string literal. LBraceLoc, if valid, provides the location of
13681/// the '{' brace. Otherwise, this linkage specification does not
13682/// have any braces.
13683Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13684 Expr *LangStr,
13685 SourceLocation LBraceLoc) {
13686 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13687 if (!Lit->isAscii()) {
13688 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13689 << LangStr->getSourceRange();
13690 return nullptr;
13691 }
13692
13693 StringRef Lang = Lit->getString();
13694 LinkageSpecDecl::LanguageIDs Language;
13695 if (Lang == "C")
13696 Language = LinkageSpecDecl::lang_c;
13697 else if (Lang == "C++")
13698 Language = LinkageSpecDecl::lang_cxx;
13699 else {
13700 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13701 << LangStr->getSourceRange();
13702 return nullptr;
13703 }
13704
13705 // FIXME: Add all the various semantics of linkage specifications
13706
13707 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13708 LangStr->getExprLoc(), Language,
13709 LBraceLoc.isValid());
13710 CurContext->addDecl(D);
13711 PushDeclContext(S, D);
13712 return D;
13713}
13714
13715/// ActOnFinishLinkageSpecification - Complete the definition of
13716/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13717/// valid, it's the position of the closing '}' brace in a linkage
13718/// specification that uses braces.
13719Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13720 Decl *LinkageSpec,
13721 SourceLocation RBraceLoc) {
13722 if (RBraceLoc.isValid()) {
13723 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13724 LSDecl->setRBraceLoc(RBraceLoc);
13725 }
13726 PopDeclContext();
13727 return LinkageSpec;
13728}
13729
13730Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13731 const ParsedAttributesView &AttrList,
13732 SourceLocation SemiLoc) {
13733 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13734 // Attribute declarations appertain to empty declaration so we handle
13735 // them here.
13736 ProcessDeclAttributeList(S, ED, AttrList);
13737
13738 CurContext->addDecl(ED);
13739 return ED;
13740}
13741
13742/// Perform semantic analysis for the variable declaration that
13743/// occurs within a C++ catch clause, returning the newly-created
13744/// variable.
13745VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13746 TypeSourceInfo *TInfo,
13747 SourceLocation StartLoc,
13748 SourceLocation Loc,
13749 IdentifierInfo *Name) {
13750 bool Invalid = false;
13751 QualType ExDeclType = TInfo->getType();
13752
13753 // Arrays and functions decay.
13754 if (ExDeclType->isArrayType())
13755 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13756 else if (ExDeclType->isFunctionType())
13757 ExDeclType = Context.getPointerType(ExDeclType);
13758
13759 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13760 // The exception-declaration shall not denote a pointer or reference to an
13761 // incomplete type, other than [cv] void*.
13762 // N2844 forbids rvalue references.
13763 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13764 Diag(Loc, diag::err_catch_rvalue_ref);
13765 Invalid = true;
13766 }
13767
13768 if (ExDeclType->isVariablyModifiedType()) {
13769 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13770 Invalid = true;
13771 }
13772
13773 QualType BaseType = ExDeclType;
13774 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13775 unsigned DK = diag::err_catch_incomplete;
13776 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13777 BaseType = Ptr->getPointeeType();
13778 Mode = 1;
13779 DK = diag::err_catch_incomplete_ptr;
13780 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13781 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13782 BaseType = Ref->getPointeeType();
13783 Mode = 2;
13784 DK = diag::err_catch_incomplete_ref;
13785 }
13786 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13787 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13788 Invalid = true;
13789
13790 if (!Invalid && !ExDeclType->isDependentType() &&
13791 RequireNonAbstractType(Loc, ExDeclType,
13792 diag::err_abstract_type_in_decl,
13793 AbstractVariableType))
13794 Invalid = true;
13795
13796 // Only the non-fragile NeXT runtime currently supports C++ catches
13797 // of ObjC types, and no runtime supports catching ObjC types by value.
13798 if (!Invalid && getLangOpts().ObjC) {
13799 QualType T = ExDeclType;
13800 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13801 T = RT->getPointeeType();
13802
13803 if (T->isObjCObjectType()) {
13804 Diag(Loc, diag::err_objc_object_catch);
13805 Invalid = true;
13806 } else if (T->isObjCObjectPointerType()) {
13807 // FIXME: should this be a test for macosx-fragile specifically?
13808 if (getLangOpts().ObjCRuntime.isFragile())
13809 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13810 }
13811 }
13812
13813 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13814 ExDeclType, TInfo, SC_None);
13815 ExDecl->setExceptionVariable(true);
13816
13817 // In ARC, infer 'retaining' for variables of retainable type.
13818 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13819 Invalid = true;
13820
13821 if (!Invalid && !ExDeclType->isDependentType()) {
13822 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13823 // Insulate this from anything else we might currently be parsing.
13824 EnterExpressionEvaluationContext scope(
13825 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13826
13827 // C++ [except.handle]p16:
13828 // The object declared in an exception-declaration or, if the
13829 // exception-declaration does not specify a name, a temporary (12.2) is
13830 // copy-initialized (8.5) from the exception object. [...]
13831 // The object is destroyed when the handler exits, after the destruction
13832 // of any automatic objects initialized within the handler.
13833 //
13834 // We just pretend to initialize the object with itself, then make sure
13835 // it can be destroyed later.
13836 QualType initType = Context.getExceptionObjectType(ExDeclType);
13837
13838 InitializedEntity entity =
13839 InitializedEntity::InitializeVariable(ExDecl);
13840 InitializationKind initKind =
13841 InitializationKind::CreateCopy(Loc, SourceLocation());
13842
13843 Expr *opaqueValue =
13844 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13845 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13846 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13847 if (result.isInvalid())
13848 Invalid = true;
13849 else {
13850 // If the constructor used was non-trivial, set this as the
13851 // "initializer".
13852 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13853 if (!construct->getConstructor()->isTrivial()) {
13854 Expr *init = MaybeCreateExprWithCleanups(construct);
13855 ExDecl->setInit(init);
13856 }
13857
13858 // And make sure it's destructable.
13859 FinalizeVarWithDestructor(ExDecl, recordType);
13860 }
13861 }
13862 }
13863
13864 if (Invalid)
13865 ExDecl->setInvalidDecl();
13866
13867 return ExDecl;
13868}
13869
13870/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13871/// handler.
13872Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13873 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13874 bool Invalid = D.isInvalidType();
13875
13876 // Check for unexpanded parameter packs.
13877 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13878 UPPC_ExceptionType)) {
13879 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13880 D.getIdentifierLoc());
13881 Invalid = true;
13882 }
13883
13884 IdentifierInfo *II = D.getIdentifier();
13885 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13886 LookupOrdinaryName,
13887 ForVisibleRedeclaration)) {
13888 // The scope should be freshly made just for us. There is just no way
13889 // it contains any previous declaration, except for function parameters in
13890 // a function-try-block's catch statement.
13891 assert(!S->isDeclScope(PrevDecl))((!S->isDeclScope(PrevDecl)) ? static_cast<void> (0)
: __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13891, __PRETTY_FUNCTION__))
;
13892 if (isDeclInScope(PrevDecl, CurContext, S)) {
13893 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13894 << D.getIdentifier();
13895 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13896 Invalid = true;
13897 } else if (PrevDecl->isTemplateParameter())
13898 // Maybe we will complain about the shadowed template parameter.
13899 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13900 }
13901
13902 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13903 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13904 << D.getCXXScopeSpec().getRange();
13905 Invalid = true;
13906 }
13907
13908 VarDecl *ExDecl = BuildExceptionDeclaration(
13909 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13910 if (Invalid)
13911 ExDecl->setInvalidDecl();
13912
13913 // Add the exception declaration into this scope.
13914 if (II)
13915 PushOnScopeChains(ExDecl, S);
13916 else
13917 CurContext->addDecl(ExDecl);
13918
13919 ProcessDeclAttributes(S, ExDecl, D);
13920 return ExDecl;
13921}
13922
13923Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13924 Expr *AssertExpr,
13925 Expr *AssertMessageExpr,
13926 SourceLocation RParenLoc) {
13927 StringLiteral *AssertMessage =
13928 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13929
13930 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13931 return nullptr;
13932
13933 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13934 AssertMessage, RParenLoc, false);
13935}
13936
13937Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13938 Expr *AssertExpr,
13939 StringLiteral *AssertMessage,
13940 SourceLocation RParenLoc,
13941 bool Failed) {
13942 assert(AssertExpr != nullptr && "Expected non-null condition")((AssertExpr != nullptr && "Expected non-null condition"
) ? static_cast<void> (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13942, __PRETTY_FUNCTION__))
;
13943 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13944 !Failed) {
13945 // In a static_assert-declaration, the constant-expression shall be a
13946 // constant expression that can be contextually converted to bool.
13947 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13948 if (Converted.isInvalid())
13949 Failed = true;
13950 else
13951 Converted = ConstantExpr::Create(Context, Converted.get());
13952
13953 llvm::APSInt Cond;
13954 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13955 diag::err_static_assert_expression_is_not_constant,
13956 /*AllowFold=*/false).isInvalid())
13957 Failed = true;
13958
13959 if (!Failed && !Cond) {
13960 SmallString<256> MsgBuffer;
13961 llvm::raw_svector_ostream Msg(MsgBuffer);
13962 if (AssertMessage)
13963 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13964
13965 Expr *InnerCond = nullptr;
13966 std::string InnerCondDescription;
13967 std::tie(InnerCond, InnerCondDescription) =
13968 findFailedBooleanCondition(Converted.get());
13969 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13970 && !isa<IntegerLiteral>(InnerCond)) {
13971 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13972 << InnerCondDescription << !AssertMessage
13973 << Msg.str() << InnerCond->getSourceRange();
13974 } else {
13975 Diag(StaticAssertLoc, diag::err_static_assert_failed)
13976 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13977 }
13978 Failed = true;
13979 }
13980 }
13981
13982 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13983 /*DiscardedValue*/false,
13984 /*IsConstexpr*/true);
13985 if (FullAssertExpr.isInvalid())
13986 Failed = true;
13987 else
13988 AssertExpr = FullAssertExpr.get();
13989
13990 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13991 AssertExpr, AssertMessage, RParenLoc,
13992 Failed);
13993
13994 CurContext->addDecl(Decl);
13995 return Decl;
13996}
13997
13998/// Perform semantic analysis of the given friend type declaration.
13999///
14000/// \returns A friend declaration that.
14001FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14002 SourceLocation FriendLoc,
14003 TypeSourceInfo *TSInfo) {
14004 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")((TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? static_cast<void> (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14004, __PRETTY_FUNCTION__))
;
14005
14006 QualType T = TSInfo->getType();
14007 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14008
14009 // C++03 [class.friend]p2:
14010 // An elaborated-type-specifier shall be used in a friend declaration
14011 // for a class.*
14012 //
14013 // * The class-key of the elaborated-type-specifier is required.
14014 if (!CodeSynthesisContexts.empty()) {
14015 // Do not complain about the form of friend template types during any kind
14016 // of code synthesis. For template instantiation, we will have complained
14017 // when the template was defined.
14018 } else {
14019 if (!T->isElaboratedTypeSpecifier()) {
14020 // If we evaluated the type to a record type, suggest putting
14021 // a tag in front.
14022 if (const RecordType *RT = T->getAs<RecordType>()) {
14023 RecordDecl *RD = RT->getDecl();
14024
14025 SmallString<16> InsertionText(" ");
14026 InsertionText += RD->getKindName();
14027
14028 Diag(TypeRange.getBegin(),
14029 getLangOpts().CPlusPlus11 ?
14030 diag::warn_cxx98_compat_unelaborated_friend_type :
14031 diag::ext_unelaborated_friend_type)
14032 << (unsigned) RD->getTagKind()
14033 << T
14034 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14035 InsertionText);
14036 } else {
14037 Diag(FriendLoc,
14038 getLangOpts().CPlusPlus11 ?
14039 diag::warn_cxx98_compat_nonclass_type_friend :
14040 diag::ext_nonclass_type_friend)
14041 << T
14042 << TypeRange;
14043 }
14044 } else if (T->getAs<EnumType>()) {
14045 Diag(FriendLoc,
14046 getLangOpts().CPlusPlus11 ?
14047 diag::warn_cxx98_compat_enum_friend :
14048 diag::ext_enum_friend)
14049 << T
14050 << TypeRange;
14051 }
14052
14053 // C++11 [class.friend]p3:
14054 // A friend declaration that does not declare a function shall have one
14055 // of the following forms:
14056 // friend elaborated-type-specifier ;
14057 // friend simple-type-specifier ;
14058 // friend typename-specifier ;
14059 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14060 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14061 }
14062
14063 // If the type specifier in a friend declaration designates a (possibly
14064 // cv-qualified) class type, that class is declared as a friend; otherwise,
14065 // the friend declaration is ignored.
14066 return FriendDecl::Create(Context, CurContext,
14067 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14068 FriendLoc);
14069}
14070
14071/// Handle a friend tag declaration where the scope specifier was
14072/// templated.
14073Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14074 unsigned TagSpec, SourceLocation TagLoc,
14075 CXXScopeSpec &SS, IdentifierInfo *Name,
14076 SourceLocation NameLoc,
14077 const ParsedAttributesView &Attr,
14078 MultiTemplateParamsArg TempParamLists) {
14079 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14080
14081 bool IsMemberSpecialization = false;
14082 bool Invalid = false;
14083
14084 if (TemplateParameterList *TemplateParams =
14085 MatchTemplateParametersToScopeSpecifier(
14086 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14087 IsMemberSpecialization, Invalid)) {
14088 if (TemplateParams->size() > 0) {
14089 // This is a declaration of a class template.
14090 if (Invalid)
14091 return nullptr;
14092
14093 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14094 NameLoc, Attr, TemplateParams, AS_public,
14095 /*ModulePrivateLoc=*/SourceLocation(),
14096 FriendLoc, TempParamLists.size() - 1,
14097 TempParamLists.data()).get();
14098 } else {
14099 // The "template<>" header is extraneous.
14100 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14101 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14102 IsMemberSpecialization = true;
14103 }
14104 }
14105
14106 if (Invalid) return nullptr;
14107
14108 bool isAllExplicitSpecializations = true;
14109 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14110 if (TempParamLists[I]->size()) {
14111 isAllExplicitSpecializations = false;
14112 break;
14113 }
14114 }
14115
14116 // FIXME: don't ignore attributes.
14117
14118 // If it's explicit specializations all the way down, just forget
14119 // about the template header and build an appropriate non-templated
14120 // friend. TODO: for source fidelity, remember the headers.
14121 if (isAllExplicitSpecializations) {
14122 if (SS.isEmpty()) {
14123 bool Owned = false;
14124 bool IsDependent = false;
14125 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14126 Attr, AS_public,
14127 /*ModulePrivateLoc=*/SourceLocation(),
14128 MultiTemplateParamsArg(), Owned, IsDependent,
14129 /*ScopedEnumKWLoc=*/SourceLocation(),
14130 /*ScopedEnumUsesClassTag=*/false,
14131 /*UnderlyingType=*/TypeResult(),
14132 /*IsTypeSpecifier=*/false,
14133 /*IsTemplateParamOrArg=*/false);
14134 }
14135
14136 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14137 ElaboratedTypeKeyword Keyword
14138 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14139 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14140 *Name, NameLoc);
14141 if (T.isNull())
14142 return nullptr;
14143
14144 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14145 if (isa<DependentNameType>(T)) {
14146 DependentNameTypeLoc TL =
14147 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14148 TL.setElaboratedKeywordLoc(TagLoc);
14149 TL.setQualifierLoc(QualifierLoc);
14150 TL.setNameLoc(NameLoc);
14151 } else {
14152 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14153 TL.setElaboratedKeywordLoc(TagLoc);
14154 TL.setQualifierLoc(QualifierLoc);
14155 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14156 }
14157
14158 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14159 TSI, FriendLoc, TempParamLists);
14160 Friend->setAccess(AS_public);
14161 CurContext->addDecl(Friend);
14162 return Friend;
14163 }
14164
14165 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")((SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? static_cast<void> (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14165, __PRETTY_FUNCTION__))
;
14166
14167
14168
14169 // Handle the case of a templated-scope friend class. e.g.
14170 // template <class T> class A<T>::B;
14171 // FIXME: we don't support these right now.
14172 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14173 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14174 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14175 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14176 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14177 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14178 TL.setElaboratedKeywordLoc(TagLoc);
14179 TL.setQualifierLoc(SS.getWithLocInContext(Context));
14180 TL.setNameLoc(NameLoc);
14181
14182 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14183 TSI, FriendLoc, TempParamLists);
14184 Friend->setAccess(AS_public);
14185 Friend->setUnsupportedFriend(true);
14186 CurContext->addDecl(Friend);
14187 return Friend;
14188}
14189
14190/// Handle a friend type declaration. This works in tandem with
14191/// ActOnTag.
14192///
14193/// Notes on friend class templates:
14194///
14195/// We generally treat friend class declarations as if they were
14196/// declaring a class. So, for example, the elaborated type specifier
14197/// in a friend declaration is required to obey the restrictions of a
14198/// class-head (i.e. no typedefs in the scope chain), template
14199/// parameters are required to match up with simple template-ids, &c.
14200/// However, unlike when declaring a template specialization, it's
14201/// okay to refer to a template specialization without an empty
14202/// template parameter declaration, e.g.
14203/// friend class A<T>::B<unsigned>;
14204/// We permit this as a special case; if there are any template
14205/// parameters present at all, require proper matching, i.e.
14206/// template <> template \<class T> friend class A<int>::B;
14207Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14208 MultiTemplateParamsArg TempParams) {
14209 SourceLocation Loc = DS.getBeginLoc();
14210
14211 assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14211, __PRETTY_FUNCTION__))
;
14212 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast
<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14212, __PRETTY_FUNCTION__))
;
14213
14214 // C++ [class.friend]p3:
14215 // A friend declaration that does not declare a function shall have one of
14216 // the following forms:
14217 // friend elaborated-type-specifier ;
14218 // friend simple-type-specifier ;
14219 // friend typename-specifier ;
14220 //
14221 // Any declaration with a type qualifier does not have that form. (It's
14222 // legal to specify a qualified type as a friend, you just can't write the
14223 // keywords.)
14224 if (DS.getTypeQualifiers()) {
14225 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14226 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14227 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14228 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14229 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14230 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14231 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14232 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14233 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14234 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14235 }
14236
14237 // Try to convert the decl specifier to a type. This works for
14238 // friend templates because ActOnTag never produces a ClassTemplateDecl
14239 // for a TUK_Friend.
14240 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14241 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14242 QualType T = TSI->getType();
14243 if (TheDeclarator.isInvalidType())
14244 return nullptr;
14245
14246 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14247 return nullptr;
14248
14249 // This is definitely an error in C++98. It's probably meant to
14250 // be forbidden in C++0x, too, but the specification is just
14251 // poorly written.
14252 //
14253 // The problem is with declarations like the following:
14254 // template <T> friend A<T>::foo;
14255 // where deciding whether a class C is a friend or not now hinges
14256 // on whether there exists an instantiation of A that causes
14257 // 'foo' to equal C. There are restrictions on class-heads
14258 // (which we declare (by fiat) elaborated friend declarations to
14259 // be) that makes this tractable.
14260 //
14261 // FIXME: handle "template <> friend class A<T>;", which
14262 // is possibly well-formed? Who even knows?
14263 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14264 Diag(Loc, diag::err_tagless_friend_type_template)
14265 << DS.getSourceRange();
14266 return nullptr;
14267 }
14268
14269 // C++98 [class.friend]p1: A friend of a class is a function
14270 // or class that is not a member of the class . . .
14271 // This is fixed in DR77, which just barely didn't make the C++03
14272 // deadline. It's also a very silly restriction that seriously
14273 // affects inner classes and which nobody else seems to implement;
14274 // thus we never diagnose it, not even in -pedantic.
14275 //
14276 // But note that we could warn about it: it's always useless to
14277 // friend one of your own members (it's not, however, worthless to
14278 // friend a member of an arbitrary specialization of your template).
14279
14280 Decl *D;
14281 if (!TempParams.empty())
14282 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14283 TempParams,
14284 TSI,
14285 DS.getFriendSpecLoc());
14286 else
14287 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14288
14289 if (!D)
14290 return nullptr;
14291
14292 D->setAccess(AS_public);
14293 CurContext->addDecl(D);
14294
14295 return D;
14296}
14297
14298NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14299 MultiTemplateParamsArg TemplateParams) {
14300 const DeclSpec &DS = D.getDeclSpec();
14301
14302 assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14302, __PRETTY_FUNCTION__))
;
14303 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast
<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14303, __PRETTY_FUNCTION__))
;
14304
14305 SourceLocation Loc = D.getIdentifierLoc();
14306 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14307
14308 // C++ [class.friend]p1
14309 // A friend of a class is a function or class....
14310 // Note that this sees through typedefs, which is intended.
14311 // It *doesn't* see through dependent types, which is correct
14312 // according to [temp.arg.type]p3:
14313 // If a declaration acquires a function type through a
14314 // type dependent on a template-parameter and this causes
14315 // a declaration that does not use the syntactic form of a
14316 // function declarator to have a function type, the program
14317 // is ill-formed.
14318 if (!TInfo->getType()->isFunctionType()) {
14319 Diag(Loc, diag::err_unexpected_friend);
14320
14321 // It might be worthwhile to try to recover by creating an
14322 // appropriate declaration.
14323 return nullptr;
14324 }
14325
14326 // C++ [namespace.memdef]p3
14327 // - If a friend declaration in a non-local class first declares a
14328 // class or function, the friend class or function is a member
14329 // of the innermost enclosing namespace.
14330 // - The name of the friend is not found by simple name lookup
14331 // until a matching declaration is provided in that namespace
14332 // scope (either before or after the class declaration granting
14333 // friendship).
14334 // - If a friend function is called, its name may be found by the
14335 // name lookup that considers functions from namespaces and
14336 // classes associated with the types of the function arguments.
14337 // - When looking for a prior declaration of a class or a function
14338 // declared as a friend, scopes outside the innermost enclosing
14339 // namespace scope are not considered.
14340
14341 CXXScopeSpec &SS = D.getCXXScopeSpec();
14342 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14343 assert(NameInfo.getName())((NameInfo.getName()) ? static_cast<void> (0) : __assert_fail
("NameInfo.getName()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14343, __PRETTY_FUNCTION__))
;
14344
14345 // Check for unexpanded parameter packs.
14346 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14347 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14348 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14349 return nullptr;
14350
14351 // The context we found the declaration in, or in which we should
14352 // create the declaration.
14353 DeclContext *DC;
14354 Scope *DCScope = S;
14355 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14356 ForExternalRedeclaration);
14357
14358 // There are five cases here.
14359 // - There's no scope specifier and we're in a local class. Only look
14360 // for functions declared in the immediately-enclosing block scope.
14361 // We recover from invalid scope qualifiers as if they just weren't there.
14362 FunctionDecl *FunctionContainingLocalClass = nullptr;
14363 if ((SS.isInvalid() || !SS.isSet()) &&
14364 (FunctionContainingLocalClass =
14365 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14366 // C++11 [class.friend]p11:
14367 // If a friend declaration appears in a local class and the name
14368 // specified is an unqualified name, a prior declaration is
14369 // looked up without considering scopes that are outside the
14370 // innermost enclosing non-class scope. For a friend function
14371 // declaration, if there is no prior declaration, the program is
14372 // ill-formed.
14373
14374 // Find the innermost enclosing non-class scope. This is the block
14375 // scope containing the local class definition (or for a nested class,
14376 // the outer local class).
14377 DCScope = S->getFnParent();
14378
14379 // Look up the function name in the scope.
14380 Previous.clear(LookupLocalFriendName);
14381 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14382
14383 if (!Previous.empty()) {
14384 // All possible previous declarations must have the same context:
14385 // either they were declared at block scope or they are members of
14386 // one of the enclosing local classes.
14387 DC = Previous.getRepresentativeDecl()->getDeclContext();
14388 } else {
14389 // This is ill-formed, but provide the context that we would have
14390 // declared the function in, if we were permitted to, for error recovery.
14391 DC = FunctionContainingLocalClass;
14392 }
14393 adjustContextForLocalExternDecl(DC);
14394
14395 // C++ [class.friend]p6:
14396 // A function can be defined in a friend declaration of a class if and
14397 // only if the class is a non-local class (9.8), the function name is
14398 // unqualified, and the function has namespace scope.
14399 if (D.isFunctionDefinition()) {
14400 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14401 }
14402
14403 // - There's no scope specifier, in which case we just go to the
14404 // appropriate scope and look for a function or function template
14405 // there as appropriate.
14406 } else if (SS.isInvalid() || !SS.isSet()) {
14407 // C++11 [namespace.memdef]p3:
14408 // If the name in a friend declaration is neither qualified nor
14409 // a template-id and the declaration is a function or an
14410 // elaborated-type-specifier, the lookup to determine whether
14411 // the entity has been previously declared shall not consider
14412 // any scopes outside the innermost enclosing namespace.
14413 bool isTemplateId =
14414 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14415
14416 // Find the appropriate context according to the above.
14417 DC = CurContext;
14418
14419 // Skip class contexts. If someone can cite chapter and verse
14420 // for this behavior, that would be nice --- it's what GCC and
14421 // EDG do, and it seems like a reasonable intent, but the spec
14422 // really only says that checks for unqualified existing
14423 // declarations should stop at the nearest enclosing namespace,
14424 // not that they should only consider the nearest enclosing
14425 // namespace.
14426 while (DC->isRecord())
14427 DC = DC->getParent();
14428
14429 DeclContext *LookupDC = DC;
14430 while (LookupDC->isTransparentContext())
14431 LookupDC = LookupDC->getParent();
14432
14433 while (true) {
14434 LookupQualifiedName(Previous, LookupDC);
14435
14436 if (!Previous.empty()) {
14437 DC = LookupDC;
14438 break;
14439 }
14440
14441 if (isTemplateId) {
14442 if (isa<TranslationUnitDecl>(LookupDC)) break;
14443 } else {
14444 if (LookupDC->isFileContext()) break;
14445 }
14446 LookupDC = LookupDC->getParent();
14447 }
14448
14449 DCScope = getScopeForDeclContext(S, DC);
14450
14451 // - There's a non-dependent scope specifier, in which case we
14452 // compute it and do a previous lookup there for a function
14453 // or function template.
14454 } else if (!SS.getScopeRep()->isDependent()) {
14455 DC = computeDeclContext(SS);
14456 if (!DC) return nullptr;
14457
14458 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14459
14460 LookupQualifiedName(Previous, DC);
14461
14462 // C++ [class.friend]p1: A friend of a class is a function or
14463 // class that is not a member of the class . . .
14464 if (DC->Equals(CurContext))
14465 Diag(DS.getFriendSpecLoc(),
14466 getLangOpts().CPlusPlus11 ?
14467 diag::warn_cxx98_compat_friend_is_member :
14468 diag::err_friend_is_member);
14469
14470 if (D.isFunctionDefinition()) {
14471 // C++ [class.friend]p6:
14472 // A function can be defined in a friend declaration of a class if and
14473 // only if the class is a non-local class (9.8), the function name is
14474 // unqualified, and the function has namespace scope.
14475 //
14476 // FIXME: We should only do this if the scope specifier names the
14477 // innermost enclosing namespace; otherwise the fixit changes the
14478 // meaning of the code.
14479 SemaDiagnosticBuilder DB
14480 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14481
14482 DB << SS.getScopeRep();
14483 if (DC->isFileContext())
14484 DB << FixItHint::CreateRemoval(SS.getRange());
14485 SS.clear();
14486 }
14487
14488 // - There's a scope specifier that does not match any template
14489 // parameter lists, in which case we use some arbitrary context,
14490 // create a method or method template, and wait for instantiation.
14491 // - There's a scope specifier that does match some template
14492 // parameter lists, which we don't handle right now.
14493 } else {
14494 if (D.isFunctionDefinition()) {
14495 // C++ [class.friend]p6:
14496 // A function can be defined in a friend declaration of a class if and
14497 // only if the class is a non-local class (9.8), the function name is
14498 // unqualified, and the function has namespace scope.
14499 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14500 << SS.getScopeRep();
14501 }
14502
14503 DC = CurContext;
14504 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")((isa<CXXRecordDecl>(DC) && "friend declaration not in class?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14504, __PRETTY_FUNCTION__))
;
14505 }
14506
14507 if (!DC->isRecord()) {
14508 int DiagArg = -1;
14509 switch (D.getName().getKind()) {
14510 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14511 case UnqualifiedIdKind::IK_ConstructorName:
14512 DiagArg = 0;
14513 break;
14514 case UnqualifiedIdKind::IK_DestructorName:
14515 DiagArg = 1;
14516 break;
14517 case UnqualifiedIdKind::IK_ConversionFunctionId:
14518 DiagArg = 2;
14519 break;
14520 case UnqualifiedIdKind::IK_DeductionGuideName:
14521 DiagArg = 3;
14522 break;
14523 case UnqualifiedIdKind::IK_Identifier:
14524 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14525 case UnqualifiedIdKind::IK_LiteralOperatorId:
14526 case UnqualifiedIdKind::IK_OperatorFunctionId:
14527 case UnqualifiedIdKind::IK_TemplateId:
14528 break;
14529 }
14530 // This implies that it has to be an operator or function.
14531 if (DiagArg >= 0) {
14532 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14533 return nullptr;
14534 }
14535 }
14536
14537 // FIXME: This is an egregious hack to cope with cases where the scope stack
14538 // does not contain the declaration context, i.e., in an out-of-line
14539 // definition of a class.
14540 Scope FakeDCScope(S, Scope::DeclScope, Diags);
14541 if (!DCScope) {
14542 FakeDCScope.setEntity(DC);
14543 DCScope = &FakeDCScope;
14544 }
14545
14546 bool AddToScope = true;
14547 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14548 TemplateParams, AddToScope);
14549 if (!ND) return nullptr;
14550
14551 assert(ND->getLexicalDeclContext() == CurContext)((ND->getLexicalDeclContext() == CurContext) ? static_cast
<void> (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14551, __PRETTY_FUNCTION__))
;
14552
14553 // If we performed typo correction, we might have added a scope specifier
14554 // and changed the decl context.
14555 DC = ND->getDeclContext();
14556
14557 // Add the function declaration to the appropriate lookup tables,
14558 // adjusting the redeclarations list as necessary. We don't
14559 // want to do this yet if the friending class is dependent.
14560 //
14561 // Also update the scope-based lookup if the target context's
14562 // lookup context is in lexical scope.
14563 if (!CurContext->isDependentContext()) {
14564 DC = DC->getRedeclContext();
14565 DC->makeDeclVisibleInContext(ND);
14566 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14567 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14568 }
14569
14570 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14571 D.getIdentifierLoc(), ND,
14572 DS.getFriendSpecLoc());
14573 FrD->setAccess(AS_public);
14574 CurContext->addDecl(FrD);
14575
14576 if (ND->isInvalidDecl()) {
14577 FrD->setInvalidDecl();
14578 } else {
14579 if (DC->isRecord()) CheckFriendAccess(ND);
14580
14581 FunctionDecl *FD;
14582 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14583 FD = FTD->getTemplatedDecl();
14584 else
14585 FD = cast<FunctionDecl>(ND);
14586
14587 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14588 // default argument expression, that declaration shall be a definition
14589 // and shall be the only declaration of the function or function
14590 // template in the translation unit.
14591 if (functionDeclHasDefaultArgument(FD)) {
14592 // We can't look at FD->getPreviousDecl() because it may not have been set
14593 // if we're in a dependent context. If the function is known to be a
14594 // redeclaration, we will have narrowed Previous down to the right decl.
14595 if (D.isRedeclaration()) {
14596 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14597 Diag(Previous.getRepresentativeDecl()->getLocation(),
14598 diag::note_previous_declaration);
14599 } else if (!D.isFunctionDefinition())
14600 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14601 }
14602
14603 // Mark templated-scope function declarations as unsupported.
14604 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14605 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14606 << SS.getScopeRep() << SS.getRange()
14607 << cast<CXXRecordDecl>(CurContext);
14608 FrD->setUnsupportedFriend(true);
14609 }
14610 }
14611
14612 return ND;
14613}
14614
14615void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14616 AdjustDeclIfTemplate(Dcl);
14617
14618 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14619 if (!Fn) {
14620 Diag(DelLoc, diag::err_deleted_non_function);
14621 return;
14622 }
14623
14624 // Deleted function does not have a body.
14625 Fn->setWillHaveBody(false);
14626
14627 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14628 // Don't consider the implicit declaration we generate for explicit
14629 // specializations. FIXME: Do not generate these implicit declarations.
14630 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14631 Prev->getPreviousDecl()) &&
14632 !Prev->isDefined()) {
14633 Diag(DelLoc, diag::err_deleted_decl_not_first);
14634 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14635 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14636 : diag::note_previous_declaration);
14637 }
14638 // If the declaration wasn't the first, we delete the function anyway for
14639 // recovery.
14640 Fn = Fn->getCanonicalDecl();
14641 }
14642
14643 // dllimport/dllexport cannot be deleted.
14644 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14645 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14646 Fn->setInvalidDecl();
14647 }
14648
14649 if (Fn->isDeleted())
14650 return;
14651
14652 // See if we're deleting a function which is already known to override a
14653 // non-deleted virtual function.
14654 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14655 bool IssuedDiagnostic = false;
14656 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14657 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14658 if (!IssuedDiagnostic) {
14659 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14660 IssuedDiagnostic = true;
14661 }
14662 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14663 }
14664 }
14665 // If this function was implicitly deleted because it was defaulted,
14666 // explain why it was deleted.
14667 if (IssuedDiagnostic && MD->isDefaulted())
14668 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14669 /*Diagnose*/true);
14670 }
14671
14672 // C++11 [basic.start.main]p3:
14673 // A program that defines main as deleted [...] is ill-formed.
14674 if (Fn->isMain())
14675 Diag(DelLoc, diag::err_deleted_main);
14676
14677 // C++11 [dcl.fct.def.delete]p4:
14678 // A deleted function is implicitly inline.
14679 Fn->setImplicitlyInline();
14680 Fn->setDeletedAsWritten();
14681}
14682
14683void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14684 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14685
14686 if (MD) {
14687 if (MD->getParent()->isDependentType()) {
14688 MD->setDefaulted();
14689 MD->setExplicitlyDefaulted();
14690 return;
14691 }
14692
14693 CXXSpecialMember Member = getSpecialMember(MD);
14694 if (Member == CXXInvalid) {
14695 if (!MD->isInvalidDecl())
14696 Diag(DefaultLoc, diag::err_default_special_members);
14697 return;
14698 }
14699
14700 MD->setDefaulted();
14701 MD->setExplicitlyDefaulted();
14702
14703 // Unset that we will have a body for this function. We might not,
14704 // if it turns out to be trivial, and we don't need this marking now
14705 // that we've marked it as defaulted.
14706 MD->setWillHaveBody(false);
14707
14708 // If this definition appears within the record, do the checking when
14709 // the record is complete.
14710 const FunctionDecl *Primary = MD;
14711 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14712 // Ask the template instantiation pattern that actually had the
14713 // '= default' on it.
14714 Primary = Pattern;
14715
14716 // If the method was defaulted on its first declaration, we will have
14717 // already performed the checking in CheckCompletedCXXClass. Such a
14718 // declaration doesn't trigger an implicit definition.
14719 if (Primary->getCanonicalDecl()->isDefaulted())
14720 return;
14721
14722 CheckExplicitlyDefaultedSpecialMember(MD);
14723
14724 if (!MD->isInvalidDecl())
14725 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14726 } else {
14727 Diag(DefaultLoc, diag::err_default_special_members);
14728 }
14729}
14730
14731static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14732 for (Stmt *SubStmt : S->children()) {
14733 if (!SubStmt)
14734 continue;
14735 if (isa<ReturnStmt>(SubStmt))
14736 Self.Diag(SubStmt->getBeginLoc(),
14737 diag::err_return_in_constructor_handler);
14738 if (!isa<Expr>(SubStmt))
14739 SearchForReturnInStmt(Self, SubStmt);
14740 }
14741}
14742
14743void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14744 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14745 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14746 SearchForReturnInStmt(*this, Handler);
14747 }
14748}
14749
14750bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14751 const CXXMethodDecl *Old) {
14752 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14753 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14754
14755 if (OldFT->hasExtParameterInfos()) {
14756 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14757 // A parameter of the overriding method should be annotated with noescape
14758 // if the corresponding parameter of the overridden method is annotated.
14759 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14760 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14761 Diag(New->getParamDecl(I)->getLocation(),
14762 diag::warn_overriding_method_missing_noescape);
14763 Diag(Old->getParamDecl(I)->getLocation(),
14764 diag::note_overridden_marked_noescape);
14765 }
14766 }
14767
14768 // Virtual overrides must have the same code_seg.
14769 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14770 const auto *NewCSA = New->getAttr<CodeSegAttr>();
14771 if ((NewCSA || OldCSA) &&
14772 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14773 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14774 Diag(Old->getLocation(), diag::note_previous_declaration);
14775 return true;
14776 }
14777
14778 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14779
14780 // If the calling conventions match, everything is fine
14781 if (NewCC == OldCC)
14782 return false;
14783
14784 // If the calling conventions mismatch because the new function is static,
14785 // suppress the calling convention mismatch error; the error about static
14786 // function override (err_static_overrides_virtual from
14787 // Sema::CheckFunctionDeclaration) is more clear.
14788 if (New->getStorageClass() == SC_Static)
14789 return false;
14790
14791 Diag(New->getLocation(),
14792 diag::err_conflicting_overriding_cc_attributes)
14793 << New->getDeclName() << New->getType() << Old->getType();
14794 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14795 return true;
14796}
14797
14798bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14799 const CXXMethodDecl *Old) {
14800 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14801 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14802
14803 if (Context.hasSameType(NewTy, OldTy) ||
14804 NewTy->isDependentType() || OldTy->isDependentType())
14805 return false;
14806
14807 // Check if the return types are covariant
14808 QualType NewClassTy, OldClassTy;
14809
14810 /// Both types must be pointers or references to classes.
14811 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14812 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14813 NewClassTy = NewPT->getPointeeType();
14814 OldClassTy = OldPT->getPointeeType();
14815 }
14816 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14817 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14818 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14819 NewClassTy = NewRT->getPointeeType();
14820 OldClassTy = OldRT->getPointeeType();
14821 }
14822 }
14823 }
14824
14825 // The return types aren't either both pointers or references to a class type.
14826 if (NewClassTy.isNull()) {
14827 Diag(New->getLocation(),
14828 diag::err_different_return_type_for_overriding_virtual_function)
14829 << New->getDeclName() << NewTy << OldTy
14830 << New->getReturnTypeSourceRange();
14831 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14832 << Old->getReturnTypeSourceRange();
14833
14834 return true;
14835 }
14836
14837 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14838 // C++14 [class.virtual]p8:
14839 // If the class type in the covariant return type of D::f differs from
14840 // that of B::f, the class type in the return type of D::f shall be
14841 // complete at the point of declaration of D::f or shall be the class
14842 // type D.
14843 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14844 if (!RT->isBeingDefined() &&
14845 RequireCompleteType(New->getLocation(), NewClassTy,
14846 diag::err_covariant_return_incomplete,
14847 New->getDeclName()))
14848 return true;
14849 }
14850
14851 // Check if the new class derives from the old class.
14852 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14853 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14854 << New->getDeclName() << NewTy << OldTy
14855 << New->getReturnTypeSourceRange();
14856 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14857 << Old->getReturnTypeSourceRange();
14858 return true;
14859 }
14860
14861 // Check if we the conversion from derived to base is valid.
14862 if (CheckDerivedToBaseConversion(
14863 NewClassTy, OldClassTy,
14864 diag::err_covariant_return_inaccessible_base,
14865 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14866 New->getLocation(), New->getReturnTypeSourceRange(),
14867 New->getDeclName(), nullptr)) {
14868 // FIXME: this note won't trigger for delayed access control
14869 // diagnostics, and it's impossible to get an undelayed error
14870 // here from access control during the original parse because
14871 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14872 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14873 << Old->getReturnTypeSourceRange();
14874 return true;
14875 }
14876 }
14877
14878 // The qualifiers of the return types must be the same.
14879 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14880 Diag(New->getLocation(),
14881 diag::err_covariant_return_type_different_qualifications)
14882 << New->getDeclName() << NewTy << OldTy
14883 << New->getReturnTypeSourceRange();
14884 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14885 << Old->getReturnTypeSourceRange();
14886 return true;
14887 }
14888
14889
14890 // The new class type must have the same or less qualifiers as the old type.
14891 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14892 Diag(New->getLocation(),
14893 diag::err_covariant_return_type_class_type_more_qualified)
14894 << New->getDeclName() << NewTy << OldTy
14895 << New->getReturnTypeSourceRange();
14896 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14897 << Old->getReturnTypeSourceRange();
14898 return true;
14899 }
14900
14901 return false;
14902}
14903
14904/// Mark the given method pure.
14905///
14906/// \param Method the method to be marked pure.
14907///
14908/// \param InitRange the source range that covers the "0" initializer.
14909bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14910 SourceLocation EndLoc = InitRange.getEnd();
14911 if (EndLoc.isValid())
14912 Method->setRangeEnd(EndLoc);
14913
14914 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14915 Method->setPure();
14916 return false;
14917 }
14918
14919 if (!Method->isInvalidDecl())
14920 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14921 << Method->getDeclName() << InitRange;
14922 return true;
14923}
14924
14925void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14926 if (D->getFriendObjectKind())
14927 Diag(D->getLocation(), diag::err_pure_friend);
14928 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14929 CheckPureMethod(M, ZeroLoc);
14930 else
14931 Diag(D->getLocation(), diag::err_illegal_initializer);
14932}
14933
14934/// Determine whether the given declaration is a global variable or
14935/// static data member.
14936static bool isNonlocalVariable(const Decl *D) {
14937 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14938 return Var->hasGlobalStorage();
14939
14940 return false;
14941}
14942
14943/// Invoked when we are about to parse an initializer for the declaration
14944/// 'Dcl'.
14945///
14946/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14947/// static data member of class X, names should be looked up in the scope of
14948/// class X. If the declaration had a scope specifier, a scope will have
14949/// been created and passed in for this purpose. Otherwise, S will be null.
14950void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14951 // If there is no declaration, there was an error parsing it.
14952 if (!D || D->isInvalidDecl())
14953 return;
14954
14955 // We will always have a nested name specifier here, but this declaration
14956 // might not be out of line if the specifier names the current namespace:
14957 // extern int n;
14958 // int ::n = 0;
14959 if (S && D->isOutOfLine())
14960 EnterDeclaratorContext(S, D->getDeclContext());
14961
14962 // If we are parsing the initializer for a static data member, push a
14963 // new expression evaluation context that is associated with this static
14964 // data member.
14965 if (isNonlocalVariable(D))
14966 PushExpressionEvaluationContext(
14967 ExpressionEvaluationContext::PotentiallyEvaluated, D);
14968}
14969
14970/// Invoked after we are finished parsing an initializer for the declaration D.
14971void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14972 // If there is no declaration, there was an error parsing it.
14973 if (!D || D->isInvalidDecl())
14974 return;
14975
14976 if (isNonlocalVariable(D))
14977 PopExpressionEvaluationContext();
14978
14979 if (S && D->isOutOfLine())
14980 ExitDeclaratorContext(S);
14981}
14982
14983/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14984/// C++ if/switch/while/for statement.
14985/// e.g: "if (int x = f()) {...}"
14986DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14987 // C++ 6.4p2:
14988 // The declarator shall not specify a function or an array.
14989 // The type-specifier-seq shall not contain typedef and shall not declare a
14990 // new class or enumeration.
14991 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class of condition decl."
) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14992, __PRETTY_FUNCTION__))
14992 "Parser allowed 'typedef' as storage class of condition decl.")((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class of condition decl."
) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14992, __PRETTY_FUNCTION__))
;
14993
14994 Decl *Dcl = ActOnDeclarator(S, D);
14995 if (!Dcl)
14996 return true;
14997
14998 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14999 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15000 << D.getSourceRange();
15001 return true;
15002 }
15003
15004 return Dcl;
15005}
15006
15007void Sema::LoadExternalVTableUses() {
15008 if (!ExternalSource)
15009 return;
15010
15011 SmallVector<ExternalVTableUse, 4> VTables;
15012 ExternalSource->ReadUsedVTables(VTables);
15013 SmallVector<VTableUse, 4> NewUses;
15014 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15015 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15016 = VTablesUsed.find(VTables[I].Record);
15017 // Even if a definition wasn't required before, it may be required now.
15018 if (Pos != VTablesUsed.end()) {
15019 if (!Pos->second && VTables[I].DefinitionRequired)
15020 Pos->second = true;
15021 continue;
15022 }
15023
15024 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15025 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15026 }
15027
15028 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15029}
15030
15031void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15032 bool DefinitionRequired) {
15033 // Ignore any vtable uses in unevaluated operands or for classes that do
15034 // not have a vtable.
15035 if (!Class->isDynamicClass() || Class->isDependentContext() ||
15036 CurContext->isDependentContext() || isUnevaluatedContext())
15037 return;
15038 // Do not mark as used if compiling for the device outside of the target
15039 // region.
15040 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15041 !isInOpenMPDeclareTargetContext() &&
15042 !isInOpenMPTargetExecutionDirective()) {
15043 if (!DefinitionRequired)
15044 MarkVirtualMembersReferenced(Loc, Class);
15045 return;
15046 }
15047
15048 // Try to insert this class into the map.
15049 LoadExternalVTableUses();
15050 Class = Class->getCanonicalDecl();
15051 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15052 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15053 if (!Pos.second) {
15054 // If we already had an entry, check to see if we are promoting this vtable
15055 // to require a definition. If so, we need to reappend to the VTableUses
15056 // list, since we may have already processed the first entry.
15057 if (DefinitionRequired && !Pos.first->second) {
15058 Pos.first->second = true;
15059 } else {
15060 // Otherwise, we can early exit.
15061 return;
15062 }
15063 } else {
15064 // The Microsoft ABI requires that we perform the destructor body
15065 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15066 // the deleting destructor is emitted with the vtable, not with the
15067 // destructor definition as in the Itanium ABI.
15068 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15069 CXXDestructorDecl *DD = Class->getDestructor();
15070 if (DD && DD->isVirtual() && !DD->isDeleted()) {
15071 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15072 // If this is an out-of-line declaration, marking it referenced will
15073 // not do anything. Manually call CheckDestructor to look up operator
15074 // delete().
15075 ContextRAII SavedContext(*this, DD);
15076 CheckDestructor(DD);
15077 } else {
15078 MarkFunctionReferenced(Loc, Class->getDestructor());
15079 }
15080 }
15081 }
15082 }
15083
15084 // Local classes need to have their virtual members marked
15085 // immediately. For all other classes, we mark their virtual members
15086 // at the end of the translation unit.
15087 if (Class->isLocalClass())
15088 MarkVirtualMembersReferenced(Loc, Class);
15089 else
15090 VTableUses.push_back(std::make_pair(Class, Loc));
15091}
15092
15093bool Sema::DefineUsedVTables() {
15094 LoadExternalVTableUses();
15095 if (VTableUses.empty())
15096 return false;
15097
15098 // Note: The VTableUses vector could grow as a result of marking
15099 // the members of a class as "used", so we check the size each
15100 // time through the loop and prefer indices (which are stable) to
15101 // iterators (which are not).
15102 bool DefinedAnything = false;
15103 for (unsigned I = 0; I != VTableUses.size(); ++I) {
15104 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15105 if (!Class)
15106 continue;
15107 TemplateSpecializationKind ClassTSK =
15108 Class->getTemplateSpecializationKind();
15109
15110 SourceLocation Loc = VTableUses[I].second;
15111
15112 bool DefineVTable = true;
15113
15114 // If this class has a key function, but that key function is
15115 // defined in another translation unit, we don't need to emit the
15116 // vtable even though we're using it.
15117 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15118 if (KeyFunction && !KeyFunction->hasBody()) {
15119 // The key function is in another translation unit.
15120 DefineVTable = false;
15121 TemplateSpecializationKind TSK =
15122 KeyFunction->getTemplateSpecializationKind();
15123 assert(TSK != TSK_ExplicitInstantiationDefinition &&((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15125, __PRETTY_FUNCTION__))
15124 TSK != TSK_ImplicitInstantiation &&((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15125, __PRETTY_FUNCTION__))
15125 "Instantiations don't have key functions")((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15125, __PRETTY_FUNCTION__))
;
15126 (void)TSK;
15127 } else if (!KeyFunction) {
15128 // If we have a class with no key function that is the subject
15129 // of an explicit instantiation declaration, suppress the
15130 // vtable; it will live with the explicit instantiation
15131 // definition.
15132 bool IsExplicitInstantiationDeclaration =
15133 ClassTSK == TSK_ExplicitInstantiationDeclaration;
15134 for (auto R : Class->redecls()) {
15135 TemplateSpecializationKind TSK
15136 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15137 if (TSK == TSK_ExplicitInstantiationDeclaration)
15138 IsExplicitInstantiationDeclaration = true;
15139 else if (TSK == TSK_ExplicitInstantiationDefinition) {
15140 IsExplicitInstantiationDeclaration = false;
15141 break;
15142 }
15143 }
15144
15145 if (IsExplicitInstantiationDeclaration)
15146 DefineVTable = false;
15147 }
15148
15149 // The exception specifications for all virtual members may be needed even
15150 // if we are not providing an authoritative form of the vtable in this TU.
15151 // We may choose to emit it available_externally anyway.
15152 if (!DefineVTable) {
15153 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15154 continue;
15155 }
15156
15157 // Mark all of the virtual members of this class as referenced, so
15158 // that we can build a vtable. Then, tell the AST consumer that a
15159 // vtable for this class is required.
15160 DefinedAnything = true;
15161 MarkVirtualMembersReferenced(Loc, Class);
15162 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15163 if (VTablesUsed[Canonical])
15164 Consumer.HandleVTable(Class);
15165
15166 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15167 // no key function or the key function is inlined. Don't warn in C++ ABIs
15168 // that lack key functions, since the user won't be able to make one.
15169 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15170 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15171 const FunctionDecl *KeyFunctionDef = nullptr;
15172 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15173 KeyFunctionDef->isInlined())) {
15174 Diag(Class->getLocation(),
15175 ClassTSK == TSK_ExplicitInstantiationDefinition
15176 ? diag::warn_weak_template_vtable
15177 : diag::warn_weak_vtable)
15178 << Class;
15179 }
15180 }
15181 }
15182 VTableUses.clear();
15183
15184 return DefinedAnything;
15185}
15186
15187void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15188 const CXXRecordDecl *RD) {
15189 for (const auto *I : RD->methods())
15190 if (I->isVirtual() && !I->isPure())
15191 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15192}
15193
15194void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15195 const CXXRecordDecl *RD) {
15196 // Mark all functions which will appear in RD's vtable as used.
15197 CXXFinalOverriderMap FinalOverriders;
15198 RD->getFinalOverriders(FinalOverriders);
15199 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15200 E = FinalOverriders.end();
15201 I != E; ++I) {
15202 for (OverridingMethods::const_iterator OI = I->second.begin(),
15203 OE = I->second.end();
15204 OI != OE; ++OI) {
15205 assert(OI->second.size() > 0 && "no final overrider")((OI->second.size() > 0 && "no final overrider"
) ? static_cast<void> (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15205, __PRETTY_FUNCTION__))
;
15206 CXXMethodDecl *Overrider = OI->second.front().Method;
15207
15208 // C++ [basic.def.odr]p2:
15209 // [...] A virtual member function is used if it is not pure. [...]
15210 if (!Overrider->isPure())
15211 MarkFunctionReferenced(Loc, Overrider);
15212 }
15213 }
15214
15215 // Only classes that have virtual bases need a VTT.
15216 if (RD->getNumVBases() == 0)
15217 return;
15218
15219 for (const auto &I : RD->bases()) {
15220 const CXXRecordDecl *Base =
15221 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15222 if (Base->getNumVBases() == 0)
15223 continue;
15224 MarkVirtualMembersReferenced(Loc, Base);
15225 }
15226}
15227
15228/// SetIvarInitializers - This routine builds initialization ASTs for the
15229/// Objective-C implementation whose ivars need be initialized.
15230void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15231 if (!getLangOpts().CPlusPlus)
15232 return;
15233 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15234 SmallVector<ObjCIvarDecl*, 8> ivars;
15235 CollectIvarsToConstructOrDestruct(OID, ivars);
15236 if (ivars.empty())
15237 return;
15238 SmallVector<CXXCtorInitializer*, 32> AllToInit;
15239 for (unsigned i = 0; i < ivars.size(); i++) {
15240 FieldDecl *Field = ivars[i];
15241 if (Field->isInvalidDecl())
15242 continue;
15243
15244 CXXCtorInitializer *Member;
15245 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15246 InitializationKind InitKind =
15247 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15248
15249 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15250 ExprResult MemberInit =
15251 InitSeq.Perform(*this, InitEntity, InitKind, None);
15252 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15253 // Note, MemberInit could actually come back empty if no initialization
15254 // is required (e.g., because it would call a trivial default constructor)
15255 if (!MemberInit.get() || MemberInit.isInvalid())
15256 continue;
15257
15258 Member =
15259 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15260 SourceLocation(),
15261 MemberInit.getAs<Expr>(),
15262 SourceLocation());
15263 AllToInit.push_back(Member);
15264
15265 // Be sure that the destructor is accessible and is marked as referenced.
15266 if (const RecordType *RecordTy =
15267 Context.getBaseElementType(Field->getType())
15268 ->getAs<RecordType>()) {
15269 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15270 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15271 MarkFunctionReferenced(Field->getLocation(), Destructor);
15272 CheckDestructorAccess(Field->getLocation(), Destructor,
15273 PDiag(diag::err_access_dtor_ivar)
15274 << Context.getBaseElementType(Field->getType()));
15275 }
15276 }
15277 }
15278 ObjCImplementation->setIvarInitializers(Context,
15279 AllToInit.data(), AllToInit.size());
15280 }
15281}
15282
15283static
15284void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15285 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15286 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15287 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15288 Sema &S) {
15289 if (Ctor->isInvalidDecl())
15290 return;
15291
15292 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15293
15294 // Target may not be determinable yet, for instance if this is a dependent
15295 // call in an uninstantiated template.
15296 if (Target) {
15297 const FunctionDecl *FNTarget = nullptr;
15298 (void)Target->hasBody(FNTarget);
15299 Target = const_cast<CXXConstructorDecl*>(
15300 cast_or_null<CXXConstructorDecl>(FNTarget));
15301 }
15302
15303 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15304 // Avoid dereferencing a null pointer here.
15305 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15306
15307 if (!Current.insert(Canonical).second)
15308 return;
15309
15310 // We know that beyond here, we aren't chaining into a cycle.
15311 if (!Target || !Target->isDelegatingConstructor() ||
15312 Target->isInvalidDecl() || Valid.count(TCanonical)) {
15313 Valid.insert(Current.begin(), Current.end());
15314 Current.clear();
15315 // We've hit a cycle.
15316 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15317 Current.count(TCanonical)) {
15318 // If we haven't diagnosed this cycle yet, do so now.
15319 if (!Invalid.count(TCanonical)) {
15320 S.Diag((*Ctor->init_begin())->getSourceLocation(),
15321 diag::warn_delegating_ctor_cycle)
15322 << Ctor;
15323
15324 // Don't add a note for a function delegating directly to itself.
15325 if (TCanonical != Canonical)
15326 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15327
15328 CXXConstructorDecl *C = Target;
15329 while (C->getCanonicalDecl() != Canonical) {
15330 const FunctionDecl *FNTarget = nullptr;
15331 (void)C->getTargetConstructor()->hasBody(FNTarget);
15332 assert(FNTarget && "Ctor cycle through bodiless function")((FNTarget && "Ctor cycle through bodiless function")
? static_cast<void> (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15332, __PRETTY_FUNCTION__))
;
15333
15334 C = const_cast<CXXConstructorDecl*>(
15335 cast<CXXConstructorDecl>(FNTarget));
15336 S.Diag(C->getLocation(), diag::note_which_delegates_to);
15337 }
15338 }
15339
15340 Invalid.insert(Current.begin(), Current.end());
15341 Current.clear();
15342 } else {
15343 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15344 }
15345}
15346
15347
15348void Sema::CheckDelegatingCtorCycles() {
15349 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15350
15351 for (DelegatingCtorDeclsType::iterator
15352 I = DelegatingCtorDecls.begin(ExternalSource),
15353 E = DelegatingCtorDecls.end();
15354 I != E; ++I)
15355 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15356
15357 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15358 (*CI)->setInvalidDecl();
15359}
15360
15361namespace {
15362 /// AST visitor that finds references to the 'this' expression.
15363 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15364 Sema &S;
15365
15366 public:
15367 explicit FindCXXThisExpr(Sema &S) : S(S) { }
15368
15369 bool VisitCXXThisExpr(CXXThisExpr *E) {
15370 S.Diag(E->getLocation(), diag::err_this_static_member_func)
15371 << E->isImplicit();
15372 return false;
15373 }
15374 };
15375}
15376
15377bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15378 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15379 if (!TSInfo)
15380 return false;
15381
15382 TypeLoc TL = TSInfo->getTypeLoc();
15383 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15384 if (!ProtoTL)
15385 return false;
15386
15387 // C++11 [expr.prim.general]p3:
15388 // [The expression this] shall not appear before the optional
15389 // cv-qualifier-seq and it shall not appear within the declaration of a
15390 // static member function (although its type and value category are defined
15391 // within a static member function as they are within a non-static member
15392 // function). [ Note: this is because declaration matching does not occur
15393 // until the complete declarator is known. - end note ]
15394 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15395 FindCXXThisExpr Finder(*this);
15396
15397 // If the return type came after the cv-qualifier-seq, check it now.
15398 if (Proto->hasTrailingReturn() &&
15399 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15400 return true;
15401
15402 // Check the exception specification.
15403 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15404 return true;
15405
15406 return checkThisInStaticMemberFunctionAttributes(Method);
15407}
15408
15409bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15410 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15411 if (!TSInfo)
15412 return false;
15413
15414 TypeLoc TL = TSInfo->getTypeLoc();
15415 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15416 if (!ProtoTL)
15417 return false;
15418
15419 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15420 FindCXXThisExpr Finder(*this);
15421
15422 switch (Proto->getExceptionSpecType()) {
15423 case EST_Unparsed:
15424 case EST_Uninstantiated:
15425 case EST_Unevaluated:
15426 case EST_BasicNoexcept:
15427 case EST_DynamicNone:
15428 case EST_MSAny:
15429 case EST_None:
15430 break;
15431
15432 case EST_DependentNoexcept:
15433 case EST_NoexceptFalse:
15434 case EST_NoexceptTrue:
15435 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15436 return true;
15437 LLVM_FALLTHROUGH[[clang::fallthrough]];
15438
15439 case EST_Dynamic:
15440 for (const auto &E : Proto->exceptions()) {
15441 if (!Finder.TraverseType(E))
15442 return true;
15443 }
15444 break;
15445 }
15446
15447 return false;
15448}
15449
15450bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15451 FindCXXThisExpr Finder(*this);
15452
15453 // Check attributes.
15454 for (const auto *A : Method->attrs()) {
15455 // FIXME: This should be emitted by tblgen.
15456 Expr *Arg = nullptr;
15457 ArrayRef<Expr *> Args;
15458 if (const auto *G = dyn_cast<GuardedByAttr>(A))
15459 Arg = G->getArg();
15460 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15461 Arg = G->getArg();
15462 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15463 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15464 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15465 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15466 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15467 Arg = ETLF->getSuccessValue();
15468 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15469 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15470 Arg = STLF->getSuccessValue();
15471 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15472 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15473 Arg = LR->getArg();
15474 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15475 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15476 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15477 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15478 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15479 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15480 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15481 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15482 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15483 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15484
15485 if (Arg && !Finder.TraverseStmt(Arg))
15486 return true;
15487
15488 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15489 if (!Finder.TraverseStmt(Args[I]))
15490 return true;
15491 }
15492 }
15493
15494 return false;
15495}
15496
15497void Sema::checkExceptionSpecification(
15498 bool IsTopLevel, ExceptionSpecificationType EST,
15499 ArrayRef<ParsedType> DynamicExceptions,
15500 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15501 SmallVectorImpl<QualType> &Exceptions,
15502 FunctionProtoType::ExceptionSpecInfo &ESI) {
15503 Exceptions.clear();
15504 ESI.Type = EST;
15505 if (EST == EST_Dynamic) {
15506 Exceptions.reserve(DynamicExceptions.size());
15507 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15508 // FIXME: Preserve type source info.
15509 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15510
15511 if (IsTopLevel) {
15512 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15513 collectUnexpandedParameterPacks(ET, Unexpanded);
15514 if (!Unexpanded.empty()) {
15515 DiagnoseUnexpandedParameterPacks(
15516 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15517 Unexpanded);
15518 continue;
15519 }
15520 }
15521
15522 // Check that the type is valid for an exception spec, and
15523 // drop it if not.
15524 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15525 Exceptions.push_back(ET);
15526 }
15527 ESI.Exceptions = Exceptions;
15528 return;
15529 }
15530
15531 if (isComputedNoexcept(EST)) {
15532 assert((NoexceptExpr->isTypeDependent() ||(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15535, __PRETTY_FUNCTION__))
15533 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15535, __PRETTY_FUNCTION__))
15534 Context.BoolTy) &&(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15535, __PRETTY_FUNCTION__))
15535 "Parser should have made sure that the expression is boolean")(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15535, __PRETTY_FUNCTION__))
;
15536 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15537 ESI.Type = EST_BasicNoexcept;
15538 return;
15539 }
15540
15541 ESI.NoexceptExpr = NoexceptExpr;
15542 return;
15543 }
15544}
15545
15546void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15547 ExceptionSpecificationType EST,
15548 SourceRange SpecificationRange,
15549 ArrayRef<ParsedType> DynamicExceptions,
15550 ArrayRef<SourceRange> DynamicExceptionRanges,
15551 Expr *NoexceptExpr) {
15552 if (!MethodD)
15553 return;
15554
15555 // Dig out the method we're referring to.
15556 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15557 MethodD = FunTmpl->getTemplatedDecl();
15558
15559 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15560 if (!Method)
15561 return;
15562
15563 // Check the exception specification.
15564 llvm::SmallVector<QualType, 4> Exceptions;
15565 FunctionProtoType::ExceptionSpecInfo ESI;
15566 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15567 DynamicExceptionRanges, NoexceptExpr, Exceptions,
15568 ESI);
15569
15570 // Update the exception specification on the function type.
15571 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15572
15573 if (Method->isStatic())
15574 checkThisInStaticMemberFunctionExceptionSpec(Method);
15575
15576 if (Method->isVirtual()) {
15577 // Check overrides, which we previously had to delay.
15578 for (const CXXMethodDecl *O : Method->overridden_methods())
15579 CheckOverridingFunctionExceptionSpec(Method, O);
15580 }
15581}
15582
15583/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15584///
15585MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15586 SourceLocation DeclStart, Declarator &D,
15587 Expr *BitWidth,
15588 InClassInitStyle InitStyle,
15589 AccessSpecifier AS,
15590 const ParsedAttr &MSPropertyAttr) {
15591 IdentifierInfo *II = D.getIdentifier();
15592 if (!II) {
15593 Diag(DeclStart, diag::err_anonymous_property);
15594 return nullptr;
15595 }
15596 SourceLocation Loc = D.getIdentifierLoc();
15597
15598 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15599 QualType T = TInfo->getType();
15600 if (getLangOpts().CPlusPlus) {
15601 CheckExtraCXXDefaultArguments(D);
15602
15603 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15604 UPPC_DataMemberType)) {
15605 D.setInvalidType();
15606 T = Context.IntTy;
15607 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15608 }
15609 }
15610
15611 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15612
15613 if (D.getDeclSpec().isInlineSpecified())
15614 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15615 << getLangOpts().CPlusPlus17;
15616 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15617 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15618 diag::err_invalid_thread)
15619 << DeclSpec::getSpecifierName(TSCS);
15620
15621 // Check to see if this name was declared as a member previously
15622 NamedDecl *PrevDecl = nullptr;
15623 LookupResult Previous(*this, II, Loc, LookupMemberName,
15624 ForVisibleRedeclaration);
15625 LookupName(Previous, S);
15626 switch (Previous.getResultKind()) {
15627 case LookupResult::Found:
15628 case LookupResult::FoundUnresolvedValue:
15629 PrevDecl = Previous.getAsSingle<NamedDecl>();
15630 break;
15631
15632 case LookupResult::FoundOverloaded:
15633 PrevDecl = Previous.getRepresentativeDecl();
15634 break;
15635
15636 case LookupResult::NotFound:
15637 case LookupResult::NotFoundInCurrentInstantiation:
15638 case LookupResult::Ambiguous:
15639 break;
15640 }
15641
15642 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15643 // Maybe we will complain about the shadowed template parameter.
15644 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15645 // Just pretend that we didn't see the previous declaration.
15646 PrevDecl = nullptr;
15647 }
15648
15649 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15650 PrevDecl = nullptr;
15651
15652 SourceLocation TSSL = D.getBeginLoc();
15653 MSPropertyDecl *NewPD =
15654 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15655 MSPropertyAttr.getPropertyDataGetter(),
15656 MSPropertyAttr.getPropertyDataSetter());
15657 ProcessDeclAttributes(TUScope, NewPD, D);
15658 NewPD->setAccess(AS);
15659
15660 if (NewPD->isInvalidDecl())
15661 Record->setInvalidDecl();
15662
15663 if (D.getDeclSpec().isModulePrivateSpecified())
15664 NewPD->setModulePrivate();
15665
15666 if (NewPD->isInvalidDecl() && PrevDecl) {
15667 // Don't introduce NewFD into scope; there's already something
15668 // with the same name in the same scope.
15669 } else if (II) {
15670 PushOnScopeChains(NewPD, S);
15671 } else
15672 Record->addDecl(NewPD);
15673
15674 return NewPD;
15675}