1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/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 "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
40 #include <map>
41 #include <set>
42
43 using namespace clang;
44
45 //===----------------------------------------------------------------------===//
46 // CheckDefaultArgumentVisitor
47 //===----------------------------------------------------------------------===//
48
49 namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
55 class CheckDefaultArgumentVisitor
56 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57 Expr *DefaultArg;
58 Sema *S;
59
60 public:
CheckDefaultArgumentVisitor(Expr * defarg,Sema * s)61 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62 : DefaultArg(defarg), S(s) {}
63
64 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
66 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67 bool VisitLambdaExpr(LambdaExpr *Lambda);
68 };
69
70 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(Expr * Node)71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
73 for (Stmt::child_range I = Node->children(); I; ++I)
74 IsInvalid |= Visit(*I);
75 return IsInvalid;
76 }
77
78 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
VisitDeclRefExpr(DeclRefExpr * DRE)81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
82 NamedDecl *Decl = DRE->getDecl();
83 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
92 return S->Diag(DRE->getLocStart(),
93 diag::err_param_default_argument_references_param)
94 << Param->getDeclName() << DefaultArg->getSourceRange();
95 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
96 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
99 if (VDecl->isLocalVarDecl())
100 return S->Diag(DRE->getLocStart(),
101 diag::err_param_default_argument_references_local)
102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
103 }
104
105 return false;
106 }
107
108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(CXXThisExpr * ThisE)109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
113 return S->Diag(ThisE->getLocStart(),
114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
116 }
117
VisitLambdaExpr(LambdaExpr * Lambda)118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
128 }
129
CalledDecl(SourceLocation CallLoc,CXXMethodDecl * Method)130 void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
145 if (EST == EST_MSAny || EST == EST_None) {
146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
198 Exceptions.push_back(*E);
199 }
200
CalledExpr(Expr * E)201 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
202 if (!E || ComputedEST == EST_MSAny)
203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
226 if (Self->canThrow(E))
227 ComputedEST = EST_None;
228 }
229
230 bool
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)231 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
232 SourceLocation EqualLoc) {
233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
251 if (Result.isInvalid())
252 return true;
253 Arg = Result.takeAs<Expr>();
254
255 CheckCompletedExpr(Arg, EqualLoc);
256 Arg = MaybeCreateExprWithCleanups(Arg);
257
258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
260
261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
273 return false;
274 }
275
276 /// ActOnParamDefaultArgument - Check whether the default argument
277 /// provided for a function parameter is well-formed. If so, attach it
278 /// to the parameter declaration.
279 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)280 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
283 return;
284
285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
286 UnparsedDefaultArgLocs.erase(Param);
287
288 // Default arguments are only permitted in C++
289 if (!getLangOpts().CPlusPlus) {
290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
292 Param->setInvalidDecl();
293 return;
294 }
295
296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
302 // Check that the default argument is well-formed
303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
305 Param->setInvalidDecl();
306 return;
307 }
308
309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
310 }
311
312 /// ActOnParamUnparsedDefaultArgument - We've seen a default
313 /// argument for a function parameter, but we can't parse it yet
314 /// because we're inside a class definition. Note that this default
315 /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)316 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
319 if (!param)
320 return;
321
322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
323 if (Param)
324 Param->setUnparsedDefaultArg();
325
326 UnparsedDefaultArgLocs[Param] = ArgLoc;
327 }
328
329 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330 /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param)331 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
332 if (!param)
333 return;
334
335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
336
337 Param->setInvalidDecl();
338
339 UnparsedDefaultArgLocs.erase(Param);
340 }
341
342 /// CheckExtraCXXDefaultArguments - Check for any extra default
343 /// arguments in the declarator, which is not a function declaration
344 /// or definition and therefore is not permitted to have default
345 /// arguments. This routine should be invoked for every declarator
346 /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)347 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
355 bool MightBeFunction = D.isFunctionDeclarationContext();
356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
357 DeclaratorChunk &chunk = D.getTypeObject(i);
358 if (chunk.Kind == DeclaratorChunk::Function) {
359 if (MightBeFunction) {
360 // This is a function declaration. It can have default arguments, but
361 // keep looking in case its return type is a function type with default
362 // arguments.
363 MightBeFunction = false;
364 continue;
365 }
366 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
367 ParmVarDecl *Param =
368 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
369 if (Param->hasUnparsedDefaultArg()) {
370 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
371 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
372 << SourceRange((*Toks)[1].getLocation(),
373 Toks->back().getLocation());
374 delete Toks;
375 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
376 } else if (Param->getDefaultArg()) {
377 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
378 << Param->getDefaultArg()->getSourceRange();
379 Param->setDefaultArg(0);
380 }
381 }
382 } else if (chunk.Kind != DeclaratorChunk::Paren) {
383 MightBeFunction = false;
384 }
385 }
386 }
387
388 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
389 /// function, once we already know that they have the same
390 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
391 /// error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)392 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
393 Scope *S) {
394 bool Invalid = false;
395
396 // C++ [dcl.fct.default]p4:
397 // For non-template functions, default arguments can be added in
398 // later declarations of a function in the same
399 // scope. Declarations in different scopes have completely
400 // distinct sets of default arguments. That is, declarations in
401 // inner scopes do not acquire default arguments from
402 // declarations in outer scopes, and vice versa. In a given
403 // function declaration, all parameters subsequent to a
404 // parameter with a default argument shall have default
405 // arguments supplied in this or previous declarations. A
406 // default argument shall not be redefined by a later
407 // declaration (not even to the same value).
408 //
409 // C++ [dcl.fct.default]p6:
410 // Except for member functions of class templates, the default arguments
411 // in a member function definition that appears outside of the class
412 // definition are added to the set of default arguments provided by the
413 // member function declaration in the class definition.
414 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
415 ParmVarDecl *OldParam = Old->getParamDecl(p);
416 ParmVarDecl *NewParam = New->getParamDecl(p);
417
418 bool OldParamHasDfl = OldParam->hasDefaultArg();
419 bool NewParamHasDfl = NewParam->hasDefaultArg();
420
421 NamedDecl *ND = Old;
422 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
423 // Ignore default parameters of old decl if they are not in
424 // the same scope.
425 OldParamHasDfl = false;
426
427 if (OldParamHasDfl && NewParamHasDfl) {
428
429 unsigned DiagDefaultParamID =
430 diag::err_param_default_argument_redefinition;
431
432 // MSVC accepts that default parameters be redefined for member functions
433 // of template class. The new default parameter's value is ignored.
434 Invalid = true;
435 if (getLangOpts().MicrosoftExt) {
436 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
437 if (MD && MD->getParent()->getDescribedClassTemplate()) {
438 // Merge the old default argument into the new parameter.
439 NewParam->setHasInheritedDefaultArg();
440 if (OldParam->hasUninstantiatedDefaultArg())
441 NewParam->setUninstantiatedDefaultArg(
442 OldParam->getUninstantiatedDefaultArg());
443 else
444 NewParam->setDefaultArg(OldParam->getInit());
445 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
446 Invalid = false;
447 }
448 }
449
450 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
451 // hint here. Alternatively, we could walk the type-source information
452 // for NewParam to find the last source location in the type... but it
453 // isn't worth the effort right now. This is the kind of test case that
454 // is hard to get right:
455 // int f(int);
456 // void g(int (*fp)(int) = f);
457 // void g(int (*fp)(int) = &f);
458 Diag(NewParam->getLocation(), DiagDefaultParamID)
459 << NewParam->getDefaultArgRange();
460
461 // Look for the function declaration where the default argument was
462 // actually written, which may be a declaration prior to Old.
463 for (FunctionDecl *Older = Old->getPreviousDecl();
464 Older; Older = Older->getPreviousDecl()) {
465 if (!Older->getParamDecl(p)->hasDefaultArg())
466 break;
467
468 OldParam = Older->getParamDecl(p);
469 }
470
471 Diag(OldParam->getLocation(), diag::note_previous_definition)
472 << OldParam->getDefaultArgRange();
473 } else if (OldParamHasDfl) {
474 // Merge the old default argument into the new parameter.
475 // It's important to use getInit() here; getDefaultArg()
476 // strips off any top-level ExprWithCleanups.
477 NewParam->setHasInheritedDefaultArg();
478 if (OldParam->hasUninstantiatedDefaultArg())
479 NewParam->setUninstantiatedDefaultArg(
480 OldParam->getUninstantiatedDefaultArg());
481 else
482 NewParam->setDefaultArg(OldParam->getInit());
483 } else if (NewParamHasDfl) {
484 if (New->getDescribedFunctionTemplate()) {
485 // Paragraph 4, quoted above, only applies to non-template functions.
486 Diag(NewParam->getLocation(),
487 diag::err_param_default_argument_template_redecl)
488 << NewParam->getDefaultArgRange();
489 Diag(Old->getLocation(), diag::note_template_prev_declaration)
490 << false;
491 } else if (New->getTemplateSpecializationKind()
492 != TSK_ImplicitInstantiation &&
493 New->getTemplateSpecializationKind() != TSK_Undeclared) {
494 // C++ [temp.expr.spec]p21:
495 // Default function arguments shall not be specified in a declaration
496 // or a definition for one of the following explicit specializations:
497 // - the explicit specialization of a function template;
498 // - the explicit specialization of a member function template;
499 // - the explicit specialization of a member function of a class
500 // template where the class template specialization to which the
501 // member function specialization belongs is implicitly
502 // instantiated.
503 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
504 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
505 << New->getDeclName()
506 << NewParam->getDefaultArgRange();
507 } else if (New->getDeclContext()->isDependentContext()) {
508 // C++ [dcl.fct.default]p6 (DR217):
509 // Default arguments for a member function of a class template shall
510 // be specified on the initial declaration of the member function
511 // within the class template.
512 //
513 // Reading the tea leaves a bit in DR217 and its reference to DR205
514 // leads me to the conclusion that one cannot add default function
515 // arguments for an out-of-line definition of a member function of a
516 // dependent type.
517 int WhichKind = 2;
518 if (CXXRecordDecl *Record
519 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
520 if (Record->getDescribedClassTemplate())
521 WhichKind = 0;
522 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
523 WhichKind = 1;
524 else
525 WhichKind = 2;
526 }
527
528 Diag(NewParam->getLocation(),
529 diag::err_param_default_argument_member_template_redecl)
530 << WhichKind
531 << NewParam->getDefaultArgRange();
532 }
533 }
534 }
535
536 // DR1344: If a default argument is added outside a class definition and that
537 // default argument makes the function a special member function, the program
538 // is ill-formed. This can only happen for constructors.
539 if (isa<CXXConstructorDecl>(New) &&
540 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
541 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
542 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
543 if (NewSM != OldSM) {
544 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
545 assert(NewParam->hasDefaultArg());
546 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
547 << NewParam->getDefaultArgRange() << NewSM;
548 Diag(Old->getLocation(), diag::note_previous_declaration);
549 }
550 }
551
552 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
553 // template has a constexpr specifier then all its declarations shall
554 // contain the constexpr specifier.
555 if (New->isConstexpr() != Old->isConstexpr()) {
556 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
557 << New << New->isConstexpr();
558 Diag(Old->getLocation(), diag::note_previous_declaration);
559 Invalid = true;
560 }
561
562 if (CheckEquivalentExceptionSpec(Old, New))
563 Invalid = true;
564
565 return Invalid;
566 }
567
568 /// \brief Merge the exception specifications of two variable declarations.
569 ///
570 /// This is called when there's a redeclaration of a VarDecl. The function
571 /// checks if the redeclaration might have an exception specification and
572 /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)573 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
574 // Shortcut if exceptions are disabled.
575 if (!getLangOpts().CXXExceptions)
576 return;
577
578 assert(Context.hasSameType(New->getType(), Old->getType()) &&
579 "Should only be called if types are otherwise the same.");
580
581 QualType NewType = New->getType();
582 QualType OldType = Old->getType();
583
584 // We're only interested in pointers and references to functions, as well
585 // as pointers to member functions.
586 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
587 NewType = R->getPointeeType();
588 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
589 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
590 NewType = P->getPointeeType();
591 OldType = OldType->getAs<PointerType>()->getPointeeType();
592 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
593 NewType = M->getPointeeType();
594 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
595 }
596
597 if (!NewType->isFunctionProtoType())
598 return;
599
600 // There's lots of special cases for functions. For function pointers, system
601 // libraries are hopefully not as broken so that we don't need these
602 // workarounds.
603 if (CheckEquivalentExceptionSpec(
604 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
605 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
606 New->setInvalidDecl();
607 }
608 }
609
610 /// CheckCXXDefaultArguments - Verify that the default arguments for a
611 /// function declaration are well-formed according to C++
612 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)613 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
614 unsigned NumParams = FD->getNumParams();
615 unsigned p;
616
617 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
618 isa<CXXMethodDecl>(FD) &&
619 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
620
621 // Find first parameter with a default argument
622 for (p = 0; p < NumParams; ++p) {
623 ParmVarDecl *Param = FD->getParamDecl(p);
624 if (Param->hasDefaultArg()) {
625 // C++11 [expr.prim.lambda]p5:
626 // [...] Default arguments (8.3.6) shall not be specified in the
627 // parameter-declaration-clause of a lambda-declarator.
628 //
629 // FIXME: Core issue 974 strikes this sentence, we only provide an
630 // extension warning.
631 if (IsLambda)
632 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
633 << Param->getDefaultArgRange();
634 break;
635 }
636 }
637
638 // C++ [dcl.fct.default]p4:
639 // In a given function declaration, all parameters
640 // subsequent to a parameter with a default argument shall
641 // have default arguments supplied in this or previous
642 // declarations. A default argument shall not be redefined
643 // by a later declaration (not even to the same value).
644 unsigned LastMissingDefaultArg = 0;
645 for (; p < NumParams; ++p) {
646 ParmVarDecl *Param = FD->getParamDecl(p);
647 if (!Param->hasDefaultArg()) {
648 if (Param->isInvalidDecl())
649 /* We already complained about this parameter. */;
650 else if (Param->getIdentifier())
651 Diag(Param->getLocation(),
652 diag::err_param_default_argument_missing_name)
653 << Param->getIdentifier();
654 else
655 Diag(Param->getLocation(),
656 diag::err_param_default_argument_missing);
657
658 LastMissingDefaultArg = p;
659 }
660 }
661
662 if (LastMissingDefaultArg > 0) {
663 // Some default arguments were missing. Clear out all of the
664 // default arguments up to (and including) the last missing
665 // default argument, so that we leave the function parameters
666 // in a semantically valid state.
667 for (p = 0; p <= LastMissingDefaultArg; ++p) {
668 ParmVarDecl *Param = FD->getParamDecl(p);
669 if (Param->hasDefaultArg()) {
670 Param->setDefaultArg(0);
671 }
672 }
673 }
674 }
675
676 // CheckConstexprParameterTypes - Check whether a function's parameter types
677 // are all literal types. If so, return true. If not, produce a suitable
678 // diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD)679 static bool CheckConstexprParameterTypes(Sema &SemaRef,
680 const FunctionDecl *FD) {
681 unsigned ArgIndex = 0;
682 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
683 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
684 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
685 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
686 SourceLocation ParamLoc = PD->getLocation();
687 if (!(*i)->isDependentType() &&
688 SemaRef.RequireLiteralType(ParamLoc, *i,
689 diag::err_constexpr_non_literal_param,
690 ArgIndex+1, PD->getSourceRange(),
691 isa<CXXConstructorDecl>(FD)))
692 return false;
693 }
694 return true;
695 }
696
697 /// \brief Get diagnostic %select index for tag kind for
698 /// record diagnostic message.
699 /// WARNING: Indexes apply to particular diagnostics only!
700 ///
701 /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)702 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
703 switch (Tag) {
704 case TTK_Struct: return 0;
705 case TTK_Interface: return 1;
706 case TTK_Class: return 2;
707 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
708 }
709 }
710
711 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
712 // the requirements of a constexpr function definition or a constexpr
713 // constructor definition. If so, return true. If not, produce appropriate
714 // diagnostics and return false.
715 //
716 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
CheckConstexprFunctionDecl(const FunctionDecl * NewFD)717 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
719 if (MD && MD->isInstance()) {
720 // C++11 [dcl.constexpr]p4:
721 // The definition of a constexpr constructor shall satisfy the following
722 // constraints:
723 // - the class shall not have any virtual base classes;
724 const CXXRecordDecl *RD = MD->getParent();
725 if (RD->getNumVBases()) {
726 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
727 << isa<CXXConstructorDecl>(NewFD)
728 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
729 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
730 E = RD->vbases_end(); I != E; ++I)
731 Diag(I->getLocStart(),
732 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
733 return false;
734 }
735 }
736
737 if (!isa<CXXConstructorDecl>(NewFD)) {
738 // C++11 [dcl.constexpr]p3:
739 // The definition of a constexpr function shall satisfy the following
740 // constraints:
741 // - it shall not be virtual;
742 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
743 if (Method && Method->isVirtual()) {
744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
745
746 // If it's not obvious why this function is virtual, find an overridden
747 // function which uses the 'virtual' keyword.
748 const CXXMethodDecl *WrittenVirtual = Method;
749 while (!WrittenVirtual->isVirtualAsWritten())
750 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
751 if (WrittenVirtual != Method)
752 Diag(WrittenVirtual->getLocation(),
753 diag::note_overridden_virtual_function);
754 return false;
755 }
756
757 // - its return type shall be a literal type;
758 QualType RT = NewFD->getResultType();
759 if (!RT->isDependentType() &&
760 RequireLiteralType(NewFD->getLocation(), RT,
761 diag::err_constexpr_non_literal_return))
762 return false;
763 }
764
765 // - each of its parameter types shall be a literal type;
766 if (!CheckConstexprParameterTypes(*this, NewFD))
767 return false;
768
769 return true;
770 }
771
772 /// Check the given declaration statement is legal within a constexpr function
773 /// body. C++0x [dcl.constexpr]p3,p4.
774 ///
775 /// \return true if the body is OK, false if we have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS)776 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
777 DeclStmt *DS) {
778 // C++0x [dcl.constexpr]p3 and p4:
779 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
780 // contain only
781 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
782 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
783 switch ((*DclIt)->getKind()) {
784 case Decl::StaticAssert:
785 case Decl::Using:
786 case Decl::UsingShadow:
787 case Decl::UsingDirective:
788 case Decl::UnresolvedUsingTypename:
789 // - static_assert-declarations
790 // - using-declarations,
791 // - using-directives,
792 continue;
793
794 case Decl::Typedef:
795 case Decl::TypeAlias: {
796 // - typedef declarations and alias-declarations that do not define
797 // classes or enumerations,
798 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
799 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
800 // Don't allow variably-modified types in constexpr functions.
801 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
802 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
803 << TL.getSourceRange() << TL.getType()
804 << isa<CXXConstructorDecl>(Dcl);
805 return false;
806 }
807 continue;
808 }
809
810 case Decl::Enum:
811 case Decl::CXXRecord:
812 // As an extension, we allow the declaration (but not the definition) of
813 // classes and enumerations in all declarations, not just in typedef and
814 // alias declarations.
815 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
817 << isa<CXXConstructorDecl>(Dcl);
818 return false;
819 }
820 continue;
821
822 case Decl::Var:
823 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
824 << isa<CXXConstructorDecl>(Dcl);
825 return false;
826
827 default:
828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
829 << isa<CXXConstructorDecl>(Dcl);
830 return false;
831 }
832 }
833
834 return true;
835 }
836
837 /// Check that the given field is initialized within a constexpr constructor.
838 ///
839 /// \param Dcl The constexpr constructor being checked.
840 /// \param Field The field being checked. This may be a member of an anonymous
841 /// struct or union nested within the class being checked.
842 /// \param Inits All declarations, including anonymous struct/union members and
843 /// indirect members, for which any initialization was provided.
844 /// \param Diagnosed Set to true if an error is produced.
CheckConstexprCtorInitializer(Sema & SemaRef,const FunctionDecl * Dcl,FieldDecl * Field,llvm::SmallSet<Decl *,16> & Inits,bool & Diagnosed)845 static void CheckConstexprCtorInitializer(Sema &SemaRef,
846 const FunctionDecl *Dcl,
847 FieldDecl *Field,
848 llvm::SmallSet<Decl*, 16> &Inits,
849 bool &Diagnosed) {
850 if (Field->isUnnamedBitfield())
851 return;
852
853 if (Field->isAnonymousStructOrUnion() &&
854 Field->getType()->getAsCXXRecordDecl()->isEmpty())
855 return;
856
857 if (!Inits.count(Field)) {
858 if (!Diagnosed) {
859 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
860 Diagnosed = true;
861 }
862 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
863 } else if (Field->isAnonymousStructOrUnion()) {
864 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
865 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
866 I != E; ++I)
867 // If an anonymous union contains an anonymous struct of which any member
868 // is initialized, all members must be initialized.
869 if (!RD->isUnion() || Inits.count(*I))
870 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
871 }
872 }
873
874 /// Check the body for the given constexpr function declaration only contains
875 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
876 ///
877 /// \return true if the body is OK, false if we have diagnosed a problem.
CheckConstexprFunctionBody(const FunctionDecl * Dcl,Stmt * Body)878 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
879 if (isa<CXXTryStmt>(Body)) {
880 // C++11 [dcl.constexpr]p3:
881 // The definition of a constexpr function shall satisfy the following
882 // constraints: [...]
883 // - its function-body shall be = delete, = default, or a
884 // compound-statement
885 //
886 // C++11 [dcl.constexpr]p4:
887 // In the definition of a constexpr constructor, [...]
888 // - its function-body shall not be a function-try-block;
889 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 // - its function-body shall be [...] a compound-statement that contains only
895 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
896
897 SmallVector<SourceLocation, 4> ReturnStmts;
898 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
899 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
900 switch ((*BodyIt)->getStmtClass()) {
901 case Stmt::NullStmtClass:
902 // - null statements,
903 continue;
904
905 case Stmt::DeclStmtClass:
906 // - static_assert-declarations
907 // - using-declarations,
908 // - using-directives,
909 // - typedef declarations and alias-declarations that do not define
910 // classes or enumerations,
911 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
912 return false;
913 continue;
914
915 case Stmt::ReturnStmtClass:
916 // - and exactly one return statement;
917 if (isa<CXXConstructorDecl>(Dcl))
918 break;
919
920 ReturnStmts.push_back((*BodyIt)->getLocStart());
921 continue;
922
923 default:
924 break;
925 }
926
927 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931
932 if (const CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Dcl)) {
934 const CXXRecordDecl *RD = Constructor->getParent();
935 // DR1359:
936 // - every non-variant non-static data member and base class sub-object
937 // shall be initialized;
938 // - if the class is a non-empty union, or for each non-empty anonymous
939 // union member of a non-union class, exactly one non-static data member
940 // shall be initialized;
941 if (RD->isUnion()) {
942 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
944 return false;
945 }
946 } else if (!Constructor->isDependentContext() &&
947 !Constructor->isDelegatingConstructor()) {
948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
949
950 // Skip detailed checking if we have enough initializers, and we would
951 // allow at most one initializer per member.
952 bool AnyAnonStructUnionMembers = false;
953 unsigned Fields = 0;
954 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
955 E = RD->field_end(); I != E; ++I, ++Fields) {
956 if (I->isAnonymousStructOrUnion()) {
957 AnyAnonStructUnionMembers = true;
958 break;
959 }
960 }
961 if (AnyAnonStructUnionMembers ||
962 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
963 // Check initialization of non-static data members. Base classes are
964 // always initialized so do not need to be checked. Dependent bases
965 // might not have initializers in the member initializer list.
966 llvm::SmallSet<Decl*, 16> Inits;
967 for (CXXConstructorDecl::init_const_iterator
968 I = Constructor->init_begin(), E = Constructor->init_end();
969 I != E; ++I) {
970 if (FieldDecl *FD = (*I)->getMember())
971 Inits.insert(FD);
972 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
973 Inits.insert(ID->chain_begin(), ID->chain_end());
974 }
975
976 bool Diagnosed = false;
977 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
978 E = RD->field_end(); I != E; ++I)
979 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
980 if (Diagnosed)
981 return false;
982 }
983 }
984 } else {
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987 return false;
988 }
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993 return false;
994 }
995 }
996
997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
1007 SmallVector<PartialDiagnosticAt, 8> Diags;
1008 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1009 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
1013 // Don't return false here: we allow this for compatibility in
1014 // system headers.
1015 }
1016
1017 return true;
1018 }
1019
1020 /// isCurrentClassName - Determine whether the identifier II is the
1021 /// name of the class type currently being defined. In the case of
1022 /// nested classes, this will only return true if II is the name of
1023 /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope *,const CXXScopeSpec * SS)1024 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1025 const CXXScopeSpec *SS) {
1026 assert(getLangOpts().CPlusPlus && "No class names in C!");
1027
1028 CXXRecordDecl *CurDecl;
1029 if (SS && SS->isSet() && !SS->isInvalid()) {
1030 DeclContext *DC = computeDeclContext(*SS, true);
1031 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1032 } else
1033 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1034
1035 if (CurDecl && CurDecl->getIdentifier())
1036 return &II == CurDecl->getIdentifier();
1037 else
1038 return false;
1039 }
1040
1041 /// \brief Determine whether the given class is a base class of the given
1042 /// class, including looking at dependent bases.
findCircularInheritance(const CXXRecordDecl * Class,const CXXRecordDecl * Current)1043 static bool findCircularInheritance(const CXXRecordDecl *Class,
1044 const CXXRecordDecl *Current) {
1045 SmallVector<const CXXRecordDecl*, 8> Queue;
1046
1047 Class = Class->getCanonicalDecl();
1048 while (true) {
1049 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1050 E = Current->bases_end();
1051 I != E; ++I) {
1052 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1053 if (!Base)
1054 continue;
1055
1056 Base = Base->getDefinition();
1057 if (!Base)
1058 continue;
1059
1060 if (Base->getCanonicalDecl() == Class)
1061 return true;
1062
1063 Queue.push_back(Base);
1064 }
1065
1066 if (Queue.empty())
1067 return false;
1068
1069 Current = Queue.back();
1070 Queue.pop_back();
1071 }
1072
1073 return false;
1074 }
1075
1076 /// \brief Check the validity of a C++ base class specifier.
1077 ///
1078 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1079 /// and returns NULL otherwise.
1080 CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)1081 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1082 SourceRange SpecifierRange,
1083 bool Virtual, AccessSpecifier Access,
1084 TypeSourceInfo *TInfo,
1085 SourceLocation EllipsisLoc) {
1086 QualType BaseType = TInfo->getType();
1087
1088 // C++ [class.union]p1:
1089 // A union shall not have base classes.
1090 if (Class->isUnion()) {
1091 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1092 << SpecifierRange;
1093 return 0;
1094 }
1095
1096 if (EllipsisLoc.isValid() &&
1097 !TInfo->getType()->containsUnexpandedParameterPack()) {
1098 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1099 << TInfo->getTypeLoc().getSourceRange();
1100 EllipsisLoc = SourceLocation();
1101 }
1102
1103 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1104
1105 if (BaseType->isDependentType()) {
1106 // Make sure that we don't have circular inheritance among our dependent
1107 // bases. For non-dependent bases, the check for completeness below handles
1108 // this.
1109 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1110 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1111 ((BaseDecl = BaseDecl->getDefinition()) &&
1112 findCircularInheritance(Class, BaseDecl))) {
1113 Diag(BaseLoc, diag::err_circular_inheritance)
1114 << BaseType << Context.getTypeDeclType(Class);
1115
1116 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1117 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1118 << BaseType;
1119
1120 return 0;
1121 }
1122 }
1123
1124 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1125 Class->getTagKind() == TTK_Class,
1126 Access, TInfo, EllipsisLoc);
1127 }
1128
1129 // Base specifiers must be record types.
1130 if (!BaseType->isRecordType()) {
1131 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1132 return 0;
1133 }
1134
1135 // C++ [class.union]p1:
1136 // A union shall not be used as a base class.
1137 if (BaseType->isUnionType()) {
1138 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1139 return 0;
1140 }
1141
1142 // C++ [class.derived]p2:
1143 // The class-name in a base-specifier shall not be an incompletely
1144 // defined class.
1145 if (RequireCompleteType(BaseLoc, BaseType,
1146 diag::err_incomplete_base_class, SpecifierRange)) {
1147 Class->setInvalidDecl();
1148 return 0;
1149 }
1150
1151 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1152 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1153 assert(BaseDecl && "Record type has no declaration");
1154 BaseDecl = BaseDecl->getDefinition();
1155 assert(BaseDecl && "Base type is not incomplete, but has no definition");
1156 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1157 assert(CXXBaseDecl && "Base type is not a C++ type");
1158
1159 // C++ [class]p3:
1160 // If a class is marked final and it appears as a base-type-specifier in
1161 // base-clause, the program is ill-formed.
1162 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1163 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1164 << CXXBaseDecl->getDeclName();
1165 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1166 << CXXBaseDecl->getDeclName();
1167 return 0;
1168 }
1169
1170 if (BaseDecl->isInvalidDecl())
1171 Class->setInvalidDecl();
1172
1173 // Create the base specifier.
1174 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1175 Class->getTagKind() == TTK_Class,
1176 Access, TInfo, EllipsisLoc);
1177 }
1178
1179 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1180 /// one entry in the base class list of a class specifier, for
1181 /// example:
1182 /// class foo : public bar, virtual private baz {
1183 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1184 BaseResult
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,ParsedAttributes & Attributes,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)1185 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1186 ParsedAttributes &Attributes,
1187 bool Virtual, AccessSpecifier Access,
1188 ParsedType basetype, SourceLocation BaseLoc,
1189 SourceLocation EllipsisLoc) {
1190 if (!classdecl)
1191 return true;
1192
1193 AdjustDeclIfTemplate(classdecl);
1194 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1195 if (!Class)
1196 return true;
1197
1198 // We do not support any C++11 attributes on base-specifiers yet.
1199 // Diagnose any attributes we see.
1200 if (!Attributes.empty()) {
1201 for (AttributeList *Attr = Attributes.getList(); Attr;
1202 Attr = Attr->getNext()) {
1203 if (Attr->isInvalid() ||
1204 Attr->getKind() == AttributeList::IgnoredAttribute)
1205 continue;
1206 Diag(Attr->getLoc(),
1207 Attr->getKind() == AttributeList::UnknownAttribute
1208 ? diag::warn_unknown_attribute_ignored
1209 : diag::err_base_specifier_attribute)
1210 << Attr->getName();
1211 }
1212 }
1213
1214 TypeSourceInfo *TInfo = 0;
1215 GetTypeFromParser(basetype, &TInfo);
1216
1217 if (EllipsisLoc.isInvalid() &&
1218 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1219 UPPC_BaseType))
1220 return true;
1221
1222 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1223 Virtual, Access, TInfo,
1224 EllipsisLoc))
1225 return BaseSpec;
1226 else
1227 Class->setInvalidDecl();
1228
1229 return true;
1230 }
1231
1232 /// \brief Performs the actual work of attaching the given base class
1233 /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,CXXBaseSpecifier ** Bases,unsigned NumBases)1234 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1235 unsigned NumBases) {
1236 if (NumBases == 0)
1237 return false;
1238
1239 // Used to keep track of which base types we have already seen, so
1240 // that we can properly diagnose redundant direct base types. Note
1241 // that the key is always the unqualified canonical type of the base
1242 // class.
1243 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1244
1245 // Copy non-redundant base specifiers into permanent storage.
1246 unsigned NumGoodBases = 0;
1247 bool Invalid = false;
1248 for (unsigned idx = 0; idx < NumBases; ++idx) {
1249 QualType NewBaseType
1250 = Context.getCanonicalType(Bases[idx]->getType());
1251 NewBaseType = NewBaseType.getLocalUnqualifiedType();
1252
1253 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1254 if (KnownBase) {
1255 // C++ [class.mi]p3:
1256 // A class shall not be specified as a direct base class of a
1257 // derived class more than once.
1258 Diag(Bases[idx]->getLocStart(),
1259 diag::err_duplicate_base_class)
1260 << KnownBase->getType()
1261 << Bases[idx]->getSourceRange();
1262
1263 // Delete the duplicate base class specifier; we're going to
1264 // overwrite its pointer later.
1265 Context.Deallocate(Bases[idx]);
1266
1267 Invalid = true;
1268 } else {
1269 // Okay, add this new base class.
1270 KnownBase = Bases[idx];
1271 Bases[NumGoodBases++] = Bases[idx];
1272 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1274 if (Class->isInterface() &&
1275 (!RD->isInterface() ||
1276 KnownBase->getAccessSpecifier() != AS_public)) {
1277 // The Microsoft extension __interface does not permit bases that
1278 // are not themselves public interfaces.
1279 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1280 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1281 << RD->getSourceRange();
1282 Invalid = true;
1283 }
1284 if (RD->hasAttr<WeakAttr>())
1285 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1286 }
1287 }
1288 }
1289
1290 // Attach the remaining base class specifiers to the derived class.
1291 Class->setBases(Bases, NumGoodBases);
1292
1293 // Delete the remaining (good) base class specifiers, since their
1294 // data has been copied into the CXXRecordDecl.
1295 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1296 Context.Deallocate(Bases[idx]);
1297
1298 return Invalid;
1299 }
1300
1301 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1302 /// class, after checking whether there are any duplicate base
1303 /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,CXXBaseSpecifier ** Bases,unsigned NumBases)1304 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1305 unsigned NumBases) {
1306 if (!ClassDecl || !Bases || !NumBases)
1307 return;
1308
1309 AdjustDeclIfTemplate(ClassDecl);
1310 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1311 (CXXBaseSpecifier**)(Bases), NumBases);
1312 }
1313
GetClassForType(QualType T)1314 static CXXRecordDecl *GetClassForType(QualType T) {
1315 if (const RecordType *RT = T->getAs<RecordType>())
1316 return cast<CXXRecordDecl>(RT->getDecl());
1317 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1318 return ICT->getDecl();
1319 else
1320 return 0;
1321 }
1322
1323 /// \brief Determine whether the type \p Derived is a C++ class that is
1324 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base)1325 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1326 if (!getLangOpts().CPlusPlus)
1327 return false;
1328
1329 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1330 if (!DerivedRD)
1331 return false;
1332
1333 CXXRecordDecl *BaseRD = GetClassForType(Base);
1334 if (!BaseRD)
1335 return false;
1336
1337 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1338 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1339 }
1340
1341 /// \brief Determine whether the type \p Derived is a C++ class that is
1342 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base,CXXBasePaths & Paths)1343 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1344 if (!getLangOpts().CPlusPlus)
1345 return false;
1346
1347 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1348 if (!DerivedRD)
1349 return false;
1350
1351 CXXRecordDecl *BaseRD = GetClassForType(Base);
1352 if (!BaseRD)
1353 return false;
1354
1355 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1356 }
1357
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)1358 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1359 CXXCastPath &BasePathArray) {
1360 assert(BasePathArray.empty() && "Base path array must be empty!");
1361 assert(Paths.isRecordingPaths() && "Must record paths!");
1362
1363 const CXXBasePath &Path = Paths.front();
1364
1365 // We first go backward and check if we have a virtual base.
1366 // FIXME: It would be better if CXXBasePath had the base specifier for
1367 // the nearest virtual base.
1368 unsigned Start = 0;
1369 for (unsigned I = Path.size(); I != 0; --I) {
1370 if (Path[I - 1].Base->isVirtual()) {
1371 Start = I - 1;
1372 break;
1373 }
1374 }
1375
1376 // Now add all bases.
1377 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1378 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1379 }
1380
1381 /// \brief Determine whether the given base path includes a virtual
1382 /// base class.
BasePathInvolvesVirtualBase(const CXXCastPath & BasePath)1383 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1384 for (CXXCastPath::const_iterator B = BasePath.begin(),
1385 BEnd = BasePath.end();
1386 B != BEnd; ++B)
1387 if ((*B)->isVirtual())
1388 return true;
1389
1390 return false;
1391 }
1392
1393 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1394 /// conversion (where Derived and Base are class types) is
1395 /// well-formed, meaning that the conversion is unambiguous (and
1396 /// that all of the base classes are accessible). Returns true
1397 /// and emits a diagnostic if the code is ill-formed, returns false
1398 /// otherwise. Loc is the location where this routine should point to
1399 /// if there is an error, and Range is the source range to highlight
1400 /// if there is an error.
1401 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbigiousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath)1402 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1403 unsigned InaccessibleBaseID,
1404 unsigned AmbigiousBaseConvID,
1405 SourceLocation Loc, SourceRange Range,
1406 DeclarationName Name,
1407 CXXCastPath *BasePath) {
1408 // First, determine whether the path from Derived to Base is
1409 // ambiguous. This is slightly more expensive than checking whether
1410 // the Derived to Base conversion exists, because here we need to
1411 // explore multiple paths to determine if there is an ambiguity.
1412 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1413 /*DetectVirtual=*/false);
1414 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1415 assert(DerivationOkay &&
1416 "Can only be used with a derived-to-base conversion");
1417 (void)DerivationOkay;
1418
1419 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1420 if (InaccessibleBaseID) {
1421 // Check that the base class can be accessed.
1422 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1423 InaccessibleBaseID)) {
1424 case AR_inaccessible:
1425 return true;
1426 case AR_accessible:
1427 case AR_dependent:
1428 case AR_delayed:
1429 break;
1430 }
1431 }
1432
1433 // Build a base path if necessary.
1434 if (BasePath)
1435 BuildBasePathArray(Paths, *BasePath);
1436 return false;
1437 }
1438
1439 // We know that the derived-to-base conversion is ambiguous, and
1440 // we're going to produce a diagnostic. Perform the derived-to-base
1441 // search just one more time to compute all of the possible paths so
1442 // that we can print them out. This is more expensive than any of
1443 // the previous derived-to-base checks we've done, but at this point
1444 // performance isn't as much of an issue.
1445 Paths.clear();
1446 Paths.setRecordingPaths(true);
1447 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1448 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1449 (void)StillOkay;
1450
1451 // Build up a textual representation of the ambiguous paths, e.g.,
1452 // D -> B -> A, that will be used to illustrate the ambiguous
1453 // conversions in the diagnostic. We only print one of the paths
1454 // to each base class subobject.
1455 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1456
1457 Diag(Loc, AmbigiousBaseConvID)
1458 << Derived << Base << PathDisplayStr << Range << Name;
1459 return true;
1460 }
1461
1462 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)1463 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1464 SourceLocation Loc, SourceRange Range,
1465 CXXCastPath *BasePath,
1466 bool IgnoreAccess) {
1467 return CheckDerivedToBaseConversion(Derived, Base,
1468 IgnoreAccess ? 0
1469 : diag::err_upcast_to_inaccessible_base,
1470 diag::err_ambiguous_derived_to_base_conv,
1471 Loc, Range, DeclarationName(),
1472 BasePath);
1473 }
1474
1475
1476 /// @brief Builds a string representing ambiguous paths from a
1477 /// specific derived class to different subobjects of the same base
1478 /// class.
1479 ///
1480 /// This function builds a string that can be used in error messages
1481 /// to show the different paths that one can take through the
1482 /// inheritance hierarchy to go from the derived class to different
1483 /// subobjects of a base class. The result looks something like this:
1484 /// @code
1485 /// struct D -> struct B -> struct A
1486 /// struct D -> struct C -> struct A
1487 /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)1488 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1489 std::string PathDisplayStr;
1490 std::set<unsigned> DisplayedPaths;
1491 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1492 Path != Paths.end(); ++Path) {
1493 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1494 // We haven't displayed a path to this particular base
1495 // class subobject yet.
1496 PathDisplayStr += "\n ";
1497 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1498 for (CXXBasePath::const_iterator Element = Path->begin();
1499 Element != Path->end(); ++Element)
1500 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1501 }
1502 }
1503
1504 return PathDisplayStr;
1505 }
1506
1507 //===----------------------------------------------------------------------===//
1508 // C++ class member Handling
1509 //===----------------------------------------------------------------------===//
1510
1511 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,AttributeList * Attrs)1512 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1513 SourceLocation ASLoc,
1514 SourceLocation ColonLoc,
1515 AttributeList *Attrs) {
1516 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1517 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1518 ASLoc, ColonLoc);
1519 CurContext->addHiddenDecl(ASDecl);
1520 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1521 }
1522
1523 /// CheckOverrideControl - Check C++11 override control semantics.
CheckOverrideControl(Decl * D)1524 void Sema::CheckOverrideControl(Decl *D) {
1525 if (D->isInvalidDecl())
1526 return;
1527
1528 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1529
1530 // Do we know which functions this declaration might be overriding?
1531 bool OverridesAreKnown = !MD ||
1532 (!MD->getParent()->hasAnyDependentBases() &&
1533 !MD->getType()->isDependentType());
1534
1535 if (!MD || !MD->isVirtual()) {
1536 if (OverridesAreKnown) {
1537 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1538 Diag(OA->getLocation(),
1539 diag::override_keyword_only_allowed_on_virtual_member_functions)
1540 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1541 D->dropAttr<OverrideAttr>();
1542 }
1543 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1544 Diag(FA->getLocation(),
1545 diag::override_keyword_only_allowed_on_virtual_member_functions)
1546 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1547 D->dropAttr<FinalAttr>();
1548 }
1549 }
1550 return;
1551 }
1552
1553 if (!OverridesAreKnown)
1554 return;
1555
1556 // C++11 [class.virtual]p5:
1557 // If a virtual function is marked with the virt-specifier override and
1558 // does not override a member function of a base class, the program is
1559 // ill-formed.
1560 bool HasOverriddenMethods =
1561 MD->begin_overridden_methods() != MD->end_overridden_methods();
1562 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1563 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1564 << MD->getDeclName();
1565 }
1566
1567 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1568 /// function overrides a virtual member function marked 'final', according to
1569 /// C++11 [class.virtual]p4.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)1570 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1571 const CXXMethodDecl *Old) {
1572 if (!Old->hasAttr<FinalAttr>())
1573 return false;
1574
1575 Diag(New->getLocation(), diag::err_final_function_overridden)
1576 << New->getDeclName();
1577 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1578 return true;
1579 }
1580
InitializationHasSideEffects(const FieldDecl & FD)1581 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1582 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1583 // FIXME: Destruction of ObjC lifetime types has side-effects.
1584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1585 return !RD->isCompleteDefinition() ||
1586 !RD->hasTrivialDefaultConstructor() ||
1587 !RD->hasTrivialDestructor();
1588 return false;
1589 }
1590
1591 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1592 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1593 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1594 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1595 /// present (but parsing it has been deferred).
1596 NamedDecl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BW,const VirtSpecifiers & VS,InClassInitStyle InitStyle)1597 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1598 MultiTemplateParamsArg TemplateParameterLists,
1599 Expr *BW, const VirtSpecifiers &VS,
1600 InClassInitStyle InitStyle) {
1601 const DeclSpec &DS = D.getDeclSpec();
1602 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1603 DeclarationName Name = NameInfo.getName();
1604 SourceLocation Loc = NameInfo.getLoc();
1605
1606 // For anonymous bitfields, the location should point to the type.
1607 if (Loc.isInvalid())
1608 Loc = D.getLocStart();
1609
1610 Expr *BitWidth = static_cast<Expr*>(BW);
1611
1612 assert(isa<CXXRecordDecl>(CurContext));
1613 assert(!DS.isFriendSpecified());
1614
1615 bool isFunc = D.isDeclarationOfFunction();
1616
1617 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1618 // The Microsoft extension __interface only permits public member functions
1619 // and prohibits constructors, destructors, operators, non-public member
1620 // functions, static methods and data members.
1621 unsigned InvalidDecl;
1622 bool ShowDeclName = true;
1623 if (!isFunc)
1624 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1625 else if (AS != AS_public)
1626 InvalidDecl = 2;
1627 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1628 InvalidDecl = 3;
1629 else switch (Name.getNameKind()) {
1630 case DeclarationName::CXXConstructorName:
1631 InvalidDecl = 4;
1632 ShowDeclName = false;
1633 break;
1634
1635 case DeclarationName::CXXDestructorName:
1636 InvalidDecl = 5;
1637 ShowDeclName = false;
1638 break;
1639
1640 case DeclarationName::CXXOperatorName:
1641 case DeclarationName::CXXConversionFunctionName:
1642 InvalidDecl = 6;
1643 break;
1644
1645 default:
1646 InvalidDecl = 0;
1647 break;
1648 }
1649
1650 if (InvalidDecl) {
1651 if (ShowDeclName)
1652 Diag(Loc, diag::err_invalid_member_in_interface)
1653 << (InvalidDecl-1) << Name;
1654 else
1655 Diag(Loc, diag::err_invalid_member_in_interface)
1656 << (InvalidDecl-1) << "";
1657 return 0;
1658 }
1659 }
1660
1661 // C++ 9.2p6: A member shall not be declared to have automatic storage
1662 // duration (auto, register) or with the extern storage-class-specifier.
1663 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1664 // data members and cannot be applied to names declared const or static,
1665 // and cannot be applied to reference members.
1666 switch (DS.getStorageClassSpec()) {
1667 case DeclSpec::SCS_unspecified:
1668 case DeclSpec::SCS_typedef:
1669 case DeclSpec::SCS_static:
1670 // FALL THROUGH.
1671 break;
1672 case DeclSpec::SCS_mutable:
1673 if (isFunc) {
1674 if (DS.getStorageClassSpecLoc().isValid())
1675 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1676 else
1677 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1678
1679 // FIXME: It would be nicer if the keyword was ignored only for this
1680 // declarator. Otherwise we could get follow-up errors.
1681 D.getMutableDeclSpec().ClearStorageClassSpecs();
1682 }
1683 break;
1684 default:
1685 if (DS.getStorageClassSpecLoc().isValid())
1686 Diag(DS.getStorageClassSpecLoc(),
1687 diag::err_storageclass_invalid_for_member);
1688 else
1689 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1690 D.getMutableDeclSpec().ClearStorageClassSpecs();
1691 }
1692
1693 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1694 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1695 !isFunc);
1696
1697 if (DS.isConstexprSpecified() && isInstField) {
1698 SemaDiagnosticBuilder B =
1699 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1700 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1701 if (InitStyle == ICIS_NoInit) {
1702 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1703 D.getMutableDeclSpec().ClearConstexprSpec();
1704 const char *PrevSpec;
1705 unsigned DiagID;
1706 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1707 PrevSpec, DiagID, getLangOpts());
1708 (void)Failed;
1709 assert(!Failed && "Making a constexpr member const shouldn't fail");
1710 } else {
1711 B << 1;
1712 const char *PrevSpec;
1713 unsigned DiagID;
1714 if (D.getMutableDeclSpec().SetStorageClassSpec(
1715 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1716 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1717 "This is the only DeclSpec that should fail to be applied");
1718 B << 1;
1719 } else {
1720 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1721 isInstField = false;
1722 }
1723 }
1724 }
1725
1726 NamedDecl *Member;
1727 if (isInstField) {
1728 CXXScopeSpec &SS = D.getCXXScopeSpec();
1729
1730 // Data members must have identifiers for names.
1731 if (!Name.isIdentifier()) {
1732 Diag(Loc, diag::err_bad_variable_name)
1733 << Name;
1734 return 0;
1735 }
1736
1737 IdentifierInfo *II = Name.getAsIdentifierInfo();
1738
1739 // Member field could not be with "template" keyword.
1740 // So TemplateParameterLists should be empty in this case.
1741 if (TemplateParameterLists.size()) {
1742 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1743 if (TemplateParams->size()) {
1744 // There is no such thing as a member field template.
1745 Diag(D.getIdentifierLoc(), diag::err_template_member)
1746 << II
1747 << SourceRange(TemplateParams->getTemplateLoc(),
1748 TemplateParams->getRAngleLoc());
1749 } else {
1750 // There is an extraneous 'template<>' for this member.
1751 Diag(TemplateParams->getTemplateLoc(),
1752 diag::err_template_member_noparams)
1753 << II
1754 << SourceRange(TemplateParams->getTemplateLoc(),
1755 TemplateParams->getRAngleLoc());
1756 }
1757 return 0;
1758 }
1759
1760 if (SS.isSet() && !SS.isInvalid()) {
1761 // The user provided a superfluous scope specifier inside a class
1762 // definition:
1763 //
1764 // class X {
1765 // int X::member;
1766 // };
1767 if (DeclContext *DC = computeDeclContext(SS, false))
1768 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1769 else
1770 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1771 << Name << SS.getRange();
1772
1773 SS.clear();
1774 }
1775
1776 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1777 InitStyle, AS);
1778 assert(Member && "HandleField never returns null");
1779 } else {
1780 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1781
1782 Member = HandleDeclarator(S, D, TemplateParameterLists);
1783 if (!Member) {
1784 return 0;
1785 }
1786
1787 // Non-instance-fields can't have a bitfield.
1788 if (BitWidth) {
1789 if (Member->isInvalidDecl()) {
1790 // don't emit another diagnostic.
1791 } else if (isa<VarDecl>(Member)) {
1792 // C++ 9.6p3: A bit-field shall not be a static member.
1793 // "static member 'A' cannot be a bit-field"
1794 Diag(Loc, diag::err_static_not_bitfield)
1795 << Name << BitWidth->getSourceRange();
1796 } else if (isa<TypedefDecl>(Member)) {
1797 // "typedef member 'x' cannot be a bit-field"
1798 Diag(Loc, diag::err_typedef_not_bitfield)
1799 << Name << BitWidth->getSourceRange();
1800 } else {
1801 // A function typedef ("typedef int f(); f a;").
1802 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1803 Diag(Loc, diag::err_not_integral_type_bitfield)
1804 << Name << cast<ValueDecl>(Member)->getType()
1805 << BitWidth->getSourceRange();
1806 }
1807
1808 BitWidth = 0;
1809 Member->setInvalidDecl();
1810 }
1811
1812 Member->setAccess(AS);
1813
1814 // If we have declared a member function template, set the access of the
1815 // templated declaration as well.
1816 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1817 FunTmpl->getTemplatedDecl()->setAccess(AS);
1818 }
1819
1820 if (VS.isOverrideSpecified())
1821 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1822 if (VS.isFinalSpecified())
1823 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1824
1825 if (VS.getLastLocation().isValid()) {
1826 // Update the end location of a method that has a virt-specifiers.
1827 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1828 MD->setRangeEnd(VS.getLastLocation());
1829 }
1830
1831 CheckOverrideControl(Member);
1832
1833 assert((Name || isInstField) && "No identifier for non-field ?");
1834
1835 if (isInstField) {
1836 FieldDecl *FD = cast<FieldDecl>(Member);
1837 FieldCollector->Add(FD);
1838
1839 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1840 FD->getLocation())
1841 != DiagnosticsEngine::Ignored) {
1842 // Remember all explicit private FieldDecls that have a name, no side
1843 // effects and are not part of a dependent type declaration.
1844 if (!FD->isImplicit() && FD->getDeclName() &&
1845 FD->getAccess() == AS_private &&
1846 !FD->hasAttr<UnusedAttr>() &&
1847 !FD->getParent()->isDependentContext() &&
1848 !InitializationHasSideEffects(*FD))
1849 UnusedPrivateFields.insert(FD);
1850 }
1851 }
1852
1853 return Member;
1854 }
1855
1856 namespace {
1857 class UninitializedFieldVisitor
1858 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1859 Sema &S;
1860 ValueDecl *VD;
1861 public:
1862 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,ValueDecl * VD)1863 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1864 S(S) {
1865 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1866 this->VD = IFD->getAnonField();
1867 else
1868 this->VD = VD;
1869 }
1870
HandleExpr(Expr * E)1871 void HandleExpr(Expr *E) {
1872 if (!E) return;
1873
1874 // Expressions like x(x) sometimes lack the surrounding expressions
1875 // but need to be checked anyways.
1876 HandleValue(E);
1877 Visit(E);
1878 }
1879
HandleValue(Expr * E)1880 void HandleValue(Expr *E) {
1881 E = E->IgnoreParens();
1882
1883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1884 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1885 return;
1886
1887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1888 // or union.
1889 MemberExpr *FieldME = ME;
1890
1891 Expr *Base = E;
1892 while (isa<MemberExpr>(Base)) {
1893 ME = cast<MemberExpr>(Base);
1894
1895 if (isa<VarDecl>(ME->getMemberDecl()))
1896 return;
1897
1898 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1899 if (!FD->isAnonymousStructOrUnion())
1900 FieldME = ME;
1901
1902 Base = ME->getBase();
1903 }
1904
1905 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1906 unsigned diag = VD->getType()->isReferenceType()
1907 ? diag::warn_reference_field_is_uninit
1908 : diag::warn_field_is_uninit;
1909 S.Diag(FieldME->getExprLoc(), diag) << VD;
1910 }
1911 return;
1912 }
1913
1914 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1915 HandleValue(CO->getTrueExpr());
1916 HandleValue(CO->getFalseExpr());
1917 return;
1918 }
1919
1920 if (BinaryConditionalOperator *BCO =
1921 dyn_cast<BinaryConditionalOperator>(E)) {
1922 HandleValue(BCO->getCommon());
1923 HandleValue(BCO->getFalseExpr());
1924 return;
1925 }
1926
1927 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1928 switch (BO->getOpcode()) {
1929 default:
1930 return;
1931 case(BO_PtrMemD):
1932 case(BO_PtrMemI):
1933 HandleValue(BO->getLHS());
1934 return;
1935 case(BO_Comma):
1936 HandleValue(BO->getRHS());
1937 return;
1938 }
1939 }
1940 }
1941
VisitImplicitCastExpr(ImplicitCastExpr * E)1942 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1943 if (E->getCastKind() == CK_LValueToRValue)
1944 HandleValue(E->getSubExpr());
1945
1946 Inherited::VisitImplicitCastExpr(E);
1947 }
1948
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)1949 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1950 Expr *Callee = E->getCallee();
1951 if (isa<MemberExpr>(Callee))
1952 HandleValue(Callee);
1953
1954 Inherited::VisitCXXMemberCallExpr(E);
1955 }
1956 };
CheckInitExprContainsUninitializedFields(Sema & S,Expr * E,ValueDecl * VD)1957 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1958 ValueDecl *VD) {
1959 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1960 }
1961 } // namespace
1962
1963 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1964 /// in-class initializer for a non-static C++ class member, and after
1965 /// instantiating an in-class initializer in a class template. Such actions
1966 /// are deferred until the class is complete.
1967 void
ActOnCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,Expr * InitExpr)1968 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1969 Expr *InitExpr) {
1970 FieldDecl *FD = cast<FieldDecl>(D);
1971 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1972 "must set init style when field is created");
1973
1974 if (!InitExpr) {
1975 FD->setInvalidDecl();
1976 FD->removeInClassInitializer();
1977 return;
1978 }
1979
1980 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1981 FD->setInvalidDecl();
1982 FD->removeInClassInitializer();
1983 return;
1984 }
1985
1986 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1987 != DiagnosticsEngine::Ignored) {
1988 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1989 }
1990
1991 ExprResult Init = InitExpr;
1992 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1993 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1994 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1995 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1996 }
1997 Expr **Inits = &InitExpr;
1998 unsigned NumInits = 1;
1999 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2000 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2001 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2002 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2003 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2004 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
2005 if (Init.isInvalid()) {
2006 FD->setInvalidDecl();
2007 return;
2008 }
2009 }
2010
2011 // C++11 [class.base.init]p7:
2012 // The initialization of each base and member constitutes a
2013 // full-expression.
2014 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2015 if (Init.isInvalid()) {
2016 FD->setInvalidDecl();
2017 return;
2018 }
2019
2020 InitExpr = Init.release();
2021
2022 FD->setInClassInitializer(InitExpr);
2023 }
2024
2025 /// \brief Find the direct and/or virtual base specifiers that
2026 /// correspond to the given base type, for use in base initialization
2027 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)2028 static bool FindBaseInitializer(Sema &SemaRef,
2029 CXXRecordDecl *ClassDecl,
2030 QualType BaseType,
2031 const CXXBaseSpecifier *&DirectBaseSpec,
2032 const CXXBaseSpecifier *&VirtualBaseSpec) {
2033 // First, check for a direct base class.
2034 DirectBaseSpec = 0;
2035 for (CXXRecordDecl::base_class_const_iterator Base
2036 = ClassDecl->bases_begin();
2037 Base != ClassDecl->bases_end(); ++Base) {
2038 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2039 // We found a direct base of this type. That's what we're
2040 // initializing.
2041 DirectBaseSpec = &*Base;
2042 break;
2043 }
2044 }
2045
2046 // Check for a virtual base class.
2047 // FIXME: We might be able to short-circuit this if we know in advance that
2048 // there are no virtual bases.
2049 VirtualBaseSpec = 0;
2050 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2051 // We haven't found a base yet; search the class hierarchy for a
2052 // virtual base class.
2053 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2054 /*DetectVirtual=*/false);
2055 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2056 BaseType, Paths)) {
2057 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2058 Path != Paths.end(); ++Path) {
2059 if (Path->back().Base->isVirtual()) {
2060 VirtualBaseSpec = Path->back().Base;
2061 break;
2062 }
2063 }
2064 }
2065 }
2066
2067 return DirectBaseSpec || VirtualBaseSpec;
2068 }
2069
2070 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2071 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)2072 Sema::ActOnMemInitializer(Decl *ConstructorD,
2073 Scope *S,
2074 CXXScopeSpec &SS,
2075 IdentifierInfo *MemberOrBase,
2076 ParsedType TemplateTypeTy,
2077 const DeclSpec &DS,
2078 SourceLocation IdLoc,
2079 Expr *InitList,
2080 SourceLocation EllipsisLoc) {
2081 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2082 DS, IdLoc, InitList,
2083 EllipsisLoc);
2084 }
2085
2086 /// \brief Handle a C++ member initializer using parentheses syntax.
2087 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc,SourceLocation EllipsisLoc)2088 Sema::ActOnMemInitializer(Decl *ConstructorD,
2089 Scope *S,
2090 CXXScopeSpec &SS,
2091 IdentifierInfo *MemberOrBase,
2092 ParsedType TemplateTypeTy,
2093 const DeclSpec &DS,
2094 SourceLocation IdLoc,
2095 SourceLocation LParenLoc,
2096 Expr **Args, unsigned NumArgs,
2097 SourceLocation RParenLoc,
2098 SourceLocation EllipsisLoc) {
2099 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2100 llvm::makeArrayRef(Args, NumArgs),
2101 RParenLoc);
2102 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2103 DS, IdLoc, List, EllipsisLoc);
2104 }
2105
2106 namespace {
2107
2108 // Callback to only accept typo corrections that can be a valid C++ member
2109 // intializer: either a non-static field member or a base class.
2110 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2111 public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)2112 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2113 : ClassDecl(ClassDecl) {}
2114
ValidateCandidate(const TypoCorrection & candidate)2115 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2116 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2117 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2118 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2119 else
2120 return isa<TypeDecl>(ND);
2121 }
2122 return false;
2123 }
2124
2125 private:
2126 CXXRecordDecl *ClassDecl;
2127 };
2128
2129 }
2130
2131 /// \brief Handle a C++ member initializer.
2132 MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)2133 Sema::BuildMemInitializer(Decl *ConstructorD,
2134 Scope *S,
2135 CXXScopeSpec &SS,
2136 IdentifierInfo *MemberOrBase,
2137 ParsedType TemplateTypeTy,
2138 const DeclSpec &DS,
2139 SourceLocation IdLoc,
2140 Expr *Init,
2141 SourceLocation EllipsisLoc) {
2142 if (!ConstructorD)
2143 return true;
2144
2145 AdjustDeclIfTemplate(ConstructorD);
2146
2147 CXXConstructorDecl *Constructor
2148 = dyn_cast<CXXConstructorDecl>(ConstructorD);
2149 if (!Constructor) {
2150 // The user wrote a constructor initializer on a function that is
2151 // not a C++ constructor. Ignore the error for now, because we may
2152 // have more member initializers coming; we'll diagnose it just
2153 // once in ActOnMemInitializers.
2154 return true;
2155 }
2156
2157 CXXRecordDecl *ClassDecl = Constructor->getParent();
2158
2159 // C++ [class.base.init]p2:
2160 // Names in a mem-initializer-id are looked up in the scope of the
2161 // constructor's class and, if not found in that scope, are looked
2162 // up in the scope containing the constructor's definition.
2163 // [Note: if the constructor's class contains a member with the
2164 // same name as a direct or virtual base class of the class, a
2165 // mem-initializer-id naming the member or base class and composed
2166 // of a single identifier refers to the class member. A
2167 // mem-initializer-id for the hidden base class may be specified
2168 // using a qualified name. ]
2169 if (!SS.getScopeRep() && !TemplateTypeTy) {
2170 // Look for a member, first.
2171 DeclContext::lookup_result Result
2172 = ClassDecl->lookup(MemberOrBase);
2173 if (!Result.empty()) {
2174 ValueDecl *Member;
2175 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2176 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2177 if (EllipsisLoc.isValid())
2178 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2179 << MemberOrBase
2180 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2181
2182 return BuildMemberInitializer(Member, Init, IdLoc);
2183 }
2184 }
2185 }
2186 // It didn't name a member, so see if it names a class.
2187 QualType BaseType;
2188 TypeSourceInfo *TInfo = 0;
2189
2190 if (TemplateTypeTy) {
2191 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2192 } else if (DS.getTypeSpecType() == TST_decltype) {
2193 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2194 } else {
2195 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2196 LookupParsedName(R, S, &SS);
2197
2198 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2199 if (!TyD) {
2200 if (R.isAmbiguous()) return true;
2201
2202 // We don't want access-control diagnostics here.
2203 R.suppressDiagnostics();
2204
2205 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2206 bool NotUnknownSpecialization = false;
2207 DeclContext *DC = computeDeclContext(SS, false);
2208 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2209 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2210
2211 if (!NotUnknownSpecialization) {
2212 // When the scope specifier can refer to a member of an unknown
2213 // specialization, we take it as a type name.
2214 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2215 SS.getWithLocInContext(Context),
2216 *MemberOrBase, IdLoc);
2217 if (BaseType.isNull())
2218 return true;
2219
2220 R.clear();
2221 R.setLookupName(MemberOrBase);
2222 }
2223 }
2224
2225 // If no results were found, try to correct typos.
2226 TypoCorrection Corr;
2227 MemInitializerValidatorCCC Validator(ClassDecl);
2228 if (R.empty() && BaseType.isNull() &&
2229 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2230 Validator, ClassDecl))) {
2231 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2232 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2233 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2234 // We have found a non-static data member with a similar
2235 // name to what was typed; complain and initialize that
2236 // member.
2237 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2238 << MemberOrBase << true << CorrectedQuotedStr
2239 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2240 Diag(Member->getLocation(), diag::note_previous_decl)
2241 << CorrectedQuotedStr;
2242
2243 return BuildMemberInitializer(Member, Init, IdLoc);
2244 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2245 const CXXBaseSpecifier *DirectBaseSpec;
2246 const CXXBaseSpecifier *VirtualBaseSpec;
2247 if (FindBaseInitializer(*this, ClassDecl,
2248 Context.getTypeDeclType(Type),
2249 DirectBaseSpec, VirtualBaseSpec)) {
2250 // We have found a direct or virtual base class with a
2251 // similar name to what was typed; complain and initialize
2252 // that base class.
2253 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2254 << MemberOrBase << false << CorrectedQuotedStr
2255 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2256
2257 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2258 : VirtualBaseSpec;
2259 Diag(BaseSpec->getLocStart(),
2260 diag::note_base_class_specified_here)
2261 << BaseSpec->getType()
2262 << BaseSpec->getSourceRange();
2263
2264 TyD = Type;
2265 }
2266 }
2267 }
2268
2269 if (!TyD && BaseType.isNull()) {
2270 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2271 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2272 return true;
2273 }
2274 }
2275
2276 if (BaseType.isNull()) {
2277 BaseType = Context.getTypeDeclType(TyD);
2278 if (SS.isSet()) {
2279 NestedNameSpecifier *Qualifier =
2280 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2281
2282 // FIXME: preserve source range information
2283 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2284 }
2285 }
2286 }
2287
2288 if (!TInfo)
2289 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2290
2291 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2292 }
2293
2294 /// Checks a member initializer expression for cases where reference (or
2295 /// pointer) members are bound to by-value parameters (or their addresses).
CheckForDanglingReferenceOrPointer(Sema & S,ValueDecl * Member,Expr * Init,SourceLocation IdLoc)2296 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2297 Expr *Init,
2298 SourceLocation IdLoc) {
2299 QualType MemberTy = Member->getType();
2300
2301 // We only handle pointers and references currently.
2302 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2303 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2304 return;
2305
2306 const bool IsPointer = MemberTy->isPointerType();
2307 if (IsPointer) {
2308 if (const UnaryOperator *Op
2309 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2310 // The only case we're worried about with pointers requires taking the
2311 // address.
2312 if (Op->getOpcode() != UO_AddrOf)
2313 return;
2314
2315 Init = Op->getSubExpr();
2316 } else {
2317 // We only handle address-of expression initializers for pointers.
2318 return;
2319 }
2320 }
2321
2322 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2323 // Taking the address of a temporary will be diagnosed as a hard error.
2324 if (IsPointer)
2325 return;
2326
2327 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2328 << Member << Init->getSourceRange();
2329 } else if (const DeclRefExpr *DRE
2330 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2331 // We only warn when referring to a non-reference parameter declaration.
2332 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2333 if (!Parameter || Parameter->getType()->isReferenceType())
2334 return;
2335
2336 S.Diag(Init->getExprLoc(),
2337 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2338 : diag::warn_bind_ref_member_to_parameter)
2339 << Member << Parameter << Init->getSourceRange();
2340 } else {
2341 // Other initializers are fine.
2342 return;
2343 }
2344
2345 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2346 << (unsigned)IsPointer;
2347 }
2348
2349 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)2350 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2351 SourceLocation IdLoc) {
2352 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2353 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2354 assert((DirectMember || IndirectMember) &&
2355 "Member must be a FieldDecl or IndirectFieldDecl");
2356
2357 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2358 return true;
2359
2360 if (Member->isInvalidDecl())
2361 return true;
2362
2363 // Diagnose value-uses of fields to initialize themselves, e.g.
2364 // foo(foo)
2365 // where foo is not also a parameter to the constructor.
2366 // TODO: implement -Wuninitialized and fold this into that framework.
2367 Expr **Args;
2368 unsigned NumArgs;
2369 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2370 Args = ParenList->getExprs();
2371 NumArgs = ParenList->getNumExprs();
2372 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2373 Args = InitList->getInits();
2374 NumArgs = InitList->getNumInits();
2375 } else {
2376 // Template instantiation doesn't reconstruct ParenListExprs for us.
2377 Args = &Init;
2378 NumArgs = 1;
2379 }
2380
2381 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2382 != DiagnosticsEngine::Ignored)
2383 for (unsigned i = 0; i < NumArgs; ++i)
2384 // FIXME: Warn about the case when other fields are used before being
2385 // initialized. For example, let this field be the i'th field. When
2386 // initializing the i'th field, throw a warning if any of the >= i'th
2387 // fields are used, as they are not yet initialized.
2388 // Right now we are only handling the case where the i'th field uses
2389 // itself in its initializer.
2390 // Also need to take into account that some fields may be initialized by
2391 // in-class initializers, see C++11 [class.base.init]p9.
2392 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2393
2394 SourceRange InitRange = Init->getSourceRange();
2395
2396 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2397 // Can't check initialization for a member of dependent type or when
2398 // any of the arguments are type-dependent expressions.
2399 DiscardCleanupsInEvaluationContext();
2400 } else {
2401 bool InitList = false;
2402 if (isa<InitListExpr>(Init)) {
2403 InitList = true;
2404 Args = &Init;
2405 NumArgs = 1;
2406
2407 if (isStdInitializerList(Member->getType(), 0)) {
2408 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2409 << /*at end of ctor*/1 << InitRange;
2410 }
2411 }
2412
2413 // Initialize the member.
2414 InitializedEntity MemberEntity =
2415 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2416 : InitializedEntity::InitializeMember(IndirectMember, 0);
2417 InitializationKind Kind =
2418 InitList ? InitializationKind::CreateDirectList(IdLoc)
2419 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2420 InitRange.getEnd());
2421
2422 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2423 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2424 MultiExprArg(Args, NumArgs),
2425 0);
2426 if (MemberInit.isInvalid())
2427 return true;
2428
2429 // C++11 [class.base.init]p7:
2430 // The initialization of each base and member constitutes a
2431 // full-expression.
2432 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2433 if (MemberInit.isInvalid())
2434 return true;
2435
2436 Init = MemberInit.get();
2437 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2438 }
2439
2440 if (DirectMember) {
2441 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2442 InitRange.getBegin(), Init,
2443 InitRange.getEnd());
2444 } else {
2445 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2446 InitRange.getBegin(), Init,
2447 InitRange.getEnd());
2448 }
2449 }
2450
2451 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)2452 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2453 CXXRecordDecl *ClassDecl) {
2454 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2455 if (!LangOpts.CPlusPlus11)
2456 return Diag(NameLoc, diag::err_delegating_ctor)
2457 << TInfo->getTypeLoc().getLocalSourceRange();
2458 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2459
2460 bool InitList = true;
2461 Expr **Args = &Init;
2462 unsigned NumArgs = 1;
2463 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2464 InitList = false;
2465 Args = ParenList->getExprs();
2466 NumArgs = ParenList->getNumExprs();
2467 }
2468
2469 SourceRange InitRange = Init->getSourceRange();
2470 // Initialize the object.
2471 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2472 QualType(ClassDecl->getTypeForDecl(), 0));
2473 InitializationKind Kind =
2474 InitList ? InitializationKind::CreateDirectList(NameLoc)
2475 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2476 InitRange.getEnd());
2477 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2478 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2479 MultiExprArg(Args, NumArgs),
2480 0);
2481 if (DelegationInit.isInvalid())
2482 return true;
2483
2484 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2485 "Delegating constructor with no target?");
2486
2487 // C++11 [class.base.init]p7:
2488 // The initialization of each base and member constitutes a
2489 // full-expression.
2490 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2491 InitRange.getBegin());
2492 if (DelegationInit.isInvalid())
2493 return true;
2494
2495 // If we are in a dependent context, template instantiation will
2496 // perform this type-checking again. Just save the arguments that we
2497 // received in a ParenListExpr.
2498 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2499 // of the information that we have about the base
2500 // initializer. However, deconstructing the ASTs is a dicey process,
2501 // and this approach is far more likely to get the corner cases right.
2502 if (CurContext->isDependentContext())
2503 DelegationInit = Owned(Init);
2504
2505 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2506 DelegationInit.takeAs<Expr>(),
2507 InitRange.getEnd());
2508 }
2509
2510 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)2511 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2512 Expr *Init, CXXRecordDecl *ClassDecl,
2513 SourceLocation EllipsisLoc) {
2514 SourceLocation BaseLoc
2515 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2516
2517 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2518 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2519 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2520
2521 // C++ [class.base.init]p2:
2522 // [...] Unless the mem-initializer-id names a nonstatic data
2523 // member of the constructor's class or a direct or virtual base
2524 // of that class, the mem-initializer is ill-formed. A
2525 // mem-initializer-list can initialize a base class using any
2526 // name that denotes that base class type.
2527 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2528
2529 SourceRange InitRange = Init->getSourceRange();
2530 if (EllipsisLoc.isValid()) {
2531 // This is a pack expansion.
2532 if (!BaseType->containsUnexpandedParameterPack()) {
2533 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2534 << SourceRange(BaseLoc, InitRange.getEnd());
2535
2536 EllipsisLoc = SourceLocation();
2537 }
2538 } else {
2539 // Check for any unexpanded parameter packs.
2540 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2541 return true;
2542
2543 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2544 return true;
2545 }
2546
2547 // Check for direct and virtual base classes.
2548 const CXXBaseSpecifier *DirectBaseSpec = 0;
2549 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2550 if (!Dependent) {
2551 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2552 BaseType))
2553 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2554
2555 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2556 VirtualBaseSpec);
2557
2558 // C++ [base.class.init]p2:
2559 // Unless the mem-initializer-id names a nonstatic data member of the
2560 // constructor's class or a direct or virtual base of that class, the
2561 // mem-initializer is ill-formed.
2562 if (!DirectBaseSpec && !VirtualBaseSpec) {
2563 // If the class has any dependent bases, then it's possible that
2564 // one of those types will resolve to the same type as
2565 // BaseType. Therefore, just treat this as a dependent base
2566 // class initialization. FIXME: Should we try to check the
2567 // initialization anyway? It seems odd.
2568 if (ClassDecl->hasAnyDependentBases())
2569 Dependent = true;
2570 else
2571 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2572 << BaseType << Context.getTypeDeclType(ClassDecl)
2573 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2574 }
2575 }
2576
2577 if (Dependent) {
2578 DiscardCleanupsInEvaluationContext();
2579
2580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2581 /*IsVirtual=*/false,
2582 InitRange.getBegin(), Init,
2583 InitRange.getEnd(), EllipsisLoc);
2584 }
2585
2586 // C++ [base.class.init]p2:
2587 // If a mem-initializer-id is ambiguous because it designates both
2588 // a direct non-virtual base class and an inherited virtual base
2589 // class, the mem-initializer is ill-formed.
2590 if (DirectBaseSpec && VirtualBaseSpec)
2591 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2592 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2593
2594 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2595 if (!BaseSpec)
2596 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2597
2598 // Initialize the base.
2599 bool InitList = true;
2600 Expr **Args = &Init;
2601 unsigned NumArgs = 1;
2602 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2603 InitList = false;
2604 Args = ParenList->getExprs();
2605 NumArgs = ParenList->getNumExprs();
2606 }
2607
2608 InitializedEntity BaseEntity =
2609 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2610 InitializationKind Kind =
2611 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2612 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2613 InitRange.getEnd());
2614 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2615 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2616 MultiExprArg(Args, NumArgs), 0);
2617 if (BaseInit.isInvalid())
2618 return true;
2619
2620 // C++11 [class.base.init]p7:
2621 // The initialization of each base and member constitutes a
2622 // full-expression.
2623 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2624 if (BaseInit.isInvalid())
2625 return true;
2626
2627 // If we are in a dependent context, template instantiation will
2628 // perform this type-checking again. Just save the arguments that we
2629 // received in a ParenListExpr.
2630 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2631 // of the information that we have about the base
2632 // initializer. However, deconstructing the ASTs is a dicey process,
2633 // and this approach is far more likely to get the corner cases right.
2634 if (CurContext->isDependentContext())
2635 BaseInit = Owned(Init);
2636
2637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2638 BaseSpec->isVirtual(),
2639 InitRange.getBegin(),
2640 BaseInit.takeAs<Expr>(),
2641 InitRange.getEnd(), EllipsisLoc);
2642 }
2643
2644 // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E,QualType T=QualType ())2645 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2646 if (T.isNull()) T = E->getType();
2647 QualType TargetType = SemaRef.BuildReferenceType(
2648 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2649 SourceLocation ExprLoc = E->getLocStart();
2650 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2651 TargetType, ExprLoc);
2652
2653 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2654 SourceRange(ExprLoc, ExprLoc),
2655 E->getSourceRange()).take();
2656 }
2657
2658 /// ImplicitInitializerKind - How an implicit base or member initializer should
2659 /// initialize its base or member.
2660 enum ImplicitInitializerKind {
2661 IIK_Default,
2662 IIK_Copy,
2663 IIK_Move,
2664 IIK_Inherit
2665 };
2666
2667 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)2668 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2669 ImplicitInitializerKind ImplicitInitKind,
2670 CXXBaseSpecifier *BaseSpec,
2671 bool IsInheritedVirtualBase,
2672 CXXCtorInitializer *&CXXBaseInit) {
2673 InitializedEntity InitEntity
2674 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2675 IsInheritedVirtualBase);
2676
2677 ExprResult BaseInit;
2678
2679 switch (ImplicitInitKind) {
2680 case IIK_Inherit: {
2681 const CXXRecordDecl *Inherited =
2682 Constructor->getInheritedConstructor()->getParent();
2683 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2684 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2685 // C++11 [class.inhctor]p8:
2686 // Each expression in the expression-list is of the form
2687 // static_cast<T&&>(p), where p is the name of the corresponding
2688 // constructor parameter and T is the declared type of p.
2689 SmallVector<Expr*, 16> Args;
2690 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2691 ParmVarDecl *PD = Constructor->getParamDecl(I);
2692 ExprResult ArgExpr =
2693 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2694 VK_LValue, SourceLocation());
2695 if (ArgExpr.isInvalid())
2696 return true;
2697 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2698 }
2699
2700 InitializationKind InitKind = InitializationKind::CreateDirect(
2701 Constructor->getLocation(), SourceLocation(), SourceLocation());
2702 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2703 Args.data(), Args.size());
2704 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2705 break;
2706 }
2707 }
2708 // Fall through.
2709 case IIK_Default: {
2710 InitializationKind InitKind
2711 = InitializationKind::CreateDefault(Constructor->getLocation());
2712 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2713 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2714 break;
2715 }
2716
2717 case IIK_Move:
2718 case IIK_Copy: {
2719 bool Moving = ImplicitInitKind == IIK_Move;
2720 ParmVarDecl *Param = Constructor->getParamDecl(0);
2721 QualType ParamType = Param->getType().getNonReferenceType();
2722
2723 Expr *CopyCtorArg =
2724 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2725 SourceLocation(), Param, false,
2726 Constructor->getLocation(), ParamType,
2727 VK_LValue, 0);
2728
2729 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2730
2731 // Cast to the base class to avoid ambiguities.
2732 QualType ArgTy =
2733 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2734 ParamType.getQualifiers());
2735
2736 if (Moving) {
2737 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2738 }
2739
2740 CXXCastPath BasePath;
2741 BasePath.push_back(BaseSpec);
2742 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2743 CK_UncheckedDerivedToBase,
2744 Moving ? VK_XValue : VK_LValue,
2745 &BasePath).take();
2746
2747 InitializationKind InitKind
2748 = InitializationKind::CreateDirect(Constructor->getLocation(),
2749 SourceLocation(), SourceLocation());
2750 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2751 &CopyCtorArg, 1);
2752 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2753 MultiExprArg(&CopyCtorArg, 1));
2754 break;
2755 }
2756 }
2757
2758 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2759 if (BaseInit.isInvalid())
2760 return true;
2761
2762 CXXBaseInit =
2763 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2764 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2765 SourceLocation()),
2766 BaseSpec->isVirtual(),
2767 SourceLocation(),
2768 BaseInit.takeAs<Expr>(),
2769 SourceLocation(),
2770 SourceLocation());
2771
2772 return false;
2773 }
2774
RefersToRValueRef(Expr * MemRef)2775 static bool RefersToRValueRef(Expr *MemRef) {
2776 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2777 return Referenced->getType()->isRValueReferenceType();
2778 }
2779
2780 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)2781 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2782 ImplicitInitializerKind ImplicitInitKind,
2783 FieldDecl *Field, IndirectFieldDecl *Indirect,
2784 CXXCtorInitializer *&CXXMemberInit) {
2785 if (Field->isInvalidDecl())
2786 return true;
2787
2788 SourceLocation Loc = Constructor->getLocation();
2789
2790 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2791 bool Moving = ImplicitInitKind == IIK_Move;
2792 ParmVarDecl *Param = Constructor->getParamDecl(0);
2793 QualType ParamType = Param->getType().getNonReferenceType();
2794
2795 // Suppress copying zero-width bitfields.
2796 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2797 return false;
2798
2799 Expr *MemberExprBase =
2800 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2801 SourceLocation(), Param, false,
2802 Loc, ParamType, VK_LValue, 0);
2803
2804 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2805
2806 if (Moving) {
2807 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2808 }
2809
2810 // Build a reference to this field within the parameter.
2811 CXXScopeSpec SS;
2812 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2813 Sema::LookupMemberName);
2814 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2815 : cast<ValueDecl>(Field), AS_public);
2816 MemberLookup.resolveKind();
2817 ExprResult CtorArg
2818 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2819 ParamType, Loc,
2820 /*IsArrow=*/false,
2821 SS,
2822 /*TemplateKWLoc=*/SourceLocation(),
2823 /*FirstQualifierInScope=*/0,
2824 MemberLookup,
2825 /*TemplateArgs=*/0);
2826 if (CtorArg.isInvalid())
2827 return true;
2828
2829 // C++11 [class.copy]p15:
2830 // - if a member m has rvalue reference type T&&, it is direct-initialized
2831 // with static_cast<T&&>(x.m);
2832 if (RefersToRValueRef(CtorArg.get())) {
2833 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2834 }
2835
2836 // When the field we are copying is an array, create index variables for
2837 // each dimension of the array. We use these index variables to subscript
2838 // the source array, and other clients (e.g., CodeGen) will perform the
2839 // necessary iteration with these index variables.
2840 SmallVector<VarDecl *, 4> IndexVariables;
2841 QualType BaseType = Field->getType();
2842 QualType SizeType = SemaRef.Context.getSizeType();
2843 bool InitializingArray = false;
2844 while (const ConstantArrayType *Array
2845 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2846 InitializingArray = true;
2847 // Create the iteration variable for this array index.
2848 IdentifierInfo *IterationVarName = 0;
2849 {
2850 SmallString<8> Str;
2851 llvm::raw_svector_ostream OS(Str);
2852 OS << "__i" << IndexVariables.size();
2853 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2854 }
2855 VarDecl *IterationVar
2856 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2857 IterationVarName, SizeType,
2858 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2859 SC_None, SC_None);
2860 IndexVariables.push_back(IterationVar);
2861
2862 // Create a reference to the iteration variable.
2863 ExprResult IterationVarRef
2864 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2865 assert(!IterationVarRef.isInvalid() &&
2866 "Reference to invented variable cannot fail!");
2867 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2868 assert(!IterationVarRef.isInvalid() &&
2869 "Conversion of invented variable cannot fail!");
2870
2871 // Subscript the array with this iteration variable.
2872 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2873 IterationVarRef.take(),
2874 Loc);
2875 if (CtorArg.isInvalid())
2876 return true;
2877
2878 BaseType = Array->getElementType();
2879 }
2880
2881 // The array subscript expression is an lvalue, which is wrong for moving.
2882 if (Moving && InitializingArray)
2883 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2884
2885 // Construct the entity that we will be initializing. For an array, this
2886 // will be first element in the array, which may require several levels
2887 // of array-subscript entities.
2888 SmallVector<InitializedEntity, 4> Entities;
2889 Entities.reserve(1 + IndexVariables.size());
2890 if (Indirect)
2891 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2892 else
2893 Entities.push_back(InitializedEntity::InitializeMember(Field));
2894 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2895 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2896 0,
2897 Entities.back()));
2898
2899 // Direct-initialize to use the copy constructor.
2900 InitializationKind InitKind =
2901 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2902
2903 Expr *CtorArgE = CtorArg.takeAs<Expr>();
2904 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2905 &CtorArgE, 1);
2906
2907 ExprResult MemberInit
2908 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2909 MultiExprArg(&CtorArgE, 1));
2910 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2911 if (MemberInit.isInvalid())
2912 return true;
2913
2914 if (Indirect) {
2915 assert(IndexVariables.size() == 0 &&
2916 "Indirect field improperly initialized");
2917 CXXMemberInit
2918 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2919 Loc, Loc,
2920 MemberInit.takeAs<Expr>(),
2921 Loc);
2922 } else
2923 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2924 Loc, MemberInit.takeAs<Expr>(),
2925 Loc,
2926 IndexVariables.data(),
2927 IndexVariables.size());
2928 return false;
2929 }
2930
2931 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2932 "Unhandled implicit init kind!");
2933
2934 QualType FieldBaseElementType =
2935 SemaRef.Context.getBaseElementType(Field->getType());
2936
2937 if (FieldBaseElementType->isRecordType()) {
2938 InitializedEntity InitEntity
2939 = Indirect? InitializedEntity::InitializeMember(Indirect)
2940 : InitializedEntity::InitializeMember(Field);
2941 InitializationKind InitKind =
2942 InitializationKind::CreateDefault(Loc);
2943
2944 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2945 ExprResult MemberInit =
2946 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2947
2948 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2949 if (MemberInit.isInvalid())
2950 return true;
2951
2952 if (Indirect)
2953 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2954 Indirect, Loc,
2955 Loc,
2956 MemberInit.get(),
2957 Loc);
2958 else
2959 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2960 Field, Loc, Loc,
2961 MemberInit.get(),
2962 Loc);
2963 return false;
2964 }
2965
2966 if (!Field->getParent()->isUnion()) {
2967 if (FieldBaseElementType->isReferenceType()) {
2968 SemaRef.Diag(Constructor->getLocation(),
2969 diag::err_uninitialized_member_in_ctor)
2970 << (int)Constructor->isImplicit()
2971 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2972 << 0 << Field->getDeclName();
2973 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2974 return true;
2975 }
2976
2977 if (FieldBaseElementType.isConstQualified()) {
2978 SemaRef.Diag(Constructor->getLocation(),
2979 diag::err_uninitialized_member_in_ctor)
2980 << (int)Constructor->isImplicit()
2981 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2982 << 1 << Field->getDeclName();
2983 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2984 return true;
2985 }
2986 }
2987
2988 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2989 FieldBaseElementType->isObjCRetainableType() &&
2990 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2991 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2992 // ARC:
2993 // Default-initialize Objective-C pointers to NULL.
2994 CXXMemberInit
2995 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2996 Loc, Loc,
2997 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2998 Loc);
2999 return false;
3000 }
3001
3002 // Nothing to initialize.
3003 CXXMemberInit = 0;
3004 return false;
3005 }
3006
3007 namespace {
3008 struct BaseAndFieldInfo {
3009 Sema &S;
3010 CXXConstructorDecl *Ctor;
3011 bool AnyErrorsInInits;
3012 ImplicitInitializerKind IIK;
3013 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3014 SmallVector<CXXCtorInitializer*, 8> AllToInit;
3015
BaseAndFieldInfo__anon53c188c80411::BaseAndFieldInfo3016 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3017 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3018 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3019 if (Generated && Ctor->isCopyConstructor())
3020 IIK = IIK_Copy;
3021 else if (Generated && Ctor->isMoveConstructor())
3022 IIK = IIK_Move;
3023 else if (Ctor->getInheritedConstructor())
3024 IIK = IIK_Inherit;
3025 else
3026 IIK = IIK_Default;
3027 }
3028
isImplicitCopyOrMove__anon53c188c80411::BaseAndFieldInfo3029 bool isImplicitCopyOrMove() const {
3030 switch (IIK) {
3031 case IIK_Copy:
3032 case IIK_Move:
3033 return true;
3034
3035 case IIK_Default:
3036 case IIK_Inherit:
3037 return false;
3038 }
3039
3040 llvm_unreachable("Invalid ImplicitInitializerKind!");
3041 }
3042
addFieldInitializer__anon53c188c80411::BaseAndFieldInfo3043 bool addFieldInitializer(CXXCtorInitializer *Init) {
3044 AllToInit.push_back(Init);
3045
3046 // Check whether this initializer makes the field "used".
3047 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3048 S.UnusedPrivateFields.remove(Init->getAnyMember());
3049
3050 return false;
3051 }
3052 };
3053 }
3054
3055 /// \brief Determine whether the given indirect field declaration is somewhere
3056 /// within an anonymous union.
isWithinAnonymousUnion(IndirectFieldDecl * F)3057 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3058 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3059 CEnd = F->chain_end();
3060 C != CEnd; ++C)
3061 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3062 if (Record->isUnion())
3063 return true;
3064
3065 return false;
3066 }
3067
3068 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3069 /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)3070 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3071 if (T->isIncompleteArrayType())
3072 return true;
3073
3074 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3075 if (!ArrayT->getSize())
3076 return true;
3077
3078 T = ArrayT->getElementType();
3079 }
3080
3081 return false;
3082 }
3083
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=0)3084 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3085 FieldDecl *Field,
3086 IndirectFieldDecl *Indirect = 0) {
3087
3088 // Overwhelmingly common case: we have a direct initializer for this field.
3089 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3090 return Info.addFieldInitializer(Init);
3091
3092 // C++11 [class.base.init]p8: if the entity is a non-static data member that
3093 // has a brace-or-equal-initializer, the entity is initialized as specified
3094 // in [dcl.init].
3095 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3096 CXXCtorInitializer *Init;
3097 if (Indirect)
3098 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3099 SourceLocation(),
3100 SourceLocation(), 0,
3101 SourceLocation());
3102 else
3103 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3104 SourceLocation(),
3105 SourceLocation(), 0,
3106 SourceLocation());
3107 return Info.addFieldInitializer(Init);
3108 }
3109
3110 // Don't build an implicit initializer for union members if none was
3111 // explicitly specified.
3112 if (Field->getParent()->isUnion() ||
3113 (Indirect && isWithinAnonymousUnion(Indirect)))
3114 return false;
3115
3116 // Don't initialize incomplete or zero-length arrays.
3117 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3118 return false;
3119
3120 // Don't try to build an implicit initializer if there were semantic
3121 // errors in any of the initializers (and therefore we might be
3122 // missing some that the user actually wrote).
3123 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3124 return false;
3125
3126 CXXCtorInitializer *Init = 0;
3127 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3128 Indirect, Init))
3129 return true;
3130
3131 if (!Init)
3132 return false;
3133
3134 return Info.addFieldInitializer(Init);
3135 }
3136
3137 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)3138 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3139 CXXCtorInitializer *Initializer) {
3140 assert(Initializer->isDelegatingInitializer());
3141 Constructor->setNumCtorInitializers(1);
3142 CXXCtorInitializer **initializer =
3143 new (Context) CXXCtorInitializer*[1];
3144 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3145 Constructor->setCtorInitializers(initializer);
3146
3147 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3148 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3149 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3150 }
3151
3152 DelegatingCtorDecls.push_back(Constructor);
3153
3154 return false;
3155 }
3156
SetCtorInitializers(CXXConstructorDecl * Constructor,bool AnyErrors,ArrayRef<CXXCtorInitializer * > Initializers)3157 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3158 ArrayRef<CXXCtorInitializer *> Initializers) {
3159 if (Constructor->isDependentContext()) {
3160 // Just store the initializers as written, they will be checked during
3161 // instantiation.
3162 if (!Initializers.empty()) {
3163 Constructor->setNumCtorInitializers(Initializers.size());
3164 CXXCtorInitializer **baseOrMemberInitializers =
3165 new (Context) CXXCtorInitializer*[Initializers.size()];
3166 memcpy(baseOrMemberInitializers, Initializers.data(),
3167 Initializers.size() * sizeof(CXXCtorInitializer*));
3168 Constructor->setCtorInitializers(baseOrMemberInitializers);
3169 }
3170
3171 // Let template instantiation know whether we had errors.
3172 if (AnyErrors)
3173 Constructor->setInvalidDecl();
3174
3175 return false;
3176 }
3177
3178 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3179
3180 // We need to build the initializer AST according to order of construction
3181 // and not what user specified in the Initializers list.
3182 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3183 if (!ClassDecl)
3184 return true;
3185
3186 bool HadError = false;
3187
3188 for (unsigned i = 0; i < Initializers.size(); i++) {
3189 CXXCtorInitializer *Member = Initializers[i];
3190
3191 if (Member->isBaseInitializer())
3192 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3193 else
3194 Info.AllBaseFields[Member->getAnyMember()] = Member;
3195 }
3196
3197 // Keep track of the direct virtual bases.
3198 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3199 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3200 E = ClassDecl->bases_end(); I != E; ++I) {
3201 if (I->isVirtual())
3202 DirectVBases.insert(I);
3203 }
3204
3205 // Push virtual bases before others.
3206 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3207 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3208
3209 if (CXXCtorInitializer *Value
3210 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3211 Info.AllToInit.push_back(Value);
3212 } else if (!AnyErrors) {
3213 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3214 CXXCtorInitializer *CXXBaseInit;
3215 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3216 VBase, IsInheritedVirtualBase,
3217 CXXBaseInit)) {
3218 HadError = true;
3219 continue;
3220 }
3221
3222 Info.AllToInit.push_back(CXXBaseInit);
3223 }
3224 }
3225
3226 // Non-virtual bases.
3227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3228 E = ClassDecl->bases_end(); Base != E; ++Base) {
3229 // Virtuals are in the virtual base list and already constructed.
3230 if (Base->isVirtual())
3231 continue;
3232
3233 if (CXXCtorInitializer *Value
3234 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3235 Info.AllToInit.push_back(Value);
3236 } else if (!AnyErrors) {
3237 CXXCtorInitializer *CXXBaseInit;
3238 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3239 Base, /*IsInheritedVirtualBase=*/false,
3240 CXXBaseInit)) {
3241 HadError = true;
3242 continue;
3243 }
3244
3245 Info.AllToInit.push_back(CXXBaseInit);
3246 }
3247 }
3248
3249 // Fields.
3250 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3251 MemEnd = ClassDecl->decls_end();
3252 Mem != MemEnd; ++Mem) {
3253 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3254 // C++ [class.bit]p2:
3255 // A declaration for a bit-field that omits the identifier declares an
3256 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3257 // initialized.
3258 if (F->isUnnamedBitfield())
3259 continue;
3260
3261 // If we're not generating the implicit copy/move constructor, then we'll
3262 // handle anonymous struct/union fields based on their individual
3263 // indirect fields.
3264 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3265 continue;
3266
3267 if (CollectFieldInitializer(*this, Info, F))
3268 HadError = true;
3269 continue;
3270 }
3271
3272 // Beyond this point, we only consider default initialization.
3273 if (Info.isImplicitCopyOrMove())
3274 continue;
3275
3276 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3277 if (F->getType()->isIncompleteArrayType()) {
3278 assert(ClassDecl->hasFlexibleArrayMember() &&
3279 "Incomplete array type is not valid");
3280 continue;
3281 }
3282
3283 // Initialize each field of an anonymous struct individually.
3284 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3285 HadError = true;
3286
3287 continue;
3288 }
3289 }
3290
3291 unsigned NumInitializers = Info.AllToInit.size();
3292 if (NumInitializers > 0) {
3293 Constructor->setNumCtorInitializers(NumInitializers);
3294 CXXCtorInitializer **baseOrMemberInitializers =
3295 new (Context) CXXCtorInitializer*[NumInitializers];
3296 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3297 NumInitializers * sizeof(CXXCtorInitializer*));
3298 Constructor->setCtorInitializers(baseOrMemberInitializers);
3299
3300 // Constructors implicitly reference the base and member
3301 // destructors.
3302 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3303 Constructor->getParent());
3304 }
3305
3306 return HadError;
3307 }
3308
PopulateKeysForFields(FieldDecl * Field,SmallVectorImpl<const void * > & IdealInits)3309 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3310 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3311 const RecordDecl *RD = RT->getDecl();
3312 if (RD->isAnonymousStructOrUnion()) {
3313 for (RecordDecl::field_iterator Field = RD->field_begin(),
3314 E = RD->field_end(); Field != E; ++Field)
3315 PopulateKeysForFields(*Field, IdealInits);
3316 return;
3317 }
3318 }
3319 IdealInits.push_back(Field);
3320 }
3321
GetKeyForBase(ASTContext & Context,QualType BaseType)3322 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3323 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3324 }
3325
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)3326 static void *GetKeyForMember(ASTContext &Context,
3327 CXXCtorInitializer *Member) {
3328 if (!Member->isAnyMemberInitializer())
3329 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3330
3331 return Member->getAnyMember();
3332 }
3333
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,ArrayRef<CXXCtorInitializer * > Inits)3334 static void DiagnoseBaseOrMemInitializerOrder(
3335 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3336 ArrayRef<CXXCtorInitializer *> Inits) {
3337 if (Constructor->getDeclContext()->isDependentContext())
3338 return;
3339
3340 // Don't check initializers order unless the warning is enabled at the
3341 // location of at least one initializer.
3342 bool ShouldCheckOrder = false;
3343 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3344 CXXCtorInitializer *Init = Inits[InitIndex];
3345 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3346 Init->getSourceLocation())
3347 != DiagnosticsEngine::Ignored) {
3348 ShouldCheckOrder = true;
3349 break;
3350 }
3351 }
3352 if (!ShouldCheckOrder)
3353 return;
3354
3355 // Build the list of bases and members in the order that they'll
3356 // actually be initialized. The explicit initializers should be in
3357 // this same order but may be missing things.
3358 SmallVector<const void*, 32> IdealInitKeys;
3359
3360 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3361
3362 // 1. Virtual bases.
3363 for (CXXRecordDecl::base_class_const_iterator VBase =
3364 ClassDecl->vbases_begin(),
3365 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3366 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3367
3368 // 2. Non-virtual bases.
3369 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3370 E = ClassDecl->bases_end(); Base != E; ++Base) {
3371 if (Base->isVirtual())
3372 continue;
3373 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3374 }
3375
3376 // 3. Direct fields.
3377 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3378 E = ClassDecl->field_end(); Field != E; ++Field) {
3379 if (Field->isUnnamedBitfield())
3380 continue;
3381
3382 PopulateKeysForFields(*Field, IdealInitKeys);
3383 }
3384
3385 unsigned NumIdealInits = IdealInitKeys.size();
3386 unsigned IdealIndex = 0;
3387
3388 CXXCtorInitializer *PrevInit = 0;
3389 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3390 CXXCtorInitializer *Init = Inits[InitIndex];
3391 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3392
3393 // Scan forward to try to find this initializer in the idealized
3394 // initializers list.
3395 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3396 if (InitKey == IdealInitKeys[IdealIndex])
3397 break;
3398
3399 // If we didn't find this initializer, it must be because we
3400 // scanned past it on a previous iteration. That can only
3401 // happen if we're out of order; emit a warning.
3402 if (IdealIndex == NumIdealInits && PrevInit) {
3403 Sema::SemaDiagnosticBuilder D =
3404 SemaRef.Diag(PrevInit->getSourceLocation(),
3405 diag::warn_initializer_out_of_order);
3406
3407 if (PrevInit->isAnyMemberInitializer())
3408 D << 0 << PrevInit->getAnyMember()->getDeclName();
3409 else
3410 D << 1 << PrevInit->getTypeSourceInfo()->getType();
3411
3412 if (Init->isAnyMemberInitializer())
3413 D << 0 << Init->getAnyMember()->getDeclName();
3414 else
3415 D << 1 << Init->getTypeSourceInfo()->getType();
3416
3417 // Move back to the initializer's location in the ideal list.
3418 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3419 if (InitKey == IdealInitKeys[IdealIndex])
3420 break;
3421
3422 assert(IdealIndex != NumIdealInits &&
3423 "initializer not found in initializer list");
3424 }
3425
3426 PrevInit = Init;
3427 }
3428 }
3429
3430 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)3431 bool CheckRedundantInit(Sema &S,
3432 CXXCtorInitializer *Init,
3433 CXXCtorInitializer *&PrevInit) {
3434 if (!PrevInit) {
3435 PrevInit = Init;
3436 return false;
3437 }
3438
3439 if (FieldDecl *Field = Init->getMember())
3440 S.Diag(Init->getSourceLocation(),
3441 diag::err_multiple_mem_initialization)
3442 << Field->getDeclName()
3443 << Init->getSourceRange();
3444 else {
3445 const Type *BaseClass = Init->getBaseClass();
3446 assert(BaseClass && "neither field nor base");
3447 S.Diag(Init->getSourceLocation(),
3448 diag::err_multiple_base_initialization)
3449 << QualType(BaseClass, 0)
3450 << Init->getSourceRange();
3451 }
3452 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3453 << 0 << PrevInit->getSourceRange();
3454
3455 return true;
3456 }
3457
3458 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3459 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3460
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)3461 bool CheckRedundantUnionInit(Sema &S,
3462 CXXCtorInitializer *Init,
3463 RedundantUnionMap &Unions) {
3464 FieldDecl *Field = Init->getAnyMember();
3465 RecordDecl *Parent = Field->getParent();
3466 NamedDecl *Child = Field;
3467
3468 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3469 if (Parent->isUnion()) {
3470 UnionEntry &En = Unions[Parent];
3471 if (En.first && En.first != Child) {
3472 S.Diag(Init->getSourceLocation(),
3473 diag::err_multiple_mem_union_initialization)
3474 << Field->getDeclName()
3475 << Init->getSourceRange();
3476 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3477 << 0 << En.second->getSourceRange();
3478 return true;
3479 }
3480 if (!En.first) {
3481 En.first = Child;
3482 En.second = Init;
3483 }
3484 if (!Parent->isAnonymousStructOrUnion())
3485 return false;
3486 }
3487
3488 Child = Parent;
3489 Parent = cast<RecordDecl>(Parent->getDeclContext());
3490 }
3491
3492 return false;
3493 }
3494 }
3495
3496 /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,ArrayRef<CXXCtorInitializer * > MemInits,bool AnyErrors)3497 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3498 SourceLocation ColonLoc,
3499 ArrayRef<CXXCtorInitializer*> MemInits,
3500 bool AnyErrors) {
3501 if (!ConstructorDecl)
3502 return;
3503
3504 AdjustDeclIfTemplate(ConstructorDecl);
3505
3506 CXXConstructorDecl *Constructor
3507 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3508
3509 if (!Constructor) {
3510 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3511 return;
3512 }
3513
3514 // Mapping for the duplicate initializers check.
3515 // For member initializers, this is keyed with a FieldDecl*.
3516 // For base initializers, this is keyed with a Type*.
3517 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3518
3519 // Mapping for the inconsistent anonymous-union initializers check.
3520 RedundantUnionMap MemberUnions;
3521
3522 bool HadError = false;
3523 for (unsigned i = 0; i < MemInits.size(); i++) {
3524 CXXCtorInitializer *Init = MemInits[i];
3525
3526 // Set the source order index.
3527 Init->setSourceOrder(i);
3528
3529 if (Init->isAnyMemberInitializer()) {
3530 FieldDecl *Field = Init->getAnyMember();
3531 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3532 CheckRedundantUnionInit(*this, Init, MemberUnions))
3533 HadError = true;
3534 } else if (Init->isBaseInitializer()) {
3535 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3536 if (CheckRedundantInit(*this, Init, Members[Key]))
3537 HadError = true;
3538 } else {
3539 assert(Init->isDelegatingInitializer());
3540 // This must be the only initializer
3541 if (MemInits.size() != 1) {
3542 Diag(Init->getSourceLocation(),
3543 diag::err_delegating_initializer_alone)
3544 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3545 // We will treat this as being the only initializer.
3546 }
3547 SetDelegatingInitializer(Constructor, MemInits[i]);
3548 // Return immediately as the initializer is set.
3549 return;
3550 }
3551 }
3552
3553 if (HadError)
3554 return;
3555
3556 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3557
3558 SetCtorInitializers(Constructor, AnyErrors, MemInits);
3559 }
3560
3561 void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)3562 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3563 CXXRecordDecl *ClassDecl) {
3564 // Ignore dependent contexts. Also ignore unions, since their members never
3565 // have destructors implicitly called.
3566 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3567 return;
3568
3569 // FIXME: all the access-control diagnostics are positioned on the
3570 // field/base declaration. That's probably good; that said, the
3571 // user might reasonably want to know why the destructor is being
3572 // emitted, and we currently don't say.
3573
3574 // Non-static data members.
3575 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3576 E = ClassDecl->field_end(); I != E; ++I) {
3577 FieldDecl *Field = *I;
3578 if (Field->isInvalidDecl())
3579 continue;
3580
3581 // Don't destroy incomplete or zero-length arrays.
3582 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3583 continue;
3584
3585 QualType FieldType = Context.getBaseElementType(Field->getType());
3586
3587 const RecordType* RT = FieldType->getAs<RecordType>();
3588 if (!RT)
3589 continue;
3590
3591 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3592 if (FieldClassDecl->isInvalidDecl())
3593 continue;
3594 if (FieldClassDecl->hasIrrelevantDestructor())
3595 continue;
3596 // The destructor for an implicit anonymous union member is never invoked.
3597 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3598 continue;
3599
3600 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3601 assert(Dtor && "No dtor found for FieldClassDecl!");
3602 CheckDestructorAccess(Field->getLocation(), Dtor,
3603 PDiag(diag::err_access_dtor_field)
3604 << Field->getDeclName()
3605 << FieldType);
3606
3607 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3608 DiagnoseUseOfDecl(Dtor, Location);
3609 }
3610
3611 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3612
3613 // Bases.
3614 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3615 E = ClassDecl->bases_end(); Base != E; ++Base) {
3616 // Bases are always records in a well-formed non-dependent class.
3617 const RecordType *RT = Base->getType()->getAs<RecordType>();
3618
3619 // Remember direct virtual bases.
3620 if (Base->isVirtual())
3621 DirectVirtualBases.insert(RT);
3622
3623 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3624 // If our base class is invalid, we probably can't get its dtor anyway.
3625 if (BaseClassDecl->isInvalidDecl())
3626 continue;
3627 if (BaseClassDecl->hasIrrelevantDestructor())
3628 continue;
3629
3630 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3631 assert(Dtor && "No dtor found for BaseClassDecl!");
3632
3633 // FIXME: caret should be on the start of the class name
3634 CheckDestructorAccess(Base->getLocStart(), Dtor,
3635 PDiag(diag::err_access_dtor_base)
3636 << Base->getType()
3637 << Base->getSourceRange(),
3638 Context.getTypeDeclType(ClassDecl));
3639
3640 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3641 DiagnoseUseOfDecl(Dtor, Location);
3642 }
3643
3644 // Virtual bases.
3645 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3646 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3647
3648 // Bases are always records in a well-formed non-dependent class.
3649 const RecordType *RT = VBase->getType()->castAs<RecordType>();
3650
3651 // Ignore direct virtual bases.
3652 if (DirectVirtualBases.count(RT))
3653 continue;
3654
3655 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3656 // If our base class is invalid, we probably can't get its dtor anyway.
3657 if (BaseClassDecl->isInvalidDecl())
3658 continue;
3659 if (BaseClassDecl->hasIrrelevantDestructor())
3660 continue;
3661
3662 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3663 assert(Dtor && "No dtor found for BaseClassDecl!");
3664 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3665 PDiag(diag::err_access_dtor_vbase)
3666 << VBase->getType(),
3667 Context.getTypeDeclType(ClassDecl));
3668
3669 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3670 DiagnoseUseOfDecl(Dtor, Location);
3671 }
3672 }
3673
ActOnDefaultCtorInitializers(Decl * CDtorDecl)3674 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3675 if (!CDtorDecl)
3676 return;
3677
3678 if (CXXConstructorDecl *Constructor
3679 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3680 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3681 }
3682
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,AbstractDiagSelID SelID)3683 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3684 unsigned DiagID, AbstractDiagSelID SelID) {
3685 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3686 unsigned DiagID;
3687 AbstractDiagSelID SelID;
3688
3689 public:
3690 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3691 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3692
3693 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3694 if (Suppressed) return;
3695 if (SelID == -1)
3696 S.Diag(Loc, DiagID) << T;
3697 else
3698 S.Diag(Loc, DiagID) << SelID << T;
3699 }
3700 } Diagnoser(DiagID, SelID);
3701
3702 return RequireNonAbstractType(Loc, T, Diagnoser);
3703 }
3704
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)3705 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3706 TypeDiagnoser &Diagnoser) {
3707 if (!getLangOpts().CPlusPlus)
3708 return false;
3709
3710 if (const ArrayType *AT = Context.getAsArrayType(T))
3711 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3712
3713 if (const PointerType *PT = T->getAs<PointerType>()) {
3714 // Find the innermost pointer type.
3715 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3716 PT = T;
3717
3718 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3719 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3720 }
3721
3722 const RecordType *RT = T->getAs<RecordType>();
3723 if (!RT)
3724 return false;
3725
3726 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3727
3728 // We can't answer whether something is abstract until it has a
3729 // definition. If it's currently being defined, we'll walk back
3730 // over all the declarations when we have a full definition.
3731 const CXXRecordDecl *Def = RD->getDefinition();
3732 if (!Def || Def->isBeingDefined())
3733 return false;
3734
3735 if (!RD->isAbstract())
3736 return false;
3737
3738 Diagnoser.diagnose(*this, Loc, T);
3739 DiagnoseAbstractType(RD);
3740
3741 return true;
3742 }
3743
DiagnoseAbstractType(const CXXRecordDecl * RD)3744 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3745 // Check if we've already emitted the list of pure virtual functions
3746 // for this class.
3747 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3748 return;
3749
3750 CXXFinalOverriderMap FinalOverriders;
3751 RD->getFinalOverriders(FinalOverriders);
3752
3753 // Keep a set of seen pure methods so we won't diagnose the same method
3754 // more than once.
3755 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3756
3757 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3758 MEnd = FinalOverriders.end();
3759 M != MEnd;
3760 ++M) {
3761 for (OverridingMethods::iterator SO = M->second.begin(),
3762 SOEnd = M->second.end();
3763 SO != SOEnd; ++SO) {
3764 // C++ [class.abstract]p4:
3765 // A class is abstract if it contains or inherits at least one
3766 // pure virtual function for which the final overrider is pure
3767 // virtual.
3768
3769 //
3770 if (SO->second.size() != 1)
3771 continue;
3772
3773 if (!SO->second.front().Method->isPure())
3774 continue;
3775
3776 if (!SeenPureMethods.insert(SO->second.front().Method))
3777 continue;
3778
3779 Diag(SO->second.front().Method->getLocation(),
3780 diag::note_pure_virtual_function)
3781 << SO->second.front().Method->getDeclName() << RD->getDeclName();
3782 }
3783 }
3784
3785 if (!PureVirtualClassDiagSet)
3786 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3787 PureVirtualClassDiagSet->insert(RD);
3788 }
3789
3790 namespace {
3791 struct AbstractUsageInfo {
3792 Sema &S;
3793 CXXRecordDecl *Record;
3794 CanQualType AbstractType;
3795 bool Invalid;
3796
AbstractUsageInfo__anon53c188c80611::AbstractUsageInfo3797 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3798 : S(S), Record(Record),
3799 AbstractType(S.Context.getCanonicalType(
3800 S.Context.getTypeDeclType(Record))),
3801 Invalid(false) {}
3802
DiagnoseAbstractType__anon53c188c80611::AbstractUsageInfo3803 void DiagnoseAbstractType() {
3804 if (Invalid) return;
3805 S.DiagnoseAbstractType(Record);
3806 Invalid = true;
3807 }
3808
3809 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3810 };
3811
3812 struct CheckAbstractUsage {
3813 AbstractUsageInfo &Info;
3814 const NamedDecl *Ctx;
3815
CheckAbstractUsage__anon53c188c80611::CheckAbstractUsage3816 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3817 : Info(Info), Ctx(Ctx) {}
3818
Visit__anon53c188c80611::CheckAbstractUsage3819 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3820 switch (TL.getTypeLocClass()) {
3821 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3822 #define TYPELOC(CLASS, PARENT) \
3823 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3824 #include "clang/AST/TypeLocNodes.def"
3825 }
3826 }
3827
Check__anon53c188c80611::CheckAbstractUsage3828 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3829 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3830 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3831 if (!TL.getArg(I))
3832 continue;
3833
3834 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3835 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3836 }
3837 }
3838
Check__anon53c188c80611::CheckAbstractUsage3839 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3840 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3841 }
3842
Check__anon53c188c80611::CheckAbstractUsage3843 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3844 // Visit the type parameters from a permissive context.
3845 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3846 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3847 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3848 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3849 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3850 // TODO: other template argument types?
3851 }
3852 }
3853
3854 // Visit pointee types from a permissive context.
3855 #define CheckPolymorphic(Type) \
3856 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3857 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3858 }
3859 CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon53c188c80611::CheckAbstractUsage3860 CheckPolymorphic(ReferenceTypeLoc)
3861 CheckPolymorphic(MemberPointerTypeLoc)
3862 CheckPolymorphic(BlockPointerTypeLoc)
3863 CheckPolymorphic(AtomicTypeLoc)
3864
3865 /// Handle all the types we haven't given a more specific
3866 /// implementation for above.
3867 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3868 // Every other kind of type that we haven't called out already
3869 // that has an inner type is either (1) sugar or (2) contains that
3870 // inner type in some way as a subobject.
3871 if (TypeLoc Next = TL.getNextTypeLoc())
3872 return Visit(Next, Sel);
3873
3874 // If there's no inner type and we're in a permissive context,
3875 // don't diagnose.
3876 if (Sel == Sema::AbstractNone) return;
3877
3878 // Check whether the type matches the abstract type.
3879 QualType T = TL.getType();
3880 if (T->isArrayType()) {
3881 Sel = Sema::AbstractArrayType;
3882 T = Info.S.Context.getBaseElementType(T);
3883 }
3884 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3885 if (CT != Info.AbstractType) return;
3886
3887 // It matched; do some magic.
3888 if (Sel == Sema::AbstractArrayType) {
3889 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3890 << T << TL.getSourceRange();
3891 } else {
3892 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3893 << Sel << T << TL.getSourceRange();
3894 }
3895 Info.DiagnoseAbstractType();
3896 }
3897 };
3898
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)3899 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3900 Sema::AbstractDiagSelID Sel) {
3901 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3902 }
3903
3904 }
3905
3906 /// Check for invalid uses of an abstract type in a method declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXMethodDecl * MD)3907 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3908 CXXMethodDecl *MD) {
3909 // No need to do the check on definitions, which require that
3910 // the return/param types be complete.
3911 if (MD->doesThisDeclarationHaveABody())
3912 return;
3913
3914 // For safety's sake, just ignore it if we don't have type source
3915 // information. This should never happen for non-implicit methods,
3916 // but...
3917 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3918 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3919 }
3920
3921 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)3922 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3923 CXXRecordDecl *RD) {
3924 for (CXXRecordDecl::decl_iterator
3925 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3926 Decl *D = *I;
3927 if (D->isImplicit()) continue;
3928
3929 // Methods and method templates.
3930 if (isa<CXXMethodDecl>(D)) {
3931 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3932 } else if (isa<FunctionTemplateDecl>(D)) {
3933 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3934 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3935
3936 // Fields and static variables.
3937 } else if (isa<FieldDecl>(D)) {
3938 FieldDecl *FD = cast<FieldDecl>(D);
3939 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3940 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3941 } else if (isa<VarDecl>(D)) {
3942 VarDecl *VD = cast<VarDecl>(D);
3943 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3944 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3945
3946 // Nested classes and class templates.
3947 } else if (isa<CXXRecordDecl>(D)) {
3948 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3949 } else if (isa<ClassTemplateDecl>(D)) {
3950 CheckAbstractClassUsage(Info,
3951 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3952 }
3953 }
3954 }
3955
3956 /// \brief Perform semantic checks on a class definition that has been
3957 /// completing, introducing implicitly-declared members, checking for
3958 /// abstract types, etc.
CheckCompletedCXXClass(CXXRecordDecl * Record)3959 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3960 if (!Record)
3961 return;
3962
3963 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3964 AbstractUsageInfo Info(*this, Record);
3965 CheckAbstractClassUsage(Info, Record);
3966 }
3967
3968 // If this is not an aggregate type and has no user-declared constructor,
3969 // complain about any non-static data members of reference or const scalar
3970 // type, since they will never get initializers.
3971 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3972 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3973 !Record->isLambda()) {
3974 bool Complained = false;
3975 for (RecordDecl::field_iterator F = Record->field_begin(),
3976 FEnd = Record->field_end();
3977 F != FEnd; ++F) {
3978 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3979 continue;
3980
3981 if (F->getType()->isReferenceType() ||
3982 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3983 if (!Complained) {
3984 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3985 << Record->getTagKind() << Record;
3986 Complained = true;
3987 }
3988
3989 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3990 << F->getType()->isReferenceType()
3991 << F->getDeclName();
3992 }
3993 }
3994 }
3995
3996 if (Record->isDynamicClass() && !Record->isDependentType())
3997 DynamicClasses.push_back(Record);
3998
3999 if (Record->getIdentifier()) {
4000 // C++ [class.mem]p13:
4001 // If T is the name of a class, then each of the following shall have a
4002 // name different from T:
4003 // - every member of every anonymous union that is a member of class T.
4004 //
4005 // C++ [class.mem]p14:
4006 // In addition, if class T has a user-declared constructor (12.1), every
4007 // non-static data member of class T shall have a name different from T.
4008 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4009 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4010 ++I) {
4011 NamedDecl *D = *I;
4012 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4013 isa<IndirectFieldDecl>(D)) {
4014 Diag(D->getLocation(), diag::err_member_name_of_class)
4015 << D->getDeclName();
4016 break;
4017 }
4018 }
4019 }
4020
4021 // Warn if the class has virtual methods but non-virtual public destructor.
4022 if (Record->isPolymorphic() && !Record->isDependentType()) {
4023 CXXDestructorDecl *dtor = Record->getDestructor();
4024 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4025 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4026 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4027 }
4028
4029 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4030 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4031 DiagnoseAbstractType(Record);
4032 }
4033
4034 if (!Record->isDependentType()) {
4035 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4036 MEnd = Record->method_end();
4037 M != MEnd; ++M) {
4038 // See if a method overloads virtual methods in a base
4039 // class without overriding any.
4040 if (!M->isStatic())
4041 DiagnoseHiddenVirtualMethods(Record, *M);
4042
4043 // Check whether the explicitly-defaulted special members are valid.
4044 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4045 CheckExplicitlyDefaultedSpecialMember(*M);
4046
4047 // For an explicitly defaulted or deleted special member, we defer
4048 // determining triviality until the class is complete. That time is now!
4049 if (!M->isImplicit() && !M->isUserProvided()) {
4050 CXXSpecialMember CSM = getSpecialMember(*M);
4051 if (CSM != CXXInvalid) {
4052 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4053
4054 // Inform the class that we've finished declaring this member.
4055 Record->finishedDefaultedOrDeletedMember(*M);
4056 }
4057 }
4058 }
4059 }
4060
4061 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4062 // function that is not a constructor declares that member function to be
4063 // const. [...] The class of which that function is a member shall be
4064 // a literal type.
4065 //
4066 // If the class has virtual bases, any constexpr members will already have
4067 // been diagnosed by the checks performed on the member declaration, so
4068 // suppress this (less useful) diagnostic.
4069 //
4070 // We delay this until we know whether an explicitly-defaulted (or deleted)
4071 // destructor for the class is trivial.
4072 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4073 !Record->isLiteral() && !Record->getNumVBases()) {
4074 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4075 MEnd = Record->method_end();
4076 M != MEnd; ++M) {
4077 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4078 switch (Record->getTemplateSpecializationKind()) {
4079 case TSK_ImplicitInstantiation:
4080 case TSK_ExplicitInstantiationDeclaration:
4081 case TSK_ExplicitInstantiationDefinition:
4082 // If a template instantiates to a non-literal type, but its members
4083 // instantiate to constexpr functions, the template is technically
4084 // ill-formed, but we allow it for sanity.
4085 continue;
4086
4087 case TSK_Undeclared:
4088 case TSK_ExplicitSpecialization:
4089 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4090 diag::err_constexpr_method_non_literal);
4091 break;
4092 }
4093
4094 // Only produce one error per class.
4095 break;
4096 }
4097 }
4098 }
4099
4100 // Declare inheriting constructors. We do this eagerly here because:
4101 // - The standard requires an eager diagnostic for conflicting inheriting
4102 // constructors from different classes.
4103 // - The lazy declaration of the other implicit constructors is so as to not
4104 // waste space and performance on classes that are not meant to be
4105 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4106 // have inheriting constructors.
4107 DeclareInheritingConstructors(Record);
4108 }
4109
4110 /// Is the special member function which would be selected to perform the
4111 /// specified operation on the specified class type a constexpr constructor?
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg)4112 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4113 Sema::CXXSpecialMember CSM,
4114 bool ConstArg) {
4115 Sema::SpecialMemberOverloadResult *SMOR =
4116 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4117 false, false, false, false);
4118 if (!SMOR || !SMOR->getMethod())
4119 // A constructor we wouldn't select can't be "involved in initializing"
4120 // anything.
4121 return true;
4122 return SMOR->getMethod()->isConstexpr();
4123 }
4124
4125 /// Determine whether the specified special member function would be constexpr
4126 /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg)4127 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4128 Sema::CXXSpecialMember CSM,
4129 bool ConstArg) {
4130 if (!S.getLangOpts().CPlusPlus11)
4131 return false;
4132
4133 // C++11 [dcl.constexpr]p4:
4134 // In the definition of a constexpr constructor [...]
4135 switch (CSM) {
4136 case Sema::CXXDefaultConstructor:
4137 // Since default constructor lookup is essentially trivial (and cannot
4138 // involve, for instance, template instantiation), we compute whether a
4139 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4140 //
4141 // This is important for performance; we need to know whether the default
4142 // constructor is constexpr to determine whether the type is a literal type.
4143 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4144
4145 case Sema::CXXCopyConstructor:
4146 case Sema::CXXMoveConstructor:
4147 // For copy or move constructors, we need to perform overload resolution.
4148 break;
4149
4150 case Sema::CXXCopyAssignment:
4151 case Sema::CXXMoveAssignment:
4152 case Sema::CXXDestructor:
4153 case Sema::CXXInvalid:
4154 return false;
4155 }
4156
4157 // -- if the class is a non-empty union, or for each non-empty anonymous
4158 // union member of a non-union class, exactly one non-static data member
4159 // shall be initialized; [DR1359]
4160 //
4161 // If we squint, this is guaranteed, since exactly one non-static data member
4162 // will be initialized (if the constructor isn't deleted), we just don't know
4163 // which one.
4164 if (ClassDecl->isUnion())
4165 return true;
4166
4167 // -- the class shall not have any virtual base classes;
4168 if (ClassDecl->getNumVBases())
4169 return false;
4170
4171 // -- every constructor involved in initializing [...] base class
4172 // sub-objects shall be a constexpr constructor;
4173 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4174 BEnd = ClassDecl->bases_end();
4175 B != BEnd; ++B) {
4176 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4177 if (!BaseType) continue;
4178
4179 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4180 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4181 return false;
4182 }
4183
4184 // -- every constructor involved in initializing non-static data members
4185 // [...] shall be a constexpr constructor;
4186 // -- every non-static data member and base class sub-object shall be
4187 // initialized
4188 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4189 FEnd = ClassDecl->field_end();
4190 F != FEnd; ++F) {
4191 if (F->isInvalidDecl())
4192 continue;
4193 if (const RecordType *RecordTy =
4194 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4195 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4196 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4197 return false;
4198 }
4199 }
4200
4201 // All OK, it's constexpr!
4202 return true;
4203 }
4204
4205 static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD)4206 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4207 switch (S.getSpecialMember(MD)) {
4208 case Sema::CXXDefaultConstructor:
4209 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4210 case Sema::CXXCopyConstructor:
4211 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4212 case Sema::CXXCopyAssignment:
4213 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4214 case Sema::CXXMoveConstructor:
4215 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4216 case Sema::CXXMoveAssignment:
4217 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4218 case Sema::CXXDestructor:
4219 return S.ComputeDefaultedDtorExceptionSpec(MD);
4220 case Sema::CXXInvalid:
4221 break;
4222 }
4223 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4224 "only special members have implicit exception specs");
4225 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4226 }
4227
4228 static void
updateExceptionSpec(Sema & S,FunctionDecl * FD,const FunctionProtoType * FPT,const Sema::ImplicitExceptionSpecification & ExceptSpec)4229 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4230 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4231 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4232 ExceptSpec.getEPI(EPI);
4233 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4234 S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI));
4235 FD->setType(QualType(NewFPT, 0));
4236 }
4237
EvaluateImplicitExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)4238 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4239 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4240 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4241 return;
4242
4243 // Evaluate the exception specification.
4244 ImplicitExceptionSpecification ExceptSpec =
4245 computeImplicitExceptionSpec(*this, Loc, MD);
4246
4247 // Update the type of the special member to use it.
4248 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4249
4250 // A user-provided destructor can be defined outside the class. When that
4251 // happens, be sure to update the exception specification on both
4252 // declarations.
4253 const FunctionProtoType *CanonicalFPT =
4254 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4255 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4256 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4257 CanonicalFPT, ExceptSpec);
4258 }
4259
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD)4260 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4261 CXXRecordDecl *RD = MD->getParent();
4262 CXXSpecialMember CSM = getSpecialMember(MD);
4263
4264 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4265 "not an explicitly-defaulted special member");
4266
4267 // Whether this was the first-declared instance of the constructor.
4268 // This affects whether we implicitly add an exception spec and constexpr.
4269 bool First = MD == MD->getCanonicalDecl();
4270
4271 bool HadError = false;
4272
4273 // C++11 [dcl.fct.def.default]p1:
4274 // A function that is explicitly defaulted shall
4275 // -- be a special member function (checked elsewhere),
4276 // -- have the same type (except for ref-qualifiers, and except that a
4277 // copy operation can take a non-const reference) as an implicit
4278 // declaration, and
4279 // -- not have default arguments.
4280 unsigned ExpectedParams = 1;
4281 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4282 ExpectedParams = 0;
4283 if (MD->getNumParams() != ExpectedParams) {
4284 // This also checks for default arguments: a copy or move constructor with a
4285 // default argument is classified as a default constructor, and assignment
4286 // operations and destructors can't have default arguments.
4287 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4288 << CSM << MD->getSourceRange();
4289 HadError = true;
4290 } else if (MD->isVariadic()) {
4291 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4292 << CSM << MD->getSourceRange();
4293 HadError = true;
4294 }
4295
4296 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4297
4298 bool CanHaveConstParam = false;
4299 if (CSM == CXXCopyConstructor)
4300 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4301 else if (CSM == CXXCopyAssignment)
4302 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4303
4304 QualType ReturnType = Context.VoidTy;
4305 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4306 // Check for return type matching.
4307 ReturnType = Type->getResultType();
4308 QualType ExpectedReturnType =
4309 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4310 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4311 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4312 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4313 HadError = true;
4314 }
4315
4316 // A defaulted special member cannot have cv-qualifiers.
4317 if (Type->getTypeQuals()) {
4318 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4319 << (CSM == CXXMoveAssignment);
4320 HadError = true;
4321 }
4322 }
4323
4324 // Check for parameter type matching.
4325 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4326 bool HasConstParam = false;
4327 if (ExpectedParams && ArgType->isReferenceType()) {
4328 // Argument must be reference to possibly-const T.
4329 QualType ReferentType = ArgType->getPointeeType();
4330 HasConstParam = ReferentType.isConstQualified();
4331
4332 if (ReferentType.isVolatileQualified()) {
4333 Diag(MD->getLocation(),
4334 diag::err_defaulted_special_member_volatile_param) << CSM;
4335 HadError = true;
4336 }
4337
4338 if (HasConstParam && !CanHaveConstParam) {
4339 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4340 Diag(MD->getLocation(),
4341 diag::err_defaulted_special_member_copy_const_param)
4342 << (CSM == CXXCopyAssignment);
4343 // FIXME: Explain why this special member can't be const.
4344 } else {
4345 Diag(MD->getLocation(),
4346 diag::err_defaulted_special_member_move_const_param)
4347 << (CSM == CXXMoveAssignment);
4348 }
4349 HadError = true;
4350 }
4351 } else if (ExpectedParams) {
4352 // A copy assignment operator can take its argument by value, but a
4353 // defaulted one cannot.
4354 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4355 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4356 HadError = true;
4357 }
4358
4359 // C++11 [dcl.fct.def.default]p2:
4360 // An explicitly-defaulted function may be declared constexpr only if it
4361 // would have been implicitly declared as constexpr,
4362 // Do not apply this rule to members of class templates, since core issue 1358
4363 // makes such functions always instantiate to constexpr functions. For
4364 // non-constructors, this is checked elsewhere.
4365 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4366 HasConstParam);
4367 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4368 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4369 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4370 // FIXME: Explain why the constructor can't be constexpr.
4371 HadError = true;
4372 }
4373
4374 // and may have an explicit exception-specification only if it is compatible
4375 // with the exception-specification on the implicit declaration.
4376 if (Type->hasExceptionSpec()) {
4377 // Delay the check if this is the first declaration of the special member,
4378 // since we may not have parsed some necessary in-class initializers yet.
4379 if (First)
4380 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4381 else
4382 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4383 }
4384
4385 // If a function is explicitly defaulted on its first declaration,
4386 if (First) {
4387 // -- it is implicitly considered to be constexpr if the implicit
4388 // definition would be,
4389 MD->setConstexpr(Constexpr);
4390
4391 // -- it is implicitly considered to have the same exception-specification
4392 // as if it had been implicitly declared,
4393 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4394 EPI.ExceptionSpecType = EST_Unevaluated;
4395 EPI.ExceptionSpecDecl = MD;
4396 MD->setType(Context.getFunctionType(ReturnType,
4397 ArrayRef<QualType>(&ArgType,
4398 ExpectedParams),
4399 EPI));
4400 }
4401
4402 if (ShouldDeleteSpecialMember(MD, CSM)) {
4403 if (First) {
4404 MD->setDeletedAsWritten();
4405 } else {
4406 // C++11 [dcl.fct.def.default]p4:
4407 // [For a] user-provided explicitly-defaulted function [...] if such a
4408 // function is implicitly defined as deleted, the program is ill-formed.
4409 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4410 HadError = true;
4411 }
4412 }
4413
4414 if (HadError)
4415 MD->setInvalidDecl();
4416 }
4417
4418 /// Check whether the exception specification provided for an
4419 /// explicitly-defaulted special member matches the exception specification
4420 /// that would have been generated for an implicit special member, per
4421 /// C++11 [dcl.fct.def.default]p2.
CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl * MD,const FunctionProtoType * SpecifiedType)4422 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4423 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4424 // Compute the implicit exception specification.
4425 FunctionProtoType::ExtProtoInfo EPI;
4426 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4427 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4428 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
4429
4430 // Ensure that it matches.
4431 CheckEquivalentExceptionSpec(
4432 PDiag(diag::err_incorrect_defaulted_exception_spec)
4433 << getSpecialMember(MD), PDiag(),
4434 ImplicitType, SourceLocation(),
4435 SpecifiedType, MD->getLocation());
4436 }
4437
CheckDelayedExplicitlyDefaultedMemberExceptionSpecs()4438 void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4439 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4440 I != N; ++I)
4441 CheckExplicitlyDefaultedMemberExceptionSpec(
4442 DelayedDefaultedMemberExceptionSpecs[I].first,
4443 DelayedDefaultedMemberExceptionSpecs[I].second);
4444
4445 DelayedDefaultedMemberExceptionSpecs.clear();
4446 }
4447
4448 namespace {
4449 struct SpecialMemberDeletionInfo {
4450 Sema &S;
4451 CXXMethodDecl *MD;
4452 Sema::CXXSpecialMember CSM;
4453 bool Diagnose;
4454
4455 // Properties of the special member, computed for convenience.
4456 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4457 SourceLocation Loc;
4458
4459 bool AllFieldsAreConst;
4460
SpecialMemberDeletionInfo__anon53c188c80711::SpecialMemberDeletionInfo4461 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4462 Sema::CXXSpecialMember CSM, bool Diagnose)
4463 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4464 IsConstructor(false), IsAssignment(false), IsMove(false),
4465 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4466 AllFieldsAreConst(true) {
4467 switch (CSM) {
4468 case Sema::CXXDefaultConstructor:
4469 case Sema::CXXCopyConstructor:
4470 IsConstructor = true;
4471 break;
4472 case Sema::CXXMoveConstructor:
4473 IsConstructor = true;
4474 IsMove = true;
4475 break;
4476 case Sema::CXXCopyAssignment:
4477 IsAssignment = true;
4478 break;
4479 case Sema::CXXMoveAssignment:
4480 IsAssignment = true;
4481 IsMove = true;
4482 break;
4483 case Sema::CXXDestructor:
4484 break;
4485 case Sema::CXXInvalid:
4486 llvm_unreachable("invalid special member kind");
4487 }
4488
4489 if (MD->getNumParams()) {
4490 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4491 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4492 }
4493 }
4494
inUnion__anon53c188c80711::SpecialMemberDeletionInfo4495 bool inUnion() const { return MD->getParent()->isUnion(); }
4496
4497 /// Look up the corresponding special member in the given class.
lookupIn__anon53c188c80711::SpecialMemberDeletionInfo4498 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4499 unsigned Quals) {
4500 unsigned TQ = MD->getTypeQualifiers();
4501 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4502 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4503 Quals = 0;
4504 return S.LookupSpecialMember(Class, CSM,
4505 ConstArg || (Quals & Qualifiers::Const),
4506 VolatileArg || (Quals & Qualifiers::Volatile),
4507 MD->getRefQualifier() == RQ_RValue,
4508 TQ & Qualifiers::Const,
4509 TQ & Qualifiers::Volatile);
4510 }
4511
4512 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4513
4514 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4515 bool shouldDeleteForField(FieldDecl *FD);
4516 bool shouldDeleteForAllConstMembers();
4517
4518 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4519 unsigned Quals);
4520 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4521 Sema::SpecialMemberOverloadResult *SMOR,
4522 bool IsDtorCallInCtor);
4523
4524 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4525 };
4526 }
4527
4528 /// Is the given special member inaccessible when used on the given
4529 /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)4530 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4531 CXXMethodDecl *target) {
4532 /// If we're operating on a base class, the object type is the
4533 /// type of this special member.
4534 QualType objectTy;
4535 AccessSpecifier access = target->getAccess();
4536 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4537 objectTy = S.Context.getTypeDeclType(MD->getParent());
4538 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4539
4540 // If we're operating on a field, the object type is the type of the field.
4541 } else {
4542 objectTy = S.Context.getTypeDeclType(target->getParent());
4543 }
4544
4545 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4546 }
4547
4548 /// Check whether we should delete a special member due to the implicit
4549 /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult * SMOR,bool IsDtorCallInCtor)4550 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4551 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4552 bool IsDtorCallInCtor) {
4553 CXXMethodDecl *Decl = SMOR->getMethod();
4554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4555
4556 int DiagKind = -1;
4557
4558 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4559 DiagKind = !Decl ? 0 : 1;
4560 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4561 DiagKind = 2;
4562 else if (!isAccessible(Subobj, Decl))
4563 DiagKind = 3;
4564 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4565 !Decl->isTrivial()) {
4566 // A member of a union must have a trivial corresponding special member.
4567 // As a weird special case, a destructor call from a union's constructor
4568 // must be accessible and non-deleted, but need not be trivial. Such a
4569 // destructor is never actually called, but is semantically checked as
4570 // if it were.
4571 DiagKind = 4;
4572 }
4573
4574 if (DiagKind == -1)
4575 return false;
4576
4577 if (Diagnose) {
4578 if (Field) {
4579 S.Diag(Field->getLocation(),
4580 diag::note_deleted_special_member_class_subobject)
4581 << CSM << MD->getParent() << /*IsField*/true
4582 << Field << DiagKind << IsDtorCallInCtor;
4583 } else {
4584 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4585 S.Diag(Base->getLocStart(),
4586 diag::note_deleted_special_member_class_subobject)
4587 << CSM << MD->getParent() << /*IsField*/false
4588 << Base->getType() << DiagKind << IsDtorCallInCtor;
4589 }
4590
4591 if (DiagKind == 1)
4592 S.NoteDeletedFunction(Decl);
4593 // FIXME: Explain inaccessibility if DiagKind == 3.
4594 }
4595
4596 return true;
4597 }
4598
4599 /// Check whether we should delete a special member function due to having a
4600 /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)4601 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4602 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4603 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4604
4605 // C++11 [class.ctor]p5:
4606 // -- any direct or virtual base class, or non-static data member with no
4607 // brace-or-equal-initializer, has class type M (or array thereof) and
4608 // either M has no default constructor or overload resolution as applied
4609 // to M's default constructor results in an ambiguity or in a function
4610 // that is deleted or inaccessible
4611 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4612 // -- a direct or virtual base class B that cannot be copied/moved because
4613 // overload resolution, as applied to B's corresponding special member,
4614 // results in an ambiguity or a function that is deleted or inaccessible
4615 // from the defaulted special member
4616 // C++11 [class.dtor]p5:
4617 // -- any direct or virtual base class [...] has a type with a destructor
4618 // that is deleted or inaccessible
4619 if (!(CSM == Sema::CXXDefaultConstructor &&
4620 Field && Field->hasInClassInitializer()) &&
4621 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4622 return true;
4623
4624 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4625 // -- any direct or virtual base class or non-static data member has a
4626 // type with a destructor that is deleted or inaccessible
4627 if (IsConstructor) {
4628 Sema::SpecialMemberOverloadResult *SMOR =
4629 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4630 false, false, false, false, false);
4631 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4632 return true;
4633 }
4634
4635 return false;
4636 }
4637
4638 /// Check whether we should delete a special member function due to the class
4639 /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)4640 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4641 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4642 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4643 }
4644
4645 /// Check whether we should delete a special member function due to the class
4646 /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)4647 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4648 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4649 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4650
4651 if (CSM == Sema::CXXDefaultConstructor) {
4652 // For a default constructor, all references must be initialized in-class
4653 // and, if a union, it must have a non-const member.
4654 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4655 if (Diagnose)
4656 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4657 << MD->getParent() << FD << FieldType << /*Reference*/0;
4658 return true;
4659 }
4660 // C++11 [class.ctor]p5: any non-variant non-static data member of
4661 // const-qualified type (or array thereof) with no
4662 // brace-or-equal-initializer does not have a user-provided default
4663 // constructor.
4664 if (!inUnion() && FieldType.isConstQualified() &&
4665 !FD->hasInClassInitializer() &&
4666 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4667 if (Diagnose)
4668 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4669 << MD->getParent() << FD << FD->getType() << /*Const*/1;
4670 return true;
4671 }
4672
4673 if (inUnion() && !FieldType.isConstQualified())
4674 AllFieldsAreConst = false;
4675 } else if (CSM == Sema::CXXCopyConstructor) {
4676 // For a copy constructor, data members must not be of rvalue reference
4677 // type.
4678 if (FieldType->isRValueReferenceType()) {
4679 if (Diagnose)
4680 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4681 << MD->getParent() << FD << FieldType;
4682 return true;
4683 }
4684 } else if (IsAssignment) {
4685 // For an assignment operator, data members must not be of reference type.
4686 if (FieldType->isReferenceType()) {
4687 if (Diagnose)
4688 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4689 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4690 return true;
4691 }
4692 if (!FieldRecord && FieldType.isConstQualified()) {
4693 // C++11 [class.copy]p23:
4694 // -- a non-static data member of const non-class type (or array thereof)
4695 if (Diagnose)
4696 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4697 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4698 return true;
4699 }
4700 }
4701
4702 if (FieldRecord) {
4703 // Some additional restrictions exist on the variant members.
4704 if (!inUnion() && FieldRecord->isUnion() &&
4705 FieldRecord->isAnonymousStructOrUnion()) {
4706 bool AllVariantFieldsAreConst = true;
4707
4708 // FIXME: Handle anonymous unions declared within anonymous unions.
4709 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4710 UE = FieldRecord->field_end();
4711 UI != UE; ++UI) {
4712 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4713
4714 if (!UnionFieldType.isConstQualified())
4715 AllVariantFieldsAreConst = false;
4716
4717 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4718 if (UnionFieldRecord &&
4719 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4720 UnionFieldType.getCVRQualifiers()))
4721 return true;
4722 }
4723
4724 // At least one member in each anonymous union must be non-const
4725 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4726 FieldRecord->field_begin() != FieldRecord->field_end()) {
4727 if (Diagnose)
4728 S.Diag(FieldRecord->getLocation(),
4729 diag::note_deleted_default_ctor_all_const)
4730 << MD->getParent() << /*anonymous union*/1;
4731 return true;
4732 }
4733
4734 // Don't check the implicit member of the anonymous union type.
4735 // This is technically non-conformant, but sanity demands it.
4736 return false;
4737 }
4738
4739 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4740 FieldType.getCVRQualifiers()))
4741 return true;
4742 }
4743
4744 return false;
4745 }
4746
4747 /// C++11 [class.ctor] p5:
4748 /// A defaulted default constructor for a class X is defined as deleted if
4749 /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()4750 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4751 // This is a silly definition, because it gives an empty union a deleted
4752 // default constructor. Don't do that.
4753 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4754 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4755 if (Diagnose)
4756 S.Diag(MD->getParent()->getLocation(),
4757 diag::note_deleted_default_ctor_all_const)
4758 << MD->getParent() << /*not anonymous union*/0;
4759 return true;
4760 }
4761 return false;
4762 }
4763
4764 /// Determine whether a defaulted special member function should be defined as
4765 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4766 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,bool Diagnose)4767 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4768 bool Diagnose) {
4769 if (MD->isInvalidDecl())
4770 return false;
4771 CXXRecordDecl *RD = MD->getParent();
4772 assert(!RD->isDependentType() && "do deletion after instantiation");
4773 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4774 return false;
4775
4776 // C++11 [expr.lambda.prim]p19:
4777 // The closure type associated with a lambda-expression has a
4778 // deleted (8.4.3) default constructor and a deleted copy
4779 // assignment operator.
4780 if (RD->isLambda() &&
4781 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4782 if (Diagnose)
4783 Diag(RD->getLocation(), diag::note_lambda_decl);
4784 return true;
4785 }
4786
4787 // For an anonymous struct or union, the copy and assignment special members
4788 // will never be used, so skip the check. For an anonymous union declared at
4789 // namespace scope, the constructor and destructor are used.
4790 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4791 RD->isAnonymousStructOrUnion())
4792 return false;
4793
4794 // C++11 [class.copy]p7, p18:
4795 // If the class definition declares a move constructor or move assignment
4796 // operator, an implicitly declared copy constructor or copy assignment
4797 // operator is defined as deleted.
4798 if (MD->isImplicit() &&
4799 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4800 CXXMethodDecl *UserDeclaredMove = 0;
4801
4802 // In Microsoft mode, a user-declared move only causes the deletion of the
4803 // corresponding copy operation, not both copy operations.
4804 if (RD->hasUserDeclaredMoveConstructor() &&
4805 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4806 if (!Diagnose) return true;
4807
4808 // Find any user-declared move constructor.
4809 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4810 E = RD->ctor_end(); I != E; ++I) {
4811 if (I->isMoveConstructor()) {
4812 UserDeclaredMove = *I;
4813 break;
4814 }
4815 }
4816 assert(UserDeclaredMove);
4817 } else if (RD->hasUserDeclaredMoveAssignment() &&
4818 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4819 if (!Diagnose) return true;
4820
4821 // Find any user-declared move assignment operator.
4822 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4823 E = RD->method_end(); I != E; ++I) {
4824 if (I->isMoveAssignmentOperator()) {
4825 UserDeclaredMove = *I;
4826 break;
4827 }
4828 }
4829 assert(UserDeclaredMove);
4830 }
4831
4832 if (UserDeclaredMove) {
4833 Diag(UserDeclaredMove->getLocation(),
4834 diag::note_deleted_copy_user_declared_move)
4835 << (CSM == CXXCopyAssignment) << RD
4836 << UserDeclaredMove->isMoveAssignmentOperator();
4837 return true;
4838 }
4839 }
4840
4841 // Do access control from the special member function
4842 ContextRAII MethodContext(*this, MD);
4843
4844 // C++11 [class.dtor]p5:
4845 // -- for a virtual destructor, lookup of the non-array deallocation function
4846 // results in an ambiguity or in a function that is deleted or inaccessible
4847 if (CSM == CXXDestructor && MD->isVirtual()) {
4848 FunctionDecl *OperatorDelete = 0;
4849 DeclarationName Name =
4850 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4851 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4852 OperatorDelete, false)) {
4853 if (Diagnose)
4854 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4855 return true;
4856 }
4857 }
4858
4859 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4860
4861 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4862 BE = RD->bases_end(); BI != BE; ++BI)
4863 if (!BI->isVirtual() &&
4864 SMI.shouldDeleteForBase(BI))
4865 return true;
4866
4867 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4868 BE = RD->vbases_end(); BI != BE; ++BI)
4869 if (SMI.shouldDeleteForBase(BI))
4870 return true;
4871
4872 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4873 FE = RD->field_end(); FI != FE; ++FI)
4874 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4875 SMI.shouldDeleteForField(*FI))
4876 return true;
4877
4878 if (SMI.shouldDeleteForAllConstMembers())
4879 return true;
4880
4881 return false;
4882 }
4883
4884 /// Perform lookup for a special member of the specified kind, and determine
4885 /// whether it is trivial. If the triviality can be determined without the
4886 /// lookup, skip it. This is intended for use when determining whether a
4887 /// special member of a containing object is trivial, and thus does not ever
4888 /// perform overload resolution for default constructors.
4889 ///
4890 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4891 /// member that was most likely to be intended to be trivial, if any.
findTrivialSpecialMember(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,unsigned Quals,CXXMethodDecl ** Selected)4892 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4893 Sema::CXXSpecialMember CSM, unsigned Quals,
4894 CXXMethodDecl **Selected) {
4895 if (Selected)
4896 *Selected = 0;
4897
4898 switch (CSM) {
4899 case Sema::CXXInvalid:
4900 llvm_unreachable("not a special member");
4901
4902 case Sema::CXXDefaultConstructor:
4903 // C++11 [class.ctor]p5:
4904 // A default constructor is trivial if:
4905 // - all the [direct subobjects] have trivial default constructors
4906 //
4907 // Note, no overload resolution is performed in this case.
4908 if (RD->hasTrivialDefaultConstructor())
4909 return true;
4910
4911 if (Selected) {
4912 // If there's a default constructor which could have been trivial, dig it
4913 // out. Otherwise, if there's any user-provided default constructor, point
4914 // to that as an example of why there's not a trivial one.
4915 CXXConstructorDecl *DefCtor = 0;
4916 if (RD->needsImplicitDefaultConstructor())
4917 S.DeclareImplicitDefaultConstructor(RD);
4918 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4919 CE = RD->ctor_end(); CI != CE; ++CI) {
4920 if (!CI->isDefaultConstructor())
4921 continue;
4922 DefCtor = *CI;
4923 if (!DefCtor->isUserProvided())
4924 break;
4925 }
4926
4927 *Selected = DefCtor;
4928 }
4929
4930 return false;
4931
4932 case Sema::CXXDestructor:
4933 // C++11 [class.dtor]p5:
4934 // A destructor is trivial if:
4935 // - all the direct [subobjects] have trivial destructors
4936 if (RD->hasTrivialDestructor())
4937 return true;
4938
4939 if (Selected) {
4940 if (RD->needsImplicitDestructor())
4941 S.DeclareImplicitDestructor(RD);
4942 *Selected = RD->getDestructor();
4943 }
4944
4945 return false;
4946
4947 case Sema::CXXCopyConstructor:
4948 // C++11 [class.copy]p12:
4949 // A copy constructor is trivial if:
4950 // - the constructor selected to copy each direct [subobject] is trivial
4951 if (RD->hasTrivialCopyConstructor()) {
4952 if (Quals == Qualifiers::Const)
4953 // We must either select the trivial copy constructor or reach an
4954 // ambiguity; no need to actually perform overload resolution.
4955 return true;
4956 } else if (!Selected) {
4957 return false;
4958 }
4959 // In C++98, we are not supposed to perform overload resolution here, but we
4960 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4961 // cases like B as having a non-trivial copy constructor:
4962 // struct A { template<typename T> A(T&); };
4963 // struct B { mutable A a; };
4964 goto NeedOverloadResolution;
4965
4966 case Sema::CXXCopyAssignment:
4967 // C++11 [class.copy]p25:
4968 // A copy assignment operator is trivial if:
4969 // - the assignment operator selected to copy each direct [subobject] is
4970 // trivial
4971 if (RD->hasTrivialCopyAssignment()) {
4972 if (Quals == Qualifiers::Const)
4973 return true;
4974 } else if (!Selected) {
4975 return false;
4976 }
4977 // In C++98, we are not supposed to perform overload resolution here, but we
4978 // treat that as a language defect.
4979 goto NeedOverloadResolution;
4980
4981 case Sema::CXXMoveConstructor:
4982 case Sema::CXXMoveAssignment:
4983 NeedOverloadResolution:
4984 Sema::SpecialMemberOverloadResult *SMOR =
4985 S.LookupSpecialMember(RD, CSM,
4986 Quals & Qualifiers::Const,
4987 Quals & Qualifiers::Volatile,
4988 /*RValueThis*/false, /*ConstThis*/false,
4989 /*VolatileThis*/false);
4990
4991 // The standard doesn't describe how to behave if the lookup is ambiguous.
4992 // We treat it as not making the member non-trivial, just like the standard
4993 // mandates for the default constructor. This should rarely matter, because
4994 // the member will also be deleted.
4995 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4996 return true;
4997
4998 if (!SMOR->getMethod()) {
4999 assert(SMOR->getKind() ==
5000 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5001 return false;
5002 }
5003
5004 // We deliberately don't check if we found a deleted special member. We're
5005 // not supposed to!
5006 if (Selected)
5007 *Selected = SMOR->getMethod();
5008 return SMOR->getMethod()->isTrivial();
5009 }
5010
5011 llvm_unreachable("unknown special method kind");
5012 }
5013
findUserDeclaredCtor(CXXRecordDecl * RD)5014 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5015 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5016 CI != CE; ++CI)
5017 if (!CI->isImplicit())
5018 return *CI;
5019
5020 // Look for constructor templates.
5021 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5022 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5023 if (CXXConstructorDecl *CD =
5024 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5025 return CD;
5026 }
5027
5028 return 0;
5029 }
5030
5031 /// The kind of subobject we are checking for triviality. The values of this
5032 /// enumeration are used in diagnostics.
5033 enum TrivialSubobjectKind {
5034 /// The subobject is a base class.
5035 TSK_BaseClass,
5036 /// The subobject is a non-static data member.
5037 TSK_Field,
5038 /// The object is actually the complete object.
5039 TSK_CompleteObject
5040 };
5041
5042 /// Check whether the special member selected for a given type would be trivial.
checkTrivialSubobjectCall(Sema & S,SourceLocation SubobjLoc,QualType SubType,Sema::CXXSpecialMember CSM,TrivialSubobjectKind Kind,bool Diagnose)5043 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5044 QualType SubType,
5045 Sema::CXXSpecialMember CSM,
5046 TrivialSubobjectKind Kind,
5047 bool Diagnose) {
5048 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5049 if (!SubRD)
5050 return true;
5051
5052 CXXMethodDecl *Selected;
5053 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5054 Diagnose ? &Selected : 0))
5055 return true;
5056
5057 if (Diagnose) {
5058 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5059 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5060 << Kind << SubType.getUnqualifiedType();
5061 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5062 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5063 } else if (!Selected)
5064 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5065 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5066 else if (Selected->isUserProvided()) {
5067 if (Kind == TSK_CompleteObject)
5068 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5069 << Kind << SubType.getUnqualifiedType() << CSM;
5070 else {
5071 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5072 << Kind << SubType.getUnqualifiedType() << CSM;
5073 S.Diag(Selected->getLocation(), diag::note_declared_at);
5074 }
5075 } else {
5076 if (Kind != TSK_CompleteObject)
5077 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5078 << Kind << SubType.getUnqualifiedType() << CSM;
5079
5080 // Explain why the defaulted or deleted special member isn't trivial.
5081 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5082 }
5083 }
5084
5085 return false;
5086 }
5087
5088 /// Check whether the members of a class type allow a special member to be
5089 /// trivial.
checkTrivialClassMembers(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,bool ConstArg,bool Diagnose)5090 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5091 Sema::CXXSpecialMember CSM,
5092 bool ConstArg, bool Diagnose) {
5093 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5094 FE = RD->field_end(); FI != FE; ++FI) {
5095 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5096 continue;
5097
5098 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5099
5100 // Pretend anonymous struct or union members are members of this class.
5101 if (FI->isAnonymousStructOrUnion()) {
5102 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5103 CSM, ConstArg, Diagnose))
5104 return false;
5105 continue;
5106 }
5107
5108 // C++11 [class.ctor]p5:
5109 // A default constructor is trivial if [...]
5110 // -- no non-static data member of its class has a
5111 // brace-or-equal-initializer
5112 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5113 if (Diagnose)
5114 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5115 return false;
5116 }
5117
5118 // Objective C ARC 4.3.5:
5119 // [...] nontrivally ownership-qualified types are [...] not trivially
5120 // default constructible, copy constructible, move constructible, copy
5121 // assignable, move assignable, or destructible [...]
5122 if (S.getLangOpts().ObjCAutoRefCount &&
5123 FieldType.hasNonTrivialObjCLifetime()) {
5124 if (Diagnose)
5125 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5126 << RD << FieldType.getObjCLifetime();
5127 return false;
5128 }
5129
5130 if (ConstArg && !FI->isMutable())
5131 FieldType.addConst();
5132 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5133 TSK_Field, Diagnose))
5134 return false;
5135 }
5136
5137 return true;
5138 }
5139
5140 /// Diagnose why the specified class does not have a trivial special member of
5141 /// the given kind.
DiagnoseNontrivial(const CXXRecordDecl * RD,CXXSpecialMember CSM)5142 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5143 QualType Ty = Context.getRecordType(RD);
5144 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5145 Ty.addConst();
5146
5147 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5148 TSK_CompleteObject, /*Diagnose*/true);
5149 }
5150
5151 /// Determine whether a defaulted or deleted special member function is trivial,
5152 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5153 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
SpecialMemberIsTrivial(CXXMethodDecl * MD,CXXSpecialMember CSM,bool Diagnose)5154 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5155 bool Diagnose) {
5156 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5157
5158 CXXRecordDecl *RD = MD->getParent();
5159
5160 bool ConstArg = false;
5161
5162 // C++11 [class.copy]p12, p25:
5163 // A [special member] is trivial if its declared parameter type is the same
5164 // as if it had been implicitly declared [...]
5165 switch (CSM) {
5166 case CXXDefaultConstructor:
5167 case CXXDestructor:
5168 // Trivial default constructors and destructors cannot have parameters.
5169 break;
5170
5171 case CXXCopyConstructor:
5172 case CXXCopyAssignment: {
5173 // Trivial copy operations always have const, non-volatile parameter types.
5174 ConstArg = true;
5175 const ParmVarDecl *Param0 = MD->getParamDecl(0);
5176 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5177 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5178 if (Diagnose)
5179 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5180 << Param0->getSourceRange() << Param0->getType()
5181 << Context.getLValueReferenceType(
5182 Context.getRecordType(RD).withConst());
5183 return false;
5184 }
5185 break;
5186 }
5187
5188 case CXXMoveConstructor:
5189 case CXXMoveAssignment: {
5190 // Trivial move operations always have non-cv-qualified parameters.
5191 const ParmVarDecl *Param0 = MD->getParamDecl(0);
5192 const RValueReferenceType *RT =
5193 Param0->getType()->getAs<RValueReferenceType>();
5194 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5195 if (Diagnose)
5196 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5197 << Param0->getSourceRange() << Param0->getType()
5198 << Context.getRValueReferenceType(Context.getRecordType(RD));
5199 return false;
5200 }
5201 break;
5202 }
5203
5204 case CXXInvalid:
5205 llvm_unreachable("not a special member");
5206 }
5207
5208 // FIXME: We require that the parameter-declaration-clause is equivalent to
5209 // that of an implicit declaration, not just that the declared parameter type
5210 // matches, in order to prevent absuridities like a function simultaneously
5211 // being a trivial copy constructor and a non-trivial default constructor.
5212 // This issue has not yet been assigned a core issue number.
5213 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5214 if (Diagnose)
5215 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5216 diag::note_nontrivial_default_arg)
5217 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5218 return false;
5219 }
5220 if (MD->isVariadic()) {
5221 if (Diagnose)
5222 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5223 return false;
5224 }
5225
5226 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5227 // A copy/move [constructor or assignment operator] is trivial if
5228 // -- the [member] selected to copy/move each direct base class subobject
5229 // is trivial
5230 //
5231 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5232 // A [default constructor or destructor] is trivial if
5233 // -- all the direct base classes have trivial [default constructors or
5234 // destructors]
5235 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5236 BE = RD->bases_end(); BI != BE; ++BI)
5237 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5238 ConstArg ? BI->getType().withConst()
5239 : BI->getType(),
5240 CSM, TSK_BaseClass, Diagnose))
5241 return false;
5242
5243 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5244 // A copy/move [constructor or assignment operator] for a class X is
5245 // trivial if
5246 // -- for each non-static data member of X that is of class type (or array
5247 // thereof), the constructor selected to copy/move that member is
5248 // trivial
5249 //
5250 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5251 // A [default constructor or destructor] is trivial if
5252 // -- for all of the non-static data members of its class that are of class
5253 // type (or array thereof), each such class has a trivial [default
5254 // constructor or destructor]
5255 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5256 return false;
5257
5258 // C++11 [class.dtor]p5:
5259 // A destructor is trivial if [...]
5260 // -- the destructor is not virtual
5261 if (CSM == CXXDestructor && MD->isVirtual()) {
5262 if (Diagnose)
5263 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5264 return false;
5265 }
5266
5267 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5268 // A [special member] for class X is trivial if [...]
5269 // -- class X has no virtual functions and no virtual base classes
5270 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5271 if (!Diagnose)
5272 return false;
5273
5274 if (RD->getNumVBases()) {
5275 // Check for virtual bases. We already know that the corresponding
5276 // member in all bases is trivial, so vbases must all be direct.
5277 CXXBaseSpecifier &BS = *RD->vbases_begin();
5278 assert(BS.isVirtual());
5279 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5280 return false;
5281 }
5282
5283 // Must have a virtual method.
5284 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5285 ME = RD->method_end(); MI != ME; ++MI) {
5286 if (MI->isVirtual()) {
5287 SourceLocation MLoc = MI->getLocStart();
5288 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5289 return false;
5290 }
5291 }
5292
5293 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5294 }
5295
5296 // Looks like it's trivial!
5297 return true;
5298 }
5299
5300 /// \brief Data used with FindHiddenVirtualMethod
5301 namespace {
5302 struct FindHiddenVirtualMethodData {
5303 Sema *S;
5304 CXXMethodDecl *Method;
5305 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5306 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5307 };
5308 }
5309
5310 /// \brief Check whether any most overriden method from MD in Methods
CheckMostOverridenMethods(const CXXMethodDecl * MD,const llvm::SmallPtrSet<const CXXMethodDecl *,8> & Methods)5311 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5312 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5313 if (MD->size_overridden_methods() == 0)
5314 return Methods.count(MD->getCanonicalDecl());
5315 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5316 E = MD->end_overridden_methods();
5317 I != E; ++I)
5318 if (CheckMostOverridenMethods(*I, Methods))
5319 return true;
5320 return false;
5321 }
5322
5323 /// \brief Member lookup function that determines whether a given C++
5324 /// method overloads virtual methods in a base class without overriding any,
5325 /// to be used with CXXRecordDecl::lookupInBases().
FindHiddenVirtualMethod(const CXXBaseSpecifier * Specifier,CXXBasePath & Path,void * UserData)5326 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5327 CXXBasePath &Path,
5328 void *UserData) {
5329 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5330
5331 FindHiddenVirtualMethodData &Data
5332 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5333
5334 DeclarationName Name = Data.Method->getDeclName();
5335 assert(Name.getNameKind() == DeclarationName::Identifier);
5336
5337 bool foundSameNameMethod = false;
5338 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5339 for (Path.Decls = BaseRecord->lookup(Name);
5340 !Path.Decls.empty();
5341 Path.Decls = Path.Decls.slice(1)) {
5342 NamedDecl *D = Path.Decls.front();
5343 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5344 MD = MD->getCanonicalDecl();
5345 foundSameNameMethod = true;
5346 // Interested only in hidden virtual methods.
5347 if (!MD->isVirtual())
5348 continue;
5349 // If the method we are checking overrides a method from its base
5350 // don't warn about the other overloaded methods.
5351 if (!Data.S->IsOverload(Data.Method, MD, false))
5352 return true;
5353 // Collect the overload only if its hidden.
5354 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5355 overloadedMethods.push_back(MD);
5356 }
5357 }
5358
5359 if (foundSameNameMethod)
5360 Data.OverloadedMethods.append(overloadedMethods.begin(),
5361 overloadedMethods.end());
5362 return foundSameNameMethod;
5363 }
5364
5365 /// \brief Add the most overriden methods from MD to Methods
AddMostOverridenMethods(const CXXMethodDecl * MD,llvm::SmallPtrSet<const CXXMethodDecl *,8> & Methods)5366 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5367 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5368 if (MD->size_overridden_methods() == 0)
5369 Methods.insert(MD->getCanonicalDecl());
5370 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5371 E = MD->end_overridden_methods();
5372 I != E; ++I)
5373 AddMostOverridenMethods(*I, Methods);
5374 }
5375
5376 /// \brief See if a method overloads virtual methods in a base class without
5377 /// overriding any.
DiagnoseHiddenVirtualMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)5378 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5379 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5380 MD->getLocation()) == DiagnosticsEngine::Ignored)
5381 return;
5382 if (!MD->getDeclName().isIdentifier())
5383 return;
5384
5385 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5386 /*bool RecordPaths=*/false,
5387 /*bool DetectVirtual=*/false);
5388 FindHiddenVirtualMethodData Data;
5389 Data.Method = MD;
5390 Data.S = this;
5391
5392 // Keep the base methods that were overriden or introduced in the subclass
5393 // by 'using' in a set. A base method not in this set is hidden.
5394 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5395 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5396 NamedDecl *ND = *I;
5397 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5398 ND = shad->getTargetDecl();
5399 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5400 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5401 }
5402
5403 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5404 !Data.OverloadedMethods.empty()) {
5405 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5406 << MD << (Data.OverloadedMethods.size() > 1);
5407
5408 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5409 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5410 Diag(overloadedMD->getLocation(),
5411 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5412 }
5413 }
5414 }
5415
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,AttributeList * AttrList)5416 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5417 Decl *TagDecl,
5418 SourceLocation LBrac,
5419 SourceLocation RBrac,
5420 AttributeList *AttrList) {
5421 if (!TagDecl)
5422 return;
5423
5424 AdjustDeclIfTemplate(TagDecl);
5425
5426 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5427 if (l->getKind() != AttributeList::AT_Visibility)
5428 continue;
5429 l->setInvalid();
5430 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5431 l->getName();
5432 }
5433
5434 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5435 // strict aliasing violation!
5436 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5437 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5438
5439 CheckCompletedCXXClass(
5440 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5441 }
5442
5443 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5444 /// special functions, such as the default constructor, copy
5445 /// constructor, or destructor, to the given C++ class (C++
5446 /// [special]p1). This routine can only be executed just before the
5447 /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)5448 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5449 if (!ClassDecl->hasUserDeclaredConstructor())
5450 ++ASTContext::NumImplicitDefaultConstructors;
5451
5452 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5453 ++ASTContext::NumImplicitCopyConstructors;
5454
5455 // If the properties or semantics of the copy constructor couldn't be
5456 // determined while the class was being declared, force a declaration
5457 // of it now.
5458 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5459 DeclareImplicitCopyConstructor(ClassDecl);
5460 }
5461
5462 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5463 ++ASTContext::NumImplicitMoveConstructors;
5464
5465 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5466 DeclareImplicitMoveConstructor(ClassDecl);
5467 }
5468
5469 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5470 ++ASTContext::NumImplicitCopyAssignmentOperators;
5471
5472 // If we have a dynamic class, then the copy assignment operator may be
5473 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5474 // it shows up in the right place in the vtable and that we diagnose
5475 // problems with the implicit exception specification.
5476 if (ClassDecl->isDynamicClass() ||
5477 ClassDecl->needsOverloadResolutionForCopyAssignment())
5478 DeclareImplicitCopyAssignment(ClassDecl);
5479 }
5480
5481 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5482 ++ASTContext::NumImplicitMoveAssignmentOperators;
5483
5484 // Likewise for the move assignment operator.
5485 if (ClassDecl->isDynamicClass() ||
5486 ClassDecl->needsOverloadResolutionForMoveAssignment())
5487 DeclareImplicitMoveAssignment(ClassDecl);
5488 }
5489
5490 if (!ClassDecl->hasUserDeclaredDestructor()) {
5491 ++ASTContext::NumImplicitDestructors;
5492
5493 // If we have a dynamic class, then the destructor may be virtual, so we
5494 // have to declare the destructor immediately. This ensures that, e.g., it
5495 // shows up in the right place in the vtable and that we diagnose problems
5496 // with the implicit exception specification.
5497 if (ClassDecl->isDynamicClass() ||
5498 ClassDecl->needsOverloadResolutionForDestructor())
5499 DeclareImplicitDestructor(ClassDecl);
5500 }
5501 }
5502
ActOnReenterDeclaratorTemplateScope(Scope * S,DeclaratorDecl * D)5503 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5504 if (!D)
5505 return;
5506
5507 int NumParamList = D->getNumTemplateParameterLists();
5508 for (int i = 0; i < NumParamList; i++) {
5509 TemplateParameterList* Params = D->getTemplateParameterList(i);
5510 for (TemplateParameterList::iterator Param = Params->begin(),
5511 ParamEnd = Params->end();
5512 Param != ParamEnd; ++Param) {
5513 NamedDecl *Named = cast<NamedDecl>(*Param);
5514 if (Named->getDeclName()) {
5515 S->AddDecl(Named);
5516 IdResolver.AddDecl(Named);
5517 }
5518 }
5519 }
5520 }
5521
ActOnReenterTemplateScope(Scope * S,Decl * D)5522 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5523 if (!D)
5524 return;
5525
5526 TemplateParameterList *Params = 0;
5527 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5528 Params = Template->getTemplateParameters();
5529 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5530 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5531 Params = PartialSpec->getTemplateParameters();
5532 else
5533 return;
5534
5535 for (TemplateParameterList::iterator Param = Params->begin(),
5536 ParamEnd = Params->end();
5537 Param != ParamEnd; ++Param) {
5538 NamedDecl *Named = cast<NamedDecl>(*Param);
5539 if (Named->getDeclName()) {
5540 S->AddDecl(Named);
5541 IdResolver.AddDecl(Named);
5542 }
5543 }
5544 }
5545
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)5546 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5547 if (!RecordD) return;
5548 AdjustDeclIfTemplate(RecordD);
5549 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5550 PushDeclContext(S, Record);
5551 }
5552
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)5553 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5554 if (!RecordD) return;
5555 PopDeclContext();
5556 }
5557
5558 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5559 /// parsing a top-level (non-nested) C++ class, and we are now
5560 /// parsing those parts of the given Method declaration that could
5561 /// not be parsed earlier (C++ [class.mem]p2), such as default
5562 /// arguments. This action should enter the scope of the given
5563 /// Method declaration as if we had just parsed the qualified method
5564 /// name. However, it should not bring the parameters into scope;
5565 /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)5566 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5567 }
5568
5569 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
5570 /// C++ method declaration. We're (re-)introducing the given
5571 /// function parameter into scope for use in parsing later parts of
5572 /// the method declaration. For example, we could see an
5573 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)5574 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5575 if (!ParamD)
5576 return;
5577
5578 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5579
5580 // If this parameter has an unparsed default argument, clear it out
5581 // to make way for the parsed default argument.
5582 if (Param->hasUnparsedDefaultArg())
5583 Param->setDefaultArg(0);
5584
5585 S->AddDecl(Param);
5586 if (Param->getDeclName())
5587 IdResolver.AddDecl(Param);
5588 }
5589
5590 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5591 /// processing the delayed method declaration for Method. The method
5592 /// declaration is now considered finished. There may be a separate
5593 /// ActOnStartOfFunctionDef action later (not necessarily
5594 /// immediately!) for this method, if it was also defined inside the
5595 /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)5596 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5597 if (!MethodD)
5598 return;
5599
5600 AdjustDeclIfTemplate(MethodD);
5601
5602 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5603
5604 // Now that we have our default arguments, check the constructor
5605 // again. It could produce additional diagnostics or affect whether
5606 // the class has implicitly-declared destructors, among other
5607 // things.
5608 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5609 CheckConstructor(Constructor);
5610
5611 // Check the default arguments, which we may have added.
5612 if (!Method->isInvalidDecl())
5613 CheckCXXDefaultArguments(Method);
5614 }
5615
5616 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5617 /// the well-formedness of the constructor declarator @p D with type @p
5618 /// R. If there are any errors in the declarator, this routine will
5619 /// emit diagnostics and set the invalid bit to true. In any case, the type
5620 /// will be updated to reflect a well-formed type for the constructor and
5621 /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)5622 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5623 StorageClass &SC) {
5624 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5625
5626 // C++ [class.ctor]p3:
5627 // A constructor shall not be virtual (10.3) or static (9.4). A
5628 // constructor can be invoked for a const, volatile or const
5629 // volatile object. A constructor shall not be declared const,
5630 // volatile, or const volatile (9.3.2).
5631 if (isVirtual) {
5632 if (!D.isInvalidType())
5633 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5634 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5635 << SourceRange(D.getIdentifierLoc());
5636 D.setInvalidType();
5637 }
5638 if (SC == SC_Static) {
5639 if (!D.isInvalidType())
5640 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5641 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5642 << SourceRange(D.getIdentifierLoc());
5643 D.setInvalidType();
5644 SC = SC_None;
5645 }
5646
5647 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5648 if (FTI.TypeQuals != 0) {
5649 if (FTI.TypeQuals & Qualifiers::Const)
5650 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5651 << "const" << SourceRange(D.getIdentifierLoc());
5652 if (FTI.TypeQuals & Qualifiers::Volatile)
5653 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5654 << "volatile" << SourceRange(D.getIdentifierLoc());
5655 if (FTI.TypeQuals & Qualifiers::Restrict)
5656 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5657 << "restrict" << SourceRange(D.getIdentifierLoc());
5658 D.setInvalidType();
5659 }
5660
5661 // C++0x [class.ctor]p4:
5662 // A constructor shall not be declared with a ref-qualifier.
5663 if (FTI.hasRefQualifier()) {
5664 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5665 << FTI.RefQualifierIsLValueRef
5666 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5667 D.setInvalidType();
5668 }
5669
5670 // Rebuild the function type "R" without any type qualifiers (in
5671 // case any of the errors above fired) and with "void" as the
5672 // return type, since constructors don't have return types.
5673 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5674 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5675 return R;
5676
5677 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5678 EPI.TypeQuals = 0;
5679 EPI.RefQualifier = RQ_None;
5680
5681 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5682 }
5683
5684 /// CheckConstructor - Checks a fully-formed constructor for
5685 /// well-formedness, issuing any diagnostics required. Returns true if
5686 /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)5687 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5688 CXXRecordDecl *ClassDecl
5689 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5690 if (!ClassDecl)
5691 return Constructor->setInvalidDecl();
5692
5693 // C++ [class.copy]p3:
5694 // A declaration of a constructor for a class X is ill-formed if
5695 // its first parameter is of type (optionally cv-qualified) X and
5696 // either there are no other parameters or else all other
5697 // parameters have default arguments.
5698 if (!Constructor->isInvalidDecl() &&
5699 ((Constructor->getNumParams() == 1) ||
5700 (Constructor->getNumParams() > 1 &&
5701 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5702 Constructor->getTemplateSpecializationKind()
5703 != TSK_ImplicitInstantiation) {
5704 QualType ParamType = Constructor->getParamDecl(0)->getType();
5705 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5706 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5707 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5708 const char *ConstRef
5709 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5710 : " const &";
5711 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5712 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5713
5714 // FIXME: Rather that making the constructor invalid, we should endeavor
5715 // to fix the type.
5716 Constructor->setInvalidDecl();
5717 }
5718 }
5719 }
5720
5721 /// CheckDestructor - Checks a fully-formed destructor definition for
5722 /// well-formedness, issuing any diagnostics required. Returns true
5723 /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)5724 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5725 CXXRecordDecl *RD = Destructor->getParent();
5726
5727 if (Destructor->isVirtual()) {
5728 SourceLocation Loc;
5729
5730 if (!Destructor->isImplicit())
5731 Loc = Destructor->getLocation();
5732 else
5733 Loc = RD->getLocation();
5734
5735 // If we have a virtual destructor, look up the deallocation function
5736 FunctionDecl *OperatorDelete = 0;
5737 DeclarationName Name =
5738 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5739 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5740 return true;
5741
5742 MarkFunctionReferenced(Loc, OperatorDelete);
5743
5744 Destructor->setOperatorDelete(OperatorDelete);
5745 }
5746
5747 return false;
5748 }
5749
5750 static inline bool
FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo & FTI)5751 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5752 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5753 FTI.ArgInfo[0].Param &&
5754 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5755 }
5756
5757 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5758 /// the well-formednes of the destructor declarator @p D with type @p
5759 /// R. If there are any errors in the declarator, this routine will
5760 /// emit diagnostics and set the declarator to invalid. Even if this happens,
5761 /// will be updated to reflect a well-formed type for the destructor and
5762 /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)5763 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5764 StorageClass& SC) {
5765 // C++ [class.dtor]p1:
5766 // [...] A typedef-name that names a class is a class-name
5767 // (7.1.3); however, a typedef-name that names a class shall not
5768 // be used as the identifier in the declarator for a destructor
5769 // declaration.
5770 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5771 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5772 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5773 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5774 else if (const TemplateSpecializationType *TST =
5775 DeclaratorType->getAs<TemplateSpecializationType>())
5776 if (TST->isTypeAlias())
5777 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5778 << DeclaratorType << 1;
5779
5780 // C++ [class.dtor]p2:
5781 // A destructor is used to destroy objects of its class type. A
5782 // destructor takes no parameters, and no return type can be
5783 // specified for it (not even void). The address of a destructor
5784 // shall not be taken. A destructor shall not be static. A
5785 // destructor can be invoked for a const, volatile or const
5786 // volatile object. A destructor shall not be declared const,
5787 // volatile or const volatile (9.3.2).
5788 if (SC == SC_Static) {
5789 if (!D.isInvalidType())
5790 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5791 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5792 << SourceRange(D.getIdentifierLoc())
5793 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5794
5795 SC = SC_None;
5796 }
5797 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5798 // Destructors don't have return types, but the parser will
5799 // happily parse something like:
5800 //
5801 // class X {
5802 // float ~X();
5803 // };
5804 //
5805 // The return type will be eliminated later.
5806 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5807 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5808 << SourceRange(D.getIdentifierLoc());
5809 }
5810
5811 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5812 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5813 if (FTI.TypeQuals & Qualifiers::Const)
5814 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5815 << "const" << SourceRange(D.getIdentifierLoc());
5816 if (FTI.TypeQuals & Qualifiers::Volatile)
5817 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5818 << "volatile" << SourceRange(D.getIdentifierLoc());
5819 if (FTI.TypeQuals & Qualifiers::Restrict)
5820 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5821 << "restrict" << SourceRange(D.getIdentifierLoc());
5822 D.setInvalidType();
5823 }
5824
5825 // C++0x [class.dtor]p2:
5826 // A destructor shall not be declared with a ref-qualifier.
5827 if (FTI.hasRefQualifier()) {
5828 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5829 << FTI.RefQualifierIsLValueRef
5830 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5831 D.setInvalidType();
5832 }
5833
5834 // Make sure we don't have any parameters.
5835 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5836 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5837
5838 // Delete the parameters.
5839 FTI.freeArgs();
5840 D.setInvalidType();
5841 }
5842
5843 // Make sure the destructor isn't variadic.
5844 if (FTI.isVariadic) {
5845 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5846 D.setInvalidType();
5847 }
5848
5849 // Rebuild the function type "R" without any type qualifiers or
5850 // parameters (in case any of the errors above fired) and with
5851 // "void" as the return type, since destructors don't have return
5852 // types.
5853 if (!D.isInvalidType())
5854 return R;
5855
5856 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5857 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5858 EPI.Variadic = false;
5859 EPI.TypeQuals = 0;
5860 EPI.RefQualifier = RQ_None;
5861 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
5862 }
5863
5864 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5865 /// well-formednes of the conversion function declarator @p D with
5866 /// type @p R. If there are any errors in the declarator, this routine
5867 /// will emit diagnostics and return true. Otherwise, it will return
5868 /// false. Either way, the type @p R will be updated to reflect a
5869 /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)5870 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5871 StorageClass& SC) {
5872 // C++ [class.conv.fct]p1:
5873 // Neither parameter types nor return type can be specified. The
5874 // type of a conversion function (8.3.5) is "function taking no
5875 // parameter returning conversion-type-id."
5876 if (SC == SC_Static) {
5877 if (!D.isInvalidType())
5878 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5879 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5880 << SourceRange(D.getIdentifierLoc());
5881 D.setInvalidType();
5882 SC = SC_None;
5883 }
5884
5885 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5886
5887 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5888 // Conversion functions don't have return types, but the parser will
5889 // happily parse something like:
5890 //
5891 // class X {
5892 // float operator bool();
5893 // };
5894 //
5895 // The return type will be changed later anyway.
5896 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5897 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5898 << SourceRange(D.getIdentifierLoc());
5899 D.setInvalidType();
5900 }
5901
5902 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5903
5904 // Make sure we don't have any parameters.
5905 if (Proto->getNumArgs() > 0) {
5906 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5907
5908 // Delete the parameters.
5909 D.getFunctionTypeInfo().freeArgs();
5910 D.setInvalidType();
5911 } else if (Proto->isVariadic()) {
5912 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5913 D.setInvalidType();
5914 }
5915
5916 // Diagnose "&operator bool()" and other such nonsense. This
5917 // is actually a gcc extension which we don't support.
5918 if (Proto->getResultType() != ConvType) {
5919 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5920 << Proto->getResultType();
5921 D.setInvalidType();
5922 ConvType = Proto->getResultType();
5923 }
5924
5925 // C++ [class.conv.fct]p4:
5926 // The conversion-type-id shall not represent a function type nor
5927 // an array type.
5928 if (ConvType->isArrayType()) {
5929 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5930 ConvType = Context.getPointerType(ConvType);
5931 D.setInvalidType();
5932 } else if (ConvType->isFunctionType()) {
5933 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5934 ConvType = Context.getPointerType(ConvType);
5935 D.setInvalidType();
5936 }
5937
5938 // Rebuild the function type "R" without any parameters (in case any
5939 // of the errors above fired) and with the conversion type as the
5940 // return type.
5941 if (D.isInvalidType())
5942 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5943 Proto->getExtProtoInfo());
5944
5945 // C++0x explicit conversion operators.
5946 if (D.getDeclSpec().isExplicitSpecified())
5947 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5948 getLangOpts().CPlusPlus11 ?
5949 diag::warn_cxx98_compat_explicit_conversion_functions :
5950 diag::ext_explicit_conversion_functions)
5951 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5952 }
5953
5954 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5955 /// the declaration of the given C++ conversion function. This routine
5956 /// is responsible for recording the conversion function in the C++
5957 /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)5958 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5959 assert(Conversion && "Expected to receive a conversion function declaration");
5960
5961 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5962
5963 // Make sure we aren't redeclaring the conversion function.
5964 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5965
5966 // C++ [class.conv.fct]p1:
5967 // [...] A conversion function is never used to convert a
5968 // (possibly cv-qualified) object to the (possibly cv-qualified)
5969 // same object type (or a reference to it), to a (possibly
5970 // cv-qualified) base class of that type (or a reference to it),
5971 // or to (possibly cv-qualified) void.
5972 // FIXME: Suppress this warning if the conversion function ends up being a
5973 // virtual function that overrides a virtual function in a base class.
5974 QualType ClassType
5975 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5976 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5977 ConvType = ConvTypeRef->getPointeeType();
5978 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5979 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5980 /* Suppress diagnostics for instantiations. */;
5981 else if (ConvType->isRecordType()) {
5982 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5983 if (ConvType == ClassType)
5984 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5985 << ClassType;
5986 else if (IsDerivedFrom(ClassType, ConvType))
5987 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5988 << ClassType << ConvType;
5989 } else if (ConvType->isVoidType()) {
5990 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5991 << ClassType << ConvType;
5992 }
5993
5994 if (FunctionTemplateDecl *ConversionTemplate
5995 = Conversion->getDescribedFunctionTemplate())
5996 return ConversionTemplate;
5997
5998 return Conversion;
5999 }
6000
6001 //===----------------------------------------------------------------------===//
6002 // Namespace Handling
6003 //===----------------------------------------------------------------------===//
6004
6005 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6006 /// reopened.
DiagnoseNamespaceInlineMismatch(Sema & S,SourceLocation KeywordLoc,SourceLocation Loc,IdentifierInfo * II,bool * IsInline,NamespaceDecl * PrevNS)6007 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6008 SourceLocation Loc,
6009 IdentifierInfo *II, bool *IsInline,
6010 NamespaceDecl *PrevNS) {
6011 assert(*IsInline != PrevNS->isInline());
6012
6013 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6014 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6015 // inline namespaces, with the intention of bringing names into namespace std.
6016 //
6017 // We support this just well enough to get that case working; this is not
6018 // sufficient to support reopening namespaces as inline in general.
6019 if (*IsInline && II && II->getName().startswith("__atomic") &&
6020 S.getSourceManager().isInSystemHeader(Loc)) {
6021 // Mark all prior declarations of the namespace as inline.
6022 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6023 NS = NS->getPreviousDecl())
6024 NS->setInline(*IsInline);
6025 // Patch up the lookup table for the containing namespace. This isn't really
6026 // correct, but it's good enough for this particular case.
6027 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6028 E = PrevNS->decls_end(); I != E; ++I)
6029 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6030 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6031 return;
6032 }
6033
6034 if (PrevNS->isInline())
6035 // The user probably just forgot the 'inline', so suggest that it
6036 // be added back.
6037 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6038 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6039 else
6040 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6041 << IsInline;
6042
6043 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6044 *IsInline = PrevNS->isInline();
6045 }
6046
6047 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6048 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,AttributeList * AttrList)6049 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6050 SourceLocation InlineLoc,
6051 SourceLocation NamespaceLoc,
6052 SourceLocation IdentLoc,
6053 IdentifierInfo *II,
6054 SourceLocation LBrace,
6055 AttributeList *AttrList) {
6056 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6057 // For anonymous namespace, take the location of the left brace.
6058 SourceLocation Loc = II ? IdentLoc : LBrace;
6059 bool IsInline = InlineLoc.isValid();
6060 bool IsInvalid = false;
6061 bool IsStd = false;
6062 bool AddToKnown = false;
6063 Scope *DeclRegionScope = NamespcScope->getParent();
6064
6065 NamespaceDecl *PrevNS = 0;
6066 if (II) {
6067 // C++ [namespace.def]p2:
6068 // The identifier in an original-namespace-definition shall not
6069 // have been previously defined in the declarative region in
6070 // which the original-namespace-definition appears. The
6071 // identifier in an original-namespace-definition is the name of
6072 // the namespace. Subsequently in that declarative region, it is
6073 // treated as an original-namespace-name.
6074 //
6075 // Since namespace names are unique in their scope, and we don't
6076 // look through using directives, just look for any ordinary names.
6077
6078 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6079 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6080 Decl::IDNS_Namespace;
6081 NamedDecl *PrevDecl = 0;
6082 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6083 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6084 ++I) {
6085 if ((*I)->getIdentifierNamespace() & IDNS) {
6086 PrevDecl = *I;
6087 break;
6088 }
6089 }
6090
6091 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6092
6093 if (PrevNS) {
6094 // This is an extended namespace definition.
6095 if (IsInline != PrevNS->isInline())
6096 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6097 &IsInline, PrevNS);
6098 } else if (PrevDecl) {
6099 // This is an invalid name redefinition.
6100 Diag(Loc, diag::err_redefinition_different_kind)
6101 << II;
6102 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6103 IsInvalid = true;
6104 // Continue on to push Namespc as current DeclContext and return it.
6105 } else if (II->isStr("std") &&
6106 CurContext->getRedeclContext()->isTranslationUnit()) {
6107 // This is the first "real" definition of the namespace "std", so update
6108 // our cache of the "std" namespace to point at this definition.
6109 PrevNS = getStdNamespace();
6110 IsStd = true;
6111 AddToKnown = !IsInline;
6112 } else {
6113 // We've seen this namespace for the first time.
6114 AddToKnown = !IsInline;
6115 }
6116 } else {
6117 // Anonymous namespaces.
6118
6119 // Determine whether the parent already has an anonymous namespace.
6120 DeclContext *Parent = CurContext->getRedeclContext();
6121 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6122 PrevNS = TU->getAnonymousNamespace();
6123 } else {
6124 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6125 PrevNS = ND->getAnonymousNamespace();
6126 }
6127
6128 if (PrevNS && IsInline != PrevNS->isInline())
6129 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6130 &IsInline, PrevNS);
6131 }
6132
6133 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6134 StartLoc, Loc, II, PrevNS);
6135 if (IsInvalid)
6136 Namespc->setInvalidDecl();
6137
6138 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6139
6140 // FIXME: Should we be merging attributes?
6141 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6142 PushNamespaceVisibilityAttr(Attr, Loc);
6143
6144 if (IsStd)
6145 StdNamespace = Namespc;
6146 if (AddToKnown)
6147 KnownNamespaces[Namespc] = false;
6148
6149 if (II) {
6150 PushOnScopeChains(Namespc, DeclRegionScope);
6151 } else {
6152 // Link the anonymous namespace into its parent.
6153 DeclContext *Parent = CurContext->getRedeclContext();
6154 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6155 TU->setAnonymousNamespace(Namespc);
6156 } else {
6157 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6158 }
6159
6160 CurContext->addDecl(Namespc);
6161
6162 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6163 // behaves as if it were replaced by
6164 // namespace unique { /* empty body */ }
6165 // using namespace unique;
6166 // namespace unique { namespace-body }
6167 // where all occurrences of 'unique' in a translation unit are
6168 // replaced by the same identifier and this identifier differs
6169 // from all other identifiers in the entire program.
6170
6171 // We just create the namespace with an empty name and then add an
6172 // implicit using declaration, just like the standard suggests.
6173 //
6174 // CodeGen enforces the "universally unique" aspect by giving all
6175 // declarations semantically contained within an anonymous
6176 // namespace internal linkage.
6177
6178 if (!PrevNS) {
6179 UsingDirectiveDecl* UD
6180 = UsingDirectiveDecl::Create(Context, Parent,
6181 /* 'using' */ LBrace,
6182 /* 'namespace' */ SourceLocation(),
6183 /* qualifier */ NestedNameSpecifierLoc(),
6184 /* identifier */ SourceLocation(),
6185 Namespc,
6186 /* Ancestor */ Parent);
6187 UD->setImplicit();
6188 Parent->addDecl(UD);
6189 }
6190 }
6191
6192 ActOnDocumentableDecl(Namespc);
6193
6194 // Although we could have an invalid decl (i.e. the namespace name is a
6195 // redefinition), push it as current DeclContext and try to continue parsing.
6196 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6197 // for the namespace has the declarations that showed up in that particular
6198 // namespace definition.
6199 PushDeclContext(NamespcScope, Namespc);
6200 return Namespc;
6201 }
6202
6203 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6204 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)6205 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6206 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6207 return AD->getNamespace();
6208 return dyn_cast_or_null<NamespaceDecl>(D);
6209 }
6210
6211 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6212 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)6213 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6214 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6215 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6216 Namespc->setRBraceLoc(RBrace);
6217 PopDeclContext();
6218 if (Namespc->hasAttr<VisibilityAttr>())
6219 PopPragmaVisibility(true, RBrace);
6220 }
6221
getStdBadAlloc() const6222 CXXRecordDecl *Sema::getStdBadAlloc() const {
6223 return cast_or_null<CXXRecordDecl>(
6224 StdBadAlloc.get(Context.getExternalSource()));
6225 }
6226
getStdNamespace() const6227 NamespaceDecl *Sema::getStdNamespace() const {
6228 return cast_or_null<NamespaceDecl>(
6229 StdNamespace.get(Context.getExternalSource()));
6230 }
6231
6232 /// \brief Retrieve the special "std" namespace, which may require us to
6233 /// implicitly define the namespace.
getOrCreateStdNamespace()6234 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6235 if (!StdNamespace) {
6236 // The "std" namespace has not yet been defined, so build one implicitly.
6237 StdNamespace = NamespaceDecl::Create(Context,
6238 Context.getTranslationUnitDecl(),
6239 /*Inline=*/false,
6240 SourceLocation(), SourceLocation(),
6241 &PP.getIdentifierTable().get("std"),
6242 /*PrevDecl=*/0);
6243 getStdNamespace()->setImplicit(true);
6244 }
6245
6246 return getStdNamespace();
6247 }
6248
isStdInitializerList(QualType Ty,QualType * Element)6249 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6250 assert(getLangOpts().CPlusPlus &&
6251 "Looking for std::initializer_list outside of C++.");
6252
6253 // We're looking for implicit instantiations of
6254 // template <typename E> class std::initializer_list.
6255
6256 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6257 return false;
6258
6259 ClassTemplateDecl *Template = 0;
6260 const TemplateArgument *Arguments = 0;
6261
6262 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6263
6264 ClassTemplateSpecializationDecl *Specialization =
6265 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6266 if (!Specialization)
6267 return false;
6268
6269 Template = Specialization->getSpecializedTemplate();
6270 Arguments = Specialization->getTemplateArgs().data();
6271 } else if (const TemplateSpecializationType *TST =
6272 Ty->getAs<TemplateSpecializationType>()) {
6273 Template = dyn_cast_or_null<ClassTemplateDecl>(
6274 TST->getTemplateName().getAsTemplateDecl());
6275 Arguments = TST->getArgs();
6276 }
6277 if (!Template)
6278 return false;
6279
6280 if (!StdInitializerList) {
6281 // Haven't recognized std::initializer_list yet, maybe this is it.
6282 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6283 if (TemplateClass->getIdentifier() !=
6284 &PP.getIdentifierTable().get("initializer_list") ||
6285 !getStdNamespace()->InEnclosingNamespaceSetOf(
6286 TemplateClass->getDeclContext()))
6287 return false;
6288 // This is a template called std::initializer_list, but is it the right
6289 // template?
6290 TemplateParameterList *Params = Template->getTemplateParameters();
6291 if (Params->getMinRequiredArguments() != 1)
6292 return false;
6293 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6294 return false;
6295
6296 // It's the right template.
6297 StdInitializerList = Template;
6298 }
6299
6300 if (Template != StdInitializerList)
6301 return false;
6302
6303 // This is an instance of std::initializer_list. Find the argument type.
6304 if (Element)
6305 *Element = Arguments[0].getAsType();
6306 return true;
6307 }
6308
LookupStdInitializerList(Sema & S,SourceLocation Loc)6309 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6310 NamespaceDecl *Std = S.getStdNamespace();
6311 if (!Std) {
6312 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6313 return 0;
6314 }
6315
6316 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6317 Loc, Sema::LookupOrdinaryName);
6318 if (!S.LookupQualifiedName(Result, Std)) {
6319 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6320 return 0;
6321 }
6322 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6323 if (!Template) {
6324 Result.suppressDiagnostics();
6325 // We found something weird. Complain about the first thing we found.
6326 NamedDecl *Found = *Result.begin();
6327 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6328 return 0;
6329 }
6330
6331 // We found some template called std::initializer_list. Now verify that it's
6332 // correct.
6333 TemplateParameterList *Params = Template->getTemplateParameters();
6334 if (Params->getMinRequiredArguments() != 1 ||
6335 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6336 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6337 return 0;
6338 }
6339
6340 return Template;
6341 }
6342
BuildStdInitializerList(QualType Element,SourceLocation Loc)6343 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6344 if (!StdInitializerList) {
6345 StdInitializerList = LookupStdInitializerList(*this, Loc);
6346 if (!StdInitializerList)
6347 return QualType();
6348 }
6349
6350 TemplateArgumentListInfo Args(Loc, Loc);
6351 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6352 Context.getTrivialTypeSourceInfo(Element,
6353 Loc)));
6354 return Context.getCanonicalType(
6355 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6356 }
6357
isInitListConstructor(const CXXConstructorDecl * Ctor)6358 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6359 // C++ [dcl.init.list]p2:
6360 // A constructor is an initializer-list constructor if its first parameter
6361 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6362 // std::initializer_list<E> for some type E, and either there are no other
6363 // parameters or else all other parameters have default arguments.
6364 if (Ctor->getNumParams() < 1 ||
6365 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6366 return false;
6367
6368 QualType ArgType = Ctor->getParamDecl(0)->getType();
6369 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6370 ArgType = RT->getPointeeType().getUnqualifiedType();
6371
6372 return isStdInitializerList(ArgType, 0);
6373 }
6374
6375 /// \brief Determine whether a using statement is in a context where it will be
6376 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)6377 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6378 switch (CurContext->getDeclKind()) {
6379 case Decl::TranslationUnit:
6380 return true;
6381 case Decl::LinkageSpec:
6382 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6383 default:
6384 return false;
6385 }
6386 }
6387
6388 namespace {
6389
6390 // Callback to only accept typo corrections that are namespaces.
6391 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6392 public:
ValidateCandidate(const TypoCorrection & candidate)6393 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6394 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6395 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6396 }
6397 return false;
6398 }
6399 };
6400
6401 }
6402
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)6403 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6404 CXXScopeSpec &SS,
6405 SourceLocation IdentLoc,
6406 IdentifierInfo *Ident) {
6407 NamespaceValidatorCCC Validator;
6408 R.clear();
6409 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6410 R.getLookupKind(), Sc, &SS,
6411 Validator)) {
6412 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6413 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6414 if (DeclContext *DC = S.computeDeclContext(SS, false))
6415 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6416 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6417 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6418 CorrectedStr);
6419 else
6420 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6421 << Ident << CorrectedQuotedStr
6422 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6423
6424 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6425 diag::note_namespace_defined_here) << CorrectedQuotedStr;
6426
6427 R.addDecl(Corrected.getCorrectionDecl());
6428 return true;
6429 }
6430 return false;
6431 }
6432
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,AttributeList * AttrList)6433 Decl *Sema::ActOnUsingDirective(Scope *S,
6434 SourceLocation UsingLoc,
6435 SourceLocation NamespcLoc,
6436 CXXScopeSpec &SS,
6437 SourceLocation IdentLoc,
6438 IdentifierInfo *NamespcName,
6439 AttributeList *AttrList) {
6440 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6441 assert(NamespcName && "Invalid NamespcName.");
6442 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6443
6444 // This can only happen along a recovery path.
6445 while (S->getFlags() & Scope::TemplateParamScope)
6446 S = S->getParent();
6447 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6448
6449 UsingDirectiveDecl *UDir = 0;
6450 NestedNameSpecifier *Qualifier = 0;
6451 if (SS.isSet())
6452 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6453
6454 // Lookup namespace name.
6455 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6456 LookupParsedName(R, S, &SS);
6457 if (R.isAmbiguous())
6458 return 0;
6459
6460 if (R.empty()) {
6461 R.clear();
6462 // Allow "using namespace std;" or "using namespace ::std;" even if
6463 // "std" hasn't been defined yet, for GCC compatibility.
6464 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6465 NamespcName->isStr("std")) {
6466 Diag(IdentLoc, diag::ext_using_undefined_std);
6467 R.addDecl(getOrCreateStdNamespace());
6468 R.resolveKind();
6469 }
6470 // Otherwise, attempt typo correction.
6471 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6472 }
6473
6474 if (!R.empty()) {
6475 NamedDecl *Named = R.getFoundDecl();
6476 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6477 && "expected namespace decl");
6478 // C++ [namespace.udir]p1:
6479 // A using-directive specifies that the names in the nominated
6480 // namespace can be used in the scope in which the
6481 // using-directive appears after the using-directive. During
6482 // unqualified name lookup (3.4.1), the names appear as if they
6483 // were declared in the nearest enclosing namespace which
6484 // contains both the using-directive and the nominated
6485 // namespace. [Note: in this context, "contains" means "contains
6486 // directly or indirectly". ]
6487
6488 // Find enclosing context containing both using-directive and
6489 // nominated namespace.
6490 NamespaceDecl *NS = getNamespaceDecl(Named);
6491 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6492 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6493 CommonAncestor = CommonAncestor->getParent();
6494
6495 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6496 SS.getWithLocInContext(Context),
6497 IdentLoc, Named, CommonAncestor);
6498
6499 if (IsUsingDirectiveInToplevelContext(CurContext) &&
6500 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6501 Diag(IdentLoc, diag::warn_using_directive_in_header);
6502 }
6503
6504 PushUsingDirective(S, UDir);
6505 } else {
6506 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6507 }
6508
6509 if (UDir)
6510 ProcessDeclAttributeList(S, UDir, AttrList);
6511
6512 return UDir;
6513 }
6514
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)6515 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6516 // If the scope has an associated entity and the using directive is at
6517 // namespace or translation unit scope, add the UsingDirectiveDecl into
6518 // its lookup structure so qualified name lookup can find it.
6519 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6520 if (Ctx && !Ctx->isFunctionOrMethod())
6521 Ctx->addDecl(UDir);
6522 else
6523 // Otherwise, it is at block sope. The using-directives will affect lookup
6524 // only to the end of the scope.
6525 S->PushUsingDirective(UDir);
6526 }
6527
6528
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,bool HasUsingKeyword,SourceLocation UsingLoc,CXXScopeSpec & SS,UnqualifiedId & Name,AttributeList * AttrList,bool IsTypeName,SourceLocation TypenameLoc)6529 Decl *Sema::ActOnUsingDeclaration(Scope *S,
6530 AccessSpecifier AS,
6531 bool HasUsingKeyword,
6532 SourceLocation UsingLoc,
6533 CXXScopeSpec &SS,
6534 UnqualifiedId &Name,
6535 AttributeList *AttrList,
6536 bool IsTypeName,
6537 SourceLocation TypenameLoc) {
6538 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6539
6540 switch (Name.getKind()) {
6541 case UnqualifiedId::IK_ImplicitSelfParam:
6542 case UnqualifiedId::IK_Identifier:
6543 case UnqualifiedId::IK_OperatorFunctionId:
6544 case UnqualifiedId::IK_LiteralOperatorId:
6545 case UnqualifiedId::IK_ConversionFunctionId:
6546 break;
6547
6548 case UnqualifiedId::IK_ConstructorName:
6549 case UnqualifiedId::IK_ConstructorTemplateId:
6550 // C++11 inheriting constructors.
6551 Diag(Name.getLocStart(),
6552 getLangOpts().CPlusPlus11 ?
6553 diag::warn_cxx98_compat_using_decl_constructor :
6554 diag::err_using_decl_constructor)
6555 << SS.getRange();
6556
6557 if (getLangOpts().CPlusPlus11) break;
6558
6559 return 0;
6560
6561 case UnqualifiedId::IK_DestructorName:
6562 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6563 << SS.getRange();
6564 return 0;
6565
6566 case UnqualifiedId::IK_TemplateId:
6567 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6568 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6569 return 0;
6570 }
6571
6572 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6573 DeclarationName TargetName = TargetNameInfo.getName();
6574 if (!TargetName)
6575 return 0;
6576
6577 // Warn about access declarations.
6578 // TODO: store that the declaration was written without 'using' and
6579 // talk about access decls instead of using decls in the
6580 // diagnostics.
6581 if (!HasUsingKeyword) {
6582 UsingLoc = Name.getLocStart();
6583
6584 Diag(UsingLoc, diag::warn_access_decl_deprecated)
6585 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6586 }
6587
6588 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6589 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6590 return 0;
6591
6592 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6593 TargetNameInfo, AttrList,
6594 /* IsInstantiation */ false,
6595 IsTypeName, TypenameLoc);
6596 if (UD)
6597 PushOnScopeChains(UD, S, /*AddToContext*/ false);
6598
6599 return UD;
6600 }
6601
6602 /// \brief Determine whether a using declaration considers the given
6603 /// declarations as "equivalent", e.g., if they are redeclarations of
6604 /// the same entity or are both typedefs of the same type.
6605 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2,bool & SuppressRedeclaration)6606 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6607 bool &SuppressRedeclaration) {
6608 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6609 SuppressRedeclaration = false;
6610 return true;
6611 }
6612
6613 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6614 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6615 SuppressRedeclaration = true;
6616 return Context.hasSameType(TD1->getUnderlyingType(),
6617 TD2->getUnderlyingType());
6618 }
6619
6620 return false;
6621 }
6622
6623
6624 /// Determines whether to create a using shadow decl for a particular
6625 /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(UsingDecl * Using,NamedDecl * Orig,const LookupResult & Previous)6626 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6627 const LookupResult &Previous) {
6628 // Diagnose finding a decl which is not from a base class of the
6629 // current class. We do this now because there are cases where this
6630 // function will silently decide not to build a shadow decl, which
6631 // will pre-empt further diagnostics.
6632 //
6633 // We don't need to do this in C++0x because we do the check once on
6634 // the qualifier.
6635 //
6636 // FIXME: diagnose the following if we care enough:
6637 // struct A { int foo; };
6638 // struct B : A { using A::foo; };
6639 // template <class T> struct C : A {};
6640 // template <class T> struct D : C<T> { using B::foo; } // <---
6641 // This is invalid (during instantiation) in C++03 because B::foo
6642 // resolves to the using decl in B, which is not a base class of D<T>.
6643 // We can't diagnose it immediately because C<T> is an unknown
6644 // specialization. The UsingShadowDecl in D<T> then points directly
6645 // to A::foo, which will look well-formed when we instantiate.
6646 // The right solution is to not collapse the shadow-decl chain.
6647 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6648 DeclContext *OrigDC = Orig->getDeclContext();
6649
6650 // Handle enums and anonymous structs.
6651 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6652 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6653 while (OrigRec->isAnonymousStructOrUnion())
6654 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6655
6656 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6657 if (OrigDC == CurContext) {
6658 Diag(Using->getLocation(),
6659 diag::err_using_decl_nested_name_specifier_is_current_class)
6660 << Using->getQualifierLoc().getSourceRange();
6661 Diag(Orig->getLocation(), diag::note_using_decl_target);
6662 return true;
6663 }
6664
6665 Diag(Using->getQualifierLoc().getBeginLoc(),
6666 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6667 << Using->getQualifier()
6668 << cast<CXXRecordDecl>(CurContext)
6669 << Using->getQualifierLoc().getSourceRange();
6670 Diag(Orig->getLocation(), diag::note_using_decl_target);
6671 return true;
6672 }
6673 }
6674
6675 if (Previous.empty()) return false;
6676
6677 NamedDecl *Target = Orig;
6678 if (isa<UsingShadowDecl>(Target))
6679 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6680
6681 // If the target happens to be one of the previous declarations, we
6682 // don't have a conflict.
6683 //
6684 // FIXME: but we might be increasing its access, in which case we
6685 // should redeclare it.
6686 NamedDecl *NonTag = 0, *Tag = 0;
6687 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6688 I != E; ++I) {
6689 NamedDecl *D = (*I)->getUnderlyingDecl();
6690 bool Result;
6691 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6692 return Result;
6693
6694 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6695 }
6696
6697 if (Target->isFunctionOrFunctionTemplate()) {
6698 FunctionDecl *FD;
6699 if (isa<FunctionTemplateDecl>(Target))
6700 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6701 else
6702 FD = cast<FunctionDecl>(Target);
6703
6704 NamedDecl *OldDecl = 0;
6705 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6706 case Ovl_Overload:
6707 return false;
6708
6709 case Ovl_NonFunction:
6710 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6711 break;
6712
6713 // We found a decl with the exact signature.
6714 case Ovl_Match:
6715 // If we're in a record, we want to hide the target, so we
6716 // return true (without a diagnostic) to tell the caller not to
6717 // build a shadow decl.
6718 if (CurContext->isRecord())
6719 return true;
6720
6721 // If we're not in a record, this is an error.
6722 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6723 break;
6724 }
6725
6726 Diag(Target->getLocation(), diag::note_using_decl_target);
6727 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6728 return true;
6729 }
6730
6731 // Target is not a function.
6732
6733 if (isa<TagDecl>(Target)) {
6734 // No conflict between a tag and a non-tag.
6735 if (!Tag) return false;
6736
6737 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6738 Diag(Target->getLocation(), diag::note_using_decl_target);
6739 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6740 return true;
6741 }
6742
6743 // No conflict between a tag and a non-tag.
6744 if (!NonTag) return false;
6745
6746 Diag(Using->getLocation(), diag::err_using_decl_conflict);
6747 Diag(Target->getLocation(), diag::note_using_decl_target);
6748 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6749 return true;
6750 }
6751
6752 /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,UsingDecl * UD,NamedDecl * Orig)6753 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6754 UsingDecl *UD,
6755 NamedDecl *Orig) {
6756
6757 // If we resolved to another shadow declaration, just coalesce them.
6758 NamedDecl *Target = Orig;
6759 if (isa<UsingShadowDecl>(Target)) {
6760 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6761 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6762 }
6763
6764 UsingShadowDecl *Shadow
6765 = UsingShadowDecl::Create(Context, CurContext,
6766 UD->getLocation(), UD, Target);
6767 UD->addShadowDecl(Shadow);
6768
6769 Shadow->setAccess(UD->getAccess());
6770 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6771 Shadow->setInvalidDecl();
6772
6773 if (S)
6774 PushOnScopeChains(Shadow, S);
6775 else
6776 CurContext->addDecl(Shadow);
6777
6778
6779 return Shadow;
6780 }
6781
6782 /// Hides a using shadow declaration. This is required by the current
6783 /// using-decl implementation when a resolvable using declaration in a
6784 /// class is followed by a declaration which would hide or override
6785 /// one or more of the using decl's targets; for example:
6786 ///
6787 /// struct Base { void foo(int); };
6788 /// struct Derived : Base {
6789 /// using Base::foo;
6790 /// void foo(int);
6791 /// };
6792 ///
6793 /// The governing language is C++03 [namespace.udecl]p12:
6794 ///
6795 /// When a using-declaration brings names from a base class into a
6796 /// derived class scope, member functions in the derived class
6797 /// override and/or hide member functions with the same name and
6798 /// parameter types in a base class (rather than conflicting).
6799 ///
6800 /// There are two ways to implement this:
6801 /// (1) optimistically create shadow decls when they're not hidden
6802 /// by existing declarations, or
6803 /// (2) don't create any shadow decls (or at least don't make them
6804 /// visible) until we've fully parsed/instantiated the class.
6805 /// The problem with (1) is that we might have to retroactively remove
6806 /// a shadow decl, which requires several O(n) operations because the
6807 /// decl structures are (very reasonably) not designed for removal.
6808 /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)6809 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6810 if (Shadow->getDeclName().getNameKind() ==
6811 DeclarationName::CXXConversionFunctionName)
6812 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6813
6814 // Remove it from the DeclContext...
6815 Shadow->getDeclContext()->removeDecl(Shadow);
6816
6817 // ...and the scope, if applicable...
6818 if (S) {
6819 S->RemoveDecl(Shadow);
6820 IdResolver.RemoveDecl(Shadow);
6821 }
6822
6823 // ...and the using decl.
6824 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6825
6826 // TODO: complain somehow if Shadow was used. It shouldn't
6827 // be possible for this to happen, because...?
6828 }
6829
6830 /// Builds a using declaration.
6831 ///
6832 /// \param IsInstantiation - Whether this call arises from an
6833 /// instantiation of an unresolved using declaration. We treat
6834 /// the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,AttributeList * AttrList,bool IsInstantiation,bool IsTypeName,SourceLocation TypenameLoc)6835 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6836 SourceLocation UsingLoc,
6837 CXXScopeSpec &SS,
6838 const DeclarationNameInfo &NameInfo,
6839 AttributeList *AttrList,
6840 bool IsInstantiation,
6841 bool IsTypeName,
6842 SourceLocation TypenameLoc) {
6843 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6844 SourceLocation IdentLoc = NameInfo.getLoc();
6845 assert(IdentLoc.isValid() && "Invalid TargetName location.");
6846
6847 // FIXME: We ignore attributes for now.
6848
6849 if (SS.isEmpty()) {
6850 Diag(IdentLoc, diag::err_using_requires_qualname);
6851 return 0;
6852 }
6853
6854 // Do the redeclaration lookup in the current scope.
6855 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6856 ForRedeclaration);
6857 Previous.setHideTags(false);
6858 if (S) {
6859 LookupName(Previous, S);
6860
6861 // It is really dumb that we have to do this.
6862 LookupResult::Filter F = Previous.makeFilter();
6863 while (F.hasNext()) {
6864 NamedDecl *D = F.next();
6865 if (!isDeclInScope(D, CurContext, S))
6866 F.erase();
6867 }
6868 F.done();
6869 } else {
6870 assert(IsInstantiation && "no scope in non-instantiation");
6871 assert(CurContext->isRecord() && "scope not record in instantiation");
6872 LookupQualifiedName(Previous, CurContext);
6873 }
6874
6875 // Check for invalid redeclarations.
6876 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6877 return 0;
6878
6879 // Check for bad qualifiers.
6880 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6881 return 0;
6882
6883 DeclContext *LookupContext = computeDeclContext(SS);
6884 NamedDecl *D;
6885 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6886 if (!LookupContext) {
6887 if (IsTypeName) {
6888 // FIXME: not all declaration name kinds are legal here
6889 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6890 UsingLoc, TypenameLoc,
6891 QualifierLoc,
6892 IdentLoc, NameInfo.getName());
6893 } else {
6894 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6895 QualifierLoc, NameInfo);
6896 }
6897 } else {
6898 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6899 NameInfo, IsTypeName);
6900 }
6901 D->setAccess(AS);
6902 CurContext->addDecl(D);
6903
6904 if (!LookupContext) return D;
6905 UsingDecl *UD = cast<UsingDecl>(D);
6906
6907 if (RequireCompleteDeclContext(SS, LookupContext)) {
6908 UD->setInvalidDecl();
6909 return UD;
6910 }
6911
6912 // The normal rules do not apply to inheriting constructor declarations.
6913 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6914 if (CheckInheritingConstructorUsingDecl(UD))
6915 UD->setInvalidDecl();
6916 return UD;
6917 }
6918
6919 // Otherwise, look up the target name.
6920
6921 LookupResult R(*this, NameInfo, LookupOrdinaryName);
6922
6923 // Unlike most lookups, we don't always want to hide tag
6924 // declarations: tag names are visible through the using declaration
6925 // even if hidden by ordinary names, *except* in a dependent context
6926 // where it's important for the sanity of two-phase lookup.
6927 if (!IsInstantiation)
6928 R.setHideTags(false);
6929
6930 // For the purposes of this lookup, we have a base object type
6931 // equal to that of the current context.
6932 if (CurContext->isRecord()) {
6933 R.setBaseObjectType(
6934 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6935 }
6936
6937 LookupQualifiedName(R, LookupContext);
6938
6939 if (R.empty()) {
6940 Diag(IdentLoc, diag::err_no_member)
6941 << NameInfo.getName() << LookupContext << SS.getRange();
6942 UD->setInvalidDecl();
6943 return UD;
6944 }
6945
6946 if (R.isAmbiguous()) {
6947 UD->setInvalidDecl();
6948 return UD;
6949 }
6950
6951 if (IsTypeName) {
6952 // If we asked for a typename and got a non-type decl, error out.
6953 if (!R.getAsSingle<TypeDecl>()) {
6954 Diag(IdentLoc, diag::err_using_typename_non_type);
6955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6956 Diag((*I)->getUnderlyingDecl()->getLocation(),
6957 diag::note_using_decl_target);
6958 UD->setInvalidDecl();
6959 return UD;
6960 }
6961 } else {
6962 // If we asked for a non-typename and we got a type, error out,
6963 // but only if this is an instantiation of an unresolved using
6964 // decl. Otherwise just silently find the type name.
6965 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6966 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6967 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6968 UD->setInvalidDecl();
6969 return UD;
6970 }
6971 }
6972
6973 // C++0x N2914 [namespace.udecl]p6:
6974 // A using-declaration shall not name a namespace.
6975 if (R.getAsSingle<NamespaceDecl>()) {
6976 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6977 << SS.getRange();
6978 UD->setInvalidDecl();
6979 return UD;
6980 }
6981
6982 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6983 if (!CheckUsingShadowDecl(UD, *I, Previous))
6984 BuildUsingShadowDecl(S, UD, *I);
6985 }
6986
6987 return UD;
6988 }
6989
6990 /// Additional checks for a using declaration referring to a constructor name.
CheckInheritingConstructorUsingDecl(UsingDecl * UD)6991 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6992 assert(!UD->isTypeName() && "expecting a constructor name");
6993
6994 const Type *SourceType = UD->getQualifier()->getAsType();
6995 assert(SourceType &&
6996 "Using decl naming constructor doesn't have type in scope spec.");
6997 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6998
6999 // Check whether the named type is a direct base class.
7000 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7001 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7002 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7003 BaseIt != BaseE; ++BaseIt) {
7004 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7005 if (CanonicalSourceType == BaseType)
7006 break;
7007 if (BaseIt->getType()->isDependentType())
7008 break;
7009 }
7010
7011 if (BaseIt == BaseE) {
7012 // Did not find SourceType in the bases.
7013 Diag(UD->getUsingLocation(),
7014 diag::err_using_decl_constructor_not_in_direct_base)
7015 << UD->getNameInfo().getSourceRange()
7016 << QualType(SourceType, 0) << TargetClass;
7017 return true;
7018 }
7019
7020 if (!CurContext->isDependentContext())
7021 BaseIt->setInheritConstructors();
7022
7023 return false;
7024 }
7025
7026 /// Checks that the given using declaration is not an invalid
7027 /// redeclaration. Note that this is checking only for the using decl
7028 /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool isTypeName,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)7029 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7030 bool isTypeName,
7031 const CXXScopeSpec &SS,
7032 SourceLocation NameLoc,
7033 const LookupResult &Prev) {
7034 // C++03 [namespace.udecl]p8:
7035 // C++0x [namespace.udecl]p10:
7036 // A using-declaration is a declaration and can therefore be used
7037 // repeatedly where (and only where) multiple declarations are
7038 // allowed.
7039 //
7040 // That's in non-member contexts.
7041 if (!CurContext->getRedeclContext()->isRecord())
7042 return false;
7043
7044 NestedNameSpecifier *Qual
7045 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7046
7047 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7048 NamedDecl *D = *I;
7049
7050 bool DTypename;
7051 NestedNameSpecifier *DQual;
7052 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7053 DTypename = UD->isTypeName();
7054 DQual = UD->getQualifier();
7055 } else if (UnresolvedUsingValueDecl *UD
7056 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7057 DTypename = false;
7058 DQual = UD->getQualifier();
7059 } else if (UnresolvedUsingTypenameDecl *UD
7060 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7061 DTypename = true;
7062 DQual = UD->getQualifier();
7063 } else continue;
7064
7065 // using decls differ if one says 'typename' and the other doesn't.
7066 // FIXME: non-dependent using decls?
7067 if (isTypeName != DTypename) continue;
7068
7069 // using decls differ if they name different scopes (but note that
7070 // template instantiation can cause this check to trigger when it
7071 // didn't before instantiation).
7072 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7073 Context.getCanonicalNestedNameSpecifier(DQual))
7074 continue;
7075
7076 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7077 Diag(D->getLocation(), diag::note_using_decl) << 1;
7078 return true;
7079 }
7080
7081 return false;
7082 }
7083
7084
7085 /// Checks that the given nested-name qualifier used in a using decl
7086 /// in the current context is appropriately related to the current
7087 /// scope. If an error is found, diagnoses it and returns true.
CheckUsingDeclQualifier(SourceLocation UsingLoc,const CXXScopeSpec & SS,SourceLocation NameLoc)7088 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7089 const CXXScopeSpec &SS,
7090 SourceLocation NameLoc) {
7091 DeclContext *NamedContext = computeDeclContext(SS);
7092
7093 if (!CurContext->isRecord()) {
7094 // C++03 [namespace.udecl]p3:
7095 // C++0x [namespace.udecl]p8:
7096 // A using-declaration for a class member shall be a member-declaration.
7097
7098 // If we weren't able to compute a valid scope, it must be a
7099 // dependent class scope.
7100 if (!NamedContext || NamedContext->isRecord()) {
7101 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7102 << SS.getRange();
7103 return true;
7104 }
7105
7106 // Otherwise, everything is known to be fine.
7107 return false;
7108 }
7109
7110 // The current scope is a record.
7111
7112 // If the named context is dependent, we can't decide much.
7113 if (!NamedContext) {
7114 // FIXME: in C++0x, we can diagnose if we can prove that the
7115 // nested-name-specifier does not refer to a base class, which is
7116 // still possible in some cases.
7117
7118 // Otherwise we have to conservatively report that things might be
7119 // okay.
7120 return false;
7121 }
7122
7123 if (!NamedContext->isRecord()) {
7124 // Ideally this would point at the last name in the specifier,
7125 // but we don't have that level of source info.
7126 Diag(SS.getRange().getBegin(),
7127 diag::err_using_decl_nested_name_specifier_is_not_class)
7128 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7129 return true;
7130 }
7131
7132 if (!NamedContext->isDependentContext() &&
7133 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7134 return true;
7135
7136 if (getLangOpts().CPlusPlus11) {
7137 // C++0x [namespace.udecl]p3:
7138 // In a using-declaration used as a member-declaration, the
7139 // nested-name-specifier shall name a base class of the class
7140 // being defined.
7141
7142 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7143 cast<CXXRecordDecl>(NamedContext))) {
7144 if (CurContext == NamedContext) {
7145 Diag(NameLoc,
7146 diag::err_using_decl_nested_name_specifier_is_current_class)
7147 << SS.getRange();
7148 return true;
7149 }
7150
7151 Diag(SS.getRange().getBegin(),
7152 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7153 << (NestedNameSpecifier*) SS.getScopeRep()
7154 << cast<CXXRecordDecl>(CurContext)
7155 << SS.getRange();
7156 return true;
7157 }
7158
7159 return false;
7160 }
7161
7162 // C++03 [namespace.udecl]p4:
7163 // A using-declaration used as a member-declaration shall refer
7164 // to a member of a base class of the class being defined [etc.].
7165
7166 // Salient point: SS doesn't have to name a base class as long as
7167 // lookup only finds members from base classes. Therefore we can
7168 // diagnose here only if we can prove that that can't happen,
7169 // i.e. if the class hierarchies provably don't intersect.
7170
7171 // TODO: it would be nice if "definitely valid" results were cached
7172 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7173 // need to be repeated.
7174
7175 struct UserData {
7176 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7177
7178 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7179 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7180 Data->Bases.insert(Base);
7181 return true;
7182 }
7183
7184 bool hasDependentBases(const CXXRecordDecl *Class) {
7185 return !Class->forallBases(collect, this);
7186 }
7187
7188 /// Returns true if the base is dependent or is one of the
7189 /// accumulated base classes.
7190 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7191 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7192 return !Data->Bases.count(Base);
7193 }
7194
7195 bool mightShareBases(const CXXRecordDecl *Class) {
7196 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7197 }
7198 };
7199
7200 UserData Data;
7201
7202 // Returns false if we find a dependent base.
7203 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7204 return false;
7205
7206 // Returns false if the class has a dependent base or if it or one
7207 // of its bases is present in the base set of the current context.
7208 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7209 return false;
7210
7211 Diag(SS.getRange().getBegin(),
7212 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7213 << (NestedNameSpecifier*) SS.getScopeRep()
7214 << cast<CXXRecordDecl>(CurContext)
7215 << SS.getRange();
7216
7217 return true;
7218 }
7219
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,AttributeList * AttrList,TypeResult Type)7220 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7221 AccessSpecifier AS,
7222 MultiTemplateParamsArg TemplateParamLists,
7223 SourceLocation UsingLoc,
7224 UnqualifiedId &Name,
7225 AttributeList *AttrList,
7226 TypeResult Type) {
7227 // Skip up to the relevant declaration scope.
7228 while (S->getFlags() & Scope::TemplateParamScope)
7229 S = S->getParent();
7230 assert((S->getFlags() & Scope::DeclScope) &&
7231 "got alias-declaration outside of declaration scope");
7232
7233 if (Type.isInvalid())
7234 return 0;
7235
7236 bool Invalid = false;
7237 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7238 TypeSourceInfo *TInfo = 0;
7239 GetTypeFromParser(Type.get(), &TInfo);
7240
7241 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7242 return 0;
7243
7244 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7245 UPPC_DeclarationType)) {
7246 Invalid = true;
7247 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7248 TInfo->getTypeLoc().getBeginLoc());
7249 }
7250
7251 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7252 LookupName(Previous, S);
7253
7254 // Warn about shadowing the name of a template parameter.
7255 if (Previous.isSingleResult() &&
7256 Previous.getFoundDecl()->isTemplateParameter()) {
7257 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7258 Previous.clear();
7259 }
7260
7261 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7262 "name in alias declaration must be an identifier");
7263 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7264 Name.StartLocation,
7265 Name.Identifier, TInfo);
7266
7267 NewTD->setAccess(AS);
7268
7269 if (Invalid)
7270 NewTD->setInvalidDecl();
7271
7272 ProcessDeclAttributeList(S, NewTD, AttrList);
7273
7274 CheckTypedefForVariablyModifiedType(S, NewTD);
7275 Invalid |= NewTD->isInvalidDecl();
7276
7277 bool Redeclaration = false;
7278
7279 NamedDecl *NewND;
7280 if (TemplateParamLists.size()) {
7281 TypeAliasTemplateDecl *OldDecl = 0;
7282 TemplateParameterList *OldTemplateParams = 0;
7283
7284 if (TemplateParamLists.size() != 1) {
7285 Diag(UsingLoc, diag::err_alias_template_extra_headers)
7286 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7287 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7288 }
7289 TemplateParameterList *TemplateParams = TemplateParamLists[0];
7290
7291 // Only consider previous declarations in the same scope.
7292 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7293 /*ExplicitInstantiationOrSpecialization*/false);
7294 if (!Previous.empty()) {
7295 Redeclaration = true;
7296
7297 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7298 if (!OldDecl && !Invalid) {
7299 Diag(UsingLoc, diag::err_redefinition_different_kind)
7300 << Name.Identifier;
7301
7302 NamedDecl *OldD = Previous.getRepresentativeDecl();
7303 if (OldD->getLocation().isValid())
7304 Diag(OldD->getLocation(), diag::note_previous_definition);
7305
7306 Invalid = true;
7307 }
7308
7309 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7310 if (TemplateParameterListsAreEqual(TemplateParams,
7311 OldDecl->getTemplateParameters(),
7312 /*Complain=*/true,
7313 TPL_TemplateMatch))
7314 OldTemplateParams = OldDecl->getTemplateParameters();
7315 else
7316 Invalid = true;
7317
7318 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7319 if (!Invalid &&
7320 !Context.hasSameType(OldTD->getUnderlyingType(),
7321 NewTD->getUnderlyingType())) {
7322 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7323 // but we can't reasonably accept it.
7324 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7325 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7326 if (OldTD->getLocation().isValid())
7327 Diag(OldTD->getLocation(), diag::note_previous_definition);
7328 Invalid = true;
7329 }
7330 }
7331 }
7332
7333 // Merge any previous default template arguments into our parameters,
7334 // and check the parameter list.
7335 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7336 TPC_TypeAliasTemplate))
7337 return 0;
7338
7339 TypeAliasTemplateDecl *NewDecl =
7340 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7341 Name.Identifier, TemplateParams,
7342 NewTD);
7343
7344 NewDecl->setAccess(AS);
7345
7346 if (Invalid)
7347 NewDecl->setInvalidDecl();
7348 else if (OldDecl)
7349 NewDecl->setPreviousDeclaration(OldDecl);
7350
7351 NewND = NewDecl;
7352 } else {
7353 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7354 NewND = NewTD;
7355 }
7356
7357 if (!Redeclaration)
7358 PushOnScopeChains(NewND, S);
7359
7360 ActOnDocumentableDecl(NewND);
7361 return NewND;
7362 }
7363
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)7364 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7365 SourceLocation NamespaceLoc,
7366 SourceLocation AliasLoc,
7367 IdentifierInfo *Alias,
7368 CXXScopeSpec &SS,
7369 SourceLocation IdentLoc,
7370 IdentifierInfo *Ident) {
7371
7372 // Lookup the namespace name.
7373 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7374 LookupParsedName(R, S, &SS);
7375
7376 // Check if we have a previous declaration with the same name.
7377 NamedDecl *PrevDecl
7378 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7379 ForRedeclaration);
7380 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7381 PrevDecl = 0;
7382
7383 if (PrevDecl) {
7384 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7385 // We already have an alias with the same name that points to the same
7386 // namespace, so don't create a new one.
7387 // FIXME: At some point, we'll want to create the (redundant)
7388 // declaration to maintain better source information.
7389 if (!R.isAmbiguous() && !R.empty() &&
7390 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7391 return 0;
7392 }
7393
7394 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7395 diag::err_redefinition_different_kind;
7396 Diag(AliasLoc, DiagID) << Alias;
7397 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7398 return 0;
7399 }
7400
7401 if (R.isAmbiguous())
7402 return 0;
7403
7404 if (R.empty()) {
7405 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7406 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7407 return 0;
7408 }
7409 }
7410
7411 NamespaceAliasDecl *AliasDecl =
7412 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7413 Alias, SS.getWithLocInContext(Context),
7414 IdentLoc, R.getFoundDecl());
7415
7416 PushOnScopeChains(AliasDecl, S);
7417 return AliasDecl;
7418 }
7419
7420 Sema::ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)7421 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7422 CXXMethodDecl *MD) {
7423 CXXRecordDecl *ClassDecl = MD->getParent();
7424
7425 // C++ [except.spec]p14:
7426 // An implicitly declared special member function (Clause 12) shall have an
7427 // exception-specification. [...]
7428 ImplicitExceptionSpecification ExceptSpec(*this);
7429 if (ClassDecl->isInvalidDecl())
7430 return ExceptSpec;
7431
7432 // Direct base-class constructors.
7433 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7434 BEnd = ClassDecl->bases_end();
7435 B != BEnd; ++B) {
7436 if (B->isVirtual()) // Handled below.
7437 continue;
7438
7439 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7440 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7441 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7442 // If this is a deleted function, add it anyway. This might be conformant
7443 // with the standard. This might not. I'm not sure. It might not matter.
7444 if (Constructor)
7445 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7446 }
7447 }
7448
7449 // Virtual base-class constructors.
7450 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7451 BEnd = ClassDecl->vbases_end();
7452 B != BEnd; ++B) {
7453 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7454 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7455 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7456 // If this is a deleted function, add it anyway. This might be conformant
7457 // with the standard. This might not. I'm not sure. It might not matter.
7458 if (Constructor)
7459 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7460 }
7461 }
7462
7463 // Field constructors.
7464 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7465 FEnd = ClassDecl->field_end();
7466 F != FEnd; ++F) {
7467 if (F->hasInClassInitializer()) {
7468 if (Expr *E = F->getInClassInitializer())
7469 ExceptSpec.CalledExpr(E);
7470 else if (!F->isInvalidDecl())
7471 // DR1351:
7472 // If the brace-or-equal-initializer of a non-static data member
7473 // invokes a defaulted default constructor of its class or of an
7474 // enclosing class in a potentially evaluated subexpression, the
7475 // program is ill-formed.
7476 //
7477 // This resolution is unworkable: the exception specification of the
7478 // default constructor can be needed in an unevaluated context, in
7479 // particular, in the operand of a noexcept-expression, and we can be
7480 // unable to compute an exception specification for an enclosed class.
7481 //
7482 // We do not allow an in-class initializer to require the evaluation
7483 // of the exception specification for any in-class initializer whose
7484 // definition is not lexically complete.
7485 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7486 } else if (const RecordType *RecordTy
7487 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7488 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7489 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7490 // If this is a deleted function, add it anyway. This might be conformant
7491 // with the standard. This might not. I'm not sure. It might not matter.
7492 // In particular, the problem is that this function never gets called. It
7493 // might just be ill-formed because this function attempts to refer to
7494 // a deleted function here.
7495 if (Constructor)
7496 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7497 }
7498 }
7499
7500 return ExceptSpec;
7501 }
7502
7503 Sema::ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(CXXMethodDecl * MD)7504 Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) {
7505 ImplicitExceptionSpecification ExceptSpec(*this);
7506 // FIXME: Compute the exception spec.
7507 return ExceptSpec;
7508 }
7509
7510 namespace {
7511 /// RAII object to register a special member as being currently declared.
7512 struct DeclaringSpecialMember {
7513 Sema &S;
7514 Sema::SpecialMemberDecl D;
7515 bool WasAlreadyBeingDeclared;
7516
DeclaringSpecialMember__anon53c188c80a11::DeclaringSpecialMember7517 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7518 : S(S), D(RD, CSM) {
7519 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7520 if (WasAlreadyBeingDeclared)
7521 // This almost never happens, but if it does, ensure that our cache
7522 // doesn't contain a stale result.
7523 S.SpecialMemberCache.clear();
7524
7525 // FIXME: Register a note to be produced if we encounter an error while
7526 // declaring the special member.
7527 }
~DeclaringSpecialMember__anon53c188c80a11::DeclaringSpecialMember7528 ~DeclaringSpecialMember() {
7529 if (!WasAlreadyBeingDeclared)
7530 S.SpecialMembersBeingDeclared.erase(D);
7531 }
7532
7533 /// \brief Are we already trying to declare this special member?
isAlreadyBeingDeclared__anon53c188c80a11::DeclaringSpecialMember7534 bool isAlreadyBeingDeclared() const {
7535 return WasAlreadyBeingDeclared;
7536 }
7537 };
7538 }
7539
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)7540 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7541 CXXRecordDecl *ClassDecl) {
7542 // C++ [class.ctor]p5:
7543 // A default constructor for a class X is a constructor of class X
7544 // that can be called without an argument. If there is no
7545 // user-declared constructor for class X, a default constructor is
7546 // implicitly declared. An implicitly-declared default constructor
7547 // is an inline public member of its class.
7548 assert(ClassDecl->needsImplicitDefaultConstructor() &&
7549 "Should not build implicit default constructor!");
7550
7551 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7552 if (DSM.isAlreadyBeingDeclared())
7553 return 0;
7554
7555 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7556 CXXDefaultConstructor,
7557 false);
7558
7559 // Create the actual constructor declaration.
7560 CanQualType ClassType
7561 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7562 SourceLocation ClassLoc = ClassDecl->getLocation();
7563 DeclarationName Name
7564 = Context.DeclarationNames.getCXXConstructorName(ClassType);
7565 DeclarationNameInfo NameInfo(Name, ClassLoc);
7566 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7567 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7568 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7569 Constexpr);
7570 DefaultCon->setAccess(AS_public);
7571 DefaultCon->setDefaulted();
7572 DefaultCon->setImplicit();
7573
7574 // Build an exception specification pointing back at this constructor.
7575 FunctionProtoType::ExtProtoInfo EPI;
7576 EPI.ExceptionSpecType = EST_Unevaluated;
7577 EPI.ExceptionSpecDecl = DefaultCon;
7578 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7579 ArrayRef<QualType>(),
7580 EPI));
7581
7582 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7583 // constructors is easy to compute.
7584 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7585
7586 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7587 DefaultCon->setDeletedAsWritten();
7588
7589 // Note that we have declared this constructor.
7590 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7591
7592 if (Scope *S = getScopeForContext(ClassDecl))
7593 PushOnScopeChains(DefaultCon, S, false);
7594 ClassDecl->addDecl(DefaultCon);
7595
7596 return DefaultCon;
7597 }
7598
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)7599 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7600 CXXConstructorDecl *Constructor) {
7601 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7602 !Constructor->doesThisDeclarationHaveABody() &&
7603 !Constructor->isDeleted()) &&
7604 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7605
7606 CXXRecordDecl *ClassDecl = Constructor->getParent();
7607 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7608
7609 SynthesizedFunctionScope Scope(*this, Constructor);
7610 DiagnosticErrorTrap Trap(Diags);
7611 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7612 Trap.hasErrorOccurred()) {
7613 Diag(CurrentLocation, diag::note_member_synthesized_at)
7614 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7615 Constructor->setInvalidDecl();
7616 return;
7617 }
7618
7619 SourceLocation Loc = Constructor->getLocation();
7620 Constructor->setBody(new (Context) CompoundStmt(Loc));
7621
7622 Constructor->setUsed();
7623 MarkVTableUsed(CurrentLocation, ClassDecl);
7624
7625 if (ASTMutationListener *L = getASTMutationListener()) {
7626 L->CompletedImplicitDefinition(Constructor);
7627 }
7628 }
7629
ActOnFinishDelayedMemberInitializers(Decl * D)7630 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7631 // Check that any explicitly-defaulted methods have exception specifications
7632 // compatible with their implicit exception specifications.
7633 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7634 }
7635
DeclareInheritingConstructors(CXXRecordDecl * ClassDecl)7636 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
7637 // We start with an initial pass over the base classes to collect those that
7638 // inherit constructors from. If there are none, we can forgo all further
7639 // processing.
7640 typedef SmallVector<const RecordType *, 4> BasesVector;
7641 BasesVector BasesToInheritFrom;
7642 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7643 BaseE = ClassDecl->bases_end();
7644 BaseIt != BaseE; ++BaseIt) {
7645 if (BaseIt->getInheritConstructors()) {
7646 QualType Base = BaseIt->getType();
7647 if (Base->isDependentType()) {
7648 // If we inherit constructors from anything that is dependent, just
7649 // abort processing altogether. We'll get another chance for the
7650 // instantiations.
7651 // FIXME: We need to ensure that any call to a constructor of this class
7652 // is considered instantiation-dependent in this case.
7653 return;
7654 }
7655 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7656 }
7657 }
7658 if (BasesToInheritFrom.empty())
7659 return;
7660
7661 // FIXME: Constructor templates.
7662
7663 // Now collect the constructors that we already have in the current class.
7664 // Those take precedence over inherited constructors.
7665 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7666 // unless there is a user-declared constructor with the same signature in
7667 // the class where the using-declaration appears.
7668 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7669 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7670 CtorE = ClassDecl->ctor_end();
7671 CtorIt != CtorE; ++CtorIt)
7672 ExistingConstructors.insert(
7673 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7674
7675 DeclarationName CreatedCtorName =
7676 Context.DeclarationNames.getCXXConstructorName(
7677 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7678
7679 // Now comes the true work.
7680 // First, we keep a map from constructor types to the base that introduced
7681 // them. Needed for finding conflicting constructors. We also keep the
7682 // actually inserted declarations in there, for pretty diagnostics.
7683 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7684 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7685 ConstructorToSourceMap InheritedConstructors;
7686 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7687 BaseE = BasesToInheritFrom.end();
7688 BaseIt != BaseE; ++BaseIt) {
7689 const RecordType *Base = *BaseIt;
7690 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7691 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7692 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7693 CtorE = BaseDecl->ctor_end();
7694 CtorIt != CtorE; ++CtorIt) {
7695 // Find the using declaration for inheriting this base's constructors.
7696 // FIXME: Don't perform name lookup just to obtain a source location!
7697 DeclarationName Name =
7698 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7699 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7700 LookupQualifiedName(Result, CurContext);
7701 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7702 SourceLocation UsingLoc = UD ? UD->getLocation() :
7703 ClassDecl->getLocation();
7704
7705 // C++11 [class.inhctor]p1:
7706 // The candidate set of inherited constructors from the class X named in
7707 // the using-declaration consists of actual constructors and notional
7708 // constructors that result from the transformation of defaulted
7709 // parameters as follows:
7710 // - all non-template constructors of X, and
7711 // - for each non-template constructor of X that has at least one
7712 // parameter with a default argument, the set of constructors that
7713 // results from omitting any ellipsis parameter specification and
7714 // successively omitting parameters with a default argument from the
7715 // end of the parameter-type-list, and
7716 // FIXME: ...also constructor templates.
7717 CXXConstructorDecl *BaseCtor = *CtorIt;
7718 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7719 const FunctionProtoType *BaseCtorType =
7720 BaseCtor->getType()->getAs<FunctionProtoType>();
7721
7722 // Determine whether this would be a copy or move constructor for the
7723 // derived class.
7724 if (BaseCtorType->getNumArgs() >= 1 &&
7725 BaseCtorType->getArgType(0)->isReferenceType() &&
7726 Context.hasSameUnqualifiedType(
7727 BaseCtorType->getArgType(0)->getPointeeType(),
7728 Context.getTagDeclType(ClassDecl)))
7729 CanBeCopyOrMove = true;
7730
7731 ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes());
7732 FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo();
7733 // Core issue (no number yet): the ellipsis is always discarded.
7734 if (EPI.Variadic) {
7735 Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7736 Diag(BaseCtor->getLocation(),
7737 diag::note_using_decl_constructor_ellipsis);
7738 EPI.Variadic = false;
7739 }
7740
7741 for (unsigned Params = BaseCtor->getMinRequiredArguments(),
7742 MaxParams = BaseCtor->getNumParams();
7743 Params <= MaxParams; ++Params) {
7744 // Skip default constructors. They're never inherited.
7745 if (Params == 0)
7746 continue;
7747
7748 // Skip copy and move constructors for both base and derived class
7749 // for the same reason.
7750 if (CanBeCopyOrMove && Params == 1)
7751 continue;
7752
7753 // Build up a function type for this particular constructor.
7754 QualType NewCtorType =
7755 Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params),
7756 EPI);
7757 const Type *CanonicalNewCtorType =
7758 Context.getCanonicalType(NewCtorType).getTypePtr();
7759
7760 // C++11 [class.inhctor]p3:
7761 // ... a constructor is implicitly declared with the same constructor
7762 // characteristics unless there is a user-declared constructor with
7763 // the same signature in the class where the using-declaration appears
7764 if (ExistingConstructors.count(CanonicalNewCtorType))
7765 continue;
7766
7767 // C++11 [class.inhctor]p7:
7768 // If two using-declarations declare inheriting constructors with the
7769 // same signature, the program is ill-formed
7770 std::pair<ConstructorToSourceMap::iterator, bool> result =
7771 InheritedConstructors.insert(std::make_pair(
7772 CanonicalNewCtorType,
7773 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7774 if (!result.second) {
7775 // Already in the map. If it came from a different class, that's an
7776 // error. Not if it's from the same.
7777 CanQualType PreviousBase = result.first->second.first;
7778 if (CanonicalBase != PreviousBase) {
7779 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7780 const CXXConstructorDecl *PrevBaseCtor =
7781 PrevCtor->getInheritedConstructor();
7782 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7783
7784 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7785 Diag(BaseCtor->getLocation(),
7786 diag::note_using_decl_constructor_conflict_current_ctor);
7787 Diag(PrevBaseCtor->getLocation(),
7788 diag::note_using_decl_constructor_conflict_previous_ctor);
7789 Diag(PrevCtor->getLocation(),
7790 diag::note_using_decl_constructor_conflict_previous_using);
7791 } else {
7792 // Core issue (no number): if the same inheriting constructor is
7793 // produced by multiple base class constructors from the same base
7794 // class, the inheriting constructor is defined as deleted.
7795 result.first->second.second->setDeletedAsWritten();
7796 }
7797 continue;
7798 }
7799
7800 // OK, we're there, now add the constructor.
7801 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7802 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7803 Context, ClassDecl, UsingLoc, DNI, NewCtorType,
7804 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7805 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7806 NewCtor->setAccess(BaseCtor->getAccess());
7807
7808 // Build an unevaluated exception specification for this constructor.
7809 EPI.ExceptionSpecType = EST_Unevaluated;
7810 EPI.ExceptionSpecDecl = NewCtor;
7811 NewCtor->setType(Context.getFunctionType(Context.VoidTy,
7812 ArgTypes.slice(0, Params),
7813 EPI));
7814
7815 // Build up the parameter decls and add them.
7816 SmallVector<ParmVarDecl *, 16> ParamDecls;
7817 for (unsigned i = 0; i < Params; ++i) {
7818 ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor,
7819 UsingLoc, UsingLoc,
7820 /*IdentifierInfo=*/0,
7821 BaseCtorType->getArgType(i),
7822 /*TInfo=*/0, SC_None,
7823 SC_None, /*DefaultArg=*/0);
7824 PD->setScopeInfo(0, i);
7825 PD->setImplicit();
7826 ParamDecls.push_back(PD);
7827 }
7828 NewCtor->setParams(ParamDecls);
7829 NewCtor->setInheritedConstructor(BaseCtor);
7830 if (BaseCtor->isDeleted())
7831 NewCtor->setDeletedAsWritten();
7832
7833 ClassDecl->addDecl(NewCtor);
7834 result.first->second.second = NewCtor;
7835 }
7836 }
7837 }
7838 }
7839
DefineInheritingConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)7840 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
7841 CXXConstructorDecl *Constructor) {
7842 CXXRecordDecl *ClassDecl = Constructor->getParent();
7843 assert(Constructor->getInheritedConstructor() &&
7844 !Constructor->doesThisDeclarationHaveABody() &&
7845 !Constructor->isDeleted());
7846
7847 SynthesizedFunctionScope Scope(*this, Constructor);
7848 DiagnosticErrorTrap Trap(Diags);
7849 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7850 Trap.hasErrorOccurred()) {
7851 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
7852 << Context.getTagDeclType(ClassDecl);
7853 Constructor->setInvalidDecl();
7854 return;
7855 }
7856
7857 SourceLocation Loc = Constructor->getLocation();
7858 Constructor->setBody(new (Context) CompoundStmt(Loc));
7859
7860 Constructor->setUsed();
7861 MarkVTableUsed(CurrentLocation, ClassDecl);
7862
7863 if (ASTMutationListener *L = getASTMutationListener()) {
7864 L->CompletedImplicitDefinition(Constructor);
7865 }
7866 }
7867
7868
7869 Sema::ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl * MD)7870 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7871 CXXRecordDecl *ClassDecl = MD->getParent();
7872
7873 // C++ [except.spec]p14:
7874 // An implicitly declared special member function (Clause 12) shall have
7875 // an exception-specification.
7876 ImplicitExceptionSpecification ExceptSpec(*this);
7877 if (ClassDecl->isInvalidDecl())
7878 return ExceptSpec;
7879
7880 // Direct base-class destructors.
7881 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7882 BEnd = ClassDecl->bases_end();
7883 B != BEnd; ++B) {
7884 if (B->isVirtual()) // Handled below.
7885 continue;
7886
7887 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7888 ExceptSpec.CalledDecl(B->getLocStart(),
7889 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7890 }
7891
7892 // Virtual base-class destructors.
7893 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7894 BEnd = ClassDecl->vbases_end();
7895 B != BEnd; ++B) {
7896 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7897 ExceptSpec.CalledDecl(B->getLocStart(),
7898 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7899 }
7900
7901 // Field destructors.
7902 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7903 FEnd = ClassDecl->field_end();
7904 F != FEnd; ++F) {
7905 if (const RecordType *RecordTy
7906 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7907 ExceptSpec.CalledDecl(F->getLocation(),
7908 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7909 }
7910
7911 return ExceptSpec;
7912 }
7913
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)7914 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7915 // C++ [class.dtor]p2:
7916 // If a class has no user-declared destructor, a destructor is
7917 // declared implicitly. An implicitly-declared destructor is an
7918 // inline public member of its class.
7919 assert(ClassDecl->needsImplicitDestructor());
7920
7921 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7922 if (DSM.isAlreadyBeingDeclared())
7923 return 0;
7924
7925 // Create the actual destructor declaration.
7926 CanQualType ClassType
7927 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7928 SourceLocation ClassLoc = ClassDecl->getLocation();
7929 DeclarationName Name
7930 = Context.DeclarationNames.getCXXDestructorName(ClassType);
7931 DeclarationNameInfo NameInfo(Name, ClassLoc);
7932 CXXDestructorDecl *Destructor
7933 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7934 QualType(), 0, /*isInline=*/true,
7935 /*isImplicitlyDeclared=*/true);
7936 Destructor->setAccess(AS_public);
7937 Destructor->setDefaulted();
7938 Destructor->setImplicit();
7939
7940 // Build an exception specification pointing back at this destructor.
7941 FunctionProtoType::ExtProtoInfo EPI;
7942 EPI.ExceptionSpecType = EST_Unevaluated;
7943 EPI.ExceptionSpecDecl = Destructor;
7944 Destructor->setType(Context.getFunctionType(Context.VoidTy,
7945 ArrayRef<QualType>(),
7946 EPI));
7947
7948 AddOverriddenMethods(ClassDecl, Destructor);
7949
7950 // We don't need to use SpecialMemberIsTrivial here; triviality for
7951 // destructors is easy to compute.
7952 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7953
7954 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7955 Destructor->setDeletedAsWritten();
7956
7957 // Note that we have declared this destructor.
7958 ++ASTContext::NumImplicitDestructorsDeclared;
7959
7960 // Introduce this destructor into its scope.
7961 if (Scope *S = getScopeForContext(ClassDecl))
7962 PushOnScopeChains(Destructor, S, false);
7963 ClassDecl->addDecl(Destructor);
7964
7965 return Destructor;
7966 }
7967
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)7968 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7969 CXXDestructorDecl *Destructor) {
7970 assert((Destructor->isDefaulted() &&
7971 !Destructor->doesThisDeclarationHaveABody() &&
7972 !Destructor->isDeleted()) &&
7973 "DefineImplicitDestructor - call it for implicit default dtor");
7974 CXXRecordDecl *ClassDecl = Destructor->getParent();
7975 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7976
7977 if (Destructor->isInvalidDecl())
7978 return;
7979
7980 SynthesizedFunctionScope Scope(*this, Destructor);
7981
7982 DiagnosticErrorTrap Trap(Diags);
7983 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7984 Destructor->getParent());
7985
7986 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7987 Diag(CurrentLocation, diag::note_member_synthesized_at)
7988 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7989
7990 Destructor->setInvalidDecl();
7991 return;
7992 }
7993
7994 SourceLocation Loc = Destructor->getLocation();
7995 Destructor->setBody(new (Context) CompoundStmt(Loc));
7996 Destructor->setImplicitlyDefined(true);
7997 Destructor->setUsed();
7998 MarkVTableUsed(CurrentLocation, ClassDecl);
7999
8000 if (ASTMutationListener *L = getASTMutationListener()) {
8001 L->CompletedImplicitDefinition(Destructor);
8002 }
8003 }
8004
8005 /// \brief Perform any semantic analysis which needs to be delayed until all
8006 /// pending class member declarations have been parsed.
ActOnFinishCXXMemberDecls()8007 void Sema::ActOnFinishCXXMemberDecls() {
8008 // If the context is an invalid C++ class, just suppress these checks.
8009 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8010 if (Record->isInvalidDecl()) {
8011 DelayedDestructorExceptionSpecChecks.clear();
8012 return;
8013 }
8014 }
8015
8016 // Perform any deferred checking of exception specifications for virtual
8017 // destructors.
8018 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8019 i != e; ++i) {
8020 const CXXDestructorDecl *Dtor =
8021 DelayedDestructorExceptionSpecChecks[i].first;
8022 assert(!Dtor->getParent()->isDependentType() &&
8023 "Should not ever add destructors of templates into the list.");
8024 CheckOverridingFunctionExceptionSpec(Dtor,
8025 DelayedDestructorExceptionSpecChecks[i].second);
8026 }
8027 DelayedDestructorExceptionSpecChecks.clear();
8028 }
8029
AdjustDestructorExceptionSpec(CXXRecordDecl * ClassDecl,CXXDestructorDecl * Destructor)8030 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8031 CXXDestructorDecl *Destructor) {
8032 assert(getLangOpts().CPlusPlus11 &&
8033 "adjusting dtor exception specs was introduced in c++11");
8034
8035 // C++11 [class.dtor]p3:
8036 // A declaration of a destructor that does not have an exception-
8037 // specification is implicitly considered to have the same exception-
8038 // specification as an implicit declaration.
8039 const FunctionProtoType *DtorType = Destructor->getType()->
8040 getAs<FunctionProtoType>();
8041 if (DtorType->hasExceptionSpec())
8042 return;
8043
8044 // Replace the destructor's type, building off the existing one. Fortunately,
8045 // the only thing of interest in the destructor type is its extended info.
8046 // The return and arguments are fixed.
8047 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8048 EPI.ExceptionSpecType = EST_Unevaluated;
8049 EPI.ExceptionSpecDecl = Destructor;
8050 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8051 ArrayRef<QualType>(),
8052 EPI));
8053
8054 // FIXME: If the destructor has a body that could throw, and the newly created
8055 // spec doesn't allow exceptions, we should emit a warning, because this
8056 // change in behavior can break conforming C++03 programs at runtime.
8057 // However, we don't have a body or an exception specification yet, so it
8058 // needs to be done somewhere else.
8059 }
8060
8061 /// When generating a defaulted copy or move assignment operator, if a field
8062 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8063 /// do so. This optimization only applies for arrays of scalars, and for arrays
8064 /// of class type where the selected copy/move-assignment operator is trivial.
8065 static StmtResult
buildMemcpyForAssignmentOp(Sema & S,SourceLocation Loc,QualType T,Expr * To,Expr * From)8066 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8067 Expr *To, Expr *From) {
8068 // Compute the size of the memory buffer to be copied.
8069 QualType SizeType = S.Context.getSizeType();
8070 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8071 S.Context.getTypeSizeInChars(T).getQuantity());
8072
8073 // Take the address of the field references for "from" and "to". We
8074 // directly construct UnaryOperators here because semantic analysis
8075 // does not permit us to take the address of an xvalue.
8076 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8077 S.Context.getPointerType(From->getType()),
8078 VK_RValue, OK_Ordinary, Loc);
8079 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8080 S.Context.getPointerType(To->getType()),
8081 VK_RValue, OK_Ordinary, Loc);
8082
8083 const Type *E = T->getBaseElementTypeUnsafe();
8084 bool NeedsCollectableMemCpy =
8085 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8086
8087 // Create a reference to the __builtin_objc_memmove_collectable function
8088 StringRef MemCpyName = NeedsCollectableMemCpy ?
8089 "__builtin_objc_memmove_collectable" :
8090 "__builtin_memcpy";
8091 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8092 Sema::LookupOrdinaryName);
8093 S.LookupName(R, S.TUScope, true);
8094
8095 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8096 if (!MemCpy)
8097 // Something went horribly wrong earlier, and we will have complained
8098 // about it.
8099 return StmtError();
8100
8101 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8102 VK_RValue, Loc, 0);
8103 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8104
8105 Expr *CallArgs[] = {
8106 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8107 };
8108 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8109 Loc, CallArgs, Loc);
8110
8111 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8112 return S.Owned(Call.takeAs<Stmt>());
8113 }
8114
8115 /// \brief Builds a statement that copies/moves the given entity from \p From to
8116 /// \c To.
8117 ///
8118 /// This routine is used to copy/move the members of a class with an
8119 /// implicitly-declared copy/move assignment operator. When the entities being
8120 /// copied are arrays, this routine builds for loops to copy them.
8121 ///
8122 /// \param S The Sema object used for type-checking.
8123 ///
8124 /// \param Loc The location where the implicit copy/move is being generated.
8125 ///
8126 /// \param T The type of the expressions being copied/moved. Both expressions
8127 /// must have this type.
8128 ///
8129 /// \param To The expression we are copying/moving to.
8130 ///
8131 /// \param From The expression we are copying/moving from.
8132 ///
8133 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8134 /// Otherwise, it's a non-static member subobject.
8135 ///
8136 /// \param Copying Whether we're copying or moving.
8137 ///
8138 /// \param Depth Internal parameter recording the depth of the recursion.
8139 ///
8140 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8141 /// if a memcpy should be used instead.
8142 static StmtResult
buildSingleCopyAssignRecursively(Sema & S,SourceLocation Loc,QualType T,Expr * To,Expr * From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)8143 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8144 Expr *To, Expr *From,
8145 bool CopyingBaseSubobject, bool Copying,
8146 unsigned Depth = 0) {
8147 // C++11 [class.copy]p28:
8148 // Each subobject is assigned in the manner appropriate to its type:
8149 //
8150 // - if the subobject is of class type, as if by a call to operator= with
8151 // the subobject as the object expression and the corresponding
8152 // subobject of x as a single function argument (as if by explicit
8153 // qualification; that is, ignoring any possible virtual overriding
8154 // functions in more derived classes);
8155 //
8156 // C++03 [class.copy]p13:
8157 // - if the subobject is of class type, the copy assignment operator for
8158 // the class is used (as if by explicit qualification; that is,
8159 // ignoring any possible virtual overriding functions in more derived
8160 // classes);
8161 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8162 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8163
8164 // Look for operator=.
8165 DeclarationName Name
8166 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8167 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8168 S.LookupQualifiedName(OpLookup, ClassDecl, false);
8169
8170 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8171 // operator.
8172 if (!S.getLangOpts().CPlusPlus11) {
8173 LookupResult::Filter F = OpLookup.makeFilter();
8174 while (F.hasNext()) {
8175 NamedDecl *D = F.next();
8176 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8177 if (Method->isCopyAssignmentOperator() ||
8178 (!Copying && Method->isMoveAssignmentOperator()))
8179 continue;
8180
8181 F.erase();
8182 }
8183 F.done();
8184 }
8185
8186 // Suppress the protected check (C++ [class.protected]) for each of the
8187 // assignment operators we found. This strange dance is required when
8188 // we're assigning via a base classes's copy-assignment operator. To
8189 // ensure that we're getting the right base class subobject (without
8190 // ambiguities), we need to cast "this" to that subobject type; to
8191 // ensure that we don't go through the virtual call mechanism, we need
8192 // to qualify the operator= name with the base class (see below). However,
8193 // this means that if the base class has a protected copy assignment
8194 // operator, the protected member access check will fail. So, we
8195 // rewrite "protected" access to "public" access in this case, since we
8196 // know by construction that we're calling from a derived class.
8197 if (CopyingBaseSubobject) {
8198 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8199 L != LEnd; ++L) {
8200 if (L.getAccess() == AS_protected)
8201 L.setAccess(AS_public);
8202 }
8203 }
8204
8205 // Create the nested-name-specifier that will be used to qualify the
8206 // reference to operator=; this is required to suppress the virtual
8207 // call mechanism.
8208 CXXScopeSpec SS;
8209 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8210 SS.MakeTrivial(S.Context,
8211 NestedNameSpecifier::Create(S.Context, 0, false,
8212 CanonicalT),
8213 Loc);
8214
8215 // Create the reference to operator=.
8216 ExprResult OpEqualRef
8217 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8218 /*TemplateKWLoc=*/SourceLocation(),
8219 /*FirstQualifierInScope=*/0,
8220 OpLookup,
8221 /*TemplateArgs=*/0,
8222 /*SuppressQualifierCheck=*/true);
8223 if (OpEqualRef.isInvalid())
8224 return StmtError();
8225
8226 // Build the call to the assignment operator.
8227
8228 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8229 OpEqualRef.takeAs<Expr>(),
8230 Loc, &From, 1, Loc);
8231 if (Call.isInvalid())
8232 return StmtError();
8233
8234 // If we built a call to a trivial 'operator=' while copying an array,
8235 // bail out. We'll replace the whole shebang with a memcpy.
8236 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8237 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8238 return StmtResult((Stmt*)0);
8239
8240 // Convert to an expression-statement, and clean up any produced
8241 // temporaries.
8242 return S.ActOnExprStmt(Call);
8243 }
8244
8245 // - if the subobject is of scalar type, the built-in assignment
8246 // operator is used.
8247 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8248 if (!ArrayTy) {
8249 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8250 if (Assignment.isInvalid())
8251 return StmtError();
8252 return S.ActOnExprStmt(Assignment);
8253 }
8254
8255 // - if the subobject is an array, each element is assigned, in the
8256 // manner appropriate to the element type;
8257
8258 // Construct a loop over the array bounds, e.g.,
8259 //
8260 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8261 //
8262 // that will copy each of the array elements.
8263 QualType SizeType = S.Context.getSizeType();
8264
8265 // Create the iteration variable.
8266 IdentifierInfo *IterationVarName = 0;
8267 {
8268 SmallString<8> Str;
8269 llvm::raw_svector_ostream OS(Str);
8270 OS << "__i" << Depth;
8271 IterationVarName = &S.Context.Idents.get(OS.str());
8272 }
8273 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8274 IterationVarName, SizeType,
8275 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8276 SC_None, SC_None);
8277
8278 // Initialize the iteration variable to zero.
8279 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8280 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8281
8282 // Create a reference to the iteration variable; we'll use this several
8283 // times throughout.
8284 Expr *IterationVarRef
8285 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8286 assert(IterationVarRef && "Reference to invented variable cannot fail!");
8287 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8288 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8289
8290 // Create the DeclStmt that holds the iteration variable.
8291 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8292
8293 // Subscript the "from" and "to" expressions with the iteration variable.
8294 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8295 IterationVarRefRVal,
8296 Loc));
8297 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8298 IterationVarRefRVal,
8299 Loc));
8300 if (!Copying) // Cast to rvalue
8301 From = CastForMoving(S, From);
8302
8303 // Build the copy/move for an individual element of the array.
8304 StmtResult Copy =
8305 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8306 To, From, CopyingBaseSubobject,
8307 Copying, Depth + 1);
8308 // Bail out if copying fails or if we determined that we should use memcpy.
8309 if (Copy.isInvalid() || !Copy.get())
8310 return Copy;
8311
8312 // Create the comparison against the array bound.
8313 llvm::APInt Upper
8314 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8315 Expr *Comparison
8316 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8317 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8318 BO_NE, S.Context.BoolTy,
8319 VK_RValue, OK_Ordinary, Loc, false);
8320
8321 // Create the pre-increment of the iteration variable.
8322 Expr *Increment
8323 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8324 VK_LValue, OK_Ordinary, Loc);
8325
8326 // Construct the loop that copies all elements of this array.
8327 return S.ActOnForStmt(Loc, Loc, InitStmt,
8328 S.MakeFullExpr(Comparison),
8329 0, S.MakeFullDiscardedValueExpr(Increment),
8330 Loc, Copy.take());
8331 }
8332
8333 static StmtResult
buildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,Expr * To,Expr * From,bool CopyingBaseSubobject,bool Copying)8334 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8335 Expr *To, Expr *From,
8336 bool CopyingBaseSubobject, bool Copying) {
8337 // Maybe we should use a memcpy?
8338 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8339 T.isTriviallyCopyableType(S.Context))
8340 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8341
8342 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8343 CopyingBaseSubobject,
8344 Copying, 0));
8345
8346 // If we ended up picking a trivial assignment operator for an array of a
8347 // non-trivially-copyable class type, just emit a memcpy.
8348 if (!Result.isInvalid() && !Result.get())
8349 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8350
8351 return Result;
8352 }
8353
8354 Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl * MD)8355 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8356 CXXRecordDecl *ClassDecl = MD->getParent();
8357
8358 ImplicitExceptionSpecification ExceptSpec(*this);
8359 if (ClassDecl->isInvalidDecl())
8360 return ExceptSpec;
8361
8362 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8363 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8364 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8365
8366 // C++ [except.spec]p14:
8367 // An implicitly declared special member function (Clause 12) shall have an
8368 // exception-specification. [...]
8369
8370 // It is unspecified whether or not an implicit copy assignment operator
8371 // attempts to deduplicate calls to assignment operators of virtual bases are
8372 // made. As such, this exception specification is effectively unspecified.
8373 // Based on a similar decision made for constness in C++0x, we're erring on
8374 // the side of assuming such calls to be made regardless of whether they
8375 // actually happen.
8376 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8377 BaseEnd = ClassDecl->bases_end();
8378 Base != BaseEnd; ++Base) {
8379 if (Base->isVirtual())
8380 continue;
8381
8382 CXXRecordDecl *BaseClassDecl
8383 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8384 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8385 ArgQuals, false, 0))
8386 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8387 }
8388
8389 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8390 BaseEnd = ClassDecl->vbases_end();
8391 Base != BaseEnd; ++Base) {
8392 CXXRecordDecl *BaseClassDecl
8393 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8394 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8395 ArgQuals, false, 0))
8396 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8397 }
8398
8399 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8400 FieldEnd = ClassDecl->field_end();
8401 Field != FieldEnd;
8402 ++Field) {
8403 QualType FieldType = Context.getBaseElementType(Field->getType());
8404 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8405 if (CXXMethodDecl *CopyAssign =
8406 LookupCopyingAssignment(FieldClassDecl,
8407 ArgQuals | FieldType.getCVRQualifiers(),
8408 false, 0))
8409 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8410 }
8411 }
8412
8413 return ExceptSpec;
8414 }
8415
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)8416 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8417 // Note: The following rules are largely analoguous to the copy
8418 // constructor rules. Note that virtual bases are not taken into account
8419 // for determining the argument type of the operator. Note also that
8420 // operators taking an object instead of a reference are allowed.
8421 assert(ClassDecl->needsImplicitCopyAssignment());
8422
8423 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8424 if (DSM.isAlreadyBeingDeclared())
8425 return 0;
8426
8427 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8428 QualType RetType = Context.getLValueReferenceType(ArgType);
8429 if (ClassDecl->implicitCopyAssignmentHasConstParam())
8430 ArgType = ArgType.withConst();
8431 ArgType = Context.getLValueReferenceType(ArgType);
8432
8433 // An implicitly-declared copy assignment operator is an inline public
8434 // member of its class.
8435 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8436 SourceLocation ClassLoc = ClassDecl->getLocation();
8437 DeclarationNameInfo NameInfo(Name, ClassLoc);
8438 CXXMethodDecl *CopyAssignment
8439 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8440 /*TInfo=*/0, /*isStatic=*/false,
8441 /*StorageClassAsWritten=*/SC_None,
8442 /*isInline=*/true, /*isConstexpr=*/false,
8443 SourceLocation());
8444 CopyAssignment->setAccess(AS_public);
8445 CopyAssignment->setDefaulted();
8446 CopyAssignment->setImplicit();
8447
8448 // Build an exception specification pointing back at this member.
8449 FunctionProtoType::ExtProtoInfo EPI;
8450 EPI.ExceptionSpecType = EST_Unevaluated;
8451 EPI.ExceptionSpecDecl = CopyAssignment;
8452 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8453
8454 // Add the parameter to the operator.
8455 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8456 ClassLoc, ClassLoc, /*Id=*/0,
8457 ArgType, /*TInfo=*/0,
8458 SC_None,
8459 SC_None, 0);
8460 CopyAssignment->setParams(FromParam);
8461
8462 AddOverriddenMethods(ClassDecl, CopyAssignment);
8463
8464 CopyAssignment->setTrivial(
8465 ClassDecl->needsOverloadResolutionForCopyAssignment()
8466 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8467 : ClassDecl->hasTrivialCopyAssignment());
8468
8469 // C++0x [class.copy]p19:
8470 // .... If the class definition does not explicitly declare a copy
8471 // assignment operator, there is no user-declared move constructor, and
8472 // there is no user-declared move assignment operator, a copy assignment
8473 // operator is implicitly declared as defaulted.
8474 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8475 CopyAssignment->setDeletedAsWritten();
8476
8477 // Note that we have added this copy-assignment operator.
8478 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8479
8480 if (Scope *S = getScopeForContext(ClassDecl))
8481 PushOnScopeChains(CopyAssignment, S, false);
8482 ClassDecl->addDecl(CopyAssignment);
8483
8484 return CopyAssignment;
8485 }
8486
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)8487 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8488 CXXMethodDecl *CopyAssignOperator) {
8489 assert((CopyAssignOperator->isDefaulted() &&
8490 CopyAssignOperator->isOverloadedOperator() &&
8491 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8492 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8493 !CopyAssignOperator->isDeleted()) &&
8494 "DefineImplicitCopyAssignment called for wrong function");
8495
8496 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8497
8498 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8499 CopyAssignOperator->setInvalidDecl();
8500 return;
8501 }
8502
8503 CopyAssignOperator->setUsed();
8504
8505 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8506 DiagnosticErrorTrap Trap(Diags);
8507
8508 // C++0x [class.copy]p30:
8509 // The implicitly-defined or explicitly-defaulted copy assignment operator
8510 // for a non-union class X performs memberwise copy assignment of its
8511 // subobjects. The direct base classes of X are assigned first, in the
8512 // order of their declaration in the base-specifier-list, and then the
8513 // immediate non-static data members of X are assigned, in the order in
8514 // which they were declared in the class definition.
8515
8516 // The statements that form the synthesized function body.
8517 SmallVector<Stmt*, 8> Statements;
8518
8519 // The parameter for the "other" object, which we are copying from.
8520 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8521 Qualifiers OtherQuals = Other->getType().getQualifiers();
8522 QualType OtherRefType = Other->getType();
8523 if (const LValueReferenceType *OtherRef
8524 = OtherRefType->getAs<LValueReferenceType>()) {
8525 OtherRefType = OtherRef->getPointeeType();
8526 OtherQuals = OtherRefType.getQualifiers();
8527 }
8528
8529 // Our location for everything implicitly-generated.
8530 SourceLocation Loc = CopyAssignOperator->getLocation();
8531
8532 // Construct a reference to the "other" object. We'll be using this
8533 // throughout the generated ASTs.
8534 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8535 assert(OtherRef && "Reference to parameter cannot fail!");
8536
8537 // Construct the "this" pointer. We'll be using this throughout the generated
8538 // ASTs.
8539 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8540 assert(This && "Reference to this cannot fail!");
8541
8542 // Assign base classes.
8543 bool Invalid = false;
8544 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8545 E = ClassDecl->bases_end(); Base != E; ++Base) {
8546 // Form the assignment:
8547 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8548 QualType BaseType = Base->getType().getUnqualifiedType();
8549 if (!BaseType->isRecordType()) {
8550 Invalid = true;
8551 continue;
8552 }
8553
8554 CXXCastPath BasePath;
8555 BasePath.push_back(Base);
8556
8557 // Construct the "from" expression, which is an implicit cast to the
8558 // appropriately-qualified base type.
8559 Expr *From = OtherRef;
8560 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8561 CK_UncheckedDerivedToBase,
8562 VK_LValue, &BasePath).take();
8563
8564 // Dereference "this".
8565 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8566
8567 // Implicitly cast "this" to the appropriately-qualified base type.
8568 To = ImpCastExprToType(To.take(),
8569 Context.getCVRQualifiedType(BaseType,
8570 CopyAssignOperator->getTypeQualifiers()),
8571 CK_UncheckedDerivedToBase,
8572 VK_LValue, &BasePath);
8573
8574 // Build the copy.
8575 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8576 To.get(), From,
8577 /*CopyingBaseSubobject=*/true,
8578 /*Copying=*/true);
8579 if (Copy.isInvalid()) {
8580 Diag(CurrentLocation, diag::note_member_synthesized_at)
8581 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8582 CopyAssignOperator->setInvalidDecl();
8583 return;
8584 }
8585
8586 // Success! Record the copy.
8587 Statements.push_back(Copy.takeAs<Expr>());
8588 }
8589
8590 // Assign non-static members.
8591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8592 FieldEnd = ClassDecl->field_end();
8593 Field != FieldEnd; ++Field) {
8594 if (Field->isUnnamedBitfield())
8595 continue;
8596
8597 // Check for members of reference type; we can't copy those.
8598 if (Field->getType()->isReferenceType()) {
8599 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8600 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8601 Diag(Field->getLocation(), diag::note_declared_at);
8602 Diag(CurrentLocation, diag::note_member_synthesized_at)
8603 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8604 Invalid = true;
8605 continue;
8606 }
8607
8608 // Check for members of const-qualified, non-class type.
8609 QualType BaseType = Context.getBaseElementType(Field->getType());
8610 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8611 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8612 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8613 Diag(Field->getLocation(), diag::note_declared_at);
8614 Diag(CurrentLocation, diag::note_member_synthesized_at)
8615 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8616 Invalid = true;
8617 continue;
8618 }
8619
8620 // Suppress assigning zero-width bitfields.
8621 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8622 continue;
8623
8624 QualType FieldType = Field->getType().getNonReferenceType();
8625 if (FieldType->isIncompleteArrayType()) {
8626 assert(ClassDecl->hasFlexibleArrayMember() &&
8627 "Incomplete array type is not valid");
8628 continue;
8629 }
8630
8631 // Build references to the field in the object we're copying from and to.
8632 CXXScopeSpec SS; // Intentionally empty
8633 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8634 LookupMemberName);
8635 MemberLookup.addDecl(*Field);
8636 MemberLookup.resolveKind();
8637 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8638 Loc, /*IsArrow=*/false,
8639 SS, SourceLocation(), 0,
8640 MemberLookup, 0);
8641 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8642 Loc, /*IsArrow=*/true,
8643 SS, SourceLocation(), 0,
8644 MemberLookup, 0);
8645 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8646 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8647
8648 // Build the copy of this field.
8649 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8650 To.get(), From.get(),
8651 /*CopyingBaseSubobject=*/false,
8652 /*Copying=*/true);
8653 if (Copy.isInvalid()) {
8654 Diag(CurrentLocation, diag::note_member_synthesized_at)
8655 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8656 CopyAssignOperator->setInvalidDecl();
8657 return;
8658 }
8659
8660 // Success! Record the copy.
8661 Statements.push_back(Copy.takeAs<Stmt>());
8662 }
8663
8664 if (!Invalid) {
8665 // Add a "return *this;"
8666 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8667
8668 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8669 if (Return.isInvalid())
8670 Invalid = true;
8671 else {
8672 Statements.push_back(Return.takeAs<Stmt>());
8673
8674 if (Trap.hasErrorOccurred()) {
8675 Diag(CurrentLocation, diag::note_member_synthesized_at)
8676 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8677 Invalid = true;
8678 }
8679 }
8680 }
8681
8682 if (Invalid) {
8683 CopyAssignOperator->setInvalidDecl();
8684 return;
8685 }
8686
8687 StmtResult Body;
8688 {
8689 CompoundScopeRAII CompoundScope(*this);
8690 Body = ActOnCompoundStmt(Loc, Loc, Statements,
8691 /*isStmtExpr=*/false);
8692 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8693 }
8694 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8695
8696 if (ASTMutationListener *L = getASTMutationListener()) {
8697 L->CompletedImplicitDefinition(CopyAssignOperator);
8698 }
8699 }
8700
8701 Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl * MD)8702 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8703 CXXRecordDecl *ClassDecl = MD->getParent();
8704
8705 ImplicitExceptionSpecification ExceptSpec(*this);
8706 if (ClassDecl->isInvalidDecl())
8707 return ExceptSpec;
8708
8709 // C++0x [except.spec]p14:
8710 // An implicitly declared special member function (Clause 12) shall have an
8711 // exception-specification. [...]
8712
8713 // It is unspecified whether or not an implicit move assignment operator
8714 // attempts to deduplicate calls to assignment operators of virtual bases are
8715 // made. As such, this exception specification is effectively unspecified.
8716 // Based on a similar decision made for constness in C++0x, we're erring on
8717 // the side of assuming such calls to be made regardless of whether they
8718 // actually happen.
8719 // Note that a move constructor is not implicitly declared when there are
8720 // virtual bases, but it can still be user-declared and explicitly defaulted.
8721 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8722 BaseEnd = ClassDecl->bases_end();
8723 Base != BaseEnd; ++Base) {
8724 if (Base->isVirtual())
8725 continue;
8726
8727 CXXRecordDecl *BaseClassDecl
8728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8729 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8730 0, false, 0))
8731 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8732 }
8733
8734 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8735 BaseEnd = ClassDecl->vbases_end();
8736 Base != BaseEnd; ++Base) {
8737 CXXRecordDecl *BaseClassDecl
8738 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8739 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8740 0, false, 0))
8741 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8742 }
8743
8744 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8745 FieldEnd = ClassDecl->field_end();
8746 Field != FieldEnd;
8747 ++Field) {
8748 QualType FieldType = Context.getBaseElementType(Field->getType());
8749 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8750 if (CXXMethodDecl *MoveAssign =
8751 LookupMovingAssignment(FieldClassDecl,
8752 FieldType.getCVRQualifiers(),
8753 false, 0))
8754 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8755 }
8756 }
8757
8758 return ExceptSpec;
8759 }
8760
8761 /// Determine whether the class type has any direct or indirect virtual base
8762 /// classes which have a non-trivial move assignment operator.
8763 static bool
hasVirtualBaseWithNonTrivialMoveAssignment(Sema & S,CXXRecordDecl * ClassDecl)8764 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8765 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8766 BaseEnd = ClassDecl->vbases_end();
8767 Base != BaseEnd; ++Base) {
8768 CXXRecordDecl *BaseClass =
8769 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8770
8771 // Try to declare the move assignment. If it would be deleted, then the
8772 // class does not have a non-trivial move assignment.
8773 if (BaseClass->needsImplicitMoveAssignment())
8774 S.DeclareImplicitMoveAssignment(BaseClass);
8775
8776 if (BaseClass->hasNonTrivialMoveAssignment())
8777 return true;
8778 }
8779
8780 return false;
8781 }
8782
8783 /// Determine whether the given type either has a move constructor or is
8784 /// trivially copyable.
8785 static bool
hasMoveOrIsTriviallyCopyable(Sema & S,QualType Type,bool IsConstructor)8786 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8787 Type = S.Context.getBaseElementType(Type);
8788
8789 // FIXME: Technically, non-trivially-copyable non-class types, such as
8790 // reference types, are supposed to return false here, but that appears
8791 // to be a standard defect.
8792 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8793 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8794 return true;
8795
8796 if (Type.isTriviallyCopyableType(S.Context))
8797 return true;
8798
8799 if (IsConstructor) {
8800 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8801 // give the right answer.
8802 if (ClassDecl->needsImplicitMoveConstructor())
8803 S.DeclareImplicitMoveConstructor(ClassDecl);
8804 return ClassDecl->hasMoveConstructor();
8805 }
8806
8807 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8808 // give the right answer.
8809 if (ClassDecl->needsImplicitMoveAssignment())
8810 S.DeclareImplicitMoveAssignment(ClassDecl);
8811 return ClassDecl->hasMoveAssignment();
8812 }
8813
8814 /// Determine whether all non-static data members and direct or virtual bases
8815 /// of class \p ClassDecl have either a move operation, or are trivially
8816 /// copyable.
subobjectsHaveMoveOrTrivialCopy(Sema & S,CXXRecordDecl * ClassDecl,bool IsConstructor)8817 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8818 bool IsConstructor) {
8819 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8820 BaseEnd = ClassDecl->bases_end();
8821 Base != BaseEnd; ++Base) {
8822 if (Base->isVirtual())
8823 continue;
8824
8825 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8826 return false;
8827 }
8828
8829 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8830 BaseEnd = ClassDecl->vbases_end();
8831 Base != BaseEnd; ++Base) {
8832 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8833 return false;
8834 }
8835
8836 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8837 FieldEnd = ClassDecl->field_end();
8838 Field != FieldEnd; ++Field) {
8839 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8840 return false;
8841 }
8842
8843 return true;
8844 }
8845
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)8846 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8847 // C++11 [class.copy]p20:
8848 // If the definition of a class X does not explicitly declare a move
8849 // assignment operator, one will be implicitly declared as defaulted
8850 // if and only if:
8851 //
8852 // - [first 4 bullets]
8853 assert(ClassDecl->needsImplicitMoveAssignment());
8854
8855 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8856 if (DSM.isAlreadyBeingDeclared())
8857 return 0;
8858
8859 // [Checked after we build the declaration]
8860 // - the move assignment operator would not be implicitly defined as
8861 // deleted,
8862
8863 // [DR1402]:
8864 // - X has no direct or indirect virtual base class with a non-trivial
8865 // move assignment operator, and
8866 // - each of X's non-static data members and direct or virtual base classes
8867 // has a type that either has a move assignment operator or is trivially
8868 // copyable.
8869 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8870 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8871 ClassDecl->setFailedImplicitMoveAssignment();
8872 return 0;
8873 }
8874
8875 // Note: The following rules are largely analoguous to the move
8876 // constructor rules.
8877
8878 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8879 QualType RetType = Context.getLValueReferenceType(ArgType);
8880 ArgType = Context.getRValueReferenceType(ArgType);
8881
8882 // An implicitly-declared move assignment operator is an inline public
8883 // member of its class.
8884 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8885 SourceLocation ClassLoc = ClassDecl->getLocation();
8886 DeclarationNameInfo NameInfo(Name, ClassLoc);
8887 CXXMethodDecl *MoveAssignment
8888 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8889 /*TInfo=*/0, /*isStatic=*/false,
8890 /*StorageClassAsWritten=*/SC_None,
8891 /*isInline=*/true,
8892 /*isConstexpr=*/false,
8893 SourceLocation());
8894 MoveAssignment->setAccess(AS_public);
8895 MoveAssignment->setDefaulted();
8896 MoveAssignment->setImplicit();
8897
8898 // Build an exception specification pointing back at this member.
8899 FunctionProtoType::ExtProtoInfo EPI;
8900 EPI.ExceptionSpecType = EST_Unevaluated;
8901 EPI.ExceptionSpecDecl = MoveAssignment;
8902 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8903
8904 // Add the parameter to the operator.
8905 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8906 ClassLoc, ClassLoc, /*Id=*/0,
8907 ArgType, /*TInfo=*/0,
8908 SC_None,
8909 SC_None, 0);
8910 MoveAssignment->setParams(FromParam);
8911
8912 AddOverriddenMethods(ClassDecl, MoveAssignment);
8913
8914 MoveAssignment->setTrivial(
8915 ClassDecl->needsOverloadResolutionForMoveAssignment()
8916 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8917 : ClassDecl->hasTrivialMoveAssignment());
8918
8919 // C++0x [class.copy]p9:
8920 // If the definition of a class X does not explicitly declare a move
8921 // assignment operator, one will be implicitly declared as defaulted if and
8922 // only if:
8923 // [...]
8924 // - the move assignment operator would not be implicitly defined as
8925 // deleted.
8926 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8927 // Cache this result so that we don't try to generate this over and over
8928 // on every lookup, leaking memory and wasting time.
8929 ClassDecl->setFailedImplicitMoveAssignment();
8930 return 0;
8931 }
8932
8933 // Note that we have added this copy-assignment operator.
8934 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8935
8936 if (Scope *S = getScopeForContext(ClassDecl))
8937 PushOnScopeChains(MoveAssignment, S, false);
8938 ClassDecl->addDecl(MoveAssignment);
8939
8940 return MoveAssignment;
8941 }
8942
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)8943 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8944 CXXMethodDecl *MoveAssignOperator) {
8945 assert((MoveAssignOperator->isDefaulted() &&
8946 MoveAssignOperator->isOverloadedOperator() &&
8947 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8948 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8949 !MoveAssignOperator->isDeleted()) &&
8950 "DefineImplicitMoveAssignment called for wrong function");
8951
8952 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8953
8954 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8955 MoveAssignOperator->setInvalidDecl();
8956 return;
8957 }
8958
8959 MoveAssignOperator->setUsed();
8960
8961 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
8962 DiagnosticErrorTrap Trap(Diags);
8963
8964 // C++0x [class.copy]p28:
8965 // The implicitly-defined or move assignment operator for a non-union class
8966 // X performs memberwise move assignment of its subobjects. The direct base
8967 // classes of X are assigned first, in the order of their declaration in the
8968 // base-specifier-list, and then the immediate non-static data members of X
8969 // are assigned, in the order in which they were declared in the class
8970 // definition.
8971
8972 // The statements that form the synthesized function body.
8973 SmallVector<Stmt*, 8> Statements;
8974
8975 // The parameter for the "other" object, which we are move from.
8976 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8977 QualType OtherRefType = Other->getType()->
8978 getAs<RValueReferenceType>()->getPointeeType();
8979 assert(OtherRefType.getQualifiers() == 0 &&
8980 "Bad argument type of defaulted move assignment");
8981
8982 // Our location for everything implicitly-generated.
8983 SourceLocation Loc = MoveAssignOperator->getLocation();
8984
8985 // Construct a reference to the "other" object. We'll be using this
8986 // throughout the generated ASTs.
8987 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8988 assert(OtherRef && "Reference to parameter cannot fail!");
8989 // Cast to rvalue.
8990 OtherRef = CastForMoving(*this, OtherRef);
8991
8992 // Construct the "this" pointer. We'll be using this throughout the generated
8993 // ASTs.
8994 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8995 assert(This && "Reference to this cannot fail!");
8996
8997 // Assign base classes.
8998 bool Invalid = false;
8999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9000 E = ClassDecl->bases_end(); Base != E; ++Base) {
9001 // Form the assignment:
9002 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9003 QualType BaseType = Base->getType().getUnqualifiedType();
9004 if (!BaseType->isRecordType()) {
9005 Invalid = true;
9006 continue;
9007 }
9008
9009 CXXCastPath BasePath;
9010 BasePath.push_back(Base);
9011
9012 // Construct the "from" expression, which is an implicit cast to the
9013 // appropriately-qualified base type.
9014 Expr *From = OtherRef;
9015 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9016 VK_XValue, &BasePath).take();
9017
9018 // Dereference "this".
9019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9020
9021 // Implicitly cast "this" to the appropriately-qualified base type.
9022 To = ImpCastExprToType(To.take(),
9023 Context.getCVRQualifiedType(BaseType,
9024 MoveAssignOperator->getTypeQualifiers()),
9025 CK_UncheckedDerivedToBase,
9026 VK_LValue, &BasePath);
9027
9028 // Build the move.
9029 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9030 To.get(), From,
9031 /*CopyingBaseSubobject=*/true,
9032 /*Copying=*/false);
9033 if (Move.isInvalid()) {
9034 Diag(CurrentLocation, diag::note_member_synthesized_at)
9035 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9036 MoveAssignOperator->setInvalidDecl();
9037 return;
9038 }
9039
9040 // Success! Record the move.
9041 Statements.push_back(Move.takeAs<Expr>());
9042 }
9043
9044 // Assign non-static members.
9045 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9046 FieldEnd = ClassDecl->field_end();
9047 Field != FieldEnd; ++Field) {
9048 if (Field->isUnnamedBitfield())
9049 continue;
9050
9051 // Check for members of reference type; we can't move those.
9052 if (Field->getType()->isReferenceType()) {
9053 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9054 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9055 Diag(Field->getLocation(), diag::note_declared_at);
9056 Diag(CurrentLocation, diag::note_member_synthesized_at)
9057 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9058 Invalid = true;
9059 continue;
9060 }
9061
9062 // Check for members of const-qualified, non-class type.
9063 QualType BaseType = Context.getBaseElementType(Field->getType());
9064 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9065 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9066 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9067 Diag(Field->getLocation(), diag::note_declared_at);
9068 Diag(CurrentLocation, diag::note_member_synthesized_at)
9069 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9070 Invalid = true;
9071 continue;
9072 }
9073
9074 // Suppress assigning zero-width bitfields.
9075 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9076 continue;
9077
9078 QualType FieldType = Field->getType().getNonReferenceType();
9079 if (FieldType->isIncompleteArrayType()) {
9080 assert(ClassDecl->hasFlexibleArrayMember() &&
9081 "Incomplete array type is not valid");
9082 continue;
9083 }
9084
9085 // Build references to the field in the object we're copying from and to.
9086 CXXScopeSpec SS; // Intentionally empty
9087 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9088 LookupMemberName);
9089 MemberLookup.addDecl(*Field);
9090 MemberLookup.resolveKind();
9091 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9092 Loc, /*IsArrow=*/false,
9093 SS, SourceLocation(), 0,
9094 MemberLookup, 0);
9095 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9096 Loc, /*IsArrow=*/true,
9097 SS, SourceLocation(), 0,
9098 MemberLookup, 0);
9099 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9100 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9101
9102 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9103 "Member reference with rvalue base must be rvalue except for reference "
9104 "members, which aren't allowed for move assignment.");
9105
9106 // Build the move of this field.
9107 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9108 To.get(), From.get(),
9109 /*CopyingBaseSubobject=*/false,
9110 /*Copying=*/false);
9111 if (Move.isInvalid()) {
9112 Diag(CurrentLocation, diag::note_member_synthesized_at)
9113 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9114 MoveAssignOperator->setInvalidDecl();
9115 return;
9116 }
9117
9118 // Success! Record the copy.
9119 Statements.push_back(Move.takeAs<Stmt>());
9120 }
9121
9122 if (!Invalid) {
9123 // Add a "return *this;"
9124 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9125
9126 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9127 if (Return.isInvalid())
9128 Invalid = true;
9129 else {
9130 Statements.push_back(Return.takeAs<Stmt>());
9131
9132 if (Trap.hasErrorOccurred()) {
9133 Diag(CurrentLocation, diag::note_member_synthesized_at)
9134 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9135 Invalid = true;
9136 }
9137 }
9138 }
9139
9140 if (Invalid) {
9141 MoveAssignOperator->setInvalidDecl();
9142 return;
9143 }
9144
9145 StmtResult Body;
9146 {
9147 CompoundScopeRAII CompoundScope(*this);
9148 Body = ActOnCompoundStmt(Loc, Loc, Statements,
9149 /*isStmtExpr=*/false);
9150 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9151 }
9152 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9153
9154 if (ASTMutationListener *L = getASTMutationListener()) {
9155 L->CompletedImplicitDefinition(MoveAssignOperator);
9156 }
9157 }
9158
9159 Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl * MD)9160 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9161 CXXRecordDecl *ClassDecl = MD->getParent();
9162
9163 ImplicitExceptionSpecification ExceptSpec(*this);
9164 if (ClassDecl->isInvalidDecl())
9165 return ExceptSpec;
9166
9167 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9168 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9169 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9170
9171 // C++ [except.spec]p14:
9172 // An implicitly declared special member function (Clause 12) shall have an
9173 // exception-specification. [...]
9174 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9175 BaseEnd = ClassDecl->bases_end();
9176 Base != BaseEnd;
9177 ++Base) {
9178 // Virtual bases are handled below.
9179 if (Base->isVirtual())
9180 continue;
9181
9182 CXXRecordDecl *BaseClassDecl
9183 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9184 if (CXXConstructorDecl *CopyConstructor =
9185 LookupCopyingConstructor(BaseClassDecl, Quals))
9186 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9187 }
9188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9189 BaseEnd = ClassDecl->vbases_end();
9190 Base != BaseEnd;
9191 ++Base) {
9192 CXXRecordDecl *BaseClassDecl
9193 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9194 if (CXXConstructorDecl *CopyConstructor =
9195 LookupCopyingConstructor(BaseClassDecl, Quals))
9196 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9197 }
9198 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9199 FieldEnd = ClassDecl->field_end();
9200 Field != FieldEnd;
9201 ++Field) {
9202 QualType FieldType = Context.getBaseElementType(Field->getType());
9203 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9204 if (CXXConstructorDecl *CopyConstructor =
9205 LookupCopyingConstructor(FieldClassDecl,
9206 Quals | FieldType.getCVRQualifiers()))
9207 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9208 }
9209 }
9210
9211 return ExceptSpec;
9212 }
9213
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)9214 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9215 CXXRecordDecl *ClassDecl) {
9216 // C++ [class.copy]p4:
9217 // If the class definition does not explicitly declare a copy
9218 // constructor, one is declared implicitly.
9219 assert(ClassDecl->needsImplicitCopyConstructor());
9220
9221 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9222 if (DSM.isAlreadyBeingDeclared())
9223 return 0;
9224
9225 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9226 QualType ArgType = ClassType;
9227 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9228 if (Const)
9229 ArgType = ArgType.withConst();
9230 ArgType = Context.getLValueReferenceType(ArgType);
9231
9232 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9233 CXXCopyConstructor,
9234 Const);
9235
9236 DeclarationName Name
9237 = Context.DeclarationNames.getCXXConstructorName(
9238 Context.getCanonicalType(ClassType));
9239 SourceLocation ClassLoc = ClassDecl->getLocation();
9240 DeclarationNameInfo NameInfo(Name, ClassLoc);
9241
9242 // An implicitly-declared copy constructor is an inline public
9243 // member of its class.
9244 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9245 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9246 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9247 Constexpr);
9248 CopyConstructor->setAccess(AS_public);
9249 CopyConstructor->setDefaulted();
9250
9251 // Build an exception specification pointing back at this member.
9252 FunctionProtoType::ExtProtoInfo EPI;
9253 EPI.ExceptionSpecType = EST_Unevaluated;
9254 EPI.ExceptionSpecDecl = CopyConstructor;
9255 CopyConstructor->setType(
9256 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9257
9258 // Add the parameter to the constructor.
9259 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9260 ClassLoc, ClassLoc,
9261 /*IdentifierInfo=*/0,
9262 ArgType, /*TInfo=*/0,
9263 SC_None,
9264 SC_None, 0);
9265 CopyConstructor->setParams(FromParam);
9266
9267 CopyConstructor->setTrivial(
9268 ClassDecl->needsOverloadResolutionForCopyConstructor()
9269 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9270 : ClassDecl->hasTrivialCopyConstructor());
9271
9272 // C++11 [class.copy]p8:
9273 // ... If the class definition does not explicitly declare a copy
9274 // constructor, there is no user-declared move constructor, and there is no
9275 // user-declared move assignment operator, a copy constructor is implicitly
9276 // declared as defaulted.
9277 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9278 CopyConstructor->setDeletedAsWritten();
9279
9280 // Note that we have declared this constructor.
9281 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9282
9283 if (Scope *S = getScopeForContext(ClassDecl))
9284 PushOnScopeChains(CopyConstructor, S, false);
9285 ClassDecl->addDecl(CopyConstructor);
9286
9287 return CopyConstructor;
9288 }
9289
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)9290 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9291 CXXConstructorDecl *CopyConstructor) {
9292 assert((CopyConstructor->isDefaulted() &&
9293 CopyConstructor->isCopyConstructor() &&
9294 !CopyConstructor->doesThisDeclarationHaveABody() &&
9295 !CopyConstructor->isDeleted()) &&
9296 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9297
9298 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9299 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9300
9301 SynthesizedFunctionScope Scope(*this, CopyConstructor);
9302 DiagnosticErrorTrap Trap(Diags);
9303
9304 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9305 Trap.hasErrorOccurred()) {
9306 Diag(CurrentLocation, diag::note_member_synthesized_at)
9307 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9308 CopyConstructor->setInvalidDecl();
9309 } else {
9310 Sema::CompoundScopeRAII CompoundScope(*this);
9311 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9312 CopyConstructor->getLocation(),
9313 MultiStmtArg(),
9314 /*isStmtExpr=*/false)
9315 .takeAs<Stmt>());
9316 CopyConstructor->setImplicitlyDefined(true);
9317 }
9318
9319 CopyConstructor->setUsed();
9320 if (ASTMutationListener *L = getASTMutationListener()) {
9321 L->CompletedImplicitDefinition(CopyConstructor);
9322 }
9323 }
9324
9325 Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl * MD)9326 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9327 CXXRecordDecl *ClassDecl = MD->getParent();
9328
9329 // C++ [except.spec]p14:
9330 // An implicitly declared special member function (Clause 12) shall have an
9331 // exception-specification. [...]
9332 ImplicitExceptionSpecification ExceptSpec(*this);
9333 if (ClassDecl->isInvalidDecl())
9334 return ExceptSpec;
9335
9336 // Direct base-class constructors.
9337 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9338 BEnd = ClassDecl->bases_end();
9339 B != BEnd; ++B) {
9340 if (B->isVirtual()) // Handled below.
9341 continue;
9342
9343 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9345 CXXConstructorDecl *Constructor =
9346 LookupMovingConstructor(BaseClassDecl, 0);
9347 // If this is a deleted function, add it anyway. This might be conformant
9348 // with the standard. This might not. I'm not sure. It might not matter.
9349 if (Constructor)
9350 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9351 }
9352 }
9353
9354 // Virtual base-class constructors.
9355 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9356 BEnd = ClassDecl->vbases_end();
9357 B != BEnd; ++B) {
9358 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9359 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9360 CXXConstructorDecl *Constructor =
9361 LookupMovingConstructor(BaseClassDecl, 0);
9362 // If this is a deleted function, add it anyway. This might be conformant
9363 // with the standard. This might not. I'm not sure. It might not matter.
9364 if (Constructor)
9365 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9366 }
9367 }
9368
9369 // Field constructors.
9370 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9371 FEnd = ClassDecl->field_end();
9372 F != FEnd; ++F) {
9373 QualType FieldType = Context.getBaseElementType(F->getType());
9374 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9375 CXXConstructorDecl *Constructor =
9376 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9377 // If this is a deleted function, add it anyway. This might be conformant
9378 // with the standard. This might not. I'm not sure. It might not matter.
9379 // In particular, the problem is that this function never gets called. It
9380 // might just be ill-formed because this function attempts to refer to
9381 // a deleted function here.
9382 if (Constructor)
9383 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9384 }
9385 }
9386
9387 return ExceptSpec;
9388 }
9389
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)9390 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9391 CXXRecordDecl *ClassDecl) {
9392 // C++11 [class.copy]p9:
9393 // If the definition of a class X does not explicitly declare a move
9394 // constructor, one will be implicitly declared as defaulted if and only if:
9395 //
9396 // - [first 4 bullets]
9397 assert(ClassDecl->needsImplicitMoveConstructor());
9398
9399 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9400 if (DSM.isAlreadyBeingDeclared())
9401 return 0;
9402
9403 // [Checked after we build the declaration]
9404 // - the move assignment operator would not be implicitly defined as
9405 // deleted,
9406
9407 // [DR1402]:
9408 // - each of X's non-static data members and direct or virtual base classes
9409 // has a type that either has a move constructor or is trivially copyable.
9410 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9411 ClassDecl->setFailedImplicitMoveConstructor();
9412 return 0;
9413 }
9414
9415 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9416 QualType ArgType = Context.getRValueReferenceType(ClassType);
9417
9418 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9419 CXXMoveConstructor,
9420 false);
9421
9422 DeclarationName Name
9423 = Context.DeclarationNames.getCXXConstructorName(
9424 Context.getCanonicalType(ClassType));
9425 SourceLocation ClassLoc = ClassDecl->getLocation();
9426 DeclarationNameInfo NameInfo(Name, ClassLoc);
9427
9428 // C++0x [class.copy]p11:
9429 // An implicitly-declared copy/move constructor is an inline public
9430 // member of its class.
9431 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9432 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9433 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9434 Constexpr);
9435 MoveConstructor->setAccess(AS_public);
9436 MoveConstructor->setDefaulted();
9437
9438 // Build an exception specification pointing back at this member.
9439 FunctionProtoType::ExtProtoInfo EPI;
9440 EPI.ExceptionSpecType = EST_Unevaluated;
9441 EPI.ExceptionSpecDecl = MoveConstructor;
9442 MoveConstructor->setType(
9443 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9444
9445 // Add the parameter to the constructor.
9446 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9447 ClassLoc, ClassLoc,
9448 /*IdentifierInfo=*/0,
9449 ArgType, /*TInfo=*/0,
9450 SC_None,
9451 SC_None, 0);
9452 MoveConstructor->setParams(FromParam);
9453
9454 MoveConstructor->setTrivial(
9455 ClassDecl->needsOverloadResolutionForMoveConstructor()
9456 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9457 : ClassDecl->hasTrivialMoveConstructor());
9458
9459 // C++0x [class.copy]p9:
9460 // If the definition of a class X does not explicitly declare a move
9461 // constructor, one will be implicitly declared as defaulted if and only if:
9462 // [...]
9463 // - the move constructor would not be implicitly defined as deleted.
9464 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9465 // Cache this result so that we don't try to generate this over and over
9466 // on every lookup, leaking memory and wasting time.
9467 ClassDecl->setFailedImplicitMoveConstructor();
9468 return 0;
9469 }
9470
9471 // Note that we have declared this constructor.
9472 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9473
9474 if (Scope *S = getScopeForContext(ClassDecl))
9475 PushOnScopeChains(MoveConstructor, S, false);
9476 ClassDecl->addDecl(MoveConstructor);
9477
9478 return MoveConstructor;
9479 }
9480
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)9481 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9482 CXXConstructorDecl *MoveConstructor) {
9483 assert((MoveConstructor->isDefaulted() &&
9484 MoveConstructor->isMoveConstructor() &&
9485 !MoveConstructor->doesThisDeclarationHaveABody() &&
9486 !MoveConstructor->isDeleted()) &&
9487 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9488
9489 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9490 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9491
9492 SynthesizedFunctionScope Scope(*this, MoveConstructor);
9493 DiagnosticErrorTrap Trap(Diags);
9494
9495 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9496 Trap.hasErrorOccurred()) {
9497 Diag(CurrentLocation, diag::note_member_synthesized_at)
9498 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9499 MoveConstructor->setInvalidDecl();
9500 } else {
9501 Sema::CompoundScopeRAII CompoundScope(*this);
9502 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9503 MoveConstructor->getLocation(),
9504 MultiStmtArg(),
9505 /*isStmtExpr=*/false)
9506 .takeAs<Stmt>());
9507 MoveConstructor->setImplicitlyDefined(true);
9508 }
9509
9510 MoveConstructor->setUsed();
9511
9512 if (ASTMutationListener *L = getASTMutationListener()) {
9513 L->CompletedImplicitDefinition(MoveConstructor);
9514 }
9515 }
9516
isImplicitlyDeleted(FunctionDecl * FD)9517 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9518 return FD->isDeleted() &&
9519 (FD->isDefaulted() || FD->isImplicit()) &&
9520 isa<CXXMethodDecl>(FD);
9521 }
9522
9523 /// \brief Mark the call operator of the given lambda closure type as "used".
markLambdaCallOperatorUsed(Sema & S,CXXRecordDecl * Lambda)9524 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9525 CXXMethodDecl *CallOperator
9526 = cast<CXXMethodDecl>(
9527 Lambda->lookup(
9528 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9529 CallOperator->setReferenced();
9530 CallOperator->setUsed();
9531 }
9532
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)9533 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9534 SourceLocation CurrentLocation,
9535 CXXConversionDecl *Conv)
9536 {
9537 CXXRecordDecl *Lambda = Conv->getParent();
9538
9539 // Make sure that the lambda call operator is marked used.
9540 markLambdaCallOperatorUsed(*this, Lambda);
9541
9542 Conv->setUsed();
9543
9544 SynthesizedFunctionScope Scope(*this, Conv);
9545 DiagnosticErrorTrap Trap(Diags);
9546
9547 // Return the address of the __invoke function.
9548 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9549 CXXMethodDecl *Invoke
9550 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9551 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9552 VK_LValue, Conv->getLocation()).take();
9553 assert(FunctionRef && "Can't refer to __invoke function?");
9554 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9555 Conv->setBody(new (Context) CompoundStmt(Context, Return,
9556 Conv->getLocation(),
9557 Conv->getLocation()));
9558
9559 // Fill in the __invoke function with a dummy implementation. IR generation
9560 // will fill in the actual details.
9561 Invoke->setUsed();
9562 Invoke->setReferenced();
9563 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9564
9565 if (ASTMutationListener *L = getASTMutationListener()) {
9566 L->CompletedImplicitDefinition(Conv);
9567 L->CompletedImplicitDefinition(Invoke);
9568 }
9569 }
9570
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)9571 void Sema::DefineImplicitLambdaToBlockPointerConversion(
9572 SourceLocation CurrentLocation,
9573 CXXConversionDecl *Conv)
9574 {
9575 Conv->setUsed();
9576
9577 SynthesizedFunctionScope Scope(*this, Conv);
9578 DiagnosticErrorTrap Trap(Diags);
9579
9580 // Copy-initialize the lambda object as needed to capture it.
9581 Expr *This = ActOnCXXThis(CurrentLocation).take();
9582 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9583
9584 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9585 Conv->getLocation(),
9586 Conv, DerefThis);
9587
9588 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9589 // behavior. Note that only the general conversion function does this
9590 // (since it's unusable otherwise); in the case where we inline the
9591 // block literal, it has block literal lifetime semantics.
9592 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9593 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9594 CK_CopyAndAutoreleaseBlockObject,
9595 BuildBlock.get(), 0, VK_RValue);
9596
9597 if (BuildBlock.isInvalid()) {
9598 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9599 Conv->setInvalidDecl();
9600 return;
9601 }
9602
9603 // Create the return statement that returns the block from the conversion
9604 // function.
9605 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9606 if (Return.isInvalid()) {
9607 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9608 Conv->setInvalidDecl();
9609 return;
9610 }
9611
9612 // Set the body of the conversion function.
9613 Stmt *ReturnS = Return.take();
9614 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9615 Conv->getLocation(),
9616 Conv->getLocation()));
9617
9618 // We're done; notify the mutation listener, if any.
9619 if (ASTMutationListener *L = getASTMutationListener()) {
9620 L->CompletedImplicitDefinition(Conv);
9621 }
9622 }
9623
9624 /// \brief Determine whether the given list arguments contains exactly one
9625 /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)9626 static bool hasOneRealArgument(MultiExprArg Args) {
9627 switch (Args.size()) {
9628 case 0:
9629 return false;
9630
9631 default:
9632 if (!Args[1]->isDefaultArgument())
9633 return false;
9634
9635 // fall through
9636 case 1:
9637 return !Args[0]->isDefaultArgument();
9638 }
9639
9640 return false;
9641 }
9642
9643 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)9644 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9645 CXXConstructorDecl *Constructor,
9646 MultiExprArg ExprArgs,
9647 bool HadMultipleCandidates,
9648 bool IsListInitialization,
9649 bool RequiresZeroInit,
9650 unsigned ConstructKind,
9651 SourceRange ParenRange) {
9652 bool Elidable = false;
9653
9654 // C++0x [class.copy]p34:
9655 // When certain criteria are met, an implementation is allowed to
9656 // omit the copy/move construction of a class object, even if the
9657 // copy/move constructor and/or destructor for the object have
9658 // side effects. [...]
9659 // - when a temporary class object that has not been bound to a
9660 // reference (12.2) would be copied/moved to a class object
9661 // with the same cv-unqualified type, the copy/move operation
9662 // can be omitted by constructing the temporary object
9663 // directly into the target of the omitted copy/move
9664 if (ConstructKind == CXXConstructExpr::CK_Complete &&
9665 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9666 Expr *SubExpr = ExprArgs[0];
9667 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9668 }
9669
9670 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9671 Elidable, ExprArgs, HadMultipleCandidates,
9672 IsListInitialization, RequiresZeroInit,
9673 ConstructKind, ParenRange);
9674 }
9675
9676 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
9677 /// including handling of its default argument expressions.
9678 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)9679 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9680 CXXConstructorDecl *Constructor, bool Elidable,
9681 MultiExprArg ExprArgs,
9682 bool HadMultipleCandidates,
9683 bool IsListInitialization,
9684 bool RequiresZeroInit,
9685 unsigned ConstructKind,
9686 SourceRange ParenRange) {
9687 MarkFunctionReferenced(ConstructLoc, Constructor);
9688 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9689 Constructor, Elidable, ExprArgs,
9690 HadMultipleCandidates,
9691 IsListInitialization, RequiresZeroInit,
9692 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9693 ParenRange));
9694 }
9695
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)9696 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9697 if (VD->isInvalidDecl()) return;
9698
9699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9700 if (ClassDecl->isInvalidDecl()) return;
9701 if (ClassDecl->hasIrrelevantDestructor()) return;
9702 if (ClassDecl->isDependentContext()) return;
9703
9704 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9705 MarkFunctionReferenced(VD->getLocation(), Destructor);
9706 CheckDestructorAccess(VD->getLocation(), Destructor,
9707 PDiag(diag::err_access_dtor_var)
9708 << VD->getDeclName()
9709 << VD->getType());
9710 DiagnoseUseOfDecl(Destructor, VD->getLocation());
9711
9712 if (!VD->hasGlobalStorage()) return;
9713
9714 // Emit warning for non-trivial dtor in global scope (a real global,
9715 // class-static, function-static).
9716 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9717
9718 // TODO: this should be re-enabled for static locals by !CXAAtExit
9719 if (!VD->isStaticLocal())
9720 Diag(VD->getLocation(), diag::warn_global_destructor);
9721 }
9722
9723 /// \brief Given a constructor and the set of arguments provided for the
9724 /// constructor, convert the arguments and add any required default arguments
9725 /// to form a proper call to this constructor.
9726 ///
9727 /// \returns true if an error occurred, false otherwise.
9728 bool
CompleteConstructorCall(CXXConstructorDecl * Constructor,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit,bool IsListInitialization)9729 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9730 MultiExprArg ArgsPtr,
9731 SourceLocation Loc,
9732 SmallVectorImpl<Expr*> &ConvertedArgs,
9733 bool AllowExplicit,
9734 bool IsListInitialization) {
9735 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9736 unsigned NumArgs = ArgsPtr.size();
9737 Expr **Args = ArgsPtr.data();
9738
9739 const FunctionProtoType *Proto
9740 = Constructor->getType()->getAs<FunctionProtoType>();
9741 assert(Proto && "Constructor without a prototype?");
9742 unsigned NumArgsInProto = Proto->getNumArgs();
9743
9744 // If too few arguments are available, we'll fill in the rest with defaults.
9745 if (NumArgs < NumArgsInProto)
9746 ConvertedArgs.reserve(NumArgsInProto);
9747 else
9748 ConvertedArgs.reserve(NumArgs);
9749
9750 VariadicCallType CallType =
9751 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9752 SmallVector<Expr *, 8> AllArgs;
9753 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9754 Proto, 0, Args, NumArgs, AllArgs,
9755 CallType, AllowExplicit,
9756 IsListInitialization);
9757 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9758
9759 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9760
9761 CheckConstructorCall(Constructor,
9762 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9763 AllArgs.size()),
9764 Proto, Loc);
9765
9766 return Invalid;
9767 }
9768
9769 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)9770 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9771 const FunctionDecl *FnDecl) {
9772 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9773 if (isa<NamespaceDecl>(DC)) {
9774 return SemaRef.Diag(FnDecl->getLocation(),
9775 diag::err_operator_new_delete_declared_in_namespace)
9776 << FnDecl->getDeclName();
9777 }
9778
9779 if (isa<TranslationUnitDecl>(DC) &&
9780 FnDecl->getStorageClass() == SC_Static) {
9781 return SemaRef.Diag(FnDecl->getLocation(),
9782 diag::err_operator_new_delete_declared_static)
9783 << FnDecl->getDeclName();
9784 }
9785
9786 return false;
9787 }
9788
9789 static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)9790 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9791 CanQualType ExpectedResultType,
9792 CanQualType ExpectedFirstParamType,
9793 unsigned DependentParamTypeDiag,
9794 unsigned InvalidParamTypeDiag) {
9795 QualType ResultType =
9796 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9797
9798 // Check that the result type is not dependent.
9799 if (ResultType->isDependentType())
9800 return SemaRef.Diag(FnDecl->getLocation(),
9801 diag::err_operator_new_delete_dependent_result_type)
9802 << FnDecl->getDeclName() << ExpectedResultType;
9803
9804 // Check that the result type is what we expect.
9805 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9806 return SemaRef.Diag(FnDecl->getLocation(),
9807 diag::err_operator_new_delete_invalid_result_type)
9808 << FnDecl->getDeclName() << ExpectedResultType;
9809
9810 // A function template must have at least 2 parameters.
9811 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9812 return SemaRef.Diag(FnDecl->getLocation(),
9813 diag::err_operator_new_delete_template_too_few_parameters)
9814 << FnDecl->getDeclName();
9815
9816 // The function decl must have at least 1 parameter.
9817 if (FnDecl->getNumParams() == 0)
9818 return SemaRef.Diag(FnDecl->getLocation(),
9819 diag::err_operator_new_delete_too_few_parameters)
9820 << FnDecl->getDeclName();
9821
9822 // Check the first parameter type is not dependent.
9823 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9824 if (FirstParamType->isDependentType())
9825 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9826 << FnDecl->getDeclName() << ExpectedFirstParamType;
9827
9828 // Check that the first parameter type is what we expect.
9829 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9830 ExpectedFirstParamType)
9831 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9832 << FnDecl->getDeclName() << ExpectedFirstParamType;
9833
9834 return false;
9835 }
9836
9837 static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)9838 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9839 // C++ [basic.stc.dynamic.allocation]p1:
9840 // A program is ill-formed if an allocation function is declared in a
9841 // namespace scope other than global scope or declared static in global
9842 // scope.
9843 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9844 return true;
9845
9846 CanQualType SizeTy =
9847 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9848
9849 // C++ [basic.stc.dynamic.allocation]p1:
9850 // The return type shall be void*. The first parameter shall have type
9851 // std::size_t.
9852 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9853 SizeTy,
9854 diag::err_operator_new_dependent_param_type,
9855 diag::err_operator_new_param_type))
9856 return true;
9857
9858 // C++ [basic.stc.dynamic.allocation]p1:
9859 // The first parameter shall not have an associated default argument.
9860 if (FnDecl->getParamDecl(0)->hasDefaultArg())
9861 return SemaRef.Diag(FnDecl->getLocation(),
9862 diag::err_operator_new_default_arg)
9863 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9864
9865 return false;
9866 }
9867
9868 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)9869 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
9870 // C++ [basic.stc.dynamic.deallocation]p1:
9871 // A program is ill-formed if deallocation functions are declared in a
9872 // namespace scope other than global scope or declared static in global
9873 // scope.
9874 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9875 return true;
9876
9877 // C++ [basic.stc.dynamic.deallocation]p2:
9878 // Each deallocation function shall return void and its first parameter
9879 // shall be void*.
9880 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9881 SemaRef.Context.VoidPtrTy,
9882 diag::err_operator_delete_dependent_param_type,
9883 diag::err_operator_delete_param_type))
9884 return true;
9885
9886 return false;
9887 }
9888
9889 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
9890 /// of this overloaded operator is well-formed. If so, returns false;
9891 /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)9892 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9893 assert(FnDecl && FnDecl->isOverloadedOperator() &&
9894 "Expected an overloaded operator declaration");
9895
9896 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9897
9898 // C++ [over.oper]p5:
9899 // The allocation and deallocation functions, operator new,
9900 // operator new[], operator delete and operator delete[], are
9901 // described completely in 3.7.3. The attributes and restrictions
9902 // found in the rest of this subclause do not apply to them unless
9903 // explicitly stated in 3.7.3.
9904 if (Op == OO_Delete || Op == OO_Array_Delete)
9905 return CheckOperatorDeleteDeclaration(*this, FnDecl);
9906
9907 if (Op == OO_New || Op == OO_Array_New)
9908 return CheckOperatorNewDeclaration(*this, FnDecl);
9909
9910 // C++ [over.oper]p6:
9911 // An operator function shall either be a non-static member
9912 // function or be a non-member function and have at least one
9913 // parameter whose type is a class, a reference to a class, an
9914 // enumeration, or a reference to an enumeration.
9915 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9916 if (MethodDecl->isStatic())
9917 return Diag(FnDecl->getLocation(),
9918 diag::err_operator_overload_static) << FnDecl->getDeclName();
9919 } else {
9920 bool ClassOrEnumParam = false;
9921 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9922 ParamEnd = FnDecl->param_end();
9923 Param != ParamEnd; ++Param) {
9924 QualType ParamType = (*Param)->getType().getNonReferenceType();
9925 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9926 ParamType->isEnumeralType()) {
9927 ClassOrEnumParam = true;
9928 break;
9929 }
9930 }
9931
9932 if (!ClassOrEnumParam)
9933 return Diag(FnDecl->getLocation(),
9934 diag::err_operator_overload_needs_class_or_enum)
9935 << FnDecl->getDeclName();
9936 }
9937
9938 // C++ [over.oper]p8:
9939 // An operator function cannot have default arguments (8.3.6),
9940 // except where explicitly stated below.
9941 //
9942 // Only the function-call operator allows default arguments
9943 // (C++ [over.call]p1).
9944 if (Op != OO_Call) {
9945 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9946 Param != FnDecl->param_end(); ++Param) {
9947 if ((*Param)->hasDefaultArg())
9948 return Diag((*Param)->getLocation(),
9949 diag::err_operator_overload_default_arg)
9950 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9951 }
9952 }
9953
9954 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9955 { false, false, false }
9956 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9957 , { Unary, Binary, MemberOnly }
9958 #include "clang/Basic/OperatorKinds.def"
9959 };
9960
9961 bool CanBeUnaryOperator = OperatorUses[Op][0];
9962 bool CanBeBinaryOperator = OperatorUses[Op][1];
9963 bool MustBeMemberOperator = OperatorUses[Op][2];
9964
9965 // C++ [over.oper]p8:
9966 // [...] Operator functions cannot have more or fewer parameters
9967 // than the number required for the corresponding operator, as
9968 // described in the rest of this subclause.
9969 unsigned NumParams = FnDecl->getNumParams()
9970 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9971 if (Op != OO_Call &&
9972 ((NumParams == 1 && !CanBeUnaryOperator) ||
9973 (NumParams == 2 && !CanBeBinaryOperator) ||
9974 (NumParams < 1) || (NumParams > 2))) {
9975 // We have the wrong number of parameters.
9976 unsigned ErrorKind;
9977 if (CanBeUnaryOperator && CanBeBinaryOperator) {
9978 ErrorKind = 2; // 2 -> unary or binary.
9979 } else if (CanBeUnaryOperator) {
9980 ErrorKind = 0; // 0 -> unary
9981 } else {
9982 assert(CanBeBinaryOperator &&
9983 "All non-call overloaded operators are unary or binary!");
9984 ErrorKind = 1; // 1 -> binary
9985 }
9986
9987 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9988 << FnDecl->getDeclName() << NumParams << ErrorKind;
9989 }
9990
9991 // Overloaded operators other than operator() cannot be variadic.
9992 if (Op != OO_Call &&
9993 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9994 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9995 << FnDecl->getDeclName();
9996 }
9997
9998 // Some operators must be non-static member functions.
9999 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10000 return Diag(FnDecl->getLocation(),
10001 diag::err_operator_overload_must_be_member)
10002 << FnDecl->getDeclName();
10003 }
10004
10005 // C++ [over.inc]p1:
10006 // The user-defined function called operator++ implements the
10007 // prefix and postfix ++ operator. If this function is a member
10008 // function with no parameters, or a non-member function with one
10009 // parameter of class or enumeration type, it defines the prefix
10010 // increment operator ++ for objects of that type. If the function
10011 // is a member function with one parameter (which shall be of type
10012 // int) or a non-member function with two parameters (the second
10013 // of which shall be of type int), it defines the postfix
10014 // increment operator ++ for objects of that type.
10015 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10016 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10017 bool ParamIsInt = false;
10018 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10019 ParamIsInt = BT->getKind() == BuiltinType::Int;
10020
10021 if (!ParamIsInt)
10022 return Diag(LastParam->getLocation(),
10023 diag::err_operator_overload_post_incdec_must_be_int)
10024 << LastParam->getType() << (Op == OO_MinusMinus);
10025 }
10026
10027 return false;
10028 }
10029
10030 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10031 /// of this literal operator function is well-formed. If so, returns
10032 /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)10033 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10034 if (isa<CXXMethodDecl>(FnDecl)) {
10035 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10036 << FnDecl->getDeclName();
10037 return true;
10038 }
10039
10040 if (FnDecl->isExternC()) {
10041 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10042 return true;
10043 }
10044
10045 bool Valid = false;
10046
10047 // This might be the definition of a literal operator template.
10048 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10049 // This might be a specialization of a literal operator template.
10050 if (!TpDecl)
10051 TpDecl = FnDecl->getPrimaryTemplate();
10052
10053 // template <char...> type operator "" name() is the only valid template
10054 // signature, and the only valid signature with no parameters.
10055 if (TpDecl) {
10056 if (FnDecl->param_size() == 0) {
10057 // Must have only one template parameter
10058 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10059 if (Params->size() == 1) {
10060 NonTypeTemplateParmDecl *PmDecl =
10061 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10062
10063 // The template parameter must be a char parameter pack.
10064 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10065 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10066 Valid = true;
10067 }
10068 }
10069 } else if (FnDecl->param_size()) {
10070 // Check the first parameter
10071 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10072
10073 QualType T = (*Param)->getType().getUnqualifiedType();
10074
10075 // unsigned long long int, long double, and any character type are allowed
10076 // as the only parameters.
10077 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10078 Context.hasSameType(T, Context.LongDoubleTy) ||
10079 Context.hasSameType(T, Context.CharTy) ||
10080 Context.hasSameType(T, Context.WCharTy) ||
10081 Context.hasSameType(T, Context.Char16Ty) ||
10082 Context.hasSameType(T, Context.Char32Ty)) {
10083 if (++Param == FnDecl->param_end())
10084 Valid = true;
10085 goto FinishedParams;
10086 }
10087
10088 // Otherwise it must be a pointer to const; let's strip those qualifiers.
10089 const PointerType *PT = T->getAs<PointerType>();
10090 if (!PT)
10091 goto FinishedParams;
10092 T = PT->getPointeeType();
10093 if (!T.isConstQualified() || T.isVolatileQualified())
10094 goto FinishedParams;
10095 T = T.getUnqualifiedType();
10096
10097 // Move on to the second parameter;
10098 ++Param;
10099
10100 // If there is no second parameter, the first must be a const char *
10101 if (Param == FnDecl->param_end()) {
10102 if (Context.hasSameType(T, Context.CharTy))
10103 Valid = true;
10104 goto FinishedParams;
10105 }
10106
10107 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10108 // are allowed as the first parameter to a two-parameter function
10109 if (!(Context.hasSameType(T, Context.CharTy) ||
10110 Context.hasSameType(T, Context.WCharTy) ||
10111 Context.hasSameType(T, Context.Char16Ty) ||
10112 Context.hasSameType(T, Context.Char32Ty)))
10113 goto FinishedParams;
10114
10115 // The second and final parameter must be an std::size_t
10116 T = (*Param)->getType().getUnqualifiedType();
10117 if (Context.hasSameType(T, Context.getSizeType()) &&
10118 ++Param == FnDecl->param_end())
10119 Valid = true;
10120 }
10121
10122 // FIXME: This diagnostic is absolutely terrible.
10123 FinishedParams:
10124 if (!Valid) {
10125 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10126 << FnDecl->getDeclName();
10127 return true;
10128 }
10129
10130 // A parameter-declaration-clause containing a default argument is not
10131 // equivalent to any of the permitted forms.
10132 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10133 ParamEnd = FnDecl->param_end();
10134 Param != ParamEnd; ++Param) {
10135 if ((*Param)->hasDefaultArg()) {
10136 Diag((*Param)->getDefaultArgRange().getBegin(),
10137 diag::err_literal_operator_default_argument)
10138 << (*Param)->getDefaultArgRange();
10139 break;
10140 }
10141 }
10142
10143 StringRef LiteralName
10144 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10145 if (LiteralName[0] != '_') {
10146 // C++11 [usrlit.suffix]p1:
10147 // Literal suffix identifiers that do not start with an underscore
10148 // are reserved for future standardization.
10149 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10150 }
10151
10152 return false;
10153 }
10154
10155 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10156 /// linkage specification, including the language and (if present)
10157 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10158 /// the location of the language string literal, which is provided
10159 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10160 /// the '{' brace. Otherwise, this linkage specification does not
10161 /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,SourceLocation LangLoc,StringRef Lang,SourceLocation LBraceLoc)10162 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10163 SourceLocation LangLoc,
10164 StringRef Lang,
10165 SourceLocation LBraceLoc) {
10166 LinkageSpecDecl::LanguageIDs Language;
10167 if (Lang == "\"C\"")
10168 Language = LinkageSpecDecl::lang_c;
10169 else if (Lang == "\"C++\"")
10170 Language = LinkageSpecDecl::lang_cxx;
10171 else {
10172 Diag(LangLoc, diag::err_bad_language);
10173 return 0;
10174 }
10175
10176 // FIXME: Add all the various semantics of linkage specifications
10177
10178 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10179 ExternLoc, LangLoc, Language);
10180 CurContext->addDecl(D);
10181 PushDeclContext(S, D);
10182 return D;
10183 }
10184
10185 /// ActOnFinishLinkageSpecification - Complete the definition of
10186 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
10187 /// valid, it's the position of the closing '}' brace in a linkage
10188 /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)10189 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10190 Decl *LinkageSpec,
10191 SourceLocation RBraceLoc) {
10192 if (LinkageSpec) {
10193 if (RBraceLoc.isValid()) {
10194 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10195 LSDecl->setRBraceLoc(RBraceLoc);
10196 }
10197 PopDeclContext();
10198 }
10199 return LinkageSpec;
10200 }
10201
ActOnEmptyDeclaration(Scope * S,AttributeList * AttrList,SourceLocation SemiLoc)10202 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10203 AttributeList *AttrList,
10204 SourceLocation SemiLoc) {
10205 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10206 // Attribute declarations appertain to empty declaration so we handle
10207 // them here.
10208 if (AttrList)
10209 ProcessDeclAttributeList(S, ED, AttrList);
10210
10211 CurContext->addDecl(ED);
10212 return ED;
10213 }
10214
10215 /// \brief Perform semantic analysis for the variable declaration that
10216 /// occurs within a C++ catch clause, returning the newly-created
10217 /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)10218 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10219 TypeSourceInfo *TInfo,
10220 SourceLocation StartLoc,
10221 SourceLocation Loc,
10222 IdentifierInfo *Name) {
10223 bool Invalid = false;
10224 QualType ExDeclType = TInfo->getType();
10225
10226 // Arrays and functions decay.
10227 if (ExDeclType->isArrayType())
10228 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10229 else if (ExDeclType->isFunctionType())
10230 ExDeclType = Context.getPointerType(ExDeclType);
10231
10232 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10233 // The exception-declaration shall not denote a pointer or reference to an
10234 // incomplete type, other than [cv] void*.
10235 // N2844 forbids rvalue references.
10236 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10237 Diag(Loc, diag::err_catch_rvalue_ref);
10238 Invalid = true;
10239 }
10240
10241 QualType BaseType = ExDeclType;
10242 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10243 unsigned DK = diag::err_catch_incomplete;
10244 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10245 BaseType = Ptr->getPointeeType();
10246 Mode = 1;
10247 DK = diag::err_catch_incomplete_ptr;
10248 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10249 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10250 BaseType = Ref->getPointeeType();
10251 Mode = 2;
10252 DK = diag::err_catch_incomplete_ref;
10253 }
10254 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10255 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10256 Invalid = true;
10257
10258 if (!Invalid && !ExDeclType->isDependentType() &&
10259 RequireNonAbstractType(Loc, ExDeclType,
10260 diag::err_abstract_type_in_decl,
10261 AbstractVariableType))
10262 Invalid = true;
10263
10264 // Only the non-fragile NeXT runtime currently supports C++ catches
10265 // of ObjC types, and no runtime supports catching ObjC types by value.
10266 if (!Invalid && getLangOpts().ObjC1) {
10267 QualType T = ExDeclType;
10268 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10269 T = RT->getPointeeType();
10270
10271 if (T->isObjCObjectType()) {
10272 Diag(Loc, diag::err_objc_object_catch);
10273 Invalid = true;
10274 } else if (T->isObjCObjectPointerType()) {
10275 // FIXME: should this be a test for macosx-fragile specifically?
10276 if (getLangOpts().ObjCRuntime.isFragile())
10277 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10278 }
10279 }
10280
10281 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10282 ExDeclType, TInfo, SC_None, SC_None);
10283 ExDecl->setExceptionVariable(true);
10284
10285 // In ARC, infer 'retaining' for variables of retainable type.
10286 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10287 Invalid = true;
10288
10289 if (!Invalid && !ExDeclType->isDependentType()) {
10290 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10291 // C++ [except.handle]p16:
10292 // The object declared in an exception-declaration or, if the
10293 // exception-declaration does not specify a name, a temporary (12.2) is
10294 // copy-initialized (8.5) from the exception object. [...]
10295 // The object is destroyed when the handler exits, after the destruction
10296 // of any automatic objects initialized within the handler.
10297 //
10298 // We just pretend to initialize the object with itself, then make sure
10299 // it can be destroyed later.
10300 QualType initType = ExDeclType;
10301
10302 InitializedEntity entity =
10303 InitializedEntity::InitializeVariable(ExDecl);
10304 InitializationKind initKind =
10305 InitializationKind::CreateCopy(Loc, SourceLocation());
10306
10307 Expr *opaqueValue =
10308 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10309 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10310 ExprResult result = sequence.Perform(*this, entity, initKind,
10311 MultiExprArg(&opaqueValue, 1));
10312 if (result.isInvalid())
10313 Invalid = true;
10314 else {
10315 // If the constructor used was non-trivial, set this as the
10316 // "initializer".
10317 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10318 if (!construct->getConstructor()->isTrivial()) {
10319 Expr *init = MaybeCreateExprWithCleanups(construct);
10320 ExDecl->setInit(init);
10321 }
10322
10323 // And make sure it's destructable.
10324 FinalizeVarWithDestructor(ExDecl, recordType);
10325 }
10326 }
10327 }
10328
10329 if (Invalid)
10330 ExDecl->setInvalidDecl();
10331
10332 return ExDecl;
10333 }
10334
10335 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10336 /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)10337 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10338 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10339 bool Invalid = D.isInvalidType();
10340
10341 // Check for unexpanded parameter packs.
10342 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10343 UPPC_ExceptionType)) {
10344 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10345 D.getIdentifierLoc());
10346 Invalid = true;
10347 }
10348
10349 IdentifierInfo *II = D.getIdentifier();
10350 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10351 LookupOrdinaryName,
10352 ForRedeclaration)) {
10353 // The scope should be freshly made just for us. There is just no way
10354 // it contains any previous declaration.
10355 assert(!S->isDeclScope(PrevDecl));
10356 if (PrevDecl->isTemplateParameter()) {
10357 // Maybe we will complain about the shadowed template parameter.
10358 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10359 PrevDecl = 0;
10360 }
10361 }
10362
10363 if (D.getCXXScopeSpec().isSet() && !Invalid) {
10364 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10365 << D.getCXXScopeSpec().getRange();
10366 Invalid = true;
10367 }
10368
10369 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10370 D.getLocStart(),
10371 D.getIdentifierLoc(),
10372 D.getIdentifier());
10373 if (Invalid)
10374 ExDecl->setInvalidDecl();
10375
10376 // Add the exception declaration into this scope.
10377 if (II)
10378 PushOnScopeChains(ExDecl, S);
10379 else
10380 CurContext->addDecl(ExDecl);
10381
10382 ProcessDeclAttributes(S, ExDecl, D);
10383 return ExDecl;
10384 }
10385
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)10386 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10387 Expr *AssertExpr,
10388 Expr *AssertMessageExpr,
10389 SourceLocation RParenLoc) {
10390 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10391
10392 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10393 return 0;
10394
10395 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10396 AssertMessage, RParenLoc, false);
10397 }
10398
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,StringLiteral * AssertMessage,SourceLocation RParenLoc,bool Failed)10399 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10400 Expr *AssertExpr,
10401 StringLiteral *AssertMessage,
10402 SourceLocation RParenLoc,
10403 bool Failed) {
10404 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10405 !Failed) {
10406 // In a static_assert-declaration, the constant-expression shall be a
10407 // constant expression that can be contextually converted to bool.
10408 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10409 if (Converted.isInvalid())
10410 Failed = true;
10411
10412 llvm::APSInt Cond;
10413 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10414 diag::err_static_assert_expression_is_not_constant,
10415 /*AllowFold=*/false).isInvalid())
10416 Failed = true;
10417
10418 if (!Failed && !Cond) {
10419 SmallString<256> MsgBuffer;
10420 llvm::raw_svector_ostream Msg(MsgBuffer);
10421 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10422 Diag(StaticAssertLoc, diag::err_static_assert_failed)
10423 << Msg.str() << AssertExpr->getSourceRange();
10424 Failed = true;
10425 }
10426 }
10427
10428 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10429 AssertExpr, AssertMessage, RParenLoc,
10430 Failed);
10431
10432 CurContext->addDecl(Decl);
10433 return Decl;
10434 }
10435
10436 /// \brief Perform semantic analysis of the given friend type declaration.
10437 ///
10438 /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation LocStart,SourceLocation FriendLoc,TypeSourceInfo * TSInfo)10439 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10440 SourceLocation FriendLoc,
10441 TypeSourceInfo *TSInfo) {
10442 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10443
10444 QualType T = TSInfo->getType();
10445 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10446
10447 // C++03 [class.friend]p2:
10448 // An elaborated-type-specifier shall be used in a friend declaration
10449 // for a class.*
10450 //
10451 // * The class-key of the elaborated-type-specifier is required.
10452 if (!ActiveTemplateInstantiations.empty()) {
10453 // Do not complain about the form of friend template types during
10454 // template instantiation; we will already have complained when the
10455 // template was declared.
10456 } else {
10457 if (!T->isElaboratedTypeSpecifier()) {
10458 // If we evaluated the type to a record type, suggest putting
10459 // a tag in front.
10460 if (const RecordType *RT = T->getAs<RecordType>()) {
10461 RecordDecl *RD = RT->getDecl();
10462
10463 std::string InsertionText = std::string(" ") + RD->getKindName();
10464
10465 Diag(TypeRange.getBegin(),
10466 getLangOpts().CPlusPlus11 ?
10467 diag::warn_cxx98_compat_unelaborated_friend_type :
10468 diag::ext_unelaborated_friend_type)
10469 << (unsigned) RD->getTagKind()
10470 << T
10471 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10472 InsertionText);
10473 } else {
10474 Diag(FriendLoc,
10475 getLangOpts().CPlusPlus11 ?
10476 diag::warn_cxx98_compat_nonclass_type_friend :
10477 diag::ext_nonclass_type_friend)
10478 << T
10479 << TypeRange;
10480 }
10481 } else if (T->getAs<EnumType>()) {
10482 Diag(FriendLoc,
10483 getLangOpts().CPlusPlus11 ?
10484 diag::warn_cxx98_compat_enum_friend :
10485 diag::ext_enum_friend)
10486 << T
10487 << TypeRange;
10488 }
10489
10490 // C++11 [class.friend]p3:
10491 // A friend declaration that does not declare a function shall have one
10492 // of the following forms:
10493 // friend elaborated-type-specifier ;
10494 // friend simple-type-specifier ;
10495 // friend typename-specifier ;
10496 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10497 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10498 }
10499
10500 // If the type specifier in a friend declaration designates a (possibly
10501 // cv-qualified) class type, that class is declared as a friend; otherwise,
10502 // the friend declaration is ignored.
10503 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10504 }
10505
10506 /// Handle a friend tag declaration where the scope specifier was
10507 /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,MultiTemplateParamsArg TempParamLists)10508 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10509 unsigned TagSpec, SourceLocation TagLoc,
10510 CXXScopeSpec &SS,
10511 IdentifierInfo *Name,
10512 SourceLocation NameLoc,
10513 AttributeList *Attr,
10514 MultiTemplateParamsArg TempParamLists) {
10515 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10516
10517 bool isExplicitSpecialization = false;
10518 bool Invalid = false;
10519
10520 if (TemplateParameterList *TemplateParams
10521 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10522 TempParamLists.data(),
10523 TempParamLists.size(),
10524 /*friend*/ true,
10525 isExplicitSpecialization,
10526 Invalid)) {
10527 if (TemplateParams->size() > 0) {
10528 // This is a declaration of a class template.
10529 if (Invalid)
10530 return 0;
10531
10532 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10533 SS, Name, NameLoc, Attr,
10534 TemplateParams, AS_public,
10535 /*ModulePrivateLoc=*/SourceLocation(),
10536 TempParamLists.size() - 1,
10537 TempParamLists.data()).take();
10538 } else {
10539 // The "template<>" header is extraneous.
10540 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10541 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10542 isExplicitSpecialization = true;
10543 }
10544 }
10545
10546 if (Invalid) return 0;
10547
10548 bool isAllExplicitSpecializations = true;
10549 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10550 if (TempParamLists[I]->size()) {
10551 isAllExplicitSpecializations = false;
10552 break;
10553 }
10554 }
10555
10556 // FIXME: don't ignore attributes.
10557
10558 // If it's explicit specializations all the way down, just forget
10559 // about the template header and build an appropriate non-templated
10560 // friend. TODO: for source fidelity, remember the headers.
10561 if (isAllExplicitSpecializations) {
10562 if (SS.isEmpty()) {
10563 bool Owned = false;
10564 bool IsDependent = false;
10565 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10566 Attr, AS_public,
10567 /*ModulePrivateLoc=*/SourceLocation(),
10568 MultiTemplateParamsArg(), Owned, IsDependent,
10569 /*ScopedEnumKWLoc=*/SourceLocation(),
10570 /*ScopedEnumUsesClassTag=*/false,
10571 /*UnderlyingType=*/TypeResult());
10572 }
10573
10574 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10575 ElaboratedTypeKeyword Keyword
10576 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10577 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10578 *Name, NameLoc);
10579 if (T.isNull())
10580 return 0;
10581
10582 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10583 if (isa<DependentNameType>(T)) {
10584 DependentNameTypeLoc TL =
10585 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10586 TL.setElaboratedKeywordLoc(TagLoc);
10587 TL.setQualifierLoc(QualifierLoc);
10588 TL.setNameLoc(NameLoc);
10589 } else {
10590 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10591 TL.setElaboratedKeywordLoc(TagLoc);
10592 TL.setQualifierLoc(QualifierLoc);
10593 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10594 }
10595
10596 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10597 TSI, FriendLoc, TempParamLists);
10598 Friend->setAccess(AS_public);
10599 CurContext->addDecl(Friend);
10600 return Friend;
10601 }
10602
10603 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10604
10605
10606
10607 // Handle the case of a templated-scope friend class. e.g.
10608 // template <class T> class A<T>::B;
10609 // FIXME: we don't support these right now.
10610 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10611 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10612 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10613 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10614 TL.setElaboratedKeywordLoc(TagLoc);
10615 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10616 TL.setNameLoc(NameLoc);
10617
10618 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10619 TSI, FriendLoc, TempParamLists);
10620 Friend->setAccess(AS_public);
10621 Friend->setUnsupportedFriend(true);
10622 CurContext->addDecl(Friend);
10623 return Friend;
10624 }
10625
10626
10627 /// Handle a friend type declaration. This works in tandem with
10628 /// ActOnTag.
10629 ///
10630 /// Notes on friend class templates:
10631 ///
10632 /// We generally treat friend class declarations as if they were
10633 /// declaring a class. So, for example, the elaborated type specifier
10634 /// in a friend declaration is required to obey the restrictions of a
10635 /// class-head (i.e. no typedefs in the scope chain), template
10636 /// parameters are required to match up with simple template-ids, &c.
10637 /// However, unlike when declaring a template specialization, it's
10638 /// okay to refer to a template specialization without an empty
10639 /// template parameter declaration, e.g.
10640 /// friend class A<T>::B<unsigned>;
10641 /// We permit this as a special case; if there are any template
10642 /// parameters present at all, require proper matching, i.e.
10643 /// template <> template \<class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)10644 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10645 MultiTemplateParamsArg TempParams) {
10646 SourceLocation Loc = DS.getLocStart();
10647
10648 assert(DS.isFriendSpecified());
10649 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10650
10651 // Try to convert the decl specifier to a type. This works for
10652 // friend templates because ActOnTag never produces a ClassTemplateDecl
10653 // for a TUK_Friend.
10654 Declarator TheDeclarator(DS, Declarator::MemberContext);
10655 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10656 QualType T = TSI->getType();
10657 if (TheDeclarator.isInvalidType())
10658 return 0;
10659
10660 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10661 return 0;
10662
10663 // This is definitely an error in C++98. It's probably meant to
10664 // be forbidden in C++0x, too, but the specification is just
10665 // poorly written.
10666 //
10667 // The problem is with declarations like the following:
10668 // template <T> friend A<T>::foo;
10669 // where deciding whether a class C is a friend or not now hinges
10670 // on whether there exists an instantiation of A that causes
10671 // 'foo' to equal C. There are restrictions on class-heads
10672 // (which we declare (by fiat) elaborated friend declarations to
10673 // be) that makes this tractable.
10674 //
10675 // FIXME: handle "template <> friend class A<T>;", which
10676 // is possibly well-formed? Who even knows?
10677 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10678 Diag(Loc, diag::err_tagless_friend_type_template)
10679 << DS.getSourceRange();
10680 return 0;
10681 }
10682
10683 // C++98 [class.friend]p1: A friend of a class is a function
10684 // or class that is not a member of the class . . .
10685 // This is fixed in DR77, which just barely didn't make the C++03
10686 // deadline. It's also a very silly restriction that seriously
10687 // affects inner classes and which nobody else seems to implement;
10688 // thus we never diagnose it, not even in -pedantic.
10689 //
10690 // But note that we could warn about it: it's always useless to
10691 // friend one of your own members (it's not, however, worthless to
10692 // friend a member of an arbitrary specialization of your template).
10693
10694 Decl *D;
10695 if (unsigned NumTempParamLists = TempParams.size())
10696 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10697 NumTempParamLists,
10698 TempParams.data(),
10699 TSI,
10700 DS.getFriendSpecLoc());
10701 else
10702 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10703
10704 if (!D)
10705 return 0;
10706
10707 D->setAccess(AS_public);
10708 CurContext->addDecl(D);
10709
10710 return D;
10711 }
10712
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)10713 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10714 MultiTemplateParamsArg TemplateParams) {
10715 const DeclSpec &DS = D.getDeclSpec();
10716
10717 assert(DS.isFriendSpecified());
10718 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10719
10720 SourceLocation Loc = D.getIdentifierLoc();
10721 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10722
10723 // C++ [class.friend]p1
10724 // A friend of a class is a function or class....
10725 // Note that this sees through typedefs, which is intended.
10726 // It *doesn't* see through dependent types, which is correct
10727 // according to [temp.arg.type]p3:
10728 // If a declaration acquires a function type through a
10729 // type dependent on a template-parameter and this causes
10730 // a declaration that does not use the syntactic form of a
10731 // function declarator to have a function type, the program
10732 // is ill-formed.
10733 if (!TInfo->getType()->isFunctionType()) {
10734 Diag(Loc, diag::err_unexpected_friend);
10735
10736 // It might be worthwhile to try to recover by creating an
10737 // appropriate declaration.
10738 return 0;
10739 }
10740
10741 // C++ [namespace.memdef]p3
10742 // - If a friend declaration in a non-local class first declares a
10743 // class or function, the friend class or function is a member
10744 // of the innermost enclosing namespace.
10745 // - The name of the friend is not found by simple name lookup
10746 // until a matching declaration is provided in that namespace
10747 // scope (either before or after the class declaration granting
10748 // friendship).
10749 // - If a friend function is called, its name may be found by the
10750 // name lookup that considers functions from namespaces and
10751 // classes associated with the types of the function arguments.
10752 // - When looking for a prior declaration of a class or a function
10753 // declared as a friend, scopes outside the innermost enclosing
10754 // namespace scope are not considered.
10755
10756 CXXScopeSpec &SS = D.getCXXScopeSpec();
10757 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10758 DeclarationName Name = NameInfo.getName();
10759 assert(Name);
10760
10761 // Check for unexpanded parameter packs.
10762 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10763 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10764 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10765 return 0;
10766
10767 // The context we found the declaration in, or in which we should
10768 // create the declaration.
10769 DeclContext *DC;
10770 Scope *DCScope = S;
10771 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10772 ForRedeclaration);
10773
10774 // FIXME: there are different rules in local classes
10775
10776 // There are four cases here.
10777 // - There's no scope specifier, in which case we just go to the
10778 // appropriate scope and look for a function or function template
10779 // there as appropriate.
10780 // Recover from invalid scope qualifiers as if they just weren't there.
10781 if (SS.isInvalid() || !SS.isSet()) {
10782 // C++0x [namespace.memdef]p3:
10783 // If the name in a friend declaration is neither qualified nor
10784 // a template-id and the declaration is a function or an
10785 // elaborated-type-specifier, the lookup to determine whether
10786 // the entity has been previously declared shall not consider
10787 // any scopes outside the innermost enclosing namespace.
10788 // C++0x [class.friend]p11:
10789 // If a friend declaration appears in a local class and the name
10790 // specified is an unqualified name, a prior declaration is
10791 // looked up without considering scopes that are outside the
10792 // innermost enclosing non-class scope. For a friend function
10793 // declaration, if there is no prior declaration, the program is
10794 // ill-formed.
10795 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10796 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10797
10798 // Find the appropriate context according to the above.
10799 DC = CurContext;
10800 while (true) {
10801 // Skip class contexts. If someone can cite chapter and verse
10802 // for this behavior, that would be nice --- it's what GCC and
10803 // EDG do, and it seems like a reasonable intent, but the spec
10804 // really only says that checks for unqualified existing
10805 // declarations should stop at the nearest enclosing namespace,
10806 // not that they should only consider the nearest enclosing
10807 // namespace.
10808 while (DC->isRecord() || DC->isTransparentContext())
10809 DC = DC->getParent();
10810
10811 LookupQualifiedName(Previous, DC);
10812
10813 // TODO: decide what we think about using declarations.
10814 if (isLocal || !Previous.empty())
10815 break;
10816
10817 if (isTemplateId) {
10818 if (isa<TranslationUnitDecl>(DC)) break;
10819 } else {
10820 if (DC->isFileContext()) break;
10821 }
10822 DC = DC->getParent();
10823 }
10824
10825 // C++ [class.friend]p1: A friend of a class is a function or
10826 // class that is not a member of the class . . .
10827 // C++11 changes this for both friend types and functions.
10828 // Most C++ 98 compilers do seem to give an error here, so
10829 // we do, too.
10830 if (!Previous.empty() && DC->Equals(CurContext))
10831 Diag(DS.getFriendSpecLoc(),
10832 getLangOpts().CPlusPlus11 ?
10833 diag::warn_cxx98_compat_friend_is_member :
10834 diag::err_friend_is_member);
10835
10836 DCScope = getScopeForDeclContext(S, DC);
10837
10838 // C++ [class.friend]p6:
10839 // A function can be defined in a friend declaration of a class if and
10840 // only if the class is a non-local class (9.8), the function name is
10841 // unqualified, and the function has namespace scope.
10842 if (isLocal && D.isFunctionDefinition()) {
10843 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10844 }
10845
10846 // - There's a non-dependent scope specifier, in which case we
10847 // compute it and do a previous lookup there for a function
10848 // or function template.
10849 } else if (!SS.getScopeRep()->isDependent()) {
10850 DC = computeDeclContext(SS);
10851 if (!DC) return 0;
10852
10853 if (RequireCompleteDeclContext(SS, DC)) return 0;
10854
10855 LookupQualifiedName(Previous, DC);
10856
10857 // Ignore things found implicitly in the wrong scope.
10858 // TODO: better diagnostics for this case. Suggesting the right
10859 // qualified scope would be nice...
10860 LookupResult::Filter F = Previous.makeFilter();
10861 while (F.hasNext()) {
10862 NamedDecl *D = F.next();
10863 if (!DC->InEnclosingNamespaceSetOf(
10864 D->getDeclContext()->getRedeclContext()))
10865 F.erase();
10866 }
10867 F.done();
10868
10869 if (Previous.empty()) {
10870 D.setInvalidType();
10871 Diag(Loc, diag::err_qualified_friend_not_found)
10872 << Name << TInfo->getType();
10873 return 0;
10874 }
10875
10876 // C++ [class.friend]p1: A friend of a class is a function or
10877 // class that is not a member of the class . . .
10878 if (DC->Equals(CurContext))
10879 Diag(DS.getFriendSpecLoc(),
10880 getLangOpts().CPlusPlus11 ?
10881 diag::warn_cxx98_compat_friend_is_member :
10882 diag::err_friend_is_member);
10883
10884 if (D.isFunctionDefinition()) {
10885 // C++ [class.friend]p6:
10886 // A function can be defined in a friend declaration of a class if and
10887 // only if the class is a non-local class (9.8), the function name is
10888 // unqualified, and the function has namespace scope.
10889 SemaDiagnosticBuilder DB
10890 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10891
10892 DB << SS.getScopeRep();
10893 if (DC->isFileContext())
10894 DB << FixItHint::CreateRemoval(SS.getRange());
10895 SS.clear();
10896 }
10897
10898 // - There's a scope specifier that does not match any template
10899 // parameter lists, in which case we use some arbitrary context,
10900 // create a method or method template, and wait for instantiation.
10901 // - There's a scope specifier that does match some template
10902 // parameter lists, which we don't handle right now.
10903 } else {
10904 if (D.isFunctionDefinition()) {
10905 // C++ [class.friend]p6:
10906 // A function can be defined in a friend declaration of a class if and
10907 // only if the class is a non-local class (9.8), the function name is
10908 // unqualified, and the function has namespace scope.
10909 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10910 << SS.getScopeRep();
10911 }
10912
10913 DC = CurContext;
10914 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10915 }
10916
10917 if (!DC->isRecord()) {
10918 // This implies that it has to be an operator or function.
10919 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10920 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10921 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10922 Diag(Loc, diag::err_introducing_special_friend) <<
10923 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10924 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10925 return 0;
10926 }
10927 }
10928
10929 // FIXME: This is an egregious hack to cope with cases where the scope stack
10930 // does not contain the declaration context, i.e., in an out-of-line
10931 // definition of a class.
10932 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10933 if (!DCScope) {
10934 FakeDCScope.setEntity(DC);
10935 DCScope = &FakeDCScope;
10936 }
10937
10938 bool AddToScope = true;
10939 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10940 TemplateParams, AddToScope);
10941 if (!ND) return 0;
10942
10943 assert(ND->getDeclContext() == DC);
10944 assert(ND->getLexicalDeclContext() == CurContext);
10945
10946 // Add the function declaration to the appropriate lookup tables,
10947 // adjusting the redeclarations list as necessary. We don't
10948 // want to do this yet if the friending class is dependent.
10949 //
10950 // Also update the scope-based lookup if the target context's
10951 // lookup context is in lexical scope.
10952 if (!CurContext->isDependentContext()) {
10953 DC = DC->getRedeclContext();
10954 DC->makeDeclVisibleInContext(ND);
10955 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10956 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10957 }
10958
10959 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10960 D.getIdentifierLoc(), ND,
10961 DS.getFriendSpecLoc());
10962 FrD->setAccess(AS_public);
10963 CurContext->addDecl(FrD);
10964
10965 if (ND->isInvalidDecl()) {
10966 FrD->setInvalidDecl();
10967 } else {
10968 if (DC->isRecord()) CheckFriendAccess(ND);
10969
10970 FunctionDecl *FD;
10971 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10972 FD = FTD->getTemplatedDecl();
10973 else
10974 FD = cast<FunctionDecl>(ND);
10975
10976 // Mark templated-scope function declarations as unsupported.
10977 if (FD->getNumTemplateParameterLists())
10978 FrD->setUnsupportedFriend(true);
10979 }
10980
10981 return ND;
10982 }
10983
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)10984 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10985 AdjustDeclIfTemplate(Dcl);
10986
10987 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
10988 if (!Fn) {
10989 Diag(DelLoc, diag::err_deleted_non_function);
10990 return;
10991 }
10992 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10993 // Don't consider the implicit declaration we generate for explicit
10994 // specializations. FIXME: Do not generate these implicit declarations.
10995 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10996 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10997 Diag(DelLoc, diag::err_deleted_decl_not_first);
10998 Diag(Prev->getLocation(), diag::note_previous_declaration);
10999 }
11000 // If the declaration wasn't the first, we delete the function anyway for
11001 // recovery.
11002 }
11003 Fn->setDeletedAsWritten();
11004 }
11005
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)11006 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11007 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11008
11009 if (MD) {
11010 if (MD->getParent()->isDependentType()) {
11011 MD->setDefaulted();
11012 MD->setExplicitlyDefaulted();
11013 return;
11014 }
11015
11016 CXXSpecialMember Member = getSpecialMember(MD);
11017 if (Member == CXXInvalid) {
11018 Diag(DefaultLoc, diag::err_default_special_members);
11019 return;
11020 }
11021
11022 MD->setDefaulted();
11023 MD->setExplicitlyDefaulted();
11024
11025 // If this definition appears within the record, do the checking when
11026 // the record is complete.
11027 const FunctionDecl *Primary = MD;
11028 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11029 // Find the uninstantiated declaration that actually had the '= default'
11030 // on it.
11031 Pattern->isDefined(Primary);
11032
11033 if (Primary == Primary->getCanonicalDecl())
11034 return;
11035
11036 CheckExplicitlyDefaultedSpecialMember(MD);
11037
11038 // The exception specification is needed because we are defining the
11039 // function.
11040 ResolveExceptionSpec(DefaultLoc,
11041 MD->getType()->castAs<FunctionProtoType>());
11042
11043 switch (Member) {
11044 case CXXDefaultConstructor: {
11045 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11046 if (!CD->isInvalidDecl())
11047 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11048 break;
11049 }
11050
11051 case CXXCopyConstructor: {
11052 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11053 if (!CD->isInvalidDecl())
11054 DefineImplicitCopyConstructor(DefaultLoc, CD);
11055 break;
11056 }
11057
11058 case CXXCopyAssignment: {
11059 if (!MD->isInvalidDecl())
11060 DefineImplicitCopyAssignment(DefaultLoc, MD);
11061 break;
11062 }
11063
11064 case CXXDestructor: {
11065 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11066 if (!DD->isInvalidDecl())
11067 DefineImplicitDestructor(DefaultLoc, DD);
11068 break;
11069 }
11070
11071 case CXXMoveConstructor: {
11072 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11073 if (!CD->isInvalidDecl())
11074 DefineImplicitMoveConstructor(DefaultLoc, CD);
11075 break;
11076 }
11077
11078 case CXXMoveAssignment: {
11079 if (!MD->isInvalidDecl())
11080 DefineImplicitMoveAssignment(DefaultLoc, MD);
11081 break;
11082 }
11083
11084 case CXXInvalid:
11085 llvm_unreachable("Invalid special member.");
11086 }
11087 } else {
11088 Diag(DefaultLoc, diag::err_default_special_members);
11089 }
11090 }
11091
SearchForReturnInStmt(Sema & Self,Stmt * S)11092 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11093 for (Stmt::child_range CI = S->children(); CI; ++CI) {
11094 Stmt *SubStmt = *CI;
11095 if (!SubStmt)
11096 continue;
11097 if (isa<ReturnStmt>(SubStmt))
11098 Self.Diag(SubStmt->getLocStart(),
11099 diag::err_return_in_constructor_handler);
11100 if (!isa<Expr>(SubStmt))
11101 SearchForReturnInStmt(Self, SubStmt);
11102 }
11103 }
11104
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)11105 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11106 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11107 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11108 SearchForReturnInStmt(*this, Handler);
11109 }
11110 }
11111
CheckOverridingFunctionAttributes(const CXXMethodDecl * New,const CXXMethodDecl * Old)11112 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11113 const CXXMethodDecl *Old) {
11114 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11115 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11116
11117 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11118
11119 // If the calling conventions match, everything is fine
11120 if (NewCC == OldCC)
11121 return false;
11122
11123 // If either of the calling conventions are set to "default", we need to pick
11124 // something more sensible based on the target. This supports code where the
11125 // one method explicitly sets thiscall, and another has no explicit calling
11126 // convention.
11127 CallingConv Default =
11128 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11129 if (NewCC == CC_Default)
11130 NewCC = Default;
11131 if (OldCC == CC_Default)
11132 OldCC = Default;
11133
11134 // If the calling conventions still don't match, then report the error
11135 if (NewCC != OldCC) {
11136 Diag(New->getLocation(),
11137 diag::err_conflicting_overriding_cc_attributes)
11138 << New->getDeclName() << New->getType() << Old->getType();
11139 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11140 return true;
11141 }
11142
11143 return false;
11144 }
11145
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)11146 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11147 const CXXMethodDecl *Old) {
11148 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11149 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11150
11151 if (Context.hasSameType(NewTy, OldTy) ||
11152 NewTy->isDependentType() || OldTy->isDependentType())
11153 return false;
11154
11155 // Check if the return types are covariant
11156 QualType NewClassTy, OldClassTy;
11157
11158 /// Both types must be pointers or references to classes.
11159 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11160 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11161 NewClassTy = NewPT->getPointeeType();
11162 OldClassTy = OldPT->getPointeeType();
11163 }
11164 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11165 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11166 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11167 NewClassTy = NewRT->getPointeeType();
11168 OldClassTy = OldRT->getPointeeType();
11169 }
11170 }
11171 }
11172
11173 // The return types aren't either both pointers or references to a class type.
11174 if (NewClassTy.isNull()) {
11175 Diag(New->getLocation(),
11176 diag::err_different_return_type_for_overriding_virtual_function)
11177 << New->getDeclName() << NewTy << OldTy;
11178 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11179
11180 return true;
11181 }
11182
11183 // C++ [class.virtual]p6:
11184 // If the return type of D::f differs from the return type of B::f, the
11185 // class type in the return type of D::f shall be complete at the point of
11186 // declaration of D::f or shall be the class type D.
11187 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11188 if (!RT->isBeingDefined() &&
11189 RequireCompleteType(New->getLocation(), NewClassTy,
11190 diag::err_covariant_return_incomplete,
11191 New->getDeclName()))
11192 return true;
11193 }
11194
11195 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11196 // Check if the new class derives from the old class.
11197 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11198 Diag(New->getLocation(),
11199 diag::err_covariant_return_not_derived)
11200 << New->getDeclName() << NewTy << OldTy;
11201 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11202 return true;
11203 }
11204
11205 // Check if we the conversion from derived to base is valid.
11206 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11207 diag::err_covariant_return_inaccessible_base,
11208 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11209 // FIXME: Should this point to the return type?
11210 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11211 // FIXME: this note won't trigger for delayed access control
11212 // diagnostics, and it's impossible to get an undelayed error
11213 // here from access control during the original parse because
11214 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11215 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11216 return true;
11217 }
11218 }
11219
11220 // The qualifiers of the return types must be the same.
11221 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11222 Diag(New->getLocation(),
11223 diag::err_covariant_return_type_different_qualifications)
11224 << New->getDeclName() << NewTy << OldTy;
11225 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11226 return true;
11227 };
11228
11229
11230 // The new class type must have the same or less qualifiers as the old type.
11231 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11232 Diag(New->getLocation(),
11233 diag::err_covariant_return_type_class_type_more_qualified)
11234 << New->getDeclName() << NewTy << OldTy;
11235 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11236 return true;
11237 };
11238
11239 return false;
11240 }
11241
11242 /// \brief Mark the given method pure.
11243 ///
11244 /// \param Method the method to be marked pure.
11245 ///
11246 /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)11247 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11248 SourceLocation EndLoc = InitRange.getEnd();
11249 if (EndLoc.isValid())
11250 Method->setRangeEnd(EndLoc);
11251
11252 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11253 Method->setPure();
11254 return false;
11255 }
11256
11257 if (!Method->isInvalidDecl())
11258 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11259 << Method->getDeclName() << InitRange;
11260 return true;
11261 }
11262
11263 /// \brief Determine whether the given declaration is a static data member.
isStaticDataMember(Decl * D)11264 static bool isStaticDataMember(Decl *D) {
11265 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11266 if (!Var)
11267 return false;
11268
11269 return Var->isStaticDataMember();
11270 }
11271 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11272 /// an initializer for the out-of-line declaration 'Dcl'. The scope
11273 /// is a fresh scope pushed for just this purpose.
11274 ///
11275 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11276 /// static data member of class X, names should be looked up in the scope of
11277 /// class X.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)11278 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11279 // If there is no declaration, there was an error parsing it.
11280 if (D == 0 || D->isInvalidDecl()) return;
11281
11282 // We should only get called for declarations with scope specifiers, like:
11283 // int foo::bar;
11284 assert(D->isOutOfLine());
11285 EnterDeclaratorContext(S, D->getDeclContext());
11286
11287 // If we are parsing the initializer for a static data member, push a
11288 // new expression evaluation context that is associated with this static
11289 // data member.
11290 if (isStaticDataMember(D))
11291 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11292 }
11293
11294 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11295 /// initializer for the out-of-line declaration 'D'.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)11296 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11297 // If there is no declaration, there was an error parsing it.
11298 if (D == 0 || D->isInvalidDecl()) return;
11299
11300 if (isStaticDataMember(D))
11301 PopExpressionEvaluationContext();
11302
11303 assert(D->isOutOfLine());
11304 ExitDeclaratorContext(S);
11305 }
11306
11307 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11308 /// C++ if/switch/while/for statement.
11309 /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)11310 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11311 // C++ 6.4p2:
11312 // The declarator shall not specify a function or an array.
11313 // The type-specifier-seq shall not contain typedef and shall not declare a
11314 // new class or enumeration.
11315 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11316 "Parser allowed 'typedef' as storage class of condition decl.");
11317
11318 Decl *Dcl = ActOnDeclarator(S, D);
11319 if (!Dcl)
11320 return true;
11321
11322 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11323 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11324 << D.getSourceRange();
11325 return true;
11326 }
11327
11328 return Dcl;
11329 }
11330
LoadExternalVTableUses()11331 void Sema::LoadExternalVTableUses() {
11332 if (!ExternalSource)
11333 return;
11334
11335 SmallVector<ExternalVTableUse, 4> VTables;
11336 ExternalSource->ReadUsedVTables(VTables);
11337 SmallVector<VTableUse, 4> NewUses;
11338 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11339 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11340 = VTablesUsed.find(VTables[I].Record);
11341 // Even if a definition wasn't required before, it may be required now.
11342 if (Pos != VTablesUsed.end()) {
11343 if (!Pos->second && VTables[I].DefinitionRequired)
11344 Pos->second = true;
11345 continue;
11346 }
11347
11348 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11349 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11350 }
11351
11352 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11353 }
11354
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)11355 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11356 bool DefinitionRequired) {
11357 // Ignore any vtable uses in unevaluated operands or for classes that do
11358 // not have a vtable.
11359 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11360 CurContext->isDependentContext() ||
11361 ExprEvalContexts.back().Context == Unevaluated)
11362 return;
11363
11364 // Try to insert this class into the map.
11365 LoadExternalVTableUses();
11366 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11367 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11368 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11369 if (!Pos.second) {
11370 // If we already had an entry, check to see if we are promoting this vtable
11371 // to required a definition. If so, we need to reappend to the VTableUses
11372 // list, since we may have already processed the first entry.
11373 if (DefinitionRequired && !Pos.first->second) {
11374 Pos.first->second = true;
11375 } else {
11376 // Otherwise, we can early exit.
11377 return;
11378 }
11379 }
11380
11381 // Local classes need to have their virtual members marked
11382 // immediately. For all other classes, we mark their virtual members
11383 // at the end of the translation unit.
11384 if (Class->isLocalClass())
11385 MarkVirtualMembersReferenced(Loc, Class);
11386 else
11387 VTableUses.push_back(std::make_pair(Class, Loc));
11388 }
11389
DefineUsedVTables()11390 bool Sema::DefineUsedVTables() {
11391 LoadExternalVTableUses();
11392 if (VTableUses.empty())
11393 return false;
11394
11395 // Note: The VTableUses vector could grow as a result of marking
11396 // the members of a class as "used", so we check the size each
11397 // time through the loop and prefer indices (which are stable) to
11398 // iterators (which are not).
11399 bool DefinedAnything = false;
11400 for (unsigned I = 0; I != VTableUses.size(); ++I) {
11401 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11402 if (!Class)
11403 continue;
11404
11405 SourceLocation Loc = VTableUses[I].second;
11406
11407 bool DefineVTable = true;
11408
11409 // If this class has a key function, but that key function is
11410 // defined in another translation unit, we don't need to emit the
11411 // vtable even though we're using it.
11412 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11413 if (KeyFunction && !KeyFunction->hasBody()) {
11414 switch (KeyFunction->getTemplateSpecializationKind()) {
11415 case TSK_Undeclared:
11416 case TSK_ExplicitSpecialization:
11417 case TSK_ExplicitInstantiationDeclaration:
11418 // The key function is in another translation unit.
11419 DefineVTable = false;
11420 break;
11421
11422 case TSK_ExplicitInstantiationDefinition:
11423 case TSK_ImplicitInstantiation:
11424 // We will be instantiating the key function.
11425 break;
11426 }
11427 } else if (!KeyFunction) {
11428 // If we have a class with no key function that is the subject
11429 // of an explicit instantiation declaration, suppress the
11430 // vtable; it will live with the explicit instantiation
11431 // definition.
11432 bool IsExplicitInstantiationDeclaration
11433 = Class->getTemplateSpecializationKind()
11434 == TSK_ExplicitInstantiationDeclaration;
11435 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11436 REnd = Class->redecls_end();
11437 R != REnd; ++R) {
11438 TemplateSpecializationKind TSK
11439 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11440 if (TSK == TSK_ExplicitInstantiationDeclaration)
11441 IsExplicitInstantiationDeclaration = true;
11442 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11443 IsExplicitInstantiationDeclaration = false;
11444 break;
11445 }
11446 }
11447
11448 if (IsExplicitInstantiationDeclaration)
11449 DefineVTable = false;
11450 }
11451
11452 // The exception specifications for all virtual members may be needed even
11453 // if we are not providing an authoritative form of the vtable in this TU.
11454 // We may choose to emit it available_externally anyway.
11455 if (!DefineVTable) {
11456 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11457 continue;
11458 }
11459
11460 // Mark all of the virtual members of this class as referenced, so
11461 // that we can build a vtable. Then, tell the AST consumer that a
11462 // vtable for this class is required.
11463 DefinedAnything = true;
11464 MarkVirtualMembersReferenced(Loc, Class);
11465 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11466 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11467
11468 // Optionally warn if we're emitting a weak vtable.
11469 if (Class->hasExternalLinkage() &&
11470 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11471 const FunctionDecl *KeyFunctionDef = 0;
11472 if (!KeyFunction ||
11473 (KeyFunction->hasBody(KeyFunctionDef) &&
11474 KeyFunctionDef->isInlined()))
11475 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11476 TSK_ExplicitInstantiationDefinition
11477 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11478 << Class;
11479 }
11480 }
11481 VTableUses.clear();
11482
11483 return DefinedAnything;
11484 }
11485
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)11486 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11487 const CXXRecordDecl *RD) {
11488 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11489 E = RD->method_end(); I != E; ++I)
11490 if ((*I)->isVirtual() && !(*I)->isPure())
11491 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11492 }
11493
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD)11494 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11495 const CXXRecordDecl *RD) {
11496 // Mark all functions which will appear in RD's vtable as used.
11497 CXXFinalOverriderMap FinalOverriders;
11498 RD->getFinalOverriders(FinalOverriders);
11499 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11500 E = FinalOverriders.end();
11501 I != E; ++I) {
11502 for (OverridingMethods::const_iterator OI = I->second.begin(),
11503 OE = I->second.end();
11504 OI != OE; ++OI) {
11505 assert(OI->second.size() > 0 && "no final overrider");
11506 CXXMethodDecl *Overrider = OI->second.front().Method;
11507
11508 // C++ [basic.def.odr]p2:
11509 // [...] A virtual member function is used if it is not pure. [...]
11510 if (!Overrider->isPure())
11511 MarkFunctionReferenced(Loc, Overrider);
11512 }
11513 }
11514
11515 // Only classes that have virtual bases need a VTT.
11516 if (RD->getNumVBases() == 0)
11517 return;
11518
11519 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11520 e = RD->bases_end(); i != e; ++i) {
11521 const CXXRecordDecl *Base =
11522 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11523 if (Base->getNumVBases() == 0)
11524 continue;
11525 MarkVirtualMembersReferenced(Loc, Base);
11526 }
11527 }
11528
11529 /// SetIvarInitializers - This routine builds initialization ASTs for the
11530 /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)11531 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11532 if (!getLangOpts().CPlusPlus)
11533 return;
11534 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11535 SmallVector<ObjCIvarDecl*, 8> ivars;
11536 CollectIvarsToConstructOrDestruct(OID, ivars);
11537 if (ivars.empty())
11538 return;
11539 SmallVector<CXXCtorInitializer*, 32> AllToInit;
11540 for (unsigned i = 0; i < ivars.size(); i++) {
11541 FieldDecl *Field = ivars[i];
11542 if (Field->isInvalidDecl())
11543 continue;
11544
11545 CXXCtorInitializer *Member;
11546 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11547 InitializationKind InitKind =
11548 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11549
11550 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11551 ExprResult MemberInit =
11552 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11553 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11554 // Note, MemberInit could actually come back empty if no initialization
11555 // is required (e.g., because it would call a trivial default constructor)
11556 if (!MemberInit.get() || MemberInit.isInvalid())
11557 continue;
11558
11559 Member =
11560 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11561 SourceLocation(),
11562 MemberInit.takeAs<Expr>(),
11563 SourceLocation());
11564 AllToInit.push_back(Member);
11565
11566 // Be sure that the destructor is accessible and is marked as referenced.
11567 if (const RecordType *RecordTy
11568 = Context.getBaseElementType(Field->getType())
11569 ->getAs<RecordType>()) {
11570 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11571 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11572 MarkFunctionReferenced(Field->getLocation(), Destructor);
11573 CheckDestructorAccess(Field->getLocation(), Destructor,
11574 PDiag(diag::err_access_dtor_ivar)
11575 << Context.getBaseElementType(Field->getType()));
11576 }
11577 }
11578 }
11579 ObjCImplementation->setIvarInitializers(Context,
11580 AllToInit.data(), AllToInit.size());
11581 }
11582 }
11583
11584 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallSet<CXXConstructorDecl *,4> & Valid,llvm::SmallSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallSet<CXXConstructorDecl *,4> & Current,Sema & S)11585 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11586 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11587 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11588 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11589 Sema &S) {
11590 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11591 CE = Current.end();
11592 if (Ctor->isInvalidDecl())
11593 return;
11594
11595 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11596
11597 // Target may not be determinable yet, for instance if this is a dependent
11598 // call in an uninstantiated template.
11599 if (Target) {
11600 const FunctionDecl *FNTarget = 0;
11601 (void)Target->hasBody(FNTarget);
11602 Target = const_cast<CXXConstructorDecl*>(
11603 cast_or_null<CXXConstructorDecl>(FNTarget));
11604 }
11605
11606 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11607 // Avoid dereferencing a null pointer here.
11608 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11609
11610 if (!Current.insert(Canonical))
11611 return;
11612
11613 // We know that beyond here, we aren't chaining into a cycle.
11614 if (!Target || !Target->isDelegatingConstructor() ||
11615 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11616 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11617 Valid.insert(*CI);
11618 Current.clear();
11619 // We've hit a cycle.
11620 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11621 Current.count(TCanonical)) {
11622 // If we haven't diagnosed this cycle yet, do so now.
11623 if (!Invalid.count(TCanonical)) {
11624 S.Diag((*Ctor->init_begin())->getSourceLocation(),
11625 diag::warn_delegating_ctor_cycle)
11626 << Ctor;
11627
11628 // Don't add a note for a function delegating directly to itself.
11629 if (TCanonical != Canonical)
11630 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11631
11632 CXXConstructorDecl *C = Target;
11633 while (C->getCanonicalDecl() != Canonical) {
11634 const FunctionDecl *FNTarget = 0;
11635 (void)C->getTargetConstructor()->hasBody(FNTarget);
11636 assert(FNTarget && "Ctor cycle through bodiless function");
11637
11638 C = const_cast<CXXConstructorDecl*>(
11639 cast<CXXConstructorDecl>(FNTarget));
11640 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11641 }
11642 }
11643
11644 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11645 Invalid.insert(*CI);
11646 Current.clear();
11647 } else {
11648 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11649 }
11650 }
11651
11652
CheckDelegatingCtorCycles()11653 void Sema::CheckDelegatingCtorCycles() {
11654 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11655
11656 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11657 CE = Current.end();
11658
11659 for (DelegatingCtorDeclsType::iterator
11660 I = DelegatingCtorDecls.begin(ExternalSource),
11661 E = DelegatingCtorDecls.end();
11662 I != E; ++I)
11663 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11664
11665 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11666 (*CI)->setInvalidDecl();
11667 }
11668
11669 namespace {
11670 /// \brief AST visitor that finds references to the 'this' expression.
11671 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11672 Sema &S;
11673
11674 public:
FindCXXThisExpr(Sema & S)11675 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11676
VisitCXXThisExpr(CXXThisExpr * E)11677 bool VisitCXXThisExpr(CXXThisExpr *E) {
11678 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11679 << E->isImplicit();
11680 return false;
11681 }
11682 };
11683 }
11684
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)11685 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11686 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11687 if (!TSInfo)
11688 return false;
11689
11690 TypeLoc TL = TSInfo->getTypeLoc();
11691 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11692 if (!ProtoTL)
11693 return false;
11694
11695 // C++11 [expr.prim.general]p3:
11696 // [The expression this] shall not appear before the optional
11697 // cv-qualifier-seq and it shall not appear within the declaration of a
11698 // static member function (although its type and value category are defined
11699 // within a static member function as they are within a non-static member
11700 // function). [ Note: this is because declaration matching does not occur
11701 // until the complete declarator is known. - end note ]
11702 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11703 FindCXXThisExpr Finder(*this);
11704
11705 // If the return type came after the cv-qualifier-seq, check it now.
11706 if (Proto->hasTrailingReturn() &&
11707 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
11708 return true;
11709
11710 // Check the exception specification.
11711 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11712 return true;
11713
11714 return checkThisInStaticMemberFunctionAttributes(Method);
11715 }
11716
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)11717 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11718 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11719 if (!TSInfo)
11720 return false;
11721
11722 TypeLoc TL = TSInfo->getTypeLoc();
11723 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11724 if (!ProtoTL)
11725 return false;
11726
11727 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11728 FindCXXThisExpr Finder(*this);
11729
11730 switch (Proto->getExceptionSpecType()) {
11731 case EST_Uninstantiated:
11732 case EST_Unevaluated:
11733 case EST_BasicNoexcept:
11734 case EST_DynamicNone:
11735 case EST_MSAny:
11736 case EST_None:
11737 break;
11738
11739 case EST_ComputedNoexcept:
11740 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11741 return true;
11742
11743 case EST_Dynamic:
11744 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11745 EEnd = Proto->exception_end();
11746 E != EEnd; ++E) {
11747 if (!Finder.TraverseType(*E))
11748 return true;
11749 }
11750 break;
11751 }
11752
11753 return false;
11754 }
11755
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)11756 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11757 FindCXXThisExpr Finder(*this);
11758
11759 // Check attributes.
11760 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11761 A != AEnd; ++A) {
11762 // FIXME: This should be emitted by tblgen.
11763 Expr *Arg = 0;
11764 ArrayRef<Expr *> Args;
11765 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11766 Arg = G->getArg();
11767 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11768 Arg = G->getArg();
11769 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11770 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11771 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11772 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11773 else if (ExclusiveLockFunctionAttr *ELF
11774 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11775 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11776 else if (SharedLockFunctionAttr *SLF
11777 = dyn_cast<SharedLockFunctionAttr>(*A))
11778 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11779 else if (ExclusiveTrylockFunctionAttr *ETLF
11780 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11781 Arg = ETLF->getSuccessValue();
11782 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11783 } else if (SharedTrylockFunctionAttr *STLF
11784 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11785 Arg = STLF->getSuccessValue();
11786 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11787 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11788 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11789 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11790 Arg = LR->getArg();
11791 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11792 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11793 else if (ExclusiveLocksRequiredAttr *ELR
11794 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11795 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11796 else if (SharedLocksRequiredAttr *SLR
11797 = dyn_cast<SharedLocksRequiredAttr>(*A))
11798 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11799
11800 if (Arg && !Finder.TraverseStmt(Arg))
11801 return true;
11802
11803 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11804 if (!Finder.TraverseStmt(Args[I]))
11805 return true;
11806 }
11807 }
11808
11809 return false;
11810 }
11811
11812 void
checkExceptionSpecification(ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExtProtoInfo & EPI)11813 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11814 ArrayRef<ParsedType> DynamicExceptions,
11815 ArrayRef<SourceRange> DynamicExceptionRanges,
11816 Expr *NoexceptExpr,
11817 SmallVectorImpl<QualType> &Exceptions,
11818 FunctionProtoType::ExtProtoInfo &EPI) {
11819 Exceptions.clear();
11820 EPI.ExceptionSpecType = EST;
11821 if (EST == EST_Dynamic) {
11822 Exceptions.reserve(DynamicExceptions.size());
11823 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11824 // FIXME: Preserve type source info.
11825 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11826
11827 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11828 collectUnexpandedParameterPacks(ET, Unexpanded);
11829 if (!Unexpanded.empty()) {
11830 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11831 UPPC_ExceptionType,
11832 Unexpanded);
11833 continue;
11834 }
11835
11836 // Check that the type is valid for an exception spec, and
11837 // drop it if not.
11838 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11839 Exceptions.push_back(ET);
11840 }
11841 EPI.NumExceptions = Exceptions.size();
11842 EPI.Exceptions = Exceptions.data();
11843 return;
11844 }
11845
11846 if (EST == EST_ComputedNoexcept) {
11847 // If an error occurred, there's no expression here.
11848 if (NoexceptExpr) {
11849 assert((NoexceptExpr->isTypeDependent() ||
11850 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11851 Context.BoolTy) &&
11852 "Parser should have made sure that the expression is boolean");
11853 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11854 EPI.ExceptionSpecType = EST_BasicNoexcept;
11855 return;
11856 }
11857
11858 if (!NoexceptExpr->isValueDependent())
11859 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11860 diag::err_noexcept_needs_constant_expression,
11861 /*AllowFold*/ false).take();
11862 EPI.NoexceptExpr = NoexceptExpr;
11863 }
11864 return;
11865 }
11866 }
11867
11868 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
IdentifyCUDATarget(const FunctionDecl * D)11869 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11870 // Implicitly declared functions (e.g. copy constructors) are
11871 // __host__ __device__
11872 if (D->isImplicit())
11873 return CFT_HostDevice;
11874
11875 if (D->hasAttr<CUDAGlobalAttr>())
11876 return CFT_Global;
11877
11878 if (D->hasAttr<CUDADeviceAttr>()) {
11879 if (D->hasAttr<CUDAHostAttr>())
11880 return CFT_HostDevice;
11881 else
11882 return CFT_Device;
11883 }
11884
11885 return CFT_Host;
11886 }
11887
CheckCUDATarget(CUDAFunctionTarget CallerTarget,CUDAFunctionTarget CalleeTarget)11888 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11889 CUDAFunctionTarget CalleeTarget) {
11890 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11891 // Callable from the device only."
11892 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11893 return true;
11894
11895 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11896 // Callable from the host only."
11897 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11898 // Callable from the host only."
11899 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11900 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11901 return true;
11902
11903 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11904 return true;
11905
11906 return false;
11907 }
11908