Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 204, column 25
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp

1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/LiteralSupport.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaInternal.h"
39#include "clang/Sema/Template.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43#include <map>
44#include <set>
45
46using namespace clang;
47
48//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
52namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
58 class CheckDefaultArgumentVisitor
59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60 Expr *DefaultArg;
61 Sema *S;
62
63 public:
64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65 : DefaultArg(defarg), S(s) {}
66
67 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
69 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70 bool VisitLambdaExpr(LambdaExpr *Lambda);
71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72 };
73
74 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
77 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
79 return IsInvalid;
80 }
81
82 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86 NamedDecl *Decl = DRE->getDecl();
87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
96 return S->Diag(DRE->getLocStart(),
97 diag::err_param_default_argument_references_param)
98 << Param->getDeclName() << DefaultArg->getSourceRange();
99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
103 if (VDecl->isLocalVarDecl())
104 return S->Diag(DRE->getLocStart(),
105 diag::err_param_default_argument_references_local)
106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
107 }
108
109 return false;
110 }
111
112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
117 return S->Diag(ThisE->getLocStart(),
118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
120 }
121
122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?")(static_cast <bool> (E && "pseudo-object binding without source expression?"
) ? void (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 131, __extension__ __PRETTY_FUNCTION__))
;
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
146 return S->Diag(Lambda->getLocStart(),
147 diag::err_lambda_capture_default_arg);
148 }
149}
150
151void
152Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171 EST = EST_BasicNoexcept;
172
173 switch(EST) {
174 // If this function can throw any exceptions, make a note of that.
175 case EST_MSAny:
176 case EST_None:
177 ClearExceptions();
178 ComputedEST = EST;
179 return;
180 // FIXME: If the call to this decl is using any of its default arguments, we
181 // need to search them for potentially-throwing calls.
182 // If this function has a basic noexcept, it doesn't affect the outcome.
183 case EST_BasicNoexcept:
184 return;
185 // If we're still at noexcept(true) and there's a nothrow() callee,
186 // change to that specification.
187 case EST_DynamicNone:
188 if (ComputedEST == EST_BasicNoexcept)
189 ComputedEST = EST_DynamicNone;
190 return;
191 // Check out noexcept specs.
192 case EST_ComputedNoexcept:
193 {
194 FunctionProtoType::NoexceptResult NR =
195 Proto->getNoexceptSpec(Self->Context);
196 assert(NR != FunctionProtoType::NR_NoNoexcept &&(static_cast <bool> (NR != FunctionProtoType::NR_NoNoexcept
&& "Must have noexcept result for EST_ComputedNoexcept."
) ? void (0) : __assert_fail ("NR != FunctionProtoType::NR_NoNoexcept && \"Must have noexcept result for EST_ComputedNoexcept.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 197, __extension__ __PRETTY_FUNCTION__))
197 "Must have noexcept result for EST_ComputedNoexcept.")(static_cast <bool> (NR != FunctionProtoType::NR_NoNoexcept
&& "Must have noexcept result for EST_ComputedNoexcept."
) ? void (0) : __assert_fail ("NR != FunctionProtoType::NR_NoNoexcept && \"Must have noexcept result for EST_ComputedNoexcept.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 197, __extension__ __PRETTY_FUNCTION__))
;
198 assert(NR != FunctionProtoType::NR_Dependent &&(static_cast <bool> (NR != FunctionProtoType::NR_Dependent
&& "Should not generate implicit declarations for dependent cases, "
"and don't know how to handle them anyway.") ? void (0) : __assert_fail
("NR != FunctionProtoType::NR_Dependent && \"Should not generate implicit declarations for dependent cases, \" \"and don't know how to handle them anyway.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 200, __extension__ __PRETTY_FUNCTION__))
199 "Should not generate implicit declarations for dependent cases, "(static_cast <bool> (NR != FunctionProtoType::NR_Dependent
&& "Should not generate implicit declarations for dependent cases, "
"and don't know how to handle them anyway.") ? void (0) : __assert_fail
("NR != FunctionProtoType::NR_Dependent && \"Should not generate implicit declarations for dependent cases, \" \"and don't know how to handle them anyway.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 200, __extension__ __PRETTY_FUNCTION__))
200 "and don't know how to handle them anyway.")(static_cast <bool> (NR != FunctionProtoType::NR_Dependent
&& "Should not generate implicit declarations for dependent cases, "
"and don't know how to handle them anyway.") ? void (0) : __assert_fail
("NR != FunctionProtoType::NR_Dependent && \"Should not generate implicit declarations for dependent cases, \" \"and don't know how to handle them anyway.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 200, __extension__ __PRETTY_FUNCTION__))
;
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209 default:
210 break;
211 }
212 assert(EST == EST_Dynamic && "EST case not considered earlier.")(static_cast <bool> (EST == EST_Dynamic && "EST case not considered earlier."
) ? void (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 212, __extension__ __PRETTY_FUNCTION__))
;
213 assert(ComputedEST != EST_None &&(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 214, __extension__ __PRETTY_FUNCTION__))
214 "Shouldn't collect exceptions when throw-all is guaranteed.")(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 214, __extension__ __PRETTY_FUNCTION__))
;
215 ComputedEST = EST_Dynamic;
216 // Record the exceptions in this function's exception specification.
217 for (const auto &E : Proto->exceptions())
218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
219 Exceptions.push_back(E);
220}
221
222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223 if (!E || ComputedEST == EST_MSAny)
224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
247 if (Self->canThrow(E))
248 ComputedEST = EST_None;
249}
250
251bool
252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253 SourceLocation EqualLoc) {
254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272 if (Result.isInvalid())
273 return true;
274 Arg = Result.getAs<Expr>();
275
276 CheckCompletedExpr(Arg, EqualLoc);
277 Arg = MaybeCreateExprWithCleanups(Arg);
278
279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
281
282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
293
294 return false;
295}
296
297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
300void
301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
304 return;
305
306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
307 UnparsedDefaultArgLocs.erase(Param);
308
309 // Default arguments are only permitted in C++
310 if (!getLangOpts().CPlusPlus) {
311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
313 Param->setInvalidDecl();
314 return;
315 }
316
317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
321 }
322
323 // C++11 [dcl.fct.default]p3
324 // A default argument expression [...] shall not be specified for a
325 // parameter pack.
326 if (Param->isParameterPack()) {
327 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
328 << DefaultArg->getSourceRange();
329 return;
330 }
331
332 // Check that the default argument is well-formed
333 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
334 if (DefaultArgChecker.Visit(DefaultArg)) {
335 Param->setInvalidDecl();
336 return;
337 }
338
339 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
340}
341
342/// ActOnParamUnparsedDefaultArgument - We've seen a default
343/// argument for a function parameter, but we can't parse it yet
344/// because we're inside a class definition. Note that this default
345/// argument will be parsed later.
346void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
347 SourceLocation EqualLoc,
348 SourceLocation ArgLoc) {
349 if (!param)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
353 Param->setUnparsedDefaultArg();
354 UnparsedDefaultArgLocs[Param] = ArgLoc;
355}
356
357/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
358/// the default argument for the parameter param failed.
359void Sema::ActOnParamDefaultArgumentError(Decl *param,
360 SourceLocation EqualLoc) {
361 if (!param)
362 return;
363
364 ParmVarDecl *Param = cast<ParmVarDecl>(param);
365 Param->setInvalidDecl();
366 UnparsedDefaultArgLocs.erase(Param);
367 Param->setDefaultArg(new(Context)
368 OpaqueValueExpr(EqualLoc,
369 Param->getType().getNonReferenceType(),
370 VK_RValue));
371}
372
373/// CheckExtraCXXDefaultArguments - Check for any extra default
374/// arguments in the declarator, which is not a function declaration
375/// or definition and therefore is not permitted to have default
376/// arguments. This routine should be invoked for every declarator
377/// that is not a function declaration or definition.
378void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
379 // C++ [dcl.fct.default]p3
380 // A default argument expression shall be specified only in the
381 // parameter-declaration-clause of a function declaration or in a
382 // template-parameter (14.1). It shall not be specified for a
383 // parameter pack. If it is specified in a
384 // parameter-declaration-clause, it shall not occur within a
385 // declarator or abstract-declarator of a parameter-declaration.
386 bool MightBeFunction = D.isFunctionDeclarationContext();
387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
388 DeclaratorChunk &chunk = D.getTypeObject(i);
389 if (chunk.Kind == DeclaratorChunk::Function) {
390 if (MightBeFunction) {
391 // This is a function declaration. It can have default arguments, but
392 // keep looking in case its return type is a function type with default
393 // arguments.
394 MightBeFunction = false;
395 continue;
396 }
397 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
398 ++argIdx) {
399 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
400 if (Param->hasUnparsedDefaultArg()) {
401 std::unique_ptr<CachedTokens> Toks =
402 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
403 SourceRange SR;
404 if (Toks->size() > 1)
405 SR = SourceRange((*Toks)[1].getLocation(),
406 Toks->back().getLocation());
407 else
408 SR = UnparsedDefaultArgLocs[Param];
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << SR;
411 } else if (Param->getDefaultArg()) {
412 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
413 << Param->getDefaultArg()->getSourceRange();
414 Param->setDefaultArg(nullptr);
415 }
416 }
417 } else if (chunk.Kind != DeclaratorChunk::Paren) {
418 MightBeFunction = false;
419 }
420 }
421}
422
423static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
424 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
425 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
426 if (!PVD->hasDefaultArg())
427 return false;
428 if (!PVD->hasInheritedDefaultArg())
429 return true;
430 }
431 return false;
432}
433
434/// MergeCXXFunctionDecl - Merge two declarations of the same C++
435/// function, once we already know that they have the same
436/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
437/// error, false otherwise.
438bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
439 Scope *S) {
440 bool Invalid = false;
441
442 // The declaration context corresponding to the scope is the semantic
443 // parent, unless this is a local function declaration, in which case
444 // it is that surrounding function.
445 DeclContext *ScopeDC = New->isLocalExternDecl()
446 ? New->getLexicalDeclContext()
447 : New->getDeclContext();
448
449 // Find the previous declaration for the purpose of default arguments.
450 FunctionDecl *PrevForDefaultArgs = Old;
451 for (/**/; PrevForDefaultArgs;
452 // Don't bother looking back past the latest decl if this is a local
453 // extern declaration; nothing else could work.
454 PrevForDefaultArgs = New->isLocalExternDecl()
455 ? nullptr
456 : PrevForDefaultArgs->getPreviousDecl()) {
457 // Ignore hidden declarations.
458 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
459 continue;
460
461 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
462 !New->isCXXClassMember()) {
463 // Ignore default arguments of old decl if they are not in
464 // the same scope and this is not an out-of-line definition of
465 // a member function.
466 continue;
467 }
468
469 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
470 // If only one of these is a local function declaration, then they are
471 // declared in different scopes, even though isDeclInScope may think
472 // they're in the same scope. (If both are local, the scope check is
473 // sufficient, and if neither is local, then they are in the same scope.)
474 continue;
475 }
476
477 // We found the right previous declaration.
478 break;
479 }
480
481 // C++ [dcl.fct.default]p4:
482 // For non-template functions, default arguments can be added in
483 // later declarations of a function in the same
484 // scope. Declarations in different scopes have completely
485 // distinct sets of default arguments. That is, declarations in
486 // inner scopes do not acquire default arguments from
487 // declarations in outer scopes, and vice versa. In a given
488 // function declaration, all parameters subsequent to a
489 // parameter with a default argument shall have default
490 // arguments supplied in this or previous declarations. A
491 // default argument shall not be redefined by a later
492 // declaration (not even to the same value).
493 //
494 // C++ [dcl.fct.default]p6:
495 // Except for member functions of class templates, the default arguments
496 // in a member function definition that appears outside of the class
497 // definition are added to the set of default arguments provided by the
498 // member function declaration in the class definition.
499 for (unsigned p = 0, NumParams = PrevForDefaultArgs
500 ? PrevForDefaultArgs->getNumParams()
501 : 0;
502 p < NumParams; ++p) {
503 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
504 ParmVarDecl *NewParam = New->getParamDecl(p);
505
506 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
507 bool NewParamHasDfl = NewParam->hasDefaultArg();
508
509 if (OldParamHasDfl && NewParamHasDfl) {
510 unsigned DiagDefaultParamID =
511 diag::err_param_default_argument_redefinition;
512
513 // MSVC accepts that default parameters be redefined for member functions
514 // of template class. The new default parameter's value is ignored.
515 Invalid = true;
516 if (getLangOpts().MicrosoftExt) {
517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
518 if (MD && MD->getParent()->getDescribedClassTemplate()) {
519 // Merge the old default argument into the new parameter.
520 NewParam->setHasInheritedDefaultArg();
521 if (OldParam->hasUninstantiatedDefaultArg())
522 NewParam->setUninstantiatedDefaultArg(
523 OldParam->getUninstantiatedDefaultArg());
524 else
525 NewParam->setDefaultArg(OldParam->getInit());
526 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
527 Invalid = false;
528 }
529 }
530
531 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
532 // hint here. Alternatively, we could walk the type-source information
533 // for NewParam to find the last source location in the type... but it
534 // isn't worth the effort right now. This is the kind of test case that
535 // is hard to get right:
536 // int f(int);
537 // void g(int (*fp)(int) = f);
538 // void g(int (*fp)(int) = &f);
539 Diag(NewParam->getLocation(), DiagDefaultParamID)
540 << NewParam->getDefaultArgRange();
541
542 // Look for the function declaration where the default argument was
543 // actually written, which may be a declaration prior to Old.
544 for (auto Older = PrevForDefaultArgs;
545 OldParam->hasInheritedDefaultArg(); /**/) {
546 Older = Older->getPreviousDecl();
547 OldParam = Older->getParamDecl(p);
548 }
549
550 Diag(OldParam->getLocation(), diag::note_previous_definition)
551 << OldParam->getDefaultArgRange();
552 } else if (OldParamHasDfl) {
553 // Merge the old default argument into the new parameter unless the new
554 // function is a friend declaration in a template class. In the latter
555 // case the default arguments will be inherited when the friend
556 // declaration will be instantiated.
557 if (New->getFriendObjectKind() == Decl::FOK_None ||
558 !New->getLexicalDeclContext()->isDependentContext()) {
559 // It's important to use getInit() here; getDefaultArg()
560 // strips off any top-level ExprWithCleanups.
561 NewParam->setHasInheritedDefaultArg();
562 if (OldParam->hasUnparsedDefaultArg())
563 NewParam->setUnparsedDefaultArg();
564 else if (OldParam->hasUninstantiatedDefaultArg())
565 NewParam->setUninstantiatedDefaultArg(
566 OldParam->getUninstantiatedDefaultArg());
567 else
568 NewParam->setDefaultArg(OldParam->getInit());
569 }
570 } else if (NewParamHasDfl) {
571 if (New->getDescribedFunctionTemplate()) {
572 // Paragraph 4, quoted above, only applies to non-template functions.
573 Diag(NewParam->getLocation(),
574 diag::err_param_default_argument_template_redecl)
575 << NewParam->getDefaultArgRange();
576 Diag(PrevForDefaultArgs->getLocation(),
577 diag::note_template_prev_declaration)
578 << false;
579 } else if (New->getTemplateSpecializationKind()
580 != TSK_ImplicitInstantiation &&
581 New->getTemplateSpecializationKind() != TSK_Undeclared) {
582 // C++ [temp.expr.spec]p21:
583 // Default function arguments shall not be specified in a declaration
584 // or a definition for one of the following explicit specializations:
585 // - the explicit specialization of a function template;
586 // - the explicit specialization of a member function template;
587 // - the explicit specialization of a member function of a class
588 // template where the class template specialization to which the
589 // member function specialization belongs is implicitly
590 // instantiated.
591 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
592 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
593 << New->getDeclName()
594 << NewParam->getDefaultArgRange();
595 } else if (New->getDeclContext()->isDependentContext()) {
596 // C++ [dcl.fct.default]p6 (DR217):
597 // Default arguments for a member function of a class template shall
598 // be specified on the initial declaration of the member function
599 // within the class template.
600 //
601 // Reading the tea leaves a bit in DR217 and its reference to DR205
602 // leads me to the conclusion that one cannot add default function
603 // arguments for an out-of-line definition of a member function of a
604 // dependent type.
605 int WhichKind = 2;
606 if (CXXRecordDecl *Record
607 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
608 if (Record->getDescribedClassTemplate())
609 WhichKind = 0;
610 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
611 WhichKind = 1;
612 else
613 WhichKind = 2;
614 }
615
616 Diag(NewParam->getLocation(),
617 diag::err_param_default_argument_member_template_redecl)
618 << WhichKind
619 << NewParam->getDefaultArgRange();
620 }
621 }
622 }
623
624 // DR1344: If a default argument is added outside a class definition and that
625 // default argument makes the function a special member function, the program
626 // is ill-formed. This can only happen for constructors.
627 if (isa<CXXConstructorDecl>(New) &&
628 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
629 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
630 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
631 if (NewSM != OldSM) {
632 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
633 assert(NewParam->hasDefaultArg())(static_cast <bool> (NewParam->hasDefaultArg()) ? void
(0) : __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 633, __extension__ __PRETTY_FUNCTION__))
;
634 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
635 << NewParam->getDefaultArgRange() << NewSM;
636 Diag(Old->getLocation(), diag::note_previous_declaration);
637 }
638 }
639
640 const FunctionDecl *Def;
641 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
642 // template has a constexpr specifier then all its declarations shall
643 // contain the constexpr specifier.
644 if (New->isConstexpr() != Old->isConstexpr()) {
645 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
646 << New << New->isConstexpr();
647 Diag(Old->getLocation(), diag::note_previous_declaration);
648 Invalid = true;
649 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
650 Old->isDefined(Def) &&
651 // If a friend function is inlined but does not have 'inline'
652 // specifier, it is a definition. Do not report attribute conflict
653 // in this case, redefinition will be diagnosed later.
654 (New->isInlineSpecified() ||
655 New->getFriendObjectKind() == Decl::FOK_None)) {
656 // C++11 [dcl.fcn.spec]p4:
657 // If the definition of a function appears in a translation unit before its
658 // first declaration as inline, the program is ill-formed.
659 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
660 Diag(Def->getLocation(), diag::note_previous_definition);
661 Invalid = true;
662 }
663
664 // FIXME: It's not clear what should happen if multiple declarations of a
665 // deduction guide have different explicitness. For now at least we simply
666 // reject any case where the explicitness changes.
667 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
668 if (NewGuide && NewGuide->isExplicitSpecified() !=
669 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
670 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
671 << NewGuide->isExplicitSpecified();
672 Diag(Old->getLocation(), diag::note_previous_declaration);
673 }
674
675 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
676 // argument expression, that declaration shall be a definition and shall be
677 // the only declaration of the function or function template in the
678 // translation unit.
679 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
680 functionDeclHasDefaultArgument(Old)) {
681 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
682 Diag(Old->getLocation(), diag::note_previous_declaration);
683 Invalid = true;
684 }
685
686 return Invalid;
687}
688
689NamedDecl *
690Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
691 MultiTemplateParamsArg TemplateParamLists) {
692 assert(D.isDecompositionDeclarator())(static_cast <bool> (D.isDecompositionDeclarator()) ? void
(0) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 692, __extension__ __PRETTY_FUNCTION__))
;
693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
694
695 // The syntax only allows a decomposition declarator as a simple-declaration,
696 // a for-range-declaration, or a condition in Clang, but we parse it in more
697 // cases than that.
698 if (!D.mayHaveDecompositionDeclarator()) {
699 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
700 << Decomp.getSourceRange();
701 return nullptr;
702 }
703
704 if (!TemplateParamLists.empty()) {
705 // FIXME: There's no rule against this, but there are also no rules that
706 // would actually make it usable, so we reject it for now.
707 Diag(TemplateParamLists.front()->getTemplateLoc(),
708 diag::err_decomp_decl_template);
709 return nullptr;
710 }
711
712 Diag(Decomp.getLSquareLoc(),
713 !getLangOpts().CPlusPlus17
714 ? diag::ext_decomp_decl
715 : D.getContext() == DeclaratorContext::ConditionContext
716 ? diag::ext_decomp_decl_cond
717 : diag::warn_cxx14_compat_decomp_decl)
718 << Decomp.getSourceRange();
719
720 // The semantic context is always just the current context.
721 DeclContext *const DC = CurContext;
722
723 // C++1z [dcl.dcl]/8:
724 // The decl-specifier-seq shall contain only the type-specifier auto
725 // and cv-qualifiers.
726 auto &DS = D.getDeclSpec();
727 {
728 SmallVector<StringRef, 8> BadSpecifiers;
729 SmallVector<SourceLocation, 8> BadSpecifierLocs;
730 if (auto SCS = DS.getStorageClassSpec()) {
731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
732 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
733 }
734 if (auto TSCS = DS.getThreadStorageClassSpec()) {
735 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
736 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
737 }
738 if (DS.isConstexprSpecified()) {
739 BadSpecifiers.push_back("constexpr");
740 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
741 }
742 if (DS.isInlineSpecified()) {
743 BadSpecifiers.push_back("inline");
744 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
745 }
746 if (!BadSpecifiers.empty()) {
747 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
748 Err << (int)BadSpecifiers.size()
749 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
750 // Don't add FixItHints to remove the specifiers; we do still respect
751 // them when building the underlying variable.
752 for (auto Loc : BadSpecifierLocs)
753 Err << SourceRange(Loc, Loc);
754 }
755 // We can't recover from it being declared as a typedef.
756 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
757 return nullptr;
758 }
759
760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
761 QualType R = TInfo->getType();
762
763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
764 UPPC_DeclarationType))
765 D.setInvalidType();
766
767 // The syntax only allows a single ref-qualifier prior to the decomposition
768 // declarator. No other declarator chunks are permitted. Also check the type
769 // specifier here.
770 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
771 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
772 (D.getNumTypeObjects() == 1 &&
773 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
774 Diag(Decomp.getLSquareLoc(),
775 (D.hasGroupingParens() ||
776 (D.getNumTypeObjects() &&
777 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
778 ? diag::err_decomp_decl_parens
779 : diag::err_decomp_decl_type)
780 << R;
781
782 // In most cases, there's no actual problem with an explicitly-specified
783 // type, but a function type won't work here, and ActOnVariableDeclarator
784 // shouldn't be called for such a type.
785 if (R->isFunctionType())
786 D.setInvalidType();
787 }
788
789 // Build the BindingDecls.
790 SmallVector<BindingDecl*, 8> Bindings;
791
792 // Build the BindingDecls.
793 for (auto &B : D.getDecompositionDeclarator().bindings()) {
794 // Check for name conflicts.
795 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
796 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
797 ForVisibleRedeclaration);
798 LookupName(Previous, S,
799 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
800
801 // It's not permitted to shadow a template parameter name.
802 if (Previous.isSingleResult() &&
803 Previous.getFoundDecl()->isTemplateParameter()) {
804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
805 Previous.getFoundDecl());
806 Previous.clear();
807 }
808
809 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
810 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
811 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
812 /*AllowInlineNamespace*/false);
813 if (!Previous.empty()) {
814 auto *Old = Previous.getRepresentativeDecl();
815 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
816 Diag(Old->getLocation(), diag::note_previous_definition);
817 }
818
819 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
820 PushOnScopeChains(BD, S, true);
821 Bindings.push_back(BD);
822 ParsingInitForAutoVars.insert(BD);
823 }
824
825 // There are no prior lookup results for the variable itself, because it
826 // is unnamed.
827 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
828 Decomp.getLSquareLoc());
829 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
830 ForVisibleRedeclaration);
831
832 // Build the variable that holds the non-decomposed object.
833 bool AddToScope = true;
834 NamedDecl *New =
835 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
836 MultiTemplateParamsArg(), AddToScope, Bindings);
837 if (AddToScope) {
838 S->AddDecl(New);
839 CurContext->addHiddenDecl(New);
840 }
841
842 if (isInOpenMPDeclareTargetContext())
843 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
844
845 return New;
846}
847
848static bool checkSimpleDecomposition(
849 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
850 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
851 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
852 if ((int64_t)Bindings.size() != NumElems) {
853 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
854 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
855 << (NumElems < Bindings.size());
856 return true;
857 }
858
859 unsigned I = 0;
860 for (auto *B : Bindings) {
861 SourceLocation Loc = B->getLocation();
862 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
863 if (E.isInvalid())
864 return true;
865 E = GetInit(Loc, E.get(), I++);
866 if (E.isInvalid())
867 return true;
868 B->setBinding(ElemType, E.get());
869 }
870
871 return false;
872}
873
874static bool checkArrayLikeDecomposition(Sema &S,
875 ArrayRef<BindingDecl *> Bindings,
876 ValueDecl *Src, QualType DecompType,
877 const llvm::APSInt &NumElems,
878 QualType ElemType) {
879 return checkSimpleDecomposition(
880 S, Bindings, Src, DecompType, NumElems, ElemType,
881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
882 ExprResult E = S.ActOnIntegerConstant(Loc, I);
883 if (E.isInvalid())
884 return ExprError();
885 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
886 });
887}
888
889static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
890 ValueDecl *Src, QualType DecompType,
891 const ConstantArrayType *CAT) {
892 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
893 llvm::APSInt(CAT->getSize()),
894 CAT->getElementType());
895}
896
897static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
898 ValueDecl *Src, QualType DecompType,
899 const VectorType *VT) {
900 return checkArrayLikeDecomposition(
901 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
902 S.Context.getQualifiedType(VT->getElementType(),
903 DecompType.getQualifiers()));
904}
905
906static bool checkComplexDecomposition(Sema &S,
907 ArrayRef<BindingDecl *> Bindings,
908 ValueDecl *Src, QualType DecompType,
909 const ComplexType *CT) {
910 return checkSimpleDecomposition(
911 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
912 S.Context.getQualifiedType(CT->getElementType(),
913 DecompType.getQualifiers()),
914 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
915 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
916 });
917}
918
919static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
920 TemplateArgumentListInfo &Args) {
921 SmallString<128> SS;
922 llvm::raw_svector_ostream OS(SS);
923 bool First = true;
924 for (auto &Arg : Args.arguments()) {
925 if (!First)
926 OS << ", ";
927 Arg.getArgument().print(PrintingPolicy, OS);
928 First = false;
929 }
930 return OS.str();
931}
932
933static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
934 SourceLocation Loc, StringRef Trait,
935 TemplateArgumentListInfo &Args,
936 unsigned DiagID) {
937 auto DiagnoseMissing = [&] {
938 if (DiagID)
939 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
940 Args);
941 return true;
942 };
943
944 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
945 NamespaceDecl *Std = S.getStdNamespace();
946 if (!Std)
947 return DiagnoseMissing();
948
949 // Look up the trait itself, within namespace std. We can diagnose various
950 // problems with this lookup even if we've been asked to not diagnose a
951 // missing specialization, because this can only fail if the user has been
952 // declaring their own names in namespace std or we don't support the
953 // standard library implementation in use.
954 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
955 Loc, Sema::LookupOrdinaryName);
956 if (!S.LookupQualifiedName(Result, Std))
957 return DiagnoseMissing();
958 if (Result.isAmbiguous())
959 return true;
960
961 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
962 if (!TraitTD) {
963 Result.suppressDiagnostics();
964 NamedDecl *Found = *Result.begin();
965 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
966 S.Diag(Found->getLocation(), diag::note_declared_at);
967 return true;
968 }
969
970 // Build the template-id.
971 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
972 if (TraitTy.isNull())
973 return true;
974 if (!S.isCompleteType(Loc, TraitTy)) {
975 if (DiagID)
976 S.RequireCompleteType(
977 Loc, TraitTy, DiagID,
978 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
979 return true;
980 }
981
982 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
983 assert(RD && "specialization of class template is not a class?")(static_cast <bool> (RD && "specialization of class template is not a class?"
) ? void (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 983, __extension__ __PRETTY_FUNCTION__))
;
984
985 // Look up the member of the trait type.
986 S.LookupQualifiedName(TraitMemberLookup, RD);
987 return TraitMemberLookup.isAmbiguous();
988}
989
990static TemplateArgumentLoc
991getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
992 uint64_t I) {
993 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
994 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
995}
996
997static TemplateArgumentLoc
998getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
999 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1000}
1001
1002namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1003
1004static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1005 llvm::APSInt &Size) {
1006 EnterExpressionEvaluationContext ContextRAII(
1007 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1008
1009 DeclarationName Value = S.PP.getIdentifierInfo("value");
1010 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1011
1012 // Form template argument list for tuple_size<T>.
1013 TemplateArgumentListInfo Args(Loc, Loc);
1014 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1015
1016 // If there's no tuple_size specialization, it's not tuple-like.
1017 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1018 return IsTupleLike::NotTupleLike;
1019
1020 // If we get this far, we've committed to the tuple interpretation, but
1021 // we can still fail if there actually isn't a usable ::value.
1022
1023 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1024 LookupResult &R;
1025 TemplateArgumentListInfo &Args;
1026 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1027 : R(R), Args(Args) {}
1028 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1029 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1030 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1031 }
1032 } Diagnoser(R, Args);
1033
1034 if (R.empty()) {
1035 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1036 return IsTupleLike::Error;
1037 }
1038
1039 ExprResult E =
1040 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1041 if (E.isInvalid())
1042 return IsTupleLike::Error;
1043
1044 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1045 if (E.isInvalid())
1046 return IsTupleLike::Error;
1047
1048 return IsTupleLike::TupleLike;
1049}
1050
1051/// \return std::tuple_element<I, T>::type.
1052static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1053 unsigned I, QualType T) {
1054 // Form template argument list for tuple_element<I, T>.
1055 TemplateArgumentListInfo Args(Loc, Loc);
1056 Args.addArgument(
1057 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1058 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1059
1060 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1061 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1062 if (lookupStdTypeTraitMember(
1063 S, R, Loc, "tuple_element", Args,
1064 diag::err_decomp_decl_std_tuple_element_not_specialized))
1065 return QualType();
1066
1067 auto *TD = R.getAsSingle<TypeDecl>();
1068 if (!TD) {
1069 R.suppressDiagnostics();
1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1072 if (!R.empty())
1073 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1074 return QualType();
1075 }
1076
1077 return S.Context.getTypeDeclType(TD);
1078}
1079
1080namespace {
1081struct BindingDiagnosticTrap {
1082 Sema &S;
1083 DiagnosticErrorTrap Trap;
1084 BindingDecl *BD;
1085
1086 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1087 : S(S), Trap(S.Diags), BD(BD) {}
1088 ~BindingDiagnosticTrap() {
1089 if (Trap.hasErrorOccurred())
1090 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1091 }
1092};
1093}
1094
1095static bool checkTupleLikeDecomposition(Sema &S,
1096 ArrayRef<BindingDecl *> Bindings,
1097 VarDecl *Src, QualType DecompType,
1098 const llvm::APSInt &TupleSize) {
1099 if ((int64_t)Bindings.size() != TupleSize) {
1100 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1101 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1102 << (TupleSize < Bindings.size());
1103 return true;
1104 }
1105
1106 if (Bindings.empty())
1107 return false;
1108
1109 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1110
1111 // [dcl.decomp]p3:
1112 // The unqualified-id get is looked up in the scope of E by class member
1113 // access lookup
1114 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1115 bool UseMemberGet = false;
1116 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1117 if (auto *RD = DecompType->getAsCXXRecordDecl())
1118 S.LookupQualifiedName(MemberGet, RD);
1119 if (MemberGet.isAmbiguous())
1120 return true;
1121 UseMemberGet = !MemberGet.empty();
1122 S.FilterAcceptableTemplateNames(MemberGet);
1123 }
1124
1125 unsigned I = 0;
1126 for (auto *B : Bindings) {
1127 BindingDiagnosticTrap Trap(S, B);
1128 SourceLocation Loc = B->getLocation();
1129
1130 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1131 if (E.isInvalid())
1132 return true;
1133
1134 // e is an lvalue if the type of the entity is an lvalue reference and
1135 // an xvalue otherwise
1136 if (!Src->getType()->isLValueReferenceType())
1137 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1138 E.get(), nullptr, VK_XValue);
1139
1140 TemplateArgumentListInfo Args(Loc, Loc);
1141 Args.addArgument(
1142 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1143
1144 if (UseMemberGet) {
1145 // if [lookup of member get] finds at least one declaration, the
1146 // initializer is e.get<i-1>().
1147 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1148 CXXScopeSpec(), SourceLocation(), nullptr,
1149 MemberGet, &Args, nullptr);
1150 if (E.isInvalid())
1151 return true;
1152
1153 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1154 } else {
1155 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1156 // in the associated namespaces.
1157 Expr *Get = UnresolvedLookupExpr::Create(
1158 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1159 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1160 UnresolvedSetIterator(), UnresolvedSetIterator());
1161
1162 Expr *Arg = E.get();
1163 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1164 }
1165 if (E.isInvalid())
1166 return true;
1167 Expr *Init = E.get();
1168
1169 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1170 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1171 if (T.isNull())
1172 return true;
1173
1174 // each vi is a variable of type "reference to T" initialized with the
1175 // initializer, where the reference is an lvalue reference if the
1176 // initializer is an lvalue and an rvalue reference otherwise
1177 QualType RefType =
1178 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1179 if (RefType.isNull())
1180 return true;
1181 auto *RefVD = VarDecl::Create(
1182 S.Context, Src->getDeclContext(), Loc, Loc,
1183 B->getDeclName().getAsIdentifierInfo(), RefType,
1184 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1185 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1186 RefVD->setTSCSpec(Src->getTSCSpec());
1187 RefVD->setImplicit();
1188 if (Src->isInlineSpecified())
1189 RefVD->setInlineSpecified();
1190 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1191
1192 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1193 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1194 InitializationSequence Seq(S, Entity, Kind, Init);
1195 E = Seq.Perform(S, Entity, Kind, Init);
1196 if (E.isInvalid())
1197 return true;
1198 E = S.ActOnFinishFullExpr(E.get(), Loc);
1199 if (E.isInvalid())
1200 return true;
1201 RefVD->setInit(E.get());
1202 RefVD->checkInitIsICE();
1203
1204 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1205 DeclarationNameInfo(B->getDeclName(), Loc),
1206 RefVD);
1207 if (E.isInvalid())
1208 return true;
1209
1210 B->setBinding(T, E.get());
1211 I++;
1212 }
1213
1214 return false;
1215}
1216
1217/// Find the base class to decompose in a built-in decomposition of a class type.
1218/// This base class search is, unfortunately, not quite like any other that we
1219/// perform anywhere else in C++.
1220static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1221 SourceLocation Loc,
1222 const CXXRecordDecl *RD,
1223 CXXCastPath &BasePath) {
1224 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1225 CXXBasePath &Path) {
1226 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1227 };
1228
1229 const CXXRecordDecl *ClassWithFields = nullptr;
1230 if (RD->hasDirectFields())
1231 // [dcl.decomp]p4:
1232 // Otherwise, all of E's non-static data members shall be public direct
1233 // members of E ...
1234 ClassWithFields = RD;
1235 else {
1236 // ... or of ...
1237 CXXBasePaths Paths;
1238 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1239 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1240 // If no classes have fields, just decompose RD itself. (This will work
1241 // if and only if zero bindings were provided.)
1242 return RD;
1243 }
1244
1245 CXXBasePath *BestPath = nullptr;
1246 for (auto &P : Paths) {
1247 if (!BestPath)
1248 BestPath = &P;
1249 else if (!S.Context.hasSameType(P.back().Base->getType(),
1250 BestPath->back().Base->getType())) {
1251 // ... the same ...
1252 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1253 << false << RD << BestPath->back().Base->getType()
1254 << P.back().Base->getType();
1255 return nullptr;
1256 } else if (P.Access < BestPath->Access) {
1257 BestPath = &P;
1258 }
1259 }
1260
1261 // ... unambiguous ...
1262 QualType BaseType = BestPath->back().Base->getType();
1263 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1264 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1265 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1266 return nullptr;
1267 }
1268
1269 // ... public base class of E.
1270 if (BestPath->Access != AS_public) {
1271 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1272 << RD << BaseType;
1273 for (auto &BS : *BestPath) {
1274 if (BS.Base->getAccessSpecifier() != AS_public) {
1275 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1276 << (BS.Base->getAccessSpecifier() == AS_protected)
1277 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1278 break;
1279 }
1280 }
1281 return nullptr;
1282 }
1283
1284 ClassWithFields = BaseType->getAsCXXRecordDecl();
1285 S.BuildBasePathArray(Paths, BasePath);
1286 }
1287
1288 // The above search did not check whether the selected class itself has base
1289 // classes with fields, so check that now.
1290 CXXBasePaths Paths;
1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293 << (ClassWithFields == RD) << RD << ClassWithFields
1294 << Paths.front().back().Base->getType();
1295 return nullptr;
1296 }
1297
1298 return ClassWithFields;
1299}
1300
1301static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302 ValueDecl *Src, QualType DecompType,
1303 const CXXRecordDecl *RD) {
1304 CXXCastPath BasePath;
1305 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1306 if (!RD)
1307 return true;
1308 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1309 DecompType.getQualifiers());
1310
1311 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1312 unsigned NumFields =
1313 std::count_if(RD->field_begin(), RD->field_end(),
1314 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1315 assert(Bindings.size() != NumFields)(static_cast <bool> (Bindings.size() != NumFields) ? void
(0) : __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1315, __extension__ __PRETTY_FUNCTION__))
;
1316 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1317 << DecompType << (unsigned)Bindings.size() << NumFields
1318 << (NumFields < Bindings.size());
1319 return true;
1320 };
1321
1322 // all of E's non-static data members shall be public [...] members,
1323 // E shall not have an anonymous union member, ...
1324 unsigned I = 0;
1325 for (auto *FD : RD->fields()) {
1326 if (FD->isUnnamedBitfield())
1327 continue;
1328
1329 if (FD->isAnonymousStructOrUnion()) {
1330 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1331 << DecompType << FD->getType()->isUnionType();
1332 S.Diag(FD->getLocation(), diag::note_declared_at);
1333 return true;
1334 }
1335
1336 // We have a real field to bind.
1337 if (I >= Bindings.size())
1338 return DiagnoseBadNumberOfBindings();
1339 auto *B = Bindings[I++];
1340
1341 SourceLocation Loc = B->getLocation();
1342 if (FD->getAccess() != AS_public) {
1343 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1344
1345 // Determine whether the access specifier was explicit.
1346 bool Implicit = true;
1347 for (const auto *D : RD->decls()) {
1348 if (declaresSameEntity(D, FD))
1349 break;
1350 if (isa<AccessSpecDecl>(D)) {
1351 Implicit = false;
1352 break;
1353 }
1354 }
1355
1356 S.Diag(FD->getLocation(), diag::note_access_natural)
1357 << (FD->getAccess() == AS_protected) << Implicit;
1358 return true;
1359 }
1360
1361 // Initialize the binding to Src.FD.
1362 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1363 if (E.isInvalid())
1364 return true;
1365 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1366 VK_LValue, &BasePath);
1367 if (E.isInvalid())
1368 return true;
1369 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1370 CXXScopeSpec(), FD,
1371 DeclAccessPair::make(FD, FD->getAccess()),
1372 DeclarationNameInfo(FD->getDeclName(), Loc));
1373 if (E.isInvalid())
1374 return true;
1375
1376 // If the type of the member is T, the referenced type is cv T, where cv is
1377 // the cv-qualification of the decomposition expression.
1378 //
1379 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1380 // 'const' to the type of the field.
1381 Qualifiers Q = DecompType.getQualifiers();
1382 if (FD->isMutable())
1383 Q.removeConst();
1384 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1385 }
1386
1387 if (I != Bindings.size())
1388 return DiagnoseBadNumberOfBindings();
1389
1390 return false;
1391}
1392
1393void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1394 QualType DecompType = DD->getType();
1395
1396 // If the type of the decomposition is dependent, then so is the type of
1397 // each binding.
1398 if (DecompType->isDependentType()) {
1399 for (auto *B : DD->bindings())
1400 B->setType(Context.DependentTy);
1401 return;
1402 }
1403
1404 DecompType = DecompType.getNonReferenceType();
1405 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1406
1407 // C++1z [dcl.decomp]/2:
1408 // If E is an array type [...]
1409 // As an extension, we also support decomposition of built-in complex and
1410 // vector types.
1411 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1412 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1413 DD->setInvalidDecl();
1414 return;
1415 }
1416 if (auto *VT = DecompType->getAs<VectorType>()) {
1417 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1418 DD->setInvalidDecl();
1419 return;
1420 }
1421 if (auto *CT = DecompType->getAs<ComplexType>()) {
1422 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1423 DD->setInvalidDecl();
1424 return;
1425 }
1426
1427 // C++1z [dcl.decomp]/3:
1428 // if the expression std::tuple_size<E>::value is a well-formed integral
1429 // constant expression, [...]
1430 llvm::APSInt TupleSize(32);
1431 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1432 case IsTupleLike::Error:
1433 DD->setInvalidDecl();
1434 return;
1435
1436 case IsTupleLike::TupleLike:
1437 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1438 DD->setInvalidDecl();
1439 return;
1440
1441 case IsTupleLike::NotTupleLike:
1442 break;
1443 }
1444
1445 // C++1z [dcl.dcl]/8:
1446 // [E shall be of array or non-union class type]
1447 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1448 if (!RD || RD->isUnion()) {
1449 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1450 << DD << !RD << DecompType;
1451 DD->setInvalidDecl();
1452 return;
1453 }
1454
1455 // C++1z [dcl.decomp]/4:
1456 // all of E's non-static data members shall be [...] direct members of
1457 // E or of the same unambiguous public base class of E, ...
1458 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1459 DD->setInvalidDecl();
1460}
1461
1462/// \brief Merge the exception specifications of two variable declarations.
1463///
1464/// This is called when there's a redeclaration of a VarDecl. The function
1465/// checks if the redeclaration might have an exception specification and
1466/// validates compatibility and merges the specs if necessary.
1467void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1468 // Shortcut if exceptions are disabled.
1469 if (!getLangOpts().CXXExceptions)
1470 return;
1471
1472 assert(Context.hasSameType(New->getType(), Old->getType()) &&(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1473, __extension__ __PRETTY_FUNCTION__))
1473 "Should only be called if types are otherwise the same.")(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1473, __extension__ __PRETTY_FUNCTION__))
;
1474
1475 QualType NewType = New->getType();
1476 QualType OldType = Old->getType();
1477
1478 // We're only interested in pointers and references to functions, as well
1479 // as pointers to member functions.
1480 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1481 NewType = R->getPointeeType();
1482 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1483 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1484 NewType = P->getPointeeType();
1485 OldType = OldType->getAs<PointerType>()->getPointeeType();
1486 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1487 NewType = M->getPointeeType();
1488 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1489 }
1490
1491 if (!NewType->isFunctionProtoType())
1492 return;
1493
1494 // There's lots of special cases for functions. For function pointers, system
1495 // libraries are hopefully not as broken so that we don't need these
1496 // workarounds.
1497 if (CheckEquivalentExceptionSpec(
1498 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1499 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1500 New->setInvalidDecl();
1501 }
1502}
1503
1504/// CheckCXXDefaultArguments - Verify that the default arguments for a
1505/// function declaration are well-formed according to C++
1506/// [dcl.fct.default].
1507void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1508 unsigned NumParams = FD->getNumParams();
1509 unsigned p;
1510
1511 // Find first parameter with a default argument
1512 for (p = 0; p < NumParams; ++p) {
1513 ParmVarDecl *Param = FD->getParamDecl(p);
1514 if (Param->hasDefaultArg())
1515 break;
1516 }
1517
1518 // C++11 [dcl.fct.default]p4:
1519 // In a given function declaration, each parameter subsequent to a parameter
1520 // with a default argument shall have a default argument supplied in this or
1521 // a previous declaration or shall be a function parameter pack. A default
1522 // argument shall not be redefined by a later declaration (not even to the
1523 // same value).
1524 unsigned LastMissingDefaultArg = 0;
1525 for (; p < NumParams; ++p) {
1526 ParmVarDecl *Param = FD->getParamDecl(p);
1527 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1528 if (Param->isInvalidDecl())
1529 /* We already complained about this parameter. */;
1530 else if (Param->getIdentifier())
1531 Diag(Param->getLocation(),
1532 diag::err_param_default_argument_missing_name)
1533 << Param->getIdentifier();
1534 else
1535 Diag(Param->getLocation(),
1536 diag::err_param_default_argument_missing);
1537
1538 LastMissingDefaultArg = p;
1539 }
1540 }
1541
1542 if (LastMissingDefaultArg > 0) {
1543 // Some default arguments were missing. Clear out all of the
1544 // default arguments up to (and including) the last missing
1545 // default argument, so that we leave the function parameters
1546 // in a semantically valid state.
1547 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1548 ParmVarDecl *Param = FD->getParamDecl(p);
1549 if (Param->hasDefaultArg()) {
1550 Param->setDefaultArg(nullptr);
1551 }
1552 }
1553 }
1554}
1555
1556// CheckConstexprParameterTypes - Check whether a function's parameter types
1557// are all literal types. If so, return true. If not, produce a suitable
1558// diagnostic and return false.
1559static bool CheckConstexprParameterTypes(Sema &SemaRef,
1560 const FunctionDecl *FD) {
1561 unsigned ArgIndex = 0;
1562 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1563 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1564 e = FT->param_type_end();
1565 i != e; ++i, ++ArgIndex) {
1566 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1567 SourceLocation ParamLoc = PD->getLocation();
1568 if (!(*i)->isDependentType() &&
1569 SemaRef.RequireLiteralType(ParamLoc, *i,
1570 diag::err_constexpr_non_literal_param,
1571 ArgIndex+1, PD->getSourceRange(),
1572 isa<CXXConstructorDecl>(FD)))
1573 return false;
1574 }
1575 return true;
1576}
1577
1578/// \brief Get diagnostic %select index for tag kind for
1579/// record diagnostic message.
1580/// WARNING: Indexes apply to particular diagnostics only!
1581///
1582/// \returns diagnostic %select index.
1583static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1584 switch (Tag) {
1585 case TTK_Struct: return 0;
1586 case TTK_Interface: return 1;
1587 case TTK_Class: return 2;
1588 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1588)
;
1589 }
1590}
1591
1592// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1593// the requirements of a constexpr function definition or a constexpr
1594// constructor definition. If so, return true. If not, produce appropriate
1595// diagnostics and return false.
1596//
1597// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1598bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1600 if (MD && MD->isInstance()) {
1601 // C++11 [dcl.constexpr]p4:
1602 // The definition of a constexpr constructor shall satisfy the following
1603 // constraints:
1604 // - the class shall not have any virtual base classes;
1605 const CXXRecordDecl *RD = MD->getParent();
1606 if (RD->getNumVBases()) {
1607 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1608 << isa<CXXConstructorDecl>(NewFD)
1609 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1610 for (const auto &I : RD->vbases())
1611 Diag(I.getLocStart(),
1612 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1613 return false;
1614 }
1615 }
1616
1617 if (!isa<CXXConstructorDecl>(NewFD)) {
1618 // C++11 [dcl.constexpr]p3:
1619 // The definition of a constexpr function shall satisfy the following
1620 // constraints:
1621 // - it shall not be virtual;
1622 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1623 if (Method && Method->isVirtual()) {
1624 Method = Method->getCanonicalDecl();
1625 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1626
1627 // If it's not obvious why this function is virtual, find an overridden
1628 // function which uses the 'virtual' keyword.
1629 const CXXMethodDecl *WrittenVirtual = Method;
1630 while (!WrittenVirtual->isVirtualAsWritten())
1631 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1632 if (WrittenVirtual != Method)
1633 Diag(WrittenVirtual->getLocation(),
1634 diag::note_overridden_virtual_function);
1635 return false;
1636 }
1637
1638 // - its return type shall be a literal type;
1639 QualType RT = NewFD->getReturnType();
1640 if (!RT->isDependentType() &&
1641 RequireLiteralType(NewFD->getLocation(), RT,
1642 diag::err_constexpr_non_literal_return))
1643 return false;
1644 }
1645
1646 // - each of its parameter types shall be a literal type;
1647 if (!CheckConstexprParameterTypes(*this, NewFD))
1648 return false;
1649
1650 return true;
1651}
1652
1653/// Check the given declaration statement is legal within a constexpr function
1654/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1655///
1656/// \return true if the body is OK (maybe only as an extension), false if we
1657/// have diagnosed a problem.
1658static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1659 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1660 // C++11 [dcl.constexpr]p3 and p4:
1661 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1662 // contain only
1663 for (const auto *DclIt : DS->decls()) {
1664 switch (DclIt->getKind()) {
1665 case Decl::StaticAssert:
1666 case Decl::Using:
1667 case Decl::UsingShadow:
1668 case Decl::UsingDirective:
1669 case Decl::UnresolvedUsingTypename:
1670 case Decl::UnresolvedUsingValue:
1671 // - static_assert-declarations
1672 // - using-declarations,
1673 // - using-directives,
1674 continue;
1675
1676 case Decl::Typedef:
1677 case Decl::TypeAlias: {
1678 // - typedef declarations and alias-declarations that do not define
1679 // classes or enumerations,
1680 const auto *TN = cast<TypedefNameDecl>(DclIt);
1681 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1682 // Don't allow variably-modified types in constexpr functions.
1683 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1684 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1685 << TL.getSourceRange() << TL.getType()
1686 << isa<CXXConstructorDecl>(Dcl);
1687 return false;
1688 }
1689 continue;
1690 }
1691
1692 case Decl::Enum:
1693 case Decl::CXXRecord:
1694 // C++1y allows types to be defined, not just declared.
1695 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1696 SemaRef.Diag(DS->getLocStart(),
1697 SemaRef.getLangOpts().CPlusPlus14
1698 ? diag::warn_cxx11_compat_constexpr_type_definition
1699 : diag::ext_constexpr_type_definition)
1700 << isa<CXXConstructorDecl>(Dcl);
1701 continue;
1702
1703 case Decl::EnumConstant:
1704 case Decl::IndirectField:
1705 case Decl::ParmVar:
1706 // These can only appear with other declarations which are banned in
1707 // C++11 and permitted in C++1y, so ignore them.
1708 continue;
1709
1710 case Decl::Var:
1711 case Decl::Decomposition: {
1712 // C++1y [dcl.constexpr]p3 allows anything except:
1713 // a definition of a variable of non-literal type or of static or
1714 // thread storage duration or for which no initialization is performed.
1715 const auto *VD = cast<VarDecl>(DclIt);
1716 if (VD->isThisDeclarationADefinition()) {
1717 if (VD->isStaticLocal()) {
1718 SemaRef.Diag(VD->getLocation(),
1719 diag::err_constexpr_local_var_static)
1720 << isa<CXXConstructorDecl>(Dcl)
1721 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1722 return false;
1723 }
1724 if (!VD->getType()->isDependentType() &&
1725 SemaRef.RequireLiteralType(
1726 VD->getLocation(), VD->getType(),
1727 diag::err_constexpr_local_var_non_literal_type,
1728 isa<CXXConstructorDecl>(Dcl)))
1729 return false;
1730 if (!VD->getType()->isDependentType() &&
1731 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1732 SemaRef.Diag(VD->getLocation(),
1733 diag::err_constexpr_local_var_no_init)
1734 << isa<CXXConstructorDecl>(Dcl);
1735 return false;
1736 }
1737 }
1738 SemaRef.Diag(VD->getLocation(),
1739 SemaRef.getLangOpts().CPlusPlus14
1740 ? diag::warn_cxx11_compat_constexpr_local_var
1741 : diag::ext_constexpr_local_var)
1742 << isa<CXXConstructorDecl>(Dcl);
1743 continue;
1744 }
1745
1746 case Decl::NamespaceAlias:
1747 case Decl::Function:
1748 // These are disallowed in C++11 and permitted in C++1y. Allow them
1749 // everywhere as an extension.
1750 if (!Cxx1yLoc.isValid())
1751 Cxx1yLoc = DS->getLocStart();
1752 continue;
1753
1754 default:
1755 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1756 << isa<CXXConstructorDecl>(Dcl);
1757 return false;
1758 }
1759 }
1760
1761 return true;
1762}
1763
1764/// Check that the given field is initialized within a constexpr constructor.
1765///
1766/// \param Dcl The constexpr constructor being checked.
1767/// \param Field The field being checked. This may be a member of an anonymous
1768/// struct or union nested within the class being checked.
1769/// \param Inits All declarations, including anonymous struct/union members and
1770/// indirect members, for which any initialization was provided.
1771/// \param Diagnosed Set to true if an error is produced.
1772static void CheckConstexprCtorInitializer(Sema &SemaRef,
1773 const FunctionDecl *Dcl,
1774 FieldDecl *Field,
1775 llvm::SmallSet<Decl*, 16> &Inits,
1776 bool &Diagnosed) {
1777 if (Field->isInvalidDecl())
1778 return;
1779
1780 if (Field->isUnnamedBitfield())
1781 return;
1782
1783 // Anonymous unions with no variant members and empty anonymous structs do not
1784 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1785 // indirect fields don't need initializing.
1786 if (Field->isAnonymousStructOrUnion() &&
1787 (Field->getType()->isUnionType()
1788 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1789 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1790 return;
1791
1792 if (!Inits.count(Field)) {
1793 if (!Diagnosed) {
1794 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1795 Diagnosed = true;
1796 }
1797 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1798 } else if (Field->isAnonymousStructOrUnion()) {
1799 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1800 for (auto *I : RD->fields())
1801 // If an anonymous union contains an anonymous struct of which any member
1802 // is initialized, all members must be initialized.
1803 if (!RD->isUnion() || Inits.count(I))
1804 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1805 }
1806}
1807
1808/// Check the provided statement is allowed in a constexpr function
1809/// definition.
1810static bool
1811CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1812 SmallVectorImpl<SourceLocation> &ReturnStmts,
1813 SourceLocation &Cxx1yLoc) {
1814 // - its function-body shall be [...] a compound-statement that contains only
1815 switch (S->getStmtClass()) {
1816 case Stmt::NullStmtClass:
1817 // - null statements,
1818 return true;
1819
1820 case Stmt::DeclStmtClass:
1821 // - static_assert-declarations
1822 // - using-declarations,
1823 // - using-directives,
1824 // - typedef declarations and alias-declarations that do not define
1825 // classes or enumerations,
1826 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1827 return false;
1828 return true;
1829
1830 case Stmt::ReturnStmtClass:
1831 // - and exactly one return statement;
1832 if (isa<CXXConstructorDecl>(Dcl)) {
1833 // C++1y allows return statements in constexpr constructors.
1834 if (!Cxx1yLoc.isValid())
1835 Cxx1yLoc = S->getLocStart();
1836 return true;
1837 }
1838
1839 ReturnStmts.push_back(S->getLocStart());
1840 return true;
1841
1842 case Stmt::CompoundStmtClass: {
1843 // C++1y allows compound-statements.
1844 if (!Cxx1yLoc.isValid())
1845 Cxx1yLoc = S->getLocStart();
1846
1847 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1848 for (auto *BodyIt : CompStmt->body()) {
1849 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1850 Cxx1yLoc))
1851 return false;
1852 }
1853 return true;
1854 }
1855
1856 case Stmt::AttributedStmtClass:
1857 if (!Cxx1yLoc.isValid())
1858 Cxx1yLoc = S->getLocStart();
1859 return true;
1860
1861 case Stmt::IfStmtClass: {
1862 // C++1y allows if-statements.
1863 if (!Cxx1yLoc.isValid())
1864 Cxx1yLoc = S->getLocStart();
1865
1866 IfStmt *If = cast<IfStmt>(S);
1867 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1868 Cxx1yLoc))
1869 return false;
1870 if (If->getElse() &&
1871 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1872 Cxx1yLoc))
1873 return false;
1874 return true;
1875 }
1876
1877 case Stmt::WhileStmtClass:
1878 case Stmt::DoStmtClass:
1879 case Stmt::ForStmtClass:
1880 case Stmt::CXXForRangeStmtClass:
1881 case Stmt::ContinueStmtClass:
1882 // C++1y allows all of these. We don't allow them as extensions in C++11,
1883 // because they don't make sense without variable mutation.
1884 if (!SemaRef.getLangOpts().CPlusPlus14)
1885 break;
1886 if (!Cxx1yLoc.isValid())
1887 Cxx1yLoc = S->getLocStart();
1888 for (Stmt *SubStmt : S->children())
1889 if (SubStmt &&
1890 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1891 Cxx1yLoc))
1892 return false;
1893 return true;
1894
1895 case Stmt::SwitchStmtClass:
1896 case Stmt::CaseStmtClass:
1897 case Stmt::DefaultStmtClass:
1898 case Stmt::BreakStmtClass:
1899 // C++1y allows switch-statements, and since they don't need variable
1900 // mutation, we can reasonably allow them in C++11 as an extension.
1901 if (!Cxx1yLoc.isValid())
1902 Cxx1yLoc = S->getLocStart();
1903 for (Stmt *SubStmt : S->children())
1904 if (SubStmt &&
1905 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1906 Cxx1yLoc))
1907 return false;
1908 return true;
1909
1910 default:
1911 if (!isa<Expr>(S))
1912 break;
1913
1914 // C++1y allows expression-statements.
1915 if (!Cxx1yLoc.isValid())
1916 Cxx1yLoc = S->getLocStart();
1917 return true;
1918 }
1919
1920 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1921 << isa<CXXConstructorDecl>(Dcl);
1922 return false;
1923}
1924
1925/// Check the body for the given constexpr function declaration only contains
1926/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1927///
1928/// \return true if the body is OK, false if we have diagnosed a problem.
1929bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1930 if (isa<CXXTryStmt>(Body)) {
1931 // C++11 [dcl.constexpr]p3:
1932 // The definition of a constexpr function shall satisfy the following
1933 // constraints: [...]
1934 // - its function-body shall be = delete, = default, or a
1935 // compound-statement
1936 //
1937 // C++11 [dcl.constexpr]p4:
1938 // In the definition of a constexpr constructor, [...]
1939 // - its function-body shall not be a function-try-block;
1940 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1941 << isa<CXXConstructorDecl>(Dcl);
1942 return false;
1943 }
1944
1945 SmallVector<SourceLocation, 4> ReturnStmts;
1946
1947 // - its function-body shall be [...] a compound-statement that contains only
1948 // [... list of cases ...]
1949 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1950 SourceLocation Cxx1yLoc;
1951 for (auto *BodyIt : CompBody->body()) {
1952 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1953 return false;
1954 }
1955
1956 if (Cxx1yLoc.isValid())
1957 Diag(Cxx1yLoc,
1958 getLangOpts().CPlusPlus14
1959 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1960 : diag::ext_constexpr_body_invalid_stmt)
1961 << isa<CXXConstructorDecl>(Dcl);
1962
1963 if (const CXXConstructorDecl *Constructor
1964 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1965 const CXXRecordDecl *RD = Constructor->getParent();
1966 // DR1359:
1967 // - every non-variant non-static data member and base class sub-object
1968 // shall be initialized;
1969 // DR1460:
1970 // - if the class is a union having variant members, exactly one of them
1971 // shall be initialized;
1972 if (RD->isUnion()) {
1973 if (Constructor->getNumCtorInitializers() == 0 &&
1974 RD->hasVariantMembers()) {
1975 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1976 return false;
1977 }
1978 } else if (!Constructor->isDependentContext() &&
1979 !Constructor->isDelegatingConstructor()) {
1980 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")(static_cast <bool> (RD->getNumVBases() == 0 &&
"constexpr ctor with virtual bases") ? void (0) : __assert_fail
("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1980, __extension__ __PRETTY_FUNCTION__))
;
1981
1982 // Skip detailed checking if we have enough initializers, and we would
1983 // allow at most one initializer per member.
1984 bool AnyAnonStructUnionMembers = false;
1985 unsigned Fields = 0;
1986 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1987 E = RD->field_end(); I != E; ++I, ++Fields) {
1988 if (I->isAnonymousStructOrUnion()) {
1989 AnyAnonStructUnionMembers = true;
1990 break;
1991 }
1992 }
1993 // DR1460:
1994 // - if the class is a union-like class, but is not a union, for each of
1995 // its anonymous union members having variant members, exactly one of
1996 // them shall be initialized;
1997 if (AnyAnonStructUnionMembers ||
1998 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1999 // Check initialization of non-static data members. Base classes are
2000 // always initialized so do not need to be checked. Dependent bases
2001 // might not have initializers in the member initializer list.
2002 llvm::SmallSet<Decl*, 16> Inits;
2003 for (const auto *I: Constructor->inits()) {
2004 if (FieldDecl *FD = I->getMember())
2005 Inits.insert(FD);
2006 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2007 Inits.insert(ID->chain_begin(), ID->chain_end());
2008 }
2009
2010 bool Diagnosed = false;
2011 for (auto *I : RD->fields())
2012 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2013 if (Diagnosed)
2014 return false;
2015 }
2016 }
2017 } else {
2018 if (ReturnStmts.empty()) {
2019 // C++1y doesn't require constexpr functions to contain a 'return'
2020 // statement. We still do, unless the return type might be void, because
2021 // otherwise if there's no return statement, the function cannot
2022 // be used in a core constant expression.
2023 bool OK = getLangOpts().CPlusPlus14 &&
2024 (Dcl->getReturnType()->isVoidType() ||
2025 Dcl->getReturnType()->isDependentType());
2026 Diag(Dcl->getLocation(),
2027 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2028 : diag::err_constexpr_body_no_return);
2029 if (!OK)
2030 return false;
2031 } else if (ReturnStmts.size() > 1) {
2032 Diag(ReturnStmts.back(),
2033 getLangOpts().CPlusPlus14
2034 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2035 : diag::ext_constexpr_body_multiple_return);
2036 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2037 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2038 }
2039 }
2040
2041 // C++11 [dcl.constexpr]p5:
2042 // if no function argument values exist such that the function invocation
2043 // substitution would produce a constant expression, the program is
2044 // ill-formed; no diagnostic required.
2045 // C++11 [dcl.constexpr]p3:
2046 // - every constructor call and implicit conversion used in initializing the
2047 // return value shall be one of those allowed in a constant expression.
2048 // C++11 [dcl.constexpr]p4:
2049 // - every constructor involved in initializing non-static data members and
2050 // base class sub-objects shall be a constexpr constructor.
2051 SmallVector<PartialDiagnosticAt, 8> Diags;
2052 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2053 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2054 << isa<CXXConstructorDecl>(Dcl);
2055 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2056 Diag(Diags[I].first, Diags[I].second);
2057 // Don't return false here: we allow this for compatibility in
2058 // system headers.
2059 }
2060
2061 return true;
2062}
2063
2064/// isCurrentClassName - Determine whether the identifier II is the
2065/// name of the class type currently being defined. In the case of
2066/// nested classes, this will only return true if II is the name of
2067/// the innermost class.
2068bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2069 const CXXScopeSpec *SS) {
2070 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No class names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2070, __extension__ __PRETTY_FUNCTION__))
;
2071
2072 CXXRecordDecl *CurDecl;
2073 if (SS && SS->isSet() && !SS->isInvalid()) {
2074 DeclContext *DC = computeDeclContext(*SS, true);
2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2076 } else
2077 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2078
2079 if (CurDecl && CurDecl->getIdentifier())
2080 return &II == CurDecl->getIdentifier();
2081 return false;
2082}
2083
2084/// \brief Determine whether the identifier II is a typo for the name of
2085/// the class type currently being defined. If so, update it to the identifier
2086/// that should have been used.
2087bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2088 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No class names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2088, __extension__ __PRETTY_FUNCTION__))
;
2089
2090 if (!getLangOpts().SpellChecking)
2091 return false;
2092
2093 CXXRecordDecl *CurDecl;
2094 if (SS && SS->isSet() && !SS->isInvalid()) {
2095 DeclContext *DC = computeDeclContext(*SS, true);
2096 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2097 } else
2098 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2099
2100 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2101 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2102 < II->getLength()) {
2103 II = CurDecl->getIdentifier();
2104 return true;
2105 }
2106
2107 return false;
2108}
2109
2110/// \brief Determine whether the given class is a base class of the given
2111/// class, including looking at dependent bases.
2112static bool findCircularInheritance(const CXXRecordDecl *Class,
2113 const CXXRecordDecl *Current) {
2114 SmallVector<const CXXRecordDecl*, 8> Queue;
2115
2116 Class = Class->getCanonicalDecl();
2117 while (true) {
2118 for (const auto &I : Current->bases()) {
2119 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2120 if (!Base)
2121 continue;
2122
2123 Base = Base->getDefinition();
2124 if (!Base)
2125 continue;
2126
2127 if (Base->getCanonicalDecl() == Class)
2128 return true;
2129
2130 Queue.push_back(Base);
2131 }
2132
2133 if (Queue.empty())
2134 return false;
2135
2136 Current = Queue.pop_back_val();
2137 }
2138
2139 return false;
2140}
2141
2142/// \brief Check the validity of a C++ base class specifier.
2143///
2144/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2145/// and returns NULL otherwise.
2146CXXBaseSpecifier *
2147Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2148 SourceRange SpecifierRange,
2149 bool Virtual, AccessSpecifier Access,
2150 TypeSourceInfo *TInfo,
2151 SourceLocation EllipsisLoc) {
2152 QualType BaseType = TInfo->getType();
2153
2154 // C++ [class.union]p1:
2155 // A union shall not have base classes.
2156 if (Class->isUnion()) {
2157 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2158 << SpecifierRange;
2159 return nullptr;
2160 }
2161
2162 if (EllipsisLoc.isValid() &&
2163 !TInfo->getType()->containsUnexpandedParameterPack()) {
2164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2165 << TInfo->getTypeLoc().getSourceRange();
2166 EllipsisLoc = SourceLocation();
2167 }
2168
2169 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2170
2171 if (BaseType->isDependentType()) {
2172 // Make sure that we don't have circular inheritance among our dependent
2173 // bases. For non-dependent bases, the check for completeness below handles
2174 // this.
2175 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2176 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2177 ((BaseDecl = BaseDecl->getDefinition()) &&
2178 findCircularInheritance(Class, BaseDecl))) {
2179 Diag(BaseLoc, diag::err_circular_inheritance)
2180 << BaseType << Context.getTypeDeclType(Class);
2181
2182 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2183 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2184 << BaseType;
2185
2186 return nullptr;
2187 }
2188 }
2189
2190 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2191 Class->getTagKind() == TTK_Class,
2192 Access, TInfo, EllipsisLoc);
2193 }
2194
2195 // Base specifiers must be record types.
2196 if (!BaseType->isRecordType()) {
2197 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2198 return nullptr;
2199 }
2200
2201 // C++ [class.union]p1:
2202 // A union shall not be used as a base class.
2203 if (BaseType->isUnionType()) {
2204 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2205 return nullptr;
2206 }
2207
2208 // For the MS ABI, propagate DLL attributes to base class templates.
2209 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2210 if (Attr *ClassAttr = getDLLAttr(Class)) {
2211 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2212 BaseType->getAsCXXRecordDecl())) {
2213 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2214 BaseLoc);
2215 }
2216 }
2217 }
2218
2219 // C++ [class.derived]p2:
2220 // The class-name in a base-specifier shall not be an incompletely
2221 // defined class.
2222 if (RequireCompleteType(BaseLoc, BaseType,
2223 diag::err_incomplete_base_class, SpecifierRange)) {
2224 Class->setInvalidDecl();
2225 return nullptr;
2226 }
2227
2228 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2229 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2230 assert(BaseDecl && "Record type has no declaration")(static_cast <bool> (BaseDecl && "Record type has no declaration"
) ? void (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2230, __extension__ __PRETTY_FUNCTION__))
;
2231 BaseDecl = BaseDecl->getDefinition();
2232 assert(BaseDecl && "Base type is not incomplete, but has no definition")(static_cast <bool> (BaseDecl && "Base type is not incomplete, but has no definition"
) ? void (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2232, __extension__ __PRETTY_FUNCTION__))
;
2233 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2234 assert(CXXBaseDecl && "Base type is not a C++ type")(static_cast <bool> (CXXBaseDecl && "Base type is not a C++ type"
) ? void (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2234, __extension__ __PRETTY_FUNCTION__))
;
2235
2236 // A class which contains a flexible array member is not suitable for use as a
2237 // base class:
2238 // - If the layout determines that a base comes before another base,
2239 // the flexible array member would index into the subsequent base.
2240 // - If the layout determines that base comes before the derived class,
2241 // the flexible array member would index into the derived class.
2242 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2243 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2244 << CXXBaseDecl->getDeclName();
2245 return nullptr;
2246 }
2247
2248 // C++ [class]p3:
2249 // If a class is marked final and it appears as a base-type-specifier in
2250 // base-clause, the program is ill-formed.
2251 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2252 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2253 << CXXBaseDecl->getDeclName()
2254 << FA->isSpelledAsSealed();
2255 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2256 << CXXBaseDecl->getDeclName() << FA->getRange();
2257 return nullptr;
2258 }
2259
2260 if (BaseDecl->isInvalidDecl())
2261 Class->setInvalidDecl();
2262
2263 // Create the base specifier.
2264 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2265 Class->getTagKind() == TTK_Class,
2266 Access, TInfo, EllipsisLoc);
2267}
2268
2269/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2270/// one entry in the base class list of a class specifier, for
2271/// example:
2272/// class foo : public bar, virtual private baz {
2273/// 'public bar' and 'virtual private baz' are each base-specifiers.
2274BaseResult
2275Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2276 ParsedAttributes &Attributes,
2277 bool Virtual, AccessSpecifier Access,
2278 ParsedType basetype, SourceLocation BaseLoc,
2279 SourceLocation EllipsisLoc) {
2280 if (!classdecl)
2281 return true;
2282
2283 AdjustDeclIfTemplate(classdecl);
2284 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2285 if (!Class)
2286 return true;
2287
2288 // We haven't yet attached the base specifiers.
2289 Class->setIsParsingBaseSpecifiers();
2290
2291 // We do not support any C++11 attributes on base-specifiers yet.
2292 // Diagnose any attributes we see.
2293 if (!Attributes.empty()) {
2294 for (AttributeList *Attr = Attributes.getList(); Attr;
2295 Attr = Attr->getNext()) {
2296 if (Attr->isInvalid() ||
2297 Attr->getKind() == AttributeList::IgnoredAttribute)
2298 continue;
2299 Diag(Attr->getLoc(),
2300 Attr->getKind() == AttributeList::UnknownAttribute
2301 ? diag::warn_unknown_attribute_ignored
2302 : diag::err_base_specifier_attribute)
2303 << Attr->getName();
2304 }
2305 }
2306
2307 TypeSourceInfo *TInfo = nullptr;
2308 GetTypeFromParser(basetype, &TInfo);
2309
2310 if (EllipsisLoc.isInvalid() &&
2311 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2312 UPPC_BaseType))
2313 return true;
2314
2315 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2316 Virtual, Access, TInfo,
2317 EllipsisLoc))
2318 return BaseSpec;
2319 else
2320 Class->setInvalidDecl();
2321
2322 return true;
2323}
2324
2325/// Use small set to collect indirect bases. As this is only used
2326/// locally, there's no need to abstract the small size parameter.
2327typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2328
2329/// \brief Recursively add the bases of Type. Don't add Type itself.
2330static void
2331NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2332 const QualType &Type)
2333{
2334 // Even though the incoming type is a base, it might not be
2335 // a class -- it could be a template parm, for instance.
2336 if (auto Rec = Type->getAs<RecordType>()) {
2337 auto Decl = Rec->getAsCXXRecordDecl();
2338
2339 // Iterate over its bases.
2340 for (const auto &BaseSpec : Decl->bases()) {
2341 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2342 .getUnqualifiedType();
2343 if (Set.insert(Base).second)
2344 // If we've not already seen it, recurse.
2345 NoteIndirectBases(Context, Set, Base);
2346 }
2347 }
2348}
2349
2350/// \brief Performs the actual work of attaching the given base class
2351/// specifiers to a C++ class.
2352bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2353 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2354 if (Bases.empty())
2355 return false;
2356
2357 // Used to keep track of which base types we have already seen, so
2358 // that we can properly diagnose redundant direct base types. Note
2359 // that the key is always the unqualified canonical type of the base
2360 // class.
2361 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2362
2363 // Used to track indirect bases so we can see if a direct base is
2364 // ambiguous.
2365 IndirectBaseSet IndirectBaseTypes;
2366
2367 // Copy non-redundant base specifiers into permanent storage.
2368 unsigned NumGoodBases = 0;
2369 bool Invalid = false;
2370 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2371 QualType NewBaseType
2372 = Context.getCanonicalType(Bases[idx]->getType());
2373 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2374
2375 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2376 if (KnownBase) {
2377 // C++ [class.mi]p3:
2378 // A class shall not be specified as a direct base class of a
2379 // derived class more than once.
2380 Diag(Bases[idx]->getLocStart(),
2381 diag::err_duplicate_base_class)
2382 << KnownBase->getType()
2383 << Bases[idx]->getSourceRange();
2384
2385 // Delete the duplicate base class specifier; we're going to
2386 // overwrite its pointer later.
2387 Context.Deallocate(Bases[idx]);
2388
2389 Invalid = true;
2390 } else {
2391 // Okay, add this new base class.
2392 KnownBase = Bases[idx];
2393 Bases[NumGoodBases++] = Bases[idx];
2394
2395 // Note this base's direct & indirect bases, if there could be ambiguity.
2396 if (Bases.size() > 1)
2397 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2398
2399 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2400 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2401 if (Class->isInterface() &&
2402 (!RD->isInterfaceLike() ||
2403 KnownBase->getAccessSpecifier() != AS_public)) {
2404 // The Microsoft extension __interface does not permit bases that
2405 // are not themselves public interfaces.
2406 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2407 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2408 << RD->getSourceRange();
2409 Invalid = true;
2410 }
2411 if (RD->hasAttr<WeakAttr>())
2412 Class->addAttr(WeakAttr::CreateImplicit(Context));
2413 }
2414 }
2415 }
2416
2417 // Attach the remaining base class specifiers to the derived class.
2418 Class->setBases(Bases.data(), NumGoodBases);
2419
2420 // Check that the only base classes that are duplicate are virtual.
2421 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2422 // Check whether this direct base is inaccessible due to ambiguity.
2423 QualType BaseType = Bases[idx]->getType();
2424
2425 // Skip all dependent types in templates being used as base specifiers.
2426 // Checks below assume that the base specifier is a CXXRecord.
2427 if (BaseType->isDependentType())
2428 continue;
2429
2430 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2431 .getUnqualifiedType();
2432
2433 if (IndirectBaseTypes.count(CanonicalBase)) {
2434 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2435 /*DetectVirtual=*/true);
2436 bool found
2437 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2438 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2438, __extension__ __PRETTY_FUNCTION__))
;
2439 (void)found;
2440
2441 if (Paths.isAmbiguous(CanonicalBase))
2442 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2443 << BaseType << getAmbiguousPathsDisplayString(Paths)
2444 << Bases[idx]->getSourceRange();
2445 else
2446 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2446, __extension__ __PRETTY_FUNCTION__))
;
2447 }
2448
2449 // Delete the base class specifier, since its data has been copied
2450 // into the CXXRecordDecl.
2451 Context.Deallocate(Bases[idx]);
2452 }
2453
2454 return Invalid;
2455}
2456
2457/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2458/// class, after checking whether there are any duplicate base
2459/// classes.
2460void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2461 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2462 if (!ClassDecl || Bases.empty())
2463 return;
2464
2465 AdjustDeclIfTemplate(ClassDecl);
2466 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2467}
2468
2469/// \brief Determine whether the type \p Derived is a C++ class that is
2470/// derived from the type \p Base.
2471bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2472 if (!getLangOpts().CPlusPlus)
2473 return false;
2474
2475 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2476 if (!DerivedRD)
2477 return false;
2478
2479 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2480 if (!BaseRD)
2481 return false;
2482
2483 // If either the base or the derived type is invalid, don't try to
2484 // check whether one is derived from the other.
2485 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2486 return false;
2487
2488 // FIXME: In a modules build, do we need the entire path to be visible for us
2489 // to be able to use the inheritance relationship?
2490 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2491 return false;
2492
2493 return DerivedRD->isDerivedFrom(BaseRD);
2494}
2495
2496/// \brief Determine whether the type \p Derived is a C++ class that is
2497/// derived from the type \p Base.
2498bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2499 CXXBasePaths &Paths) {
2500 if (!getLangOpts().CPlusPlus)
2501 return false;
2502
2503 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2504 if (!DerivedRD)
2505 return false;
2506
2507 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2508 if (!BaseRD)
2509 return false;
2510
2511 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2512 return false;
2513
2514 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2515}
2516
2517static void BuildBasePathArray(const CXXBasePath &Path,
2518 CXXCastPath &BasePathArray) {
2519 // We first go backward and check if we have a virtual base.
2520 // FIXME: It would be better if CXXBasePath had the base specifier for
2521 // the nearest virtual base.
2522 unsigned Start = 0;
2523 for (unsigned I = Path.size(); I != 0; --I) {
2524 if (Path[I - 1].Base->isVirtual()) {
2525 Start = I - 1;
2526 break;
2527 }
2528 }
2529
2530 // Now add all bases.
2531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2533}
2534
2535
2536void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2537 CXXCastPath &BasePathArray) {
2538 assert(BasePathArray.empty() && "Base path array must be empty!")(static_cast <bool> (BasePathArray.empty() && "Base path array must be empty!"
) ? void (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2538, __extension__ __PRETTY_FUNCTION__))
;
2539 assert(Paths.isRecordingPaths() && "Must record paths!")(static_cast <bool> (Paths.isRecordingPaths() &&
"Must record paths!") ? void (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2539, __extension__ __PRETTY_FUNCTION__))
;
2540 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2541}
2542/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2543/// conversion (where Derived and Base are class types) is
2544/// well-formed, meaning that the conversion is unambiguous (and
2545/// that all of the base classes are accessible). Returns true
2546/// and emits a diagnostic if the code is ill-formed, returns false
2547/// otherwise. Loc is the location where this routine should point to
2548/// if there is an error, and Range is the source range to highlight
2549/// if there is an error.
2550///
2551/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2552/// diagnostic for the respective type of error will be suppressed, but the
2553/// check for ill-formed code will still be performed.
2554bool
2555Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2556 unsigned InaccessibleBaseID,
2557 unsigned AmbigiousBaseConvID,
2558 SourceLocation Loc, SourceRange Range,
2559 DeclarationName Name,
2560 CXXCastPath *BasePath,
2561 bool IgnoreAccess) {
2562 // First, determine whether the path from Derived to Base is
2563 // ambiguous. This is slightly more expensive than checking whether
2564 // the Derived to Base conversion exists, because here we need to
2565 // explore multiple paths to determine if there is an ambiguity.
2566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2567 /*DetectVirtual=*/false);
2568 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2569 if (!DerivationOkay)
2570 return true;
2571
2572 const CXXBasePath *Path = nullptr;
2573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2574 Path = &Paths.front();
2575
2576 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2577 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2578 // user to access such bases.
2579 if (!Path && getLangOpts().MSVCCompat) {
2580 for (const CXXBasePath &PossiblePath : Paths) {
2581 if (PossiblePath.size() == 1) {
2582 Path = &PossiblePath;
2583 if (AmbigiousBaseConvID)
2584 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2585 << Base << Derived << Range;
2586 break;
2587 }
2588 }
2589 }
2590
2591 if (Path) {
2592 if (!IgnoreAccess) {
2593 // Check that the base class can be accessed.
2594 switch (
2595 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2596 case AR_inaccessible:
2597 return true;
2598 case AR_accessible:
2599 case AR_dependent:
2600 case AR_delayed:
2601 break;
2602 }
2603 }
2604
2605 // Build a base path if necessary.
2606 if (BasePath)
2607 ::BuildBasePathArray(*Path, *BasePath);
2608 return false;
2609 }
2610
2611 if (AmbigiousBaseConvID) {
2612 // We know that the derived-to-base conversion is ambiguous, and
2613 // we're going to produce a diagnostic. Perform the derived-to-base
2614 // search just one more time to compute all of the possible paths so
2615 // that we can print them out. This is more expensive than any of
2616 // the previous derived-to-base checks we've done, but at this point
2617 // performance isn't as much of an issue.
2618 Paths.clear();
2619 Paths.setRecordingPaths(true);
2620 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2621 assert(StillOkay && "Can only be used with a derived-to-base conversion")(static_cast <bool> (StillOkay && "Can only be used with a derived-to-base conversion"
) ? void (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2621, __extension__ __PRETTY_FUNCTION__))
;
2622 (void)StillOkay;
2623
2624 // Build up a textual representation of the ambiguous paths, e.g.,
2625 // D -> B -> A, that will be used to illustrate the ambiguous
2626 // conversions in the diagnostic. We only print one of the paths
2627 // to each base class subobject.
2628 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2629
2630 Diag(Loc, AmbigiousBaseConvID)
2631 << Derived << Base << PathDisplayStr << Range << Name;
2632 }
2633 return true;
2634}
2635
2636bool
2637Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2638 SourceLocation Loc, SourceRange Range,
2639 CXXCastPath *BasePath,
2640 bool IgnoreAccess) {
2641 return CheckDerivedToBaseConversion(
2642 Derived, Base, diag::err_upcast_to_inaccessible_base,
2643 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2644 BasePath, IgnoreAccess);
2645}
2646
2647
2648/// @brief Builds a string representing ambiguous paths from a
2649/// specific derived class to different subobjects of the same base
2650/// class.
2651///
2652/// This function builds a string that can be used in error messages
2653/// to show the different paths that one can take through the
2654/// inheritance hierarchy to go from the derived class to different
2655/// subobjects of a base class. The result looks something like this:
2656/// @code
2657/// struct D -> struct B -> struct A
2658/// struct D -> struct C -> struct A
2659/// @endcode
2660std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2661 std::string PathDisplayStr;
2662 std::set<unsigned> DisplayedPaths;
2663 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2664 Path != Paths.end(); ++Path) {
2665 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2666 // We haven't displayed a path to this particular base
2667 // class subobject yet.
2668 PathDisplayStr += "\n ";
2669 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2670 for (CXXBasePath::const_iterator Element = Path->begin();
2671 Element != Path->end(); ++Element)
2672 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2673 }
2674 }
2675
2676 return PathDisplayStr;
2677}
2678
2679//===----------------------------------------------------------------------===//
2680// C++ class member Handling
2681//===----------------------------------------------------------------------===//
2682
2683/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2684bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2685 SourceLocation ASLoc,
2686 SourceLocation ColonLoc,
2687 AttributeList *Attrs) {
2688 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")(static_cast <bool> (Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? void (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2688, __extension__ __PRETTY_FUNCTION__))
;
2689 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2690 ASLoc, ColonLoc);
2691 CurContext->addHiddenDecl(ASDecl);
2692 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2693}
2694
2695/// CheckOverrideControl - Check C++11 override control semantics.
2696void Sema::CheckOverrideControl(NamedDecl *D) {
2697 if (D->isInvalidDecl())
2698 return;
2699
2700 // We only care about "override" and "final" declarations.
2701 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2702 return;
2703
2704 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2705
2706 // We can't check dependent instance methods.
2707 if (MD && MD->isInstance() &&
2708 (MD->getParent()->hasAnyDependentBases() ||
2709 MD->getType()->isDependentType()))
2710 return;
2711
2712 if (MD && !MD->isVirtual()) {
2713 // If we have a non-virtual method, check if if hides a virtual method.
2714 // (In that case, it's most likely the method has the wrong type.)
2715 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2716 FindHiddenVirtualMethods(MD, OverloadedMethods);
2717
2718 if (!OverloadedMethods.empty()) {
2719 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2720 Diag(OA->getLocation(),
2721 diag::override_keyword_hides_virtual_member_function)
2722 << "override" << (OverloadedMethods.size() > 1);
2723 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2724 Diag(FA->getLocation(),
2725 diag::override_keyword_hides_virtual_member_function)
2726 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2727 << (OverloadedMethods.size() > 1);
2728 }
2729 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2730 MD->setInvalidDecl();
2731 return;
2732 }
2733 // Fall through into the general case diagnostic.
2734 // FIXME: We might want to attempt typo correction here.
2735 }
2736
2737 if (!MD || !MD->isVirtual()) {
2738 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2739 Diag(OA->getLocation(),
2740 diag::override_keyword_only_allowed_on_virtual_member_functions)
2741 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2742 D->dropAttr<OverrideAttr>();
2743 }
2744 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2745 Diag(FA->getLocation(),
2746 diag::override_keyword_only_allowed_on_virtual_member_functions)
2747 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2748 << FixItHint::CreateRemoval(FA->getLocation());
2749 D->dropAttr<FinalAttr>();
2750 }
2751 return;
2752 }
2753
2754 // C++11 [class.virtual]p5:
2755 // If a function is marked with the virt-specifier override and
2756 // does not override a member function of a base class, the program is
2757 // ill-formed.
2758 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2759 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2760 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2761 << MD->getDeclName();
2762}
2763
2764void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2765 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2766 return;
2767 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2768 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2769 return;
2770
2771 SourceLocation Loc = MD->getLocation();
2772 SourceLocation SpellingLoc = Loc;
2773 if (getSourceManager().isMacroArgExpansion(Loc))
2774 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2775 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2776 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2777 return;
2778
2779 if (MD->size_overridden_methods() > 0) {
2780 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2781 ? diag::warn_destructor_marked_not_override_overriding
2782 : diag::warn_function_marked_not_override_overriding;
2783 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2784 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2785 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2786 }
2787}
2788
2789/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2790/// function overrides a virtual member function marked 'final', according to
2791/// C++11 [class.virtual]p4.
2792bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2793 const CXXMethodDecl *Old) {
2794 FinalAttr *FA = Old->getAttr<FinalAttr>();
2795 if (!FA)
2796 return false;
2797
2798 Diag(New->getLocation(), diag::err_final_function_overridden)
2799 << New->getDeclName()
2800 << FA->isSpelledAsSealed();
2801 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2802 return true;
2803}
2804
2805static bool InitializationHasSideEffects(const FieldDecl &FD) {
2806 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2807 // FIXME: Destruction of ObjC lifetime types has side-effects.
2808 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2809 return !RD->isCompleteDefinition() ||
2810 !RD->hasTrivialDefaultConstructor() ||
2811 !RD->hasTrivialDestructor();
2812 return false;
2813}
2814
2815static AttributeList *getMSPropertyAttr(AttributeList *list) {
2816 for (AttributeList *it = list; it != nullptr; it = it->getNext())
2817 if (it->isDeclspecPropertyAttribute())
2818 return it;
2819 return nullptr;
2820}
2821
2822// Check if there is a field shadowing.
2823void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2824 DeclarationName FieldName,
2825 const CXXRecordDecl *RD) {
2826 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2827 return;
2828
2829 // To record a shadowed field in a base
2830 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2831 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2832 CXXBasePath &Path) {
2833 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2834 // Record an ambiguous path directly
2835 if (Bases.find(Base) != Bases.end())
2836 return true;
2837 for (const auto Field : Base->lookup(FieldName)) {
2838 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2839 Field->getAccess() != AS_private) {
2840 assert(Field->getAccess() != AS_none)(static_cast <bool> (Field->getAccess() != AS_none) ?
void (0) : __assert_fail ("Field->getAccess() != AS_none"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2840, __extension__ __PRETTY_FUNCTION__))
;
2841 assert(Bases.find(Base) == Bases.end())(static_cast <bool> (Bases.find(Base) == Bases.end()) ?
void (0) : __assert_fail ("Bases.find(Base) == Bases.end()",
"/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2841, __extension__ __PRETTY_FUNCTION__))
;
2842 Bases[Base] = Field;
2843 return true;
2844 }
2845 }
2846 return false;
2847 };
2848
2849 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2850 /*DetectVirtual=*/true);
2851 if (!RD->lookupInBases(FieldShadowed, Paths))
2852 return;
2853
2854 for (const auto &P : Paths) {
2855 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2856 auto It = Bases.find(Base);
2857 // Skip duplicated bases
2858 if (It == Bases.end())
2859 continue;
2860 auto BaseField = It->second;
2861 assert(BaseField->getAccess() != AS_private)(static_cast <bool> (BaseField->getAccess() != AS_private
) ? void (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2861, __extension__ __PRETTY_FUNCTION__))
;
2862 if (AS_none !=
2863 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2864 Diag(Loc, diag::warn_shadow_field)
2865 << FieldName << RD << Base;
2866 Diag(BaseField->getLocation(), diag::note_shadow_field);
2867 Bases.erase(It);
2868 }
2869 }
2870}
2871
2872/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2873/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2874/// bitfield width if there is one, 'InitExpr' specifies the initializer if
2875/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2876/// present (but parsing it has been deferred).
2877NamedDecl *
2878Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2879 MultiTemplateParamsArg TemplateParameterLists,
2880 Expr *BW, const VirtSpecifiers &VS,
2881 InClassInitStyle InitStyle) {
2882 const DeclSpec &DS = D.getDeclSpec();
2883 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2884 DeclarationName Name = NameInfo.getName();
2885 SourceLocation Loc = NameInfo.getLoc();
2886
2887 // For anonymous bitfields, the location should point to the type.
2888 if (Loc.isInvalid())
2889 Loc = D.getLocStart();
2890
2891 Expr *BitWidth = static_cast<Expr*>(BW);
2892
2893 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2893, __extension__ __PRETTY_FUNCTION__))
;
2894 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2894, __extension__ __PRETTY_FUNCTION__))
;
2895
2896 bool isFunc = D.isDeclarationOfFunction();
2897 AttributeList *MSPropertyAttr =
2898 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2899
2900 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2901 // The Microsoft extension __interface only permits public member functions
2902 // and prohibits constructors, destructors, operators, non-public member
2903 // functions, static methods and data members.
2904 unsigned InvalidDecl;
2905 bool ShowDeclName = true;
2906 if (!isFunc &&
2907 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2908 InvalidDecl = 0;
2909 else if (!isFunc)
2910 InvalidDecl = 1;
2911 else if (AS != AS_public)
2912 InvalidDecl = 2;
2913 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2914 InvalidDecl = 3;
2915 else switch (Name.getNameKind()) {
2916 case DeclarationName::CXXConstructorName:
2917 InvalidDecl = 4;
2918 ShowDeclName = false;
2919 break;
2920
2921 case DeclarationName::CXXDestructorName:
2922 InvalidDecl = 5;
2923 ShowDeclName = false;
2924 break;
2925
2926 case DeclarationName::CXXOperatorName:
2927 case DeclarationName::CXXConversionFunctionName:
2928 InvalidDecl = 6;
2929 break;
2930
2931 default:
2932 InvalidDecl = 0;
2933 break;
2934 }
2935
2936 if (InvalidDecl) {
2937 if (ShowDeclName)
2938 Diag(Loc, diag::err_invalid_member_in_interface)
2939 << (InvalidDecl-1) << Name;
2940 else
2941 Diag(Loc, diag::err_invalid_member_in_interface)
2942 << (InvalidDecl-1) << "";
2943 return nullptr;
2944 }
2945 }
2946
2947 // C++ 9.2p6: A member shall not be declared to have automatic storage
2948 // duration (auto, register) or with the extern storage-class-specifier.
2949 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2950 // data members and cannot be applied to names declared const or static,
2951 // and cannot be applied to reference members.
2952 switch (DS.getStorageClassSpec()) {
2953 case DeclSpec::SCS_unspecified:
2954 case DeclSpec::SCS_typedef:
2955 case DeclSpec::SCS_static:
2956 break;
2957 case DeclSpec::SCS_mutable:
2958 if (isFunc) {
2959 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2960
2961 // FIXME: It would be nicer if the keyword was ignored only for this
2962 // declarator. Otherwise we could get follow-up errors.
2963 D.getMutableDeclSpec().ClearStorageClassSpecs();
2964 }
2965 break;
2966 default:
2967 Diag(DS.getStorageClassSpecLoc(),
2968 diag::err_storageclass_invalid_for_member);
2969 D.getMutableDeclSpec().ClearStorageClassSpecs();
2970 break;
2971 }
2972
2973 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2974 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2975 !isFunc);
2976
2977 if (DS.isConstexprSpecified() && isInstField) {
2978 SemaDiagnosticBuilder B =
2979 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2980 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2981 if (InitStyle == ICIS_NoInit) {
2982 B << 0 << 0;
2983 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2984 B << FixItHint::CreateRemoval(ConstexprLoc);
2985 else {
2986 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2987 D.getMutableDeclSpec().ClearConstexprSpec();
2988 const char *PrevSpec;
2989 unsigned DiagID;
2990 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2991 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2992 (void)Failed;
2993 assert(!Failed && "Making a constexpr member const shouldn't fail")(static_cast <bool> (!Failed && "Making a constexpr member const shouldn't fail"
) ? void (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2993, __extension__ __PRETTY_FUNCTION__))
;
2994 }
2995 } else {
2996 B << 1;
2997 const char *PrevSpec;
2998 unsigned DiagID;
2999 if (D.getMutableDeclSpec().SetStorageClassSpec(
3000 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3001 Context.getPrintingPolicy())) {
3002 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_mutable && "This is the only DeclSpec that should fail to be applied"
) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3003, __extension__ __PRETTY_FUNCTION__))
3003 "This is the only DeclSpec that should fail to be applied")(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_mutable && "This is the only DeclSpec that should fail to be applied"
) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3003, __extension__ __PRETTY_FUNCTION__))
;
3004 B << 1;
3005 } else {
3006 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3007 isInstField = false;
3008 }
3009 }
3010 }
3011
3012 NamedDecl *Member;
3013 if (isInstField) {
3014 CXXScopeSpec &SS = D.getCXXScopeSpec();
3015
3016 // Data members must have identifiers for names.
3017 if (!Name.isIdentifier()) {
3018 Diag(Loc, diag::err_bad_variable_name)
3019 << Name;
3020 return nullptr;
3021 }
3022
3023 IdentifierInfo *II = Name.getAsIdentifierInfo();
3024
3025 // Member field could not be with "template" keyword.
3026 // So TemplateParameterLists should be empty in this case.
3027 if (TemplateParameterLists.size()) {
3028 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3029 if (TemplateParams->size()) {
3030 // There is no such thing as a member field template.
3031 Diag(D.getIdentifierLoc(), diag::err_template_member)
3032 << II
3033 << SourceRange(TemplateParams->getTemplateLoc(),
3034 TemplateParams->getRAngleLoc());
3035 } else {
3036 // There is an extraneous 'template<>' for this member.
3037 Diag(TemplateParams->getTemplateLoc(),
3038 diag::err_template_member_noparams)
3039 << II
3040 << SourceRange(TemplateParams->getTemplateLoc(),
3041 TemplateParams->getRAngleLoc());
3042 }
3043 return nullptr;
3044 }
3045
3046 if (SS.isSet() && !SS.isInvalid()) {
3047 // The user provided a superfluous scope specifier inside a class
3048 // definition:
3049 //
3050 // class X {
3051 // int X::member;
3052 // };
3053 if (DeclContext *DC = computeDeclContext(SS, false))
3054 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3055 D.getName().getKind() ==
3056 UnqualifiedIdKind::IK_TemplateId);
3057 else
3058 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3059 << Name << SS.getRange();
3060
3061 SS.clear();
3062 }
3063
3064 if (MSPropertyAttr) {
3065 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3066 BitWidth, InitStyle, AS, MSPropertyAttr);
3067 if (!Member)
3068 return nullptr;
3069 isInstField = false;
3070 } else {
3071 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3072 BitWidth, InitStyle, AS);
3073 if (!Member)
3074 return nullptr;
3075 }
3076
3077 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3078 } else {
3079 Member = HandleDeclarator(S, D, TemplateParameterLists);
3080 if (!Member)
3081 return nullptr;
3082
3083 // Non-instance-fields can't have a bitfield.
3084 if (BitWidth) {
3085 if (Member->isInvalidDecl()) {
3086 // don't emit another diagnostic.
3087 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3088 // C++ 9.6p3: A bit-field shall not be a static member.
3089 // "static member 'A' cannot be a bit-field"
3090 Diag(Loc, diag::err_static_not_bitfield)
3091 << Name << BitWidth->getSourceRange();
3092 } else if (isa<TypedefDecl>(Member)) {
3093 // "typedef member 'x' cannot be a bit-field"
3094 Diag(Loc, diag::err_typedef_not_bitfield)
3095 << Name << BitWidth->getSourceRange();
3096 } else {
3097 // A function typedef ("typedef int f(); f a;").
3098 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3099 Diag(Loc, diag::err_not_integral_type_bitfield)
3100 << Name << cast<ValueDecl>(Member)->getType()
3101 << BitWidth->getSourceRange();
3102 }
3103
3104 BitWidth = nullptr;
3105 Member->setInvalidDecl();
3106 }
3107
3108 Member->setAccess(AS);
3109
3110 // If we have declared a member function template or static data member
3111 // template, set the access of the templated declaration as well.
3112 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3113 FunTmpl->getTemplatedDecl()->setAccess(AS);
3114 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3115 VarTmpl->getTemplatedDecl()->setAccess(AS);
3116 }
3117
3118 if (VS.isOverrideSpecified())
3119 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3120 if (VS.isFinalSpecified())
3121 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3122 VS.isFinalSpelledSealed()));
3123
3124 if (VS.getLastLocation().isValid()) {
3125 // Update the end location of a method that has a virt-specifiers.
3126 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3127 MD->setRangeEnd(VS.getLastLocation());
3128 }
3129
3130 CheckOverrideControl(Member);
3131
3132 assert((Name || isInstField) && "No identifier for non-field ?")(static_cast <bool> ((Name || isInstField) && "No identifier for non-field ?"
) ? void (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3132, __extension__ __PRETTY_FUNCTION__))
;
3133
3134 if (isInstField) {
3135 FieldDecl *FD = cast<FieldDecl>(Member);
3136 FieldCollector->Add(FD);
3137
3138 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3139 // Remember all explicit private FieldDecls that have a name, no side
3140 // effects and are not part of a dependent type declaration.
3141 if (!FD->isImplicit() && FD->getDeclName() &&
3142 FD->getAccess() == AS_private &&
3143 !FD->hasAttr<UnusedAttr>() &&
3144 !FD->getParent()->isDependentContext() &&
3145 !InitializationHasSideEffects(*FD))
3146 UnusedPrivateFields.insert(FD);
3147 }
3148 }
3149
3150 return Member;
3151}
3152
3153namespace {
3154 class UninitializedFieldVisitor
3155 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3156 Sema &S;
3157 // List of Decls to generate a warning on. Also remove Decls that become
3158 // initialized.
3159 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3160 // List of base classes of the record. Classes are removed after their
3161 // initializers.
3162 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3163 // Vector of decls to be removed from the Decl set prior to visiting the
3164 // nodes. These Decls may have been initialized in the prior initializer.
3165 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3166 // If non-null, add a note to the warning pointing back to the constructor.
3167 const CXXConstructorDecl *Constructor;
3168 // Variables to hold state when processing an initializer list. When
3169 // InitList is true, special case initialization of FieldDecls matching
3170 // InitListFieldDecl.
3171 bool InitList;
3172 FieldDecl *InitListFieldDecl;
3173 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3174
3175 public:
3176 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3177 UninitializedFieldVisitor(Sema &S,
3178 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3179 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3180 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3181 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3182
3183 // Returns true if the use of ME is not an uninitialized use.
3184 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3185 bool CheckReferenceOnly) {
3186 llvm::SmallVector<FieldDecl*, 4> Fields;
3187 bool ReferenceField = false;
3188 while (ME) {
3189 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3190 if (!FD)
3191 return false;
3192 Fields.push_back(FD);
3193 if (FD->getType()->isReferenceType())
3194 ReferenceField = true;
3195 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3196 }
3197
3198 // Binding a reference to an unintialized field is not an
3199 // uninitialized use.
3200 if (CheckReferenceOnly && !ReferenceField)
3201 return true;
3202
3203 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3204 // Discard the first field since it is the field decl that is being
3205 // initialized.
3206 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3207 UsedFieldIndex.push_back((*I)->getFieldIndex());
3208 }
3209
3210 for (auto UsedIter = UsedFieldIndex.begin(),
3211 UsedEnd = UsedFieldIndex.end(),
3212 OrigIter = InitFieldIndex.begin(),
3213 OrigEnd = InitFieldIndex.end();
3214 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3215 if (*UsedIter < *OrigIter)
3216 return true;
3217 if (*UsedIter > *OrigIter)
3218 break;
3219 }
3220
3221 return false;
3222 }
3223
3224 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3225 bool AddressOf) {
3226 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3227 return;
3228
3229 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3230 // or union.
3231 MemberExpr *FieldME = ME;
3232
3233 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3234
3235 Expr *Base = ME;
3236 while (MemberExpr *SubME =
3237 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3238
3239 if (isa<VarDecl>(SubME->getMemberDecl()))
3240 return;
3241
3242 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3243 if (!FD->isAnonymousStructOrUnion())
3244 FieldME = SubME;
3245
3246 if (!FieldME->getType().isPODType(S.Context))
3247 AllPODFields = false;
3248
3249 Base = SubME->getBase();
3250 }
3251
3252 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3253 return;
3254
3255 if (AddressOf && AllPODFields)
3256 return;
3257
3258 ValueDecl* FoundVD = FieldME->getMemberDecl();
3259
3260 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3261 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3262 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3263 }
3264
3265 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3266 QualType T = BaseCast->getType();
3267 if (T->isPointerType() &&
3268 BaseClasses.count(T->getPointeeType())) {
3269 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3270 << T->getPointeeType() << FoundVD;
3271 }
3272 }
3273 }
3274
3275 if (!Decls.count(FoundVD))
3276 return;
3277
3278 const bool IsReference = FoundVD->getType()->isReferenceType();
3279
3280 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3281 // Special checking for initializer lists.
3282 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3283 return;
3284 }
3285 } else {
3286 // Prevent double warnings on use of unbounded references.
3287 if (CheckReferenceOnly && !IsReference)
3288 return;
3289 }
3290
3291 unsigned diag = IsReference
3292 ? diag::warn_reference_field_is_uninit
3293 : diag::warn_field_is_uninit;
3294 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3295 if (Constructor)
3296 S.Diag(Constructor->getLocation(),
3297 diag::note_uninit_in_this_constructor)
3298 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3299
3300 }
3301
3302 void HandleValue(Expr *E, bool AddressOf) {
3303 E = E->IgnoreParens();
3304
3305 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3306 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3307 AddressOf /*AddressOf*/);
3308 return;
3309 }
3310
3311 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3312 Visit(CO->getCond());
3313 HandleValue(CO->getTrueExpr(), AddressOf);
3314 HandleValue(CO->getFalseExpr(), AddressOf);
3315 return;
3316 }
3317
3318 if (BinaryConditionalOperator *BCO =
3319 dyn_cast<BinaryConditionalOperator>(E)) {
3320 Visit(BCO->getCond());
3321 HandleValue(BCO->getFalseExpr(), AddressOf);
3322 return;
3323 }
3324
3325 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3326 HandleValue(OVE->getSourceExpr(), AddressOf);
3327 return;
3328 }
3329
3330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3331 switch (BO->getOpcode()) {
3332 default:
3333 break;
3334 case(BO_PtrMemD):
3335 case(BO_PtrMemI):
3336 HandleValue(BO->getLHS(), AddressOf);
3337 Visit(BO->getRHS());
3338 return;
3339 case(BO_Comma):
3340 Visit(BO->getLHS());
3341 HandleValue(BO->getRHS(), AddressOf);
3342 return;
3343 }
3344 }
3345
3346 Visit(E);
3347 }
3348
3349 void CheckInitListExpr(InitListExpr *ILE) {
3350 InitFieldIndex.push_back(0);
3351 for (auto Child : ILE->children()) {
3352 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3353 CheckInitListExpr(SubList);
3354 } else {
3355 Visit(Child);
3356 }
3357 ++InitFieldIndex.back();
3358 }
3359 InitFieldIndex.pop_back();
3360 }
3361
3362 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3363 FieldDecl *Field, const Type *BaseClass) {
3364 // Remove Decls that may have been initialized in the previous
3365 // initializer.
3366 for (ValueDecl* VD : DeclsToRemove)
3367 Decls.erase(VD);
3368 DeclsToRemove.clear();
3369
3370 Constructor = FieldConstructor;
3371 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3372
3373 if (ILE && Field) {
3374 InitList = true;
3375 InitListFieldDecl = Field;
3376 InitFieldIndex.clear();
3377 CheckInitListExpr(ILE);
3378 } else {
3379 InitList = false;
3380 Visit(E);
3381 }
3382
3383 if (Field)
3384 Decls.erase(Field);
3385 if (BaseClass)
3386 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3387 }
3388
3389 void VisitMemberExpr(MemberExpr *ME) {
3390 // All uses of unbounded reference fields will warn.
3391 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3392 }
3393
3394 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3395 if (E->getCastKind() == CK_LValueToRValue) {
3396 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3397 return;
3398 }
3399
3400 Inherited::VisitImplicitCastExpr(E);
3401 }
3402
3403 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3404 if (E->getConstructor()->isCopyConstructor()) {
3405 Expr *ArgExpr = E->getArg(0);
3406 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3407 if (ILE->getNumInits() == 1)
3408 ArgExpr = ILE->getInit(0);
3409 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3410 if (ICE->getCastKind() == CK_NoOp)
3411 ArgExpr = ICE->getSubExpr();
3412 HandleValue(ArgExpr, false /*AddressOf*/);
3413 return;
3414 }
3415 Inherited::VisitCXXConstructExpr(E);
3416 }
3417
3418 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3419 Expr *Callee = E->getCallee();
3420 if (isa<MemberExpr>(Callee)) {
3421 HandleValue(Callee, false /*AddressOf*/);
3422 for (auto Arg : E->arguments())
3423 Visit(Arg);
3424 return;
3425 }
3426
3427 Inherited::VisitCXXMemberCallExpr(E);
3428 }
3429
3430 void VisitCallExpr(CallExpr *E) {
3431 // Treat std::move as a use.
3432 if (E->isCallToStdMove()) {
3433 HandleValue(E->getArg(0), /*AddressOf=*/false);
3434 return;
3435 }
3436
3437 Inherited::VisitCallExpr(E);
3438 }
3439
3440 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3441 Expr *Callee = E->getCallee();
3442
3443 if (isa<UnresolvedLookupExpr>(Callee))
3444 return Inherited::VisitCXXOperatorCallExpr(E);
3445
3446 Visit(Callee);
3447 for (auto Arg : E->arguments())
3448 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3449 }
3450
3451 void VisitBinaryOperator(BinaryOperator *E) {
3452 // If a field assignment is detected, remove the field from the
3453 // uninitiailized field set.
3454 if (E->getOpcode() == BO_Assign)
3455 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3456 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3457 if (!FD->getType()->isReferenceType())
3458 DeclsToRemove.push_back(FD);
3459
3460 if (E->isCompoundAssignmentOp()) {
3461 HandleValue(E->getLHS(), false /*AddressOf*/);
3462 Visit(E->getRHS());
3463 return;
3464 }
3465
3466 Inherited::VisitBinaryOperator(E);
3467 }
3468
3469 void VisitUnaryOperator(UnaryOperator *E) {
3470 if (E->isIncrementDecrementOp()) {
3471 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3472 return;
3473 }
3474 if (E->getOpcode() == UO_AddrOf) {
3475 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3476 HandleValue(ME->getBase(), true /*AddressOf*/);
3477 return;
3478 }
3479 }
3480
3481 Inherited::VisitUnaryOperator(E);
3482 }
3483 };
3484
3485 // Diagnose value-uses of fields to initialize themselves, e.g.
3486 // foo(foo)
3487 // where foo is not also a parameter to the constructor.
3488 // Also diagnose across field uninitialized use such as
3489 // x(y), y(x)
3490 // TODO: implement -Wuninitialized and fold this into that framework.
3491 static void DiagnoseUninitializedFields(
3492 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3493
3494 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3495 Constructor->getLocation())) {
3496 return;
3497 }
3498
3499 if (Constructor->isInvalidDecl())
3500 return;
3501
3502 const CXXRecordDecl *RD = Constructor->getParent();
3503
3504 if (RD->getDescribedClassTemplate())
3505 return;
3506
3507 // Holds fields that are uninitialized.
3508 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3509
3510 // At the beginning, all fields are uninitialized.
3511 for (auto *I : RD->decls()) {
3512 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3513 UninitializedFields.insert(FD);
3514 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3515 UninitializedFields.insert(IFD->getAnonField());
3516 }
3517 }
3518
3519 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3520 for (auto I : RD->bases())
3521 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3522
3523 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3524 return;
3525
3526 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3527 UninitializedFields,
3528 UninitializedBaseClasses);
3529
3530 for (const auto *FieldInit : Constructor->inits()) {
3531 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3532 break;
3533
3534 Expr *InitExpr = FieldInit->getInit();
3535 if (!InitExpr)
3536 continue;
3537
3538 if (CXXDefaultInitExpr *Default =
3539 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3540 InitExpr = Default->getExpr();
3541 if (!InitExpr)
3542 continue;
3543 // In class initializers will point to the constructor.
3544 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3545 FieldInit->getAnyMember(),
3546 FieldInit->getBaseClass());
3547 } else {
3548 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3549 FieldInit->getAnyMember(),
3550 FieldInit->getBaseClass());
3551 }
3552 }
3553 }
3554} // namespace
3555
3556/// \brief Enter a new C++ default initializer scope. After calling this, the
3557/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3558/// parsing or instantiating the initializer failed.
3559void Sema::ActOnStartCXXInClassMemberInitializer() {
3560 // Create a synthetic function scope to represent the call to the constructor
3561 // that notionally surrounds a use of this initializer.
3562 PushFunctionScope();
3563}
3564
3565/// \brief This is invoked after parsing an in-class initializer for a
3566/// non-static C++ class member, and after instantiating an in-class initializer
3567/// in a class template. Such actions are deferred until the class is complete.
3568void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3569 SourceLocation InitLoc,
3570 Expr *InitExpr) {
3571 // Pop the notional constructor scope we created earlier.
3572 PopFunctionScopeInfo(nullptr, D);
3573
3574 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3575 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(static_cast <bool> ((isa<MSPropertyDecl>(D) || FD
->getInClassInitStyle() != ICIS_NoInit) && "must set init style when field is created"
) ? void (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3576, __extension__ __PRETTY_FUNCTION__))
3576 "must set init style when field is created")(static_cast <bool> ((isa<MSPropertyDecl>(D) || FD
->getInClassInitStyle() != ICIS_NoInit) && "must set init style when field is created"
) ? void (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3576, __extension__ __PRETTY_FUNCTION__))
;
3577
3578 if (!InitExpr) {
3579 D->setInvalidDecl();
3580 if (FD)
3581 FD->removeInClassInitializer();
3582 return;
3583 }
3584
3585 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3586 FD->setInvalidDecl();
3587 FD->removeInClassInitializer();
3588 return;
3589 }
3590
3591 ExprResult Init = InitExpr;
3592 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3593 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3594 InitializationKind Kind =
3595 FD->getInClassInitStyle() == ICIS_ListInit
3596 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(),
3597 InitExpr->getLocStart(),
3598 InitExpr->getLocEnd())
3599 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3600 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3601 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3602 if (Init.isInvalid()) {
3603 FD->setInvalidDecl();
3604 return;
3605 }
3606 }
3607
3608 // C++11 [class.base.init]p7:
3609 // The initialization of each base and member constitutes a
3610 // full-expression.
3611 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3612 if (Init.isInvalid()) {
3613 FD->setInvalidDecl();
3614 return;
3615 }
3616
3617 InitExpr = Init.get();
3618
3619 FD->setInClassInitializer(InitExpr);
3620}
3621
3622/// \brief Find the direct and/or virtual base specifiers that
3623/// correspond to the given base type, for use in base initialization
3624/// within a constructor.
3625static bool FindBaseInitializer(Sema &SemaRef,
3626 CXXRecordDecl *ClassDecl,
3627 QualType BaseType,
3628 const CXXBaseSpecifier *&DirectBaseSpec,
3629 const CXXBaseSpecifier *&VirtualBaseSpec) {
3630 // First, check for a direct base class.
3631 DirectBaseSpec = nullptr;
3632 for (const auto &Base : ClassDecl->bases()) {
3633 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3634 // We found a direct base of this type. That's what we're
3635 // initializing.
3636 DirectBaseSpec = &Base;
3637 break;
3638 }
3639 }
3640
3641 // Check for a virtual base class.
3642 // FIXME: We might be able to short-circuit this if we know in advance that
3643 // there are no virtual bases.
3644 VirtualBaseSpec = nullptr;
3645 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3646 // We haven't found a base yet; search the class hierarchy for a
3647 // virtual base class.
3648 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3649 /*DetectVirtual=*/false);
3650 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3651 SemaRef.Context.getTypeDeclType(ClassDecl),
3652 BaseType, Paths)) {
3653 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3654 Path != Paths.end(); ++Path) {
3655 if (Path->back().Base->isVirtual()) {
3656 VirtualBaseSpec = Path->back().Base;
3657 break;
3658 }
3659 }
3660 }
3661 }
3662
3663 return DirectBaseSpec || VirtualBaseSpec;
3664}
3665
3666/// \brief Handle a C++ member initializer using braced-init-list syntax.
3667MemInitResult
3668Sema::ActOnMemInitializer(Decl *ConstructorD,
3669 Scope *S,
3670 CXXScopeSpec &SS,
3671 IdentifierInfo *MemberOrBase,
3672 ParsedType TemplateTypeTy,
3673 const DeclSpec &DS,
3674 SourceLocation IdLoc,
3675 Expr *InitList,
3676 SourceLocation EllipsisLoc) {
3677 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3678 DS, IdLoc, InitList,
3679 EllipsisLoc);
3680}
3681
3682/// \brief Handle a C++ member initializer using parentheses syntax.
3683MemInitResult
3684Sema::ActOnMemInitializer(Decl *ConstructorD,
3685 Scope *S,
3686 CXXScopeSpec &SS,
3687 IdentifierInfo *MemberOrBase,
3688 ParsedType TemplateTypeTy,
3689 const DeclSpec &DS,
3690 SourceLocation IdLoc,
3691 SourceLocation LParenLoc,
3692 ArrayRef<Expr *> Args,
3693 SourceLocation RParenLoc,
3694 SourceLocation EllipsisLoc) {
3695 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3696 Args, RParenLoc);
3697 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3698 DS, IdLoc, List, EllipsisLoc);
3699}
3700
3701namespace {
3702
3703// Callback to only accept typo corrections that can be a valid C++ member
3704// intializer: either a non-static field member or a base class.
3705class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3706public:
3707 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3708 : ClassDecl(ClassDecl) {}
3709
3710 bool ValidateCandidate(const TypoCorrection &candidate) override {
3711 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3712 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3713 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3714 return isa<TypeDecl>(ND);
3715 }
3716 return false;
3717 }
3718
3719private:
3720 CXXRecordDecl *ClassDecl;
3721};
3722
3723}
3724
3725/// \brief Handle a C++ member initializer.
3726MemInitResult
3727Sema::BuildMemInitializer(Decl *ConstructorD,
3728 Scope *S,
3729 CXXScopeSpec &SS,
3730 IdentifierInfo *MemberOrBase,
3731 ParsedType TemplateTypeTy,
3732 const DeclSpec &DS,
3733 SourceLocation IdLoc,
3734 Expr *Init,
3735 SourceLocation EllipsisLoc) {
3736 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3737 if (!Res.isUsable())
3738 return true;
3739 Init = Res.get();
3740
3741 if (!ConstructorD)
3742 return true;
3743
3744 AdjustDeclIfTemplate(ConstructorD);
3745
3746 CXXConstructorDecl *Constructor
3747 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3748 if (!Constructor) {
3749 // The user wrote a constructor initializer on a function that is
3750 // not a C++ constructor. Ignore the error for now, because we may
3751 // have more member initializers coming; we'll diagnose it just
3752 // once in ActOnMemInitializers.
3753 return true;
3754 }
3755
3756 CXXRecordDecl *ClassDecl = Constructor->getParent();
3757
3758 // C++ [class.base.init]p2:
3759 // Names in a mem-initializer-id are looked up in the scope of the
3760 // constructor's class and, if not found in that scope, are looked
3761 // up in the scope containing the constructor's definition.
3762 // [Note: if the constructor's class contains a member with the
3763 // same name as a direct or virtual base class of the class, a
3764 // mem-initializer-id naming the member or base class and composed
3765 // of a single identifier refers to the class member. A
3766 // mem-initializer-id for the hidden base class may be specified
3767 // using a qualified name. ]
3768 if (!SS.getScopeRep() && !TemplateTypeTy) {
3769 // Look for a member, first.
3770 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3771 if (!Result.empty()) {
3772 ValueDecl *Member;
3773 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3774 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3775 if (EllipsisLoc.isValid())
3776 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3777 << MemberOrBase
3778 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3779
3780 return BuildMemberInitializer(Member, Init, IdLoc);
3781 }
3782 }
3783 }
3784 // It didn't name a member, so see if it names a class.
3785 QualType BaseType;
3786 TypeSourceInfo *TInfo = nullptr;
3787
3788 if (TemplateTypeTy) {
3789 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3790 } else if (DS.getTypeSpecType() == TST_decltype) {
3791 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3792 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3793 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3794 return true;
3795 } else {
3796 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3797 LookupParsedName(R, S, &SS);
3798
3799 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3800 if (!TyD) {
3801 if (R.isAmbiguous()) return true;
3802
3803 // We don't want access-control diagnostics here.
3804 R.suppressDiagnostics();
3805
3806 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3807 bool NotUnknownSpecialization = false;
3808 DeclContext *DC = computeDeclContext(SS, false);
3809 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3810 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3811
3812 if (!NotUnknownSpecialization) {
3813 // When the scope specifier can refer to a member of an unknown
3814 // specialization, we take it as a type name.
3815 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3816 SS.getWithLocInContext(Context),
3817 *MemberOrBase, IdLoc);
3818 if (BaseType.isNull())
3819 return true;
3820
3821 TInfo = Context.CreateTypeSourceInfo(BaseType);
3822 DependentNameTypeLoc TL =
3823 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3824 if (!TL.isNull()) {
3825 TL.setNameLoc(IdLoc);
3826 TL.setElaboratedKeywordLoc(SourceLocation());
3827 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3828 }
3829
3830 R.clear();
3831 R.setLookupName(MemberOrBase);
3832 }
3833 }
3834
3835 // If no results were found, try to correct typos.
3836 TypoCorrection Corr;
3837 if (R.empty() && BaseType.isNull() &&
3838 (Corr = CorrectTypo(
3839 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3840 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3841 CTK_ErrorRecovery, ClassDecl))) {
3842 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3843 // We have found a non-static data member with a similar
3844 // name to what was typed; complain and initialize that
3845 // member.
3846 diagnoseTypo(Corr,
3847 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3848 << MemberOrBase << true);
3849 return BuildMemberInitializer(Member, Init, IdLoc);
3850 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3851 const CXXBaseSpecifier *DirectBaseSpec;
3852 const CXXBaseSpecifier *VirtualBaseSpec;
3853 if (FindBaseInitializer(*this, ClassDecl,
3854 Context.getTypeDeclType(Type),
3855 DirectBaseSpec, VirtualBaseSpec)) {
3856 // We have found a direct or virtual base class with a
3857 // similar name to what was typed; complain and initialize
3858 // that base class.
3859 diagnoseTypo(Corr,
3860 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3861 << MemberOrBase << false,
3862 PDiag() /*Suppress note, we provide our own.*/);
3863
3864 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3865 : VirtualBaseSpec;
3866 Diag(BaseSpec->getLocStart(),
3867 diag::note_base_class_specified_here)
3868 << BaseSpec->getType()
3869 << BaseSpec->getSourceRange();
3870
3871 TyD = Type;
3872 }
3873 }
3874 }
3875
3876 if (!TyD && BaseType.isNull()) {
3877 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3878 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3879 return true;
3880 }
3881 }
3882
3883 if (BaseType.isNull()) {
3884 BaseType = Context.getTypeDeclType(TyD);
3885 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3886 if (SS.isSet()) {
3887 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3888 BaseType);
3889 TInfo = Context.CreateTypeSourceInfo(BaseType);
3890 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3891 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3892 TL.setElaboratedKeywordLoc(SourceLocation());
3893 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3894 }
3895 }
3896 }
3897
3898 if (!TInfo)
3899 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3900
3901 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3902}
3903
3904/// Checks a member initializer expression for cases where reference (or
3905/// pointer) members are bound to by-value parameters (or their addresses).
3906static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3907 Expr *Init,
3908 SourceLocation IdLoc) {
3909 QualType MemberTy = Member->getType();
3910
3911 // We only handle pointers and references currently.
3912 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3913 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3914 return;
3915
3916 const bool IsPointer = MemberTy->isPointerType();
3917 if (IsPointer) {
3918 if (const UnaryOperator *Op
3919 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3920 // The only case we're worried about with pointers requires taking the
3921 // address.
3922 if (Op->getOpcode() != UO_AddrOf)
3923 return;
3924
3925 Init = Op->getSubExpr();
3926 } else {
3927 // We only handle address-of expression initializers for pointers.
3928 return;
3929 }
3930 }
3931
3932 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3933 // We only warn when referring to a non-reference parameter declaration.
3934 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3935 if (!Parameter || Parameter->getType()->isReferenceType())
3936 return;
3937
3938 S.Diag(Init->getExprLoc(),
3939 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3940 : diag::warn_bind_ref_member_to_parameter)
3941 << Member << Parameter << Init->getSourceRange();
3942 } else {
3943 // Other initializers are fine.
3944 return;
3945 }
3946
3947 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3948 << (unsigned)IsPointer;
3949}
3950
3951MemInitResult
3952Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3953 SourceLocation IdLoc) {
3954 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3955 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3956 assert((DirectMember || IndirectMember) &&(static_cast <bool> ((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl") ? void (0
) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3957, __extension__ __PRETTY_FUNCTION__))
3957 "Member must be a FieldDecl or IndirectFieldDecl")(static_cast <bool> ((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl") ? void (0
) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3957, __extension__ __PRETTY_FUNCTION__))
;
3958
3959 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3960 return true;
3961
3962 if (Member->isInvalidDecl())
3963 return true;
3964
3965 MultiExprArg Args;
3966 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3967 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3968 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3969 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3970 } else {
3971 // Template instantiation doesn't reconstruct ParenListExprs for us.
3972 Args = Init;
3973 }
3974
3975 SourceRange InitRange = Init->getSourceRange();
3976
3977 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3978 // Can't check initialization for a member of dependent type or when
3979 // any of the arguments are type-dependent expressions.
3980 DiscardCleanupsInEvaluationContext();
3981 } else {
3982 bool InitList = false;
3983 if (isa<InitListExpr>(Init)) {
3984 InitList = true;
3985 Args = Init;
3986 }
3987
3988 // Initialize the member.
3989 InitializedEntity MemberEntity =
3990 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3991 : InitializedEntity::InitializeMember(IndirectMember,
3992 nullptr);
3993 InitializationKind Kind =
3994 InitList ? InitializationKind::CreateDirectList(
3995 IdLoc, Init->getLocStart(), Init->getLocEnd())
3996 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3997 InitRange.getEnd());
3998
3999 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4000 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4001 nullptr);
4002 if (MemberInit.isInvalid())
4003 return true;
4004
4005 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
4006
4007 // C++11 [class.base.init]p7:
4008 // The initialization of each base and member constitutes a
4009 // full-expression.
4010 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
4011 if (MemberInit.isInvalid())
4012 return true;
4013
4014 Init = MemberInit.get();
4015 }
4016
4017 if (DirectMember) {
4018 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4019 InitRange.getBegin(), Init,
4020 InitRange.getEnd());
4021 } else {
4022 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4023 InitRange.getBegin(), Init,
4024 InitRange.getEnd());
4025 }
4026}
4027
4028MemInitResult
4029Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4030 CXXRecordDecl *ClassDecl) {
4031 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4032 if (!LangOpts.CPlusPlus11)
4033 return Diag(NameLoc, diag::err_delegating_ctor)
4034 << TInfo->getTypeLoc().getLocalSourceRange();
4035 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4036
4037 bool InitList = true;
4038 MultiExprArg Args = Init;
4039 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4040 InitList = false;
4041 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4042 }
4043
4044 SourceRange InitRange = Init->getSourceRange();
4045 // Initialize the object.
4046 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4047 QualType(ClassDecl->getTypeForDecl(), 0));
4048 InitializationKind Kind =
4049 InitList ? InitializationKind::CreateDirectList(
4050 NameLoc, Init->getLocStart(), Init->getLocEnd())
4051 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4052 InitRange.getEnd());
4053 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4054 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4055 Args, nullptr);
4056 if (DelegationInit.isInvalid())
4057 return true;
4058
4059 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&(static_cast <bool> (cast<CXXConstructExpr>(DelegationInit
.get())->getConstructor() && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4060, __extension__ __PRETTY_FUNCTION__))
4060 "Delegating constructor with no target?")(static_cast <bool> (cast<CXXConstructExpr>(DelegationInit
.get())->getConstructor() && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4060, __extension__ __PRETTY_FUNCTION__))
;
4061
4062 // C++11 [class.base.init]p7:
4063 // The initialization of each base and member constitutes a
4064 // full-expression.
4065 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4066 InitRange.getBegin());
4067 if (DelegationInit.isInvalid())
4068 return true;
4069
4070 // If we are in a dependent context, template instantiation will
4071 // perform this type-checking again. Just save the arguments that we
4072 // received in a ParenListExpr.
4073 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4074 // of the information that we have about the base
4075 // initializer. However, deconstructing the ASTs is a dicey process,
4076 // and this approach is far more likely to get the corner cases right.
4077 if (CurContext->isDependentContext())
4078 DelegationInit = Init;
4079
4080 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4081 DelegationInit.getAs<Expr>(),
4082 InitRange.getEnd());
4083}
4084
4085MemInitResult
4086Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4087 Expr *Init, CXXRecordDecl *ClassDecl,
4088 SourceLocation EllipsisLoc) {
4089 SourceLocation BaseLoc
4090 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4091
4092 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4093 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4094 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4095
4096 // C++ [class.base.init]p2:
4097 // [...] Unless the mem-initializer-id names a nonstatic data
4098 // member of the constructor's class or a direct or virtual base
4099 // of that class, the mem-initializer is ill-formed. A
4100 // mem-initializer-list can initialize a base class using any
4101 // name that denotes that base class type.
4102 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4103
4104 SourceRange InitRange = Init->getSourceRange();
4105 if (EllipsisLoc.isValid()) {
4106 // This is a pack expansion.
4107 if (!BaseType->containsUnexpandedParameterPack()) {
4108 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4109 << SourceRange(BaseLoc, InitRange.getEnd());
4110
4111 EllipsisLoc = SourceLocation();
4112 }
4113 } else {
4114 // Check for any unexpanded parameter packs.
4115 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4116 return true;
4117
4118 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4119 return true;
4120 }
4121
4122 // Check for direct and virtual base classes.
4123 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4124 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4125 if (!Dependent) {
4126 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4127 BaseType))
4128 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4129
4130 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4131 VirtualBaseSpec);
4132
4133 // C++ [base.class.init]p2:
4134 // Unless the mem-initializer-id names a nonstatic data member of the
4135 // constructor's class or a direct or virtual base of that class, the
4136 // mem-initializer is ill-formed.
4137 if (!DirectBaseSpec && !VirtualBaseSpec) {
4138 // If the class has any dependent bases, then it's possible that
4139 // one of those types will resolve to the same type as
4140 // BaseType. Therefore, just treat this as a dependent base
4141 // class initialization. FIXME: Should we try to check the
4142 // initialization anyway? It seems odd.
4143 if (ClassDecl->hasAnyDependentBases())
4144 Dependent = true;
4145 else
4146 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4147 << BaseType << Context.getTypeDeclType(ClassDecl)
4148 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4149 }
4150 }
4151
4152 if (Dependent) {
4153 DiscardCleanupsInEvaluationContext();
4154
4155 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4156 /*IsVirtual=*/false,
4157 InitRange.getBegin(), Init,
4158 InitRange.getEnd(), EllipsisLoc);
4159 }
4160
4161 // C++ [base.class.init]p2:
4162 // If a mem-initializer-id is ambiguous because it designates both
4163 // a direct non-virtual base class and an inherited virtual base
4164 // class, the mem-initializer is ill-formed.
4165 if (DirectBaseSpec && VirtualBaseSpec)
4166 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4167 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4168
4169 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4170 if (!BaseSpec)
4171 BaseSpec = VirtualBaseSpec;
4172
4173 // Initialize the base.
4174 bool InitList = true;
4175 MultiExprArg Args = Init;
4176 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4177 InitList = false;
4178 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4179 }
4180
4181 InitializedEntity BaseEntity =
4182 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4183 InitializationKind Kind =
4184 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4185 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4186 InitRange.getEnd());
4187 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4188 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4189 if (BaseInit.isInvalid())
4190 return true;
4191
4192 // C++11 [class.base.init]p7:
4193 // The initialization of each base and member constitutes a
4194 // full-expression.
4195 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4196 if (BaseInit.isInvalid())
4197 return true;
4198
4199 // If we are in a dependent context, template instantiation will
4200 // perform this type-checking again. Just save the arguments that we
4201 // received in a ParenListExpr.
4202 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4203 // of the information that we have about the base
4204 // initializer. However, deconstructing the ASTs is a dicey process,
4205 // and this approach is far more likely to get the corner cases right.
4206 if (CurContext->isDependentContext())
4207 BaseInit = Init;
4208
4209 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4210 BaseSpec->isVirtual(),
4211 InitRange.getBegin(),
4212 BaseInit.getAs<Expr>(),
4213 InitRange.getEnd(), EllipsisLoc);
4214}
4215
4216// Create a static_cast\<T&&>(expr).
4217static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4218 if (T.isNull()) T = E->getType();
4219 QualType TargetType = SemaRef.BuildReferenceType(
4220 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4221 SourceLocation ExprLoc = E->getLocStart();
4222 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4223 TargetType, ExprLoc);
4224
4225 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4226 SourceRange(ExprLoc, ExprLoc),
4227 E->getSourceRange()).get();
4228}
4229
4230/// ImplicitInitializerKind - How an implicit base or member initializer should
4231/// initialize its base or member.
4232enum ImplicitInitializerKind {
4233 IIK_Default,
4234 IIK_Copy,
4235 IIK_Move,
4236 IIK_Inherit
4237};
4238
4239static bool
4240BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4241 ImplicitInitializerKind ImplicitInitKind,
4242 CXXBaseSpecifier *BaseSpec,
4243 bool IsInheritedVirtualBase,
4244 CXXCtorInitializer *&CXXBaseInit) {
4245 InitializedEntity InitEntity
4246 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4247 IsInheritedVirtualBase);
4248
4249 ExprResult BaseInit;
4250
4251 switch (ImplicitInitKind) {
4252 case IIK_Inherit:
4253 case IIK_Default: {
4254 InitializationKind InitKind
4255 = InitializationKind::CreateDefault(Constructor->getLocation());
4256 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4257 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4258 break;
4259 }
4260
4261 case IIK_Move:
4262 case IIK_Copy: {
4263 bool Moving = ImplicitInitKind == IIK_Move;
4264 ParmVarDecl *Param = Constructor->getParamDecl(0);
4265 QualType ParamType = Param->getType().getNonReferenceType();
4266
4267 Expr *CopyCtorArg =
4268 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4269 SourceLocation(), Param, false,
4270 Constructor->getLocation(), ParamType,
4271 VK_LValue, nullptr);
4272
4273 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4274
4275 // Cast to the base class to avoid ambiguities.
4276 QualType ArgTy =
4277 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4278 ParamType.getQualifiers());
4279
4280 if (Moving) {
4281 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4282 }
4283
4284 CXXCastPath BasePath;
4285 BasePath.push_back(BaseSpec);
4286 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4287 CK_UncheckedDerivedToBase,
4288 Moving ? VK_XValue : VK_LValue,
4289 &BasePath).get();
4290
4291 InitializationKind InitKind
4292 = InitializationKind::CreateDirect(Constructor->getLocation(),
4293 SourceLocation(), SourceLocation());
4294 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4295 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4296 break;
4297 }
4298 }
4299
4300 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4301 if (BaseInit.isInvalid())
4302 return true;
4303
4304 CXXBaseInit =
4305 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4306 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4307 SourceLocation()),
4308 BaseSpec->isVirtual(),
4309 SourceLocation(),
4310 BaseInit.getAs<Expr>(),
4311 SourceLocation(),
4312 SourceLocation());
4313
4314 return false;
4315}
4316
4317static bool RefersToRValueRef(Expr *MemRef) {
4318 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4319 return Referenced->getType()->isRValueReferenceType();
4320}
4321
4322static bool
4323BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4324 ImplicitInitializerKind ImplicitInitKind,
4325 FieldDecl *Field, IndirectFieldDecl *Indirect,
4326 CXXCtorInitializer *&CXXMemberInit) {
4327 if (Field->isInvalidDecl())
4328 return true;
4329
4330 SourceLocation Loc = Constructor->getLocation();
4331
4332 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4333 bool Moving = ImplicitInitKind == IIK_Move;
4334 ParmVarDecl *Param = Constructor->getParamDecl(0);
4335 QualType ParamType = Param->getType().getNonReferenceType();
4336
4337 // Suppress copying zero-width bitfields.
4338 if (Field->isZeroLengthBitField(SemaRef.Context))
4339 return false;
4340
4341 Expr *MemberExprBase =
4342 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4343 SourceLocation(), Param, false,
4344 Loc, ParamType, VK_LValue, nullptr);
4345
4346 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4347
4348 if (Moving) {
4349 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4350 }
4351
4352 // Build a reference to this field within the parameter.
4353 CXXScopeSpec SS;
4354 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4355 Sema::LookupMemberName);
4356 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4357 : cast<ValueDecl>(Field), AS_public);
4358 MemberLookup.resolveKind();
4359 ExprResult CtorArg
4360 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4361 ParamType, Loc,
4362 /*IsArrow=*/false,
4363 SS,
4364 /*TemplateKWLoc=*/SourceLocation(),
4365 /*FirstQualifierInScope=*/nullptr,
4366 MemberLookup,
4367 /*TemplateArgs=*/nullptr,
4368 /*S*/nullptr);
4369 if (CtorArg.isInvalid())
4370 return true;
4371
4372 // C++11 [class.copy]p15:
4373 // - if a member m has rvalue reference type T&&, it is direct-initialized
4374 // with static_cast<T&&>(x.m);
4375 if (RefersToRValueRef(CtorArg.get())) {
4376 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4377 }
4378
4379 InitializedEntity Entity =
4380 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4381 /*Implicit*/ true)
4382 : InitializedEntity::InitializeMember(Field, nullptr,
4383 /*Implicit*/ true);
4384
4385 // Direct-initialize to use the copy constructor.
4386 InitializationKind InitKind =
4387 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4388
4389 Expr *CtorArgE = CtorArg.getAs<Expr>();
4390 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4391 ExprResult MemberInit =
4392 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4393 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4394 if (MemberInit.isInvalid())
4395 return true;
4396
4397 if (Indirect)
4398 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4399 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4400 else
4401 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4402 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4403 return false;
4404 }
4405
4406 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(static_cast <bool> ((ImplicitInitKind == IIK_Default ||
ImplicitInitKind == IIK_Inherit) && "Unhandled implicit init kind!"
) ? void (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4407, __extension__ __PRETTY_FUNCTION__))
4407 "Unhandled implicit init kind!")(static_cast <bool> ((ImplicitInitKind == IIK_Default ||
ImplicitInitKind == IIK_Inherit) && "Unhandled implicit init kind!"
) ? void (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4407, __extension__ __PRETTY_FUNCTION__))
;
4408
4409 QualType FieldBaseElementType =
4410 SemaRef.Context.getBaseElementType(Field->getType());
4411
4412 if (FieldBaseElementType->isRecordType()) {
4413 InitializedEntity InitEntity =
4414 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4415 /*Implicit*/ true)
4416 : InitializedEntity::InitializeMember(Field, nullptr,
4417 /*Implicit*/ true);
4418 InitializationKind InitKind =
4419 InitializationKind::CreateDefault(Loc);
4420
4421 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4422 ExprResult MemberInit =
4423 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4424
4425 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4426 if (MemberInit.isInvalid())
4427 return true;
4428
4429 if (Indirect)
4430 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4431 Indirect, Loc,
4432 Loc,
4433 MemberInit.get(),
4434 Loc);
4435 else
4436 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4437 Field, Loc, Loc,
4438 MemberInit.get(),
4439 Loc);
4440 return false;
4441 }
4442
4443 if (!Field->getParent()->isUnion()) {
4444 if (FieldBaseElementType->isReferenceType()) {
4445 SemaRef.Diag(Constructor->getLocation(),
4446 diag::err_uninitialized_member_in_ctor)
4447 << (int)Constructor->isImplicit()
4448 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4449 << 0 << Field->getDeclName();
4450 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4451 return true;
4452 }
4453
4454 if (FieldBaseElementType.isConstQualified()) {
4455 SemaRef.Diag(Constructor->getLocation(),
4456 diag::err_uninitialized_member_in_ctor)
4457 << (int)Constructor->isImplicit()
4458 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4459 << 1 << Field->getDeclName();
4460 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4461 return true;
4462 }
4463 }
4464
4465 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4466 // ARC and Weak:
4467 // Default-initialize Objective-C pointers to NULL.
4468 CXXMemberInit
4469 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4470 Loc, Loc,
4471 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4472 Loc);
4473 return false;
4474 }
4475
4476 // Nothing to initialize.
4477 CXXMemberInit = nullptr;
4478 return false;
4479}
4480
4481namespace {
4482struct BaseAndFieldInfo {
4483 Sema &S;
4484 CXXConstructorDecl *Ctor;
4485 bool AnyErrorsInInits;
4486 ImplicitInitializerKind IIK;
4487 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4488 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4489 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4490
4491 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4492 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4493 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4494 if (Ctor->getInheritedConstructor())
4495 IIK = IIK_Inherit;
4496 else if (Generated && Ctor->isCopyConstructor())
4497 IIK = IIK_Copy;
4498 else if (Generated && Ctor->isMoveConstructor())
4499 IIK = IIK_Move;
4500 else
4501 IIK = IIK_Default;
4502 }
4503
4504 bool isImplicitCopyOrMove() const {
4505 switch (IIK) {
4506 case IIK_Copy:
4507 case IIK_Move:
4508 return true;
4509
4510 case IIK_Default:
4511 case IIK_Inherit:
4512 return false;
4513 }
4514
4515 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4515)
;
4516 }
4517
4518 bool addFieldInitializer(CXXCtorInitializer *Init) {
4519 AllToInit.push_back(Init);
4520
4521 // Check whether this initializer makes the field "used".
4522 if (Init->getInit()->HasSideEffects(S.Context))
4523 S.UnusedPrivateFields.remove(Init->getAnyMember());
4524
4525 return false;
4526 }
4527
4528 bool isInactiveUnionMember(FieldDecl *Field) {
4529 RecordDecl *Record = Field->getParent();
4530 if (!Record->isUnion())
4531 return false;
4532
4533 if (FieldDecl *Active =
4534 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4535 return Active != Field->getCanonicalDecl();
4536
4537 // In an implicit copy or move constructor, ignore any in-class initializer.
4538 if (isImplicitCopyOrMove())
4539 return true;
4540
4541 // If there's no explicit initialization, the field is active only if it
4542 // has an in-class initializer...
4543 if (Field->hasInClassInitializer())
4544 return false;
4545 // ... or it's an anonymous struct or union whose class has an in-class
4546 // initializer.
4547 if (!Field->isAnonymousStructOrUnion())
4548 return true;
4549 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4550 return !FieldRD->hasInClassInitializer();
4551 }
4552
4553 /// \brief Determine whether the given field is, or is within, a union member
4554 /// that is inactive (because there was an initializer given for a different
4555 /// member of the union, or because the union was not initialized at all).
4556 bool isWithinInactiveUnionMember(FieldDecl *Field,
4557 IndirectFieldDecl *Indirect) {
4558 if (!Indirect)
4559 return isInactiveUnionMember(Field);
4560
4561 for (auto *C : Indirect->chain()) {
4562 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4563 if (Field && isInactiveUnionMember(Field))
4564 return true;
4565 }
4566 return false;
4567 }
4568};
4569}
4570
4571/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4572/// array type.
4573static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4574 if (T->isIncompleteArrayType())
4575 return true;
4576
4577 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4578 if (!ArrayT->getSize())
4579 return true;
4580
4581 T = ArrayT->getElementType();
4582 }
4583
4584 return false;
4585}
4586
4587static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4588 FieldDecl *Field,
4589 IndirectFieldDecl *Indirect = nullptr) {
4590 if (Field->isInvalidDecl())
4591 return false;
4592
4593 // Overwhelmingly common case: we have a direct initializer for this field.
4594 if (CXXCtorInitializer *Init =
4595 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4596 return Info.addFieldInitializer(Init);
4597
4598 // C++11 [class.base.init]p8:
4599 // if the entity is a non-static data member that has a
4600 // brace-or-equal-initializer and either
4601 // -- the constructor's class is a union and no other variant member of that
4602 // union is designated by a mem-initializer-id or
4603 // -- the constructor's class is not a union, and, if the entity is a member
4604 // of an anonymous union, no other member of that union is designated by
4605 // a mem-initializer-id,
4606 // the entity is initialized as specified in [dcl.init].
4607 //
4608 // We also apply the same rules to handle anonymous structs within anonymous
4609 // unions.
4610 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4611 return false;
4612
4613 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4614 ExprResult DIE =
4615 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4616 if (DIE.isInvalid())
4617 return true;
4618 CXXCtorInitializer *Init;
4619 if (Indirect)
4620 Init = new (SemaRef.Context)
4621 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4622 SourceLocation(), DIE.get(), SourceLocation());
4623 else
4624 Init = new (SemaRef.Context)
4625 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4626 SourceLocation(), DIE.get(), SourceLocation());
4627 return Info.addFieldInitializer(Init);
4628 }
4629
4630 // Don't initialize incomplete or zero-length arrays.
4631 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4632 return false;
4633
4634 // Don't try to build an implicit initializer if there were semantic
4635 // errors in any of the initializers (and therefore we might be
4636 // missing some that the user actually wrote).
4637 if (Info.AnyErrorsInInits)
4638 return false;
4639
4640 CXXCtorInitializer *Init = nullptr;
4641 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4642 Indirect, Init))
4643 return true;
4644
4645 if (!Init)
4646 return false;
4647
4648 return Info.addFieldInitializer(Init);
4649}
4650
4651bool
4652Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4653 CXXCtorInitializer *Initializer) {
4654 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4654, __extension__ __PRETTY_FUNCTION__))
;
4655 Constructor->setNumCtorInitializers(1);
4656 CXXCtorInitializer **initializer =
4657 new (Context) CXXCtorInitializer*[1];
4658 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4659 Constructor->setCtorInitializers(initializer);
4660
4661 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4662 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4663 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4664 }
4665
4666 DelegatingCtorDecls.push_back(Constructor);
4667
4668 DiagnoseUninitializedFields(*this, Constructor);
4669
4670 return false;
4671}
4672
4673bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4674 ArrayRef<CXXCtorInitializer *> Initializers) {
4675 if (Constructor->isDependentContext()) {
4676 // Just store the initializers as written, they will be checked during
4677 // instantiation.
4678 if (!Initializers.empty()) {
4679 Constructor->setNumCtorInitializers(Initializers.size());
4680 CXXCtorInitializer **baseOrMemberInitializers =
4681 new (Context) CXXCtorInitializer*[Initializers.size()];
4682 memcpy(baseOrMemberInitializers, Initializers.data(),
4683 Initializers.size() * sizeof(CXXCtorInitializer*));
4684 Constructor->setCtorInitializers(baseOrMemberInitializers);
4685 }
4686
4687 // Let template instantiation know whether we had errors.
4688 if (AnyErrors)
4689 Constructor->setInvalidDecl();
4690
4691 return false;
4692 }
4693
4694 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4695
4696 // We need to build the initializer AST according to order of construction
4697 // and not what user specified in the Initializers list.
4698 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4699 if (!ClassDecl)
4700 return true;
4701
4702 bool HadError = false;
4703
4704 for (unsigned i = 0; i < Initializers.size(); i++) {
4705 CXXCtorInitializer *Member = Initializers[i];
4706
4707 if (Member->isBaseInitializer())
4708 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4709 else {
4710 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4711
4712 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4713 for (auto *C : F->chain()) {
4714 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4715 if (FD && FD->getParent()->isUnion())
4716 Info.ActiveUnionMember.insert(std::make_pair(
4717 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4718 }
4719 } else if (FieldDecl *FD = Member->getMember()) {
4720 if (FD->getParent()->isUnion())
4721 Info.ActiveUnionMember.insert(std::make_pair(
4722 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4723 }
4724 }
4725 }
4726
4727 // Keep track of the direct virtual bases.
4728 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4729 for (auto &I : ClassDecl->bases()) {
4730 if (I.isVirtual())
4731 DirectVBases.insert(&I);
4732 }
4733
4734 // Push virtual bases before others.
4735 for (auto &VBase : ClassDecl->vbases()) {
4736 if (CXXCtorInitializer *Value
4737 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4738 // [class.base.init]p7, per DR257:
4739 // A mem-initializer where the mem-initializer-id names a virtual base
4740 // class is ignored during execution of a constructor of any class that
4741 // is not the most derived class.
4742 if (ClassDecl->isAbstract()) {
4743 // FIXME: Provide a fixit to remove the base specifier. This requires
4744 // tracking the location of the associated comma for a base specifier.
4745 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4746 << VBase.getType() << ClassDecl;
4747 DiagnoseAbstractType(ClassDecl);
4748 }
4749
4750 Info.AllToInit.push_back(Value);
4751 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4752 // [class.base.init]p8, per DR257:
4753 // If a given [...] base class is not named by a mem-initializer-id
4754 // [...] and the entity is not a virtual base class of an abstract
4755 // class, then [...] the entity is default-initialized.
4756 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4757 CXXCtorInitializer *CXXBaseInit;
4758 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4759 &VBase, IsInheritedVirtualBase,
4760 CXXBaseInit)) {
4761 HadError = true;
4762 continue;
4763 }
4764
4765 Info.AllToInit.push_back(CXXBaseInit);
4766 }
4767 }
4768
4769 // Non-virtual bases.
4770 for (auto &Base : ClassDecl->bases()) {
4771 // Virtuals are in the virtual base list and already constructed.
4772 if (Base.isVirtual())
4773 continue;
4774
4775 if (CXXCtorInitializer *Value
4776 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4777 Info.AllToInit.push_back(Value);
4778 } else if (!AnyErrors) {
4779 CXXCtorInitializer *CXXBaseInit;
4780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4781 &Base, /*IsInheritedVirtualBase=*/false,
4782 CXXBaseInit)) {
4783 HadError = true;
4784 continue;
4785 }
4786
4787 Info.AllToInit.push_back(CXXBaseInit);
4788 }
4789 }
4790
4791 // Fields.
4792 for (auto *Mem : ClassDecl->decls()) {
4793 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4794 // C++ [class.bit]p2:
4795 // A declaration for a bit-field that omits the identifier declares an
4796 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4797 // initialized.
4798 if (F->isUnnamedBitfield())
4799 continue;
4800
4801 // If we're not generating the implicit copy/move constructor, then we'll
4802 // handle anonymous struct/union fields based on their individual
4803 // indirect fields.
4804 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4805 continue;
4806
4807 if (CollectFieldInitializer(*this, Info, F))
4808 HadError = true;
4809 continue;
4810 }
4811
4812 // Beyond this point, we only consider default initialization.
4813 if (Info.isImplicitCopyOrMove())
4814 continue;
4815
4816 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4817 if (F->getType()->isIncompleteArrayType()) {
4818 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4819, __extension__ __PRETTY_FUNCTION__))
4819 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4819, __extension__ __PRETTY_FUNCTION__))
;
4820 continue;
4821 }
4822
4823 // Initialize each field of an anonymous struct individually.
4824 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4825 HadError = true;
4826
4827 continue;
4828 }
4829 }
4830
4831 unsigned NumInitializers = Info.AllToInit.size();
4832 if (NumInitializers > 0) {
4833 Constructor->setNumCtorInitializers(NumInitializers);
4834 CXXCtorInitializer **baseOrMemberInitializers =
4835 new (Context) CXXCtorInitializer*[NumInitializers];
4836 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4837 NumInitializers * sizeof(CXXCtorInitializer*));
4838 Constructor->setCtorInitializers(baseOrMemberInitializers);
4839
4840 // Constructors implicitly reference the base and member
4841 // destructors.
4842 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4843 Constructor->getParent());
4844 }
4845
4846 return HadError;
4847}
4848
4849static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4850 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4851 const RecordDecl *RD = RT->getDecl();
4852 if (RD->isAnonymousStructOrUnion()) {
4853 for (auto *Field : RD->fields())
4854 PopulateKeysForFields(Field, IdealInits);
4855 return;
4856 }
4857 }
4858 IdealInits.push_back(Field->getCanonicalDecl());
4859}
4860
4861static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4862 return Context.getCanonicalType(BaseType).getTypePtr();
4863}
4864
4865static const void *GetKeyForMember(ASTContext &Context,
4866 CXXCtorInitializer *Member) {
4867 if (!Member->isAnyMemberInitializer())
4868 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4869
4870 return Member->getAnyMember()->getCanonicalDecl();
4871}
4872
4873static void DiagnoseBaseOrMemInitializerOrder(
4874 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4875 ArrayRef<CXXCtorInitializer *> Inits) {
4876 if (Constructor->getDeclContext()->isDependentContext())
4877 return;
4878
4879 // Don't check initializers order unless the warning is enabled at the
4880 // location of at least one initializer.
4881 bool ShouldCheckOrder = false;
4882 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4883 CXXCtorInitializer *Init = Inits[InitIndex];
4884 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4885 Init->getSourceLocation())) {
4886 ShouldCheckOrder = true;
4887 break;
4888 }
4889 }
4890 if (!ShouldCheckOrder)
4891 return;
4892
4893 // Build the list of bases and members in the order that they'll
4894 // actually be initialized. The explicit initializers should be in
4895 // this same order but may be missing things.
4896 SmallVector<const void*, 32> IdealInitKeys;
4897
4898 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4899
4900 // 1. Virtual bases.
4901 for (const auto &VBase : ClassDecl->vbases())
4902 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4903
4904 // 2. Non-virtual bases.
4905 for (const auto &Base : ClassDecl->bases()) {
4906 if (Base.isVirtual())
4907 continue;
4908 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4909 }
4910
4911 // 3. Direct fields.
4912 for (auto *Field : ClassDecl->fields()) {
4913 if (Field->isUnnamedBitfield())
4914 continue;
4915
4916 PopulateKeysForFields(Field, IdealInitKeys);
4917 }
4918
4919 unsigned NumIdealInits = IdealInitKeys.size();
4920 unsigned IdealIndex = 0;
4921
4922 CXXCtorInitializer *PrevInit = nullptr;
4923 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4924 CXXCtorInitializer *Init = Inits[InitIndex];
4925 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4926
4927 // Scan forward to try to find this initializer in the idealized
4928 // initializers list.
4929 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4930 if (InitKey == IdealInitKeys[IdealIndex])
4931 break;
4932
4933 // If we didn't find this initializer, it must be because we
4934 // scanned past it on a previous iteration. That can only
4935 // happen if we're out of order; emit a warning.
4936 if (IdealIndex == NumIdealInits && PrevInit) {
4937 Sema::SemaDiagnosticBuilder D =
4938 SemaRef.Diag(PrevInit->getSourceLocation(),
4939 diag::warn_initializer_out_of_order);
4940
4941 if (PrevInit->isAnyMemberInitializer())
4942 D << 0 << PrevInit->getAnyMember()->getDeclName();
4943 else
4944 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4945
4946 if (Init->isAnyMemberInitializer())
4947 D << 0 << Init->getAnyMember()->getDeclName();
4948 else
4949 D << 1 << Init->getTypeSourceInfo()->getType();
4950
4951 // Move back to the initializer's location in the ideal list.
4952 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4953 if (InitKey == IdealInitKeys[IdealIndex])
4954 break;
4955
4956 assert(IdealIndex < NumIdealInits &&(static_cast <bool> (IdealIndex < NumIdealInits &&
"initializer not found in initializer list") ? void (0) : __assert_fail
("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4957, __extension__ __PRETTY_FUNCTION__))
4957 "initializer not found in initializer list")(static_cast <bool> (IdealIndex < NumIdealInits &&
"initializer not found in initializer list") ? void (0) : __assert_fail
("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4957, __extension__ __PRETTY_FUNCTION__))
;
4958 }
4959
4960 PrevInit = Init;
4961 }
4962}
4963
4964namespace {
4965bool CheckRedundantInit(Sema &S,
4966 CXXCtorInitializer *Init,
4967 CXXCtorInitializer *&PrevInit) {
4968 if (!PrevInit) {
4969 PrevInit = Init;
4970 return false;
4971 }
4972
4973 if (FieldDecl *Field = Init->getAnyMember())
4974 S.Diag(Init->getSourceLocation(),
4975 diag::err_multiple_mem_initialization)
4976 << Field->getDeclName()
4977 << Init->getSourceRange();
4978 else {
4979 const Type *BaseClass = Init->getBaseClass();
4980 assert(BaseClass && "neither field nor base")(static_cast <bool> (BaseClass && "neither field nor base"
) ? void (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4980, __extension__ __PRETTY_FUNCTION__))
;
4981 S.Diag(Init->getSourceLocation(),
4982 diag::err_multiple_base_initialization)
4983 << QualType(BaseClass, 0)
4984 << Init->getSourceRange();
4985 }
4986 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4987 << 0 << PrevInit->getSourceRange();
4988
4989 return true;
4990}
4991
4992typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4993typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4994
4995bool CheckRedundantUnionInit(Sema &S,
4996 CXXCtorInitializer *Init,
4997 RedundantUnionMap &Unions) {
4998 FieldDecl *Field = Init->getAnyMember();
4999 RecordDecl *Parent = Field->getParent();
5000 NamedDecl *Child = Field;
5001
5002 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5003 if (Parent->isUnion()) {
5004 UnionEntry &En = Unions[Parent];
5005 if (En.first && En.first != Child) {
5006 S.Diag(Init->getSourceLocation(),
5007 diag::err_multiple_mem_union_initialization)
5008 << Field->getDeclName()
5009 << Init->getSourceRange();
5010 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5011 << 0 << En.second->getSourceRange();
5012 return true;
5013 }
5014 if (!En.first) {
5015 En.first = Child;
5016 En.second = Init;
5017 }
5018 if (!Parent->isAnonymousStructOrUnion())
5019 return false;
5020 }
5021
5022 Child = Parent;
5023 Parent = cast<RecordDecl>(Parent->getDeclContext());
5024 }
5025
5026 return false;
5027}
5028}
5029
5030/// ActOnMemInitializers - Handle the member initializers for a constructor.
5031void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5032 SourceLocation ColonLoc,
5033 ArrayRef<CXXCtorInitializer*> MemInits,
5034 bool AnyErrors) {
5035 if (!ConstructorDecl)
5036 return;
5037
5038 AdjustDeclIfTemplate(ConstructorDecl);
5039
5040 CXXConstructorDecl *Constructor
5041 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5042
5043 if (!Constructor) {
5044 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5045 return;
5046 }
5047
5048 // Mapping for the duplicate initializers check.
5049 // For member initializers, this is keyed with a FieldDecl*.
5050 // For base initializers, this is keyed with a Type*.
5051 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5052
5053 // Mapping for the inconsistent anonymous-union initializers check.
5054 RedundantUnionMap MemberUnions;
5055
5056 bool HadError = false;
5057 for (unsigned i = 0; i < MemInits.size(); i++) {
5058 CXXCtorInitializer *Init = MemInits[i];
5059
5060 // Set the source order index.
5061 Init->setSourceOrder(i);
5062
5063 if (Init->isAnyMemberInitializer()) {
5064 const void *Key = GetKeyForMember(Context, Init);
5065 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5066 CheckRedundantUnionInit(*this, Init, MemberUnions))
5067 HadError = true;
5068 } else if (Init->isBaseInitializer()) {
5069 const void *Key = GetKeyForMember(Context, Init);
5070 if (CheckRedundantInit(*this, Init, Members[Key]))
5071 HadError = true;
5072 } else {
5073 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5073, __extension__ __PRETTY_FUNCTION__))
;
5074 // This must be the only initializer
5075 if (MemInits.size() != 1) {
5076 Diag(Init->getSourceLocation(),
5077 diag::err_delegating_initializer_alone)
5078 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5079 // We will treat this as being the only initializer.
5080 }
5081 SetDelegatingInitializer(Constructor, MemInits[i]);
5082 // Return immediately as the initializer is set.
5083 return;
5084 }
5085 }
5086
5087 if (HadError)
5088 return;
5089
5090 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5091
5092 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5093
5094 DiagnoseUninitializedFields(*this, Constructor);
5095}
5096
5097void
5098Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5099 CXXRecordDecl *ClassDecl) {
5100 // Ignore dependent contexts. Also ignore unions, since their members never
5101 // have destructors implicitly called.
5102 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5103 return;
5104
5105 // FIXME: all the access-control diagnostics are positioned on the
5106 // field/base declaration. That's probably good; that said, the
5107 // user might reasonably want to know why the destructor is being
5108 // emitted, and we currently don't say.
5109
5110 // Non-static data members.
5111 for (auto *Field : ClassDecl->fields()) {
5112 if (Field->isInvalidDecl())
5113 continue;
5114
5115 // Don't destroy incomplete or zero-length arrays.
5116 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5117 continue;
5118
5119 QualType FieldType = Context.getBaseElementType(Field->getType());
5120
5121 const RecordType* RT = FieldType->getAs<RecordType>();
5122 if (!RT)
5123 continue;
5124
5125 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5126 if (FieldClassDecl->isInvalidDecl())
5127 continue;
5128 if (FieldClassDecl->hasIrrelevantDestructor())
5129 continue;
5130 // The destructor for an implicit anonymous union member is never invoked.
5131 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5132 continue;
5133
5134 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5135 assert(Dtor && "No dtor found for FieldClassDecl!")(static_cast <bool> (Dtor && "No dtor found for FieldClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5135, __extension__ __PRETTY_FUNCTION__))
;
5136 CheckDestructorAccess(Field->getLocation(), Dtor,
5137 PDiag(diag::err_access_dtor_field)
5138 << Field->getDeclName()
5139 << FieldType);
5140
5141 MarkFunctionReferenced(Location, Dtor);
5142 DiagnoseUseOfDecl(Dtor, Location);
5143 }
5144
5145 // We only potentially invoke the destructors of potentially constructed
5146 // subobjects.
5147 bool VisitVirtualBases = !ClassDecl->isAbstract();
5148
5149 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5150
5151 // Bases.
5152 for (const auto &Base : ClassDecl->bases()) {
5153 // Bases are always records in a well-formed non-dependent class.
5154 const RecordType *RT = Base.getType()->getAs<RecordType>();
5155
5156 // Remember direct virtual bases.
5157 if (Base.isVirtual()) {
5158 if (!VisitVirtualBases)
5159 continue;
5160 DirectVirtualBases.insert(RT);
5161 }
5162
5163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5164 // If our base class is invalid, we probably can't get its dtor anyway.
5165 if (BaseClassDecl->isInvalidDecl())
5166 continue;
5167 if (BaseClassDecl->hasIrrelevantDestructor())
5168 continue;
5169
5170 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5171 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5171, __extension__ __PRETTY_FUNCTION__))
;
5172
5173 // FIXME: caret should be on the start of the class name
5174 CheckDestructorAccess(Base.getLocStart(), Dtor,
5175 PDiag(diag::err_access_dtor_base)
5176 << Base.getType()
5177 << Base.getSourceRange(),
5178 Context.getTypeDeclType(ClassDecl));
5179
5180 MarkFunctionReferenced(Location, Dtor);
5181 DiagnoseUseOfDecl(Dtor, Location);
5182 }
5183
5184 if (!VisitVirtualBases)
5185 return;
5186
5187 // Virtual bases.
5188 for (const auto &VBase : ClassDecl->vbases()) {
5189 // Bases are always records in a well-formed non-dependent class.
5190 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5191
5192 // Ignore direct virtual bases.
5193 if (DirectVirtualBases.count(RT))
5194 continue;
5195
5196 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5197 // If our base class is invalid, we probably can't get its dtor anyway.
5198 if (BaseClassDecl->isInvalidDecl())
5199 continue;
5200 if (BaseClassDecl->hasIrrelevantDestructor())
5201 continue;
5202
5203 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5204 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5204, __extension__ __PRETTY_FUNCTION__))
;
5205 if (CheckDestructorAccess(
5206 ClassDecl->getLocation(), Dtor,
5207 PDiag(diag::err_access_dtor_vbase)
5208 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5209 Context.getTypeDeclType(ClassDecl)) ==
5210 AR_accessible) {
5211 CheckDerivedToBaseConversion(
5212 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5213 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5214 SourceRange(), DeclarationName(), nullptr);
5215 }
5216
5217 MarkFunctionReferenced(Location, Dtor);
5218 DiagnoseUseOfDecl(Dtor, Location);
5219 }
5220}
5221
5222void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5223 if (!CDtorDecl)
5224 return;
5225
5226 if (CXXConstructorDecl *Constructor
5227 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5228 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5229 DiagnoseUninitializedFields(*this, Constructor);
5230 }
5231}
5232
5233bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5234 if (!getLangOpts().CPlusPlus)
5235 return false;
5236
5237 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5238 if (!RD)
5239 return false;
5240
5241 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5242 // class template specialization here, but doing so breaks a lot of code.
5243
5244 // We can't answer whether something is abstract until it has a
5245 // definition. If it's currently being defined, we'll walk back
5246 // over all the declarations when we have a full definition.
5247 const CXXRecordDecl *Def = RD->getDefinition();
5248 if (!Def || Def->isBeingDefined())
5249 return false;
5250
5251 return RD->isAbstract();
5252}
5253
5254bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5255 TypeDiagnoser &Diagnoser) {
5256 if (!isAbstractType(Loc, T))
5257 return false;
5258
5259 T = Context.getBaseElementType(T);
5260 Diagnoser.diagnose(*this, Loc, T);
5261 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5262 return true;
5263}
5264
5265void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5266 // Check if we've already emitted the list of pure virtual functions
5267 // for this class.
5268 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5269 return;
5270
5271 // If the diagnostic is suppressed, don't emit the notes. We're only
5272 // going to emit them once, so try to attach them to a diagnostic we're
5273 // actually going to show.
5274 if (Diags.isLastDiagnosticIgnored())
5275 return;
5276
5277 CXXFinalOverriderMap FinalOverriders;
5278 RD->getFinalOverriders(FinalOverriders);
5279
5280 // Keep a set of seen pure methods so we won't diagnose the same method
5281 // more than once.
5282 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5283
5284 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5285 MEnd = FinalOverriders.end();
5286 M != MEnd;
5287 ++M) {
5288 for (OverridingMethods::iterator SO = M->second.begin(),
5289 SOEnd = M->second.end();
5290 SO != SOEnd; ++SO) {
5291 // C++ [class.abstract]p4:
5292 // A class is abstract if it contains or inherits at least one
5293 // pure virtual function for which the final overrider is pure
5294 // virtual.
5295
5296 //
5297 if (SO->second.size() != 1)
5298 continue;
5299
5300 if (!SO->second.front().Method->isPure())
5301 continue;
5302
5303 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5304 continue;
5305
5306 Diag(SO->second.front().Method->getLocation(),
5307 diag::note_pure_virtual_function)
5308 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5309 }
5310 }
5311
5312 if (!PureVirtualClassDiagSet)
5313 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5314 PureVirtualClassDiagSet->insert(RD);
5315}
5316
5317namespace {
5318struct AbstractUsageInfo {
5319 Sema &S;
5320 CXXRecordDecl *Record;
5321 CanQualType AbstractType;
5322 bool Invalid;
5323
5324 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5325 : S(S), Record(Record),
5326 AbstractType(S.Context.getCanonicalType(
5327 S.Context.getTypeDeclType(Record))),
5328 Invalid(false) {}
5329
5330 void DiagnoseAbstractType() {
5331 if (Invalid) return;
5332 S.DiagnoseAbstractType(Record);
5333 Invalid = true;
5334 }
5335
5336 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5337};
5338
5339struct CheckAbstractUsage {
5340 AbstractUsageInfo &Info;
5341 const NamedDecl *Ctx;
5342
5343 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5344 : Info(Info), Ctx(Ctx) {}
5345
5346 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5347 switch (TL.getTypeLocClass()) {
5348#define ABSTRACT_TYPELOC(CLASS, PARENT)
5349#define TYPELOC(CLASS, PARENT) \
5350 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5351#include "clang/AST/TypeLocNodes.def"
5352 }
5353 }
5354
5355 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5356 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5357 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5358 if (!TL.getParam(I))
5359 continue;
5360
5361 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5362 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5363 }
5364 }
5365
5366 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5367 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5368 }
5369
5370 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5371 // Visit the type parameters from a permissive context.
5372 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5373 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5374 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5375 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5376 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5377 // TODO: other template argument types?
5378 }
5379 }
5380
5381 // Visit pointee types from a permissive context.
5382#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5383 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5384 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5385 }
5386 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5387 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5388 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5389 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5390 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5391
5392 /// Handle all the types we haven't given a more specific
5393 /// implementation for above.
5394 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5395 // Every other kind of type that we haven't called out already
5396 // that has an inner type is either (1) sugar or (2) contains that
5397 // inner type in some way as a subobject.
5398 if (TypeLoc Next = TL.getNextTypeLoc())
5399 return Visit(Next, Sel);
5400
5401 // If there's no inner type and we're in a permissive context,
5402 // don't diagnose.
5403 if (Sel == Sema::AbstractNone) return;
5404
5405 // Check whether the type matches the abstract type.
5406 QualType T = TL.getType();
5407 if (T->isArrayType()) {
5408 Sel = Sema::AbstractArrayType;
5409 T = Info.S.Context.getBaseElementType(T);
5410 }
5411 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5412 if (CT != Info.AbstractType) return;
5413
5414 // It matched; do some magic.
5415 if (Sel == Sema::AbstractArrayType) {
5416 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5417 << T << TL.getSourceRange();
5418 } else {
5419 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5420 << Sel << T << TL.getSourceRange();
5421 }
5422 Info.DiagnoseAbstractType();
5423 }
5424};
5425
5426void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5427 Sema::AbstractDiagSelID Sel) {
5428 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5429}
5430
5431}
5432
5433/// Check for invalid uses of an abstract type in a method declaration.
5434static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5435 CXXMethodDecl *MD) {
5436 // No need to do the check on definitions, which require that
5437 // the return/param types be complete.
5438 if (MD->doesThisDeclarationHaveABody())
5439 return;
5440
5441 // For safety's sake, just ignore it if we don't have type source
5442 // information. This should never happen for non-implicit methods,
5443 // but...
5444 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5445 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5446}
5447
5448/// Check for invalid uses of an abstract type within a class definition.
5449static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5450 CXXRecordDecl *RD) {
5451 for (auto *D : RD->decls()) {
5452 if (D->isImplicit()) continue;
5453
5454 // Methods and method templates.
5455 if (isa<CXXMethodDecl>(D)) {
5456 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5457 } else if (isa<FunctionTemplateDecl>(D)) {
5458 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5459 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5460
5461 // Fields and static variables.
5462 } else if (isa<FieldDecl>(D)) {
5463 FieldDecl *FD = cast<FieldDecl>(D);
5464 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5465 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5466 } else if (isa<VarDecl>(D)) {
5467 VarDecl *VD = cast<VarDecl>(D);
5468 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5469 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5470
5471 // Nested classes and class templates.
5472 } else if (isa<CXXRecordDecl>(D)) {
5473 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5474 } else if (isa<ClassTemplateDecl>(D)) {
5475 CheckAbstractClassUsage(Info,
5476 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5477 }
5478 }
5479}
5480
5481static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5482 Attr *ClassAttr = getDLLAttr(Class);
5483 if (!ClassAttr)
5484 return;
5485
5486 assert(ClassAttr->getKind() == attr::DLLExport)(static_cast <bool> (ClassAttr->getKind() == attr::DLLExport
) ? void (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
;
5487
5488 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5489
5490 if (TSK == TSK_ExplicitInstantiationDeclaration)
5491 // Don't go any further if this is just an explicit instantiation
5492 // declaration.
5493 return;
5494
5495 for (Decl *Member : Class->decls()) {
5496 // Defined static variables that are members of an exported base
5497 // class must be marked export too.
5498 auto *VD = dyn_cast<VarDecl>(Member);
5499 if (VD && Member->getAttr<DLLExportAttr>() &&
5500 VD->getStorageClass() == SC_Static &&
5501 TSK == TSK_ImplicitInstantiation)
5502 S.MarkVariableReferenced(VD->getLocation(), VD);
5503
5504 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5505 if (!MD)
5506 continue;
5507
5508 if (Member->getAttr<DLLExportAttr>()) {
5509 if (MD->isUserProvided()) {
5510 // Instantiate non-default class member functions ...
5511
5512 // .. except for certain kinds of template specializations.
5513 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5514 continue;
5515
5516 S.MarkFunctionReferenced(Class->getLocation(), MD);
5517
5518 // The function will be passed to the consumer when its definition is
5519 // encountered.
5520 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5521 MD->isCopyAssignmentOperator() ||
5522 MD->isMoveAssignmentOperator()) {
5523 // Synthesize and instantiate non-trivial implicit methods, explicitly
5524 // defaulted methods, and the copy and move assignment operators. The
5525 // latter are exported even if they are trivial, because the address of
5526 // an operator can be taken and should compare equal across libraries.
5527 DiagnosticErrorTrap Trap(S.Diags);
5528 S.MarkFunctionReferenced(Class->getLocation(), MD);
5529 if (Trap.hasErrorOccurred()) {
5530 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5531 << Class << !S.getLangOpts().CPlusPlus11;
5532 break;
5533 }
5534
5535 // There is no later point when we will see the definition of this
5536 // function, so pass it to the consumer now.
5537 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5538 }
5539 }
5540 }
5541}
5542
5543static void checkForMultipleExportedDefaultConstructors(Sema &S,
5544 CXXRecordDecl *Class) {
5545 // Only the MS ABI has default constructor closures, so we don't need to do
5546 // this semantic checking anywhere else.
5547 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5548 return;
5549
5550 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5551 for (Decl *Member : Class->decls()) {
5552 // Look for exported default constructors.
5553 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5554 if (!CD || !CD->isDefaultConstructor())
5555 continue;
5556 auto *Attr = CD->getAttr<DLLExportAttr>();
5557 if (!Attr)
5558 continue;
5559
5560 // If the class is non-dependent, mark the default arguments as ODR-used so
5561 // that we can properly codegen the constructor closure.
5562 if (!Class->isDependentContext()) {
5563 for (ParmVarDecl *PD : CD->parameters()) {
5564 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5565 S.DiscardCleanupsInEvaluationContext();
5566 }
5567 }
5568
5569 if (LastExportedDefaultCtor) {
5570 S.Diag(LastExportedDefaultCtor->getLocation(),
5571 diag::err_attribute_dll_ambiguous_default_ctor)
5572 << Class;
5573 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5574 << CD->getDeclName();
5575 return;
5576 }
5577 LastExportedDefaultCtor = CD;
5578 }
5579}
5580
5581/// \brief Check class-level dllimport/dllexport attribute.
5582void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5583 Attr *ClassAttr = getDLLAttr(Class);
5584
5585 // MSVC inherits DLL attributes to partial class template specializations.
5586 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5587 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5588 if (Attr *TemplateAttr =
5589 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5590 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5591 A->setInherited(true);
5592 ClassAttr = A;
5593 }
5594 }
5595 }
5596
5597 if (!ClassAttr)
5598 return;
5599
5600 if (!Class->isExternallyVisible()) {
5601 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5602 << Class << ClassAttr;
5603 return;
5604 }
5605
5606 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5607 !ClassAttr->isInherited()) {
5608 // Diagnose dll attributes on members of class with dll attribute.
5609 for (Decl *Member : Class->decls()) {
5610 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5611 continue;
5612 InheritableAttr *MemberAttr = getDLLAttr(Member);
5613 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5614 continue;
5615
5616 Diag(MemberAttr->getLocation(),
5617 diag::err_attribute_dll_member_of_dll_class)
5618 << MemberAttr << ClassAttr;
5619 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5620 Member->setInvalidDecl();
5621 }
5622 }
5623
5624 if (Class->getDescribedClassTemplate())
5625 // Don't inherit dll attribute until the template is instantiated.
5626 return;
5627
5628 // The class is either imported or exported.
5629 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5630
5631 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5632
5633 // Ignore explicit dllexport on explicit class template instantiation declarations.
5634 if (ClassExported && !ClassAttr->isInherited() &&
5635 TSK == TSK_ExplicitInstantiationDeclaration) {
5636 Class->dropAttr<DLLExportAttr>();
5637 return;
5638 }
5639
5640 // Force declaration of implicit members so they can inherit the attribute.
5641 ForceDeclarationOfImplicitMembers(Class);
5642
5643 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5644 // seem to be true in practice?
5645
5646 for (Decl *Member : Class->decls()) {
5647 VarDecl *VD = dyn_cast<VarDecl>(Member);
5648 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5649
5650 // Only methods and static fields inherit the attributes.
5651 if (!VD && !MD)
5652 continue;
5653
5654 if (MD) {
5655 // Don't process deleted methods.
5656 if (MD->isDeleted())
5657 continue;
5658
5659 if (MD->isInlined()) {
5660 // MinGW does not import or export inline methods.
5661 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5662 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5663 continue;
5664
5665 // MSVC versions before 2015 don't export the move assignment operators
5666 // and move constructor, so don't attempt to import/export them if
5667 // we have a definition.
5668 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5669 if ((MD->isMoveAssignmentOperator() ||
5670 (Ctor && Ctor->isMoveConstructor())) &&
5671 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5672 continue;
5673
5674 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5675 // operator is exported anyway.
5676 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5677 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5678 continue;
5679 }
5680 }
5681
5682 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5683 continue;
5684
5685 if (!getDLLAttr(Member)) {
5686 auto *NewAttr =
5687 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5688 NewAttr->setInherited(true);
5689 Member->addAttr(NewAttr);
5690
5691 if (MD) {
5692 // Propagate DLLAttr to friend re-declarations of MD that have already
5693 // been constructed.
5694 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5695 FD = FD->getPreviousDecl()) {
5696 if (FD->getFriendObjectKind() == Decl::FOK_None)
5697 continue;
5698 assert(!getDLLAttr(FD) &&(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5699, __extension__ __PRETTY_FUNCTION__))
5699 "friend re-decl should not already have a DLLAttr")(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5699, __extension__ __PRETTY_FUNCTION__))
;
5700 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5701 NewAttr->setInherited(true);
5702 FD->addAttr(NewAttr);
5703 }
5704 }
5705 }
5706 }
5707
5708 if (ClassExported)
5709 DelayedDllExportClasses.push_back(Class);
5710}
5711
5712/// \brief Perform propagation of DLL attributes from a derived class to a
5713/// templated base class for MS compatibility.
5714void Sema::propagateDLLAttrToBaseClassTemplate(
5715 CXXRecordDecl *Class, Attr *ClassAttr,
5716 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5717 if (getDLLAttr(
5718 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5719 // If the base class template has a DLL attribute, don't try to change it.
5720 return;
5721 }
5722
5723 auto TSK = BaseTemplateSpec->getSpecializationKind();
5724 if (!getDLLAttr(BaseTemplateSpec) &&
5725 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5726 TSK == TSK_ImplicitInstantiation)) {
5727 // The template hasn't been instantiated yet (or it has, but only as an
5728 // explicit instantiation declaration or implicit instantiation, which means
5729 // we haven't codegenned any members yet), so propagate the attribute.
5730 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5731 NewAttr->setInherited(true);
5732 BaseTemplateSpec->addAttr(NewAttr);
5733
5734 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5735 // needs to be run again to work see the new attribute. Otherwise this will
5736 // get run whenever the template is instantiated.
5737 if (TSK != TSK_Undeclared)
5738 checkClassLevelDLLAttribute(BaseTemplateSpec);
5739
5740 return;
5741 }
5742
5743 if (getDLLAttr(BaseTemplateSpec)) {
5744 // The template has already been specialized or instantiated with an
5745 // attribute, explicitly or through propagation. We should not try to change
5746 // it.
5747 return;
5748 }
5749
5750 // The template was previously instantiated or explicitly specialized without
5751 // a dll attribute, It's too late for us to add an attribute, so warn that
5752 // this is unsupported.
5753 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5754 << BaseTemplateSpec->isExplicitSpecialization();
5755 Diag(ClassAttr->getLocation(), diag::note_attribute);
5756 if (BaseTemplateSpec->isExplicitSpecialization()) {
5757 Diag(BaseTemplateSpec->getLocation(),
5758 diag::note_template_class_explicit_specialization_was_here)
5759 << BaseTemplateSpec;
5760 } else {
5761 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5762 diag::note_template_class_instantiation_was_here)
5763 << BaseTemplateSpec;
5764 }
5765}
5766
5767static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5768 SourceLocation DefaultLoc) {
5769 switch (S.getSpecialMember(MD)) {
5770 case Sema::CXXDefaultConstructor:
5771 S.DefineImplicitDefaultConstructor(DefaultLoc,
5772 cast<CXXConstructorDecl>(MD));
5773 break;
5774 case Sema::CXXCopyConstructor:
5775 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5776 break;
5777 case Sema::CXXCopyAssignment:
5778 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5779 break;
5780 case Sema::CXXDestructor:
5781 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5782 break;
5783 case Sema::CXXMoveConstructor:
5784 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5785 break;
5786 case Sema::CXXMoveAssignment:
5787 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5788 break;
5789 case Sema::CXXInvalid:
5790 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5790)
;
5791 }
5792}
5793
5794/// Determine whether a type would be destructed in the callee if it had a
5795/// non-trivial destructor. The rules here are based on C++ [class.temporary]p3,
5796/// which determines whether a struct can be passed to or returned from
5797/// functions in registers.
5798static bool paramCanBeDestroyedInCallee(Sema &S, CXXRecordDecl *D,
5799 TargetInfo::CallingConvKind CCK) {
5800 if (D->isDependentType() || D->isInvalidDecl())
5801 return false;
5802
5803 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5804 // The PS4 platform ABI follows the behavior of Clang 3.2.
5805 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5806 return !D->hasNonTrivialDestructorForCall() &&
5807 !D->hasNonTrivialCopyConstructorForCall();
5808
5809 // Per C++ [class.temporary]p3, the relevant condition is:
5810 // each copy constructor, move constructor, and destructor of X is
5811 // either trivial or deleted, and X has at least one non-deleted copy
5812 // or move constructor
5813 bool HasNonDeletedCopyOrMove = false;
5814
5815 if (D->needsImplicitCopyConstructor() &&
5816 !D->defaultedCopyConstructorIsDeleted()) {
5817 if (!D->hasTrivialCopyConstructorForCall())
5818 return false;
5819 HasNonDeletedCopyOrMove = true;
5820 }
5821
5822 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5823 !D->defaultedMoveConstructorIsDeleted()) {
5824 if (!D->hasTrivialMoveConstructorForCall())
5825 return false;
5826 HasNonDeletedCopyOrMove = true;
5827 }
5828
5829 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5830 !D->hasTrivialDestructorForCall())
5831 return false;
5832
5833 for (const CXXMethodDecl *MD : D->methods()) {
5834 if (MD->isDeleted())
5835 continue;
5836
5837 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5838 if (CD && CD->isCopyOrMoveConstructor())
5839 HasNonDeletedCopyOrMove = true;
5840 else if (!isa<CXXDestructorDecl>(MD))
5841 continue;
5842
5843 if (!MD->isTrivialForCall())
5844 return false;
5845 }
5846
5847 return HasNonDeletedCopyOrMove;
5848}
5849
5850static RecordDecl::ArgPassingKind
5851computeArgPassingRestrictions(bool DestroyedInCallee, const CXXRecordDecl *RD,
5852 TargetInfo::CallingConvKind CCK, Sema &S) {
5853 if (RD->isDependentType() || RD->isInvalidDecl())
5854 return RecordDecl::APK_CanPassInRegs;
5855
5856 // The param cannot be passed in registers if ArgPassingRestrictions is set to
5857 // APK_CanNeverPassInRegs.
5858 if (RD->getArgPassingRestrictions() == RecordDecl::APK_CanNeverPassInRegs)
5859 return RecordDecl::APK_CanNeverPassInRegs;
5860
5861 if (CCK != TargetInfo::CCK_MicrosoftX86_64)
5862 return DestroyedInCallee ? RecordDecl::APK_CanPassInRegs
5863 : RecordDecl::APK_CannotPassInRegs;
5864
5865 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5866 bool DtorIsTrivialForCall = false;
5867
5868 // If a class has at least one non-deleted, trivial copy constructor, it
5869 // is passed according to the C ABI. Otherwise, it is passed indirectly.
5870 //
5871 // Note: This permits classes with non-trivial copy or move ctors to be
5872 // passed in registers, so long as they *also* have a trivial copy ctor,
5873 // which is non-conforming.
5874 if (RD->needsImplicitCopyConstructor()) {
5875 if (!RD->defaultedCopyConstructorIsDeleted()) {
5876 if (RD->hasTrivialCopyConstructor())
5877 CopyCtorIsTrivial = true;
5878 if (RD->hasTrivialCopyConstructorForCall())
5879 CopyCtorIsTrivialForCall = true;
5880 }
5881 } else {
5882 for (const CXXConstructorDecl *CD : RD->ctors()) {
5883 if (CD->isCopyConstructor() && !CD->isDeleted()) {
5884 if (CD->isTrivial())
5885 CopyCtorIsTrivial = true;
5886 if (CD->isTrivialForCall())
5887 CopyCtorIsTrivialForCall = true;
5888 }
5889 }
5890 }
5891
5892 if (RD->needsImplicitDestructor()) {
5893 if (!RD->defaultedDestructorIsDeleted() &&
5894 RD->hasTrivialDestructorForCall())
5895 DtorIsTrivialForCall = true;
5896 } else if (const auto *D = RD->getDestructor()) {
5897 if (!D->isDeleted() && D->isTrivialForCall())
5898 DtorIsTrivialForCall = true;
5899 }
5900
5901 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5902 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5903 return RecordDecl::APK_CanPassInRegs;
5904
5905 // If a class has a destructor, we'd really like to pass it indirectly
5906 // because it allows us to elide copies. Unfortunately, MSVC makes that
5907 // impossible for small types, which it will pass in a single register or
5908 // stack slot. Most objects with dtors are large-ish, so handle that early.
5909 // We can't call out all large objects as being indirect because there are
5910 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5911 // how we pass large POD types.
5912
5913 // Note: This permits small classes with nontrivial destructors to be
5914 // passed in registers, which is non-conforming.
5915 if (CopyCtorIsTrivial &&
5916 S.getASTContext().getTypeSize(RD->getTypeForDecl()) <= 64)
5917 return RecordDecl::APK_CanPassInRegs;
5918 return RecordDecl::APK_CannotPassInRegs;
5919}
5920
5921/// \brief Perform semantic checks on a class definition that has been
5922/// completing, introducing implicitly-declared members, checking for
5923/// abstract types, etc.
5924void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5925 if (!Record)
5926 return;
5927
5928 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5929 AbstractUsageInfo Info(*this, Record);
5930 CheckAbstractClassUsage(Info, Record);
5931 }
5932
5933 // If this is not an aggregate type and has no user-declared constructor,
5934 // complain about any non-static data members of reference or const scalar
5935 // type, since they will never get initializers.
5936 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5937 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5938 !Record->isLambda()) {
5939 bool Complained = false;
5940 for (const auto *F : Record->fields()) {
5941 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5942 continue;
5943
5944 if (F->getType()->isReferenceType() ||
5945 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5946 if (!Complained) {
5947 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5948 << Record->getTagKind() << Record;
5949 Complained = true;
5950 }
5951
5952 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5953 << F->getType()->isReferenceType()
5954 << F->getDeclName();
5955 }
5956 }
5957 }
5958
5959 if (Record->getIdentifier()) {
5960 // C++ [class.mem]p13:
5961 // If T is the name of a class, then each of the following shall have a
5962 // name different from T:
5963 // - every member of every anonymous union that is a member of class T.
5964 //
5965 // C++ [class.mem]p14:
5966 // In addition, if class T has a user-declared constructor (12.1), every
5967 // non-static data member of class T shall have a name different from T.
5968 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5969 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5970 ++I) {
5971 NamedDecl *D = *I;
5972 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5973 isa<IndirectFieldDecl>(D)) {
5974 Diag(D->getLocation(), diag::err_member_name_of_class)
5975 << D->getDeclName();
5976 break;
5977 }
5978 }
5979 }
5980
5981 // Warn if the class has virtual methods but non-virtual public destructor.
5982 if (Record->isPolymorphic() && !Record->isDependentType()) {
5983 CXXDestructorDecl *dtor = Record->getDestructor();
5984 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5985 !Record->hasAttr<FinalAttr>())
5986 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5987 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5988 }
5989
5990 if (Record->isAbstract()) {
5991 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5992 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5993 << FA->isSpelledAsSealed();
5994 DiagnoseAbstractType(Record);
5995 }
5996 }
5997
5998 // Set HasTrivialSpecialMemberForCall if the record has attribute
5999 // "trivial_abi".
6000 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6001
6002 if (HasTrivialABI)
6003 Record->setHasTrivialSpecialMemberForCall();
6004
6005 bool HasMethodWithOverrideControl = false,
6006 HasOverridingMethodWithoutOverrideControl = false;
6007 if (!Record->isDependentType()) {
6008 for (auto *M : Record->methods()) {
6009 // See if a method overloads virtual methods in a base
6010 // class without overriding any.
6011 if (!M->isStatic())
6012 DiagnoseHiddenVirtualMethods(M);
6013 if (M->hasAttr<OverrideAttr>())
6014 HasMethodWithOverrideControl = true;
6015 else if (M->size_overridden_methods() > 0)
6016 HasOverridingMethodWithoutOverrideControl = true;
6017 // Check whether the explicitly-defaulted special members are valid.
6018 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6019 CheckExplicitlyDefaultedSpecialMember(M);
6020
6021 // For an explicitly defaulted or deleted special member, we defer
6022 // determining triviality until the class is complete. That time is now!
6023 CXXSpecialMember CSM = getSpecialMember(M);
6024 if (!M->isImplicit() && !M->isUserProvided()) {
6025 if (CSM != CXXInvalid) {
6026 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6027 // Inform the class that we've finished declaring this member.
6028 Record->finishedDefaultedOrDeletedMember(M);
6029 M->setTrivialForCall(
6030 HasTrivialABI ||
6031 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6032 Record->setTrivialForCallFlags(M);
6033 }
6034 }
6035
6036 // Set triviality for the purpose of calls if this is a user-provided
6037 // copy/move constructor or destructor.
6038 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6039 CSM == CXXDestructor) && M->isUserProvided()) {
6040 M->setTrivialForCall(HasTrivialABI);
6041 Record->setTrivialForCallFlags(M);
6042 }
6043
6044 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6045 M->hasAttr<DLLExportAttr>()) {
6046 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6047 M->isTrivial() &&
6048 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6049 CSM == CXXDestructor))
6050 M->dropAttr<DLLExportAttr>();
6051
6052 if (M->hasAttr<DLLExportAttr>()) {
6053 DefineImplicitSpecialMember(*this, M, M->getLocation());
6054 ActOnFinishInlineFunctionDef(M);
6055 }
6056 }
6057 }
6058 }
6059
6060 if (HasMethodWithOverrideControl &&
6061 HasOverridingMethodWithoutOverrideControl) {
6062 // At least one method has the 'override' control declared.
6063 // Diagnose all other overridden methods which do not have 'override' specified on them.
6064 for (auto *M : Record->methods())
6065 DiagnoseAbsenceOfOverrideControl(M);
6066 }
6067
6068 // ms_struct is a request to use the same ABI rules as MSVC. Check
6069 // whether this class uses any C++ features that are implemented
6070 // completely differently in MSVC, and if so, emit a diagnostic.
6071 // That diagnostic defaults to an error, but we allow projects to
6072 // map it down to a warning (or ignore it). It's a fairly common
6073 // practice among users of the ms_struct pragma to mass-annotate
6074 // headers, sweeping up a bunch of types that the project doesn't
6075 // really rely on MSVC-compatible layout for. We must therefore
6076 // support "ms_struct except for C++ stuff" as a secondary ABI.
6077 if (Record->isMsStruct(Context) &&
6078 (Record->isPolymorphic() || Record->getNumBases())) {
6079 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6080 }
6081
6082 checkClassLevelDLLAttribute(Record);
6083
6084 bool ClangABICompat4 =
6085 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6086 TargetInfo::CallingConvKind CCK =
6087 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6088 bool DestroyedInCallee = paramCanBeDestroyedInCallee(*this, Record, CCK);
6089
6090 if (Record->hasNonTrivialDestructor())
6091 Record->setParamDestroyedInCallee(DestroyedInCallee);
6092
6093 Record->setArgPassingRestrictions(
6094 computeArgPassingRestrictions(DestroyedInCallee, Record, CCK, *this));
6095}
6096
6097/// Look up the special member function that would be called by a special
6098/// member function for a subobject of class type.
6099///
6100/// \param Class The class type of the subobject.
6101/// \param CSM The kind of special member function.
6102/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6103/// \param ConstRHS True if this is a copy operation with a const object
6104/// on its RHS, that is, if the argument to the outer special member
6105/// function is 'const' and this is not a field marked 'mutable'.
6106static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6107 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6108 unsigned FieldQuals, bool ConstRHS) {
6109 unsigned LHSQuals = 0;
6110 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6111 LHSQuals = FieldQuals;
6112
6113 unsigned RHSQuals = FieldQuals;
6114 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6115 RHSQuals = 0;
6116 else if (ConstRHS)
6117 RHSQuals |= Qualifiers::Const;
6118
6119 return S.LookupSpecialMember(Class, CSM,
6120 RHSQuals & Qualifiers::Const,
6121 RHSQuals & Qualifiers::Volatile,
6122 false,
6123 LHSQuals & Qualifiers::Const,
6124 LHSQuals & Qualifiers::Volatile);
6125}
6126
6127class Sema::InheritedConstructorInfo {
6128 Sema &S;
6129 SourceLocation UseLoc;
6130
6131 /// A mapping from the base classes through which the constructor was
6132 /// inherited to the using shadow declaration in that base class (or a null
6133 /// pointer if the constructor was declared in that base class).
6134 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6135 InheritedFromBases;
6136
6137public:
6138 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6139 ConstructorUsingShadowDecl *Shadow)
6140 : S(S), UseLoc(UseLoc) {
6141 bool DiagnosedMultipleConstructedBases = false;
6142 CXXRecordDecl *ConstructedBase = nullptr;
6143 UsingDecl *ConstructedBaseUsing = nullptr;
6144
6145 // Find the set of such base class subobjects and check that there's a
6146 // unique constructed subobject.
6147 for (auto *D : Shadow->redecls()) {
6148 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6149 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6150 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6151
6152 InheritedFromBases.insert(
6153 std::make_pair(DNominatedBase->getCanonicalDecl(),
6154 DShadow->getNominatedBaseClassShadowDecl()));
6155 if (DShadow->constructsVirtualBase())
6156 InheritedFromBases.insert(
6157 std::make_pair(DConstructedBase->getCanonicalDecl(),
6158 DShadow->getConstructedBaseClassShadowDecl()));
6159 else
6160 assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase
) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6160, __extension__ __PRETTY_FUNCTION__))
;
6161
6162 // [class.inhctor.init]p2:
6163 // If the constructor was inherited from multiple base class subobjects
6164 // of type B, the program is ill-formed.
6165 if (!ConstructedBase) {
6166 ConstructedBase = DConstructedBase;
6167 ConstructedBaseUsing = D->getUsingDecl();
6168 } else if (ConstructedBase != DConstructedBase &&
6169 !Shadow->isInvalidDecl()) {
6170 if (!DiagnosedMultipleConstructedBases) {
6171 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6172 << Shadow->getTargetDecl();
6173 S.Diag(ConstructedBaseUsing->getLocation(),
6174 diag::note_ambiguous_inherited_constructor_using)
6175 << ConstructedBase;
6176 DiagnosedMultipleConstructedBases = true;
6177 }
6178 S.Diag(D->getUsingDecl()->getLocation(),
6179 diag::note_ambiguous_inherited_constructor_using)
6180 << DConstructedBase;
6181 }
6182 }
6183
6184 if (DiagnosedMultipleConstructedBases)
6185 Shadow->setInvalidDecl();
6186 }
6187
6188 /// Find the constructor to use for inherited construction of a base class,
6189 /// and whether that base class constructor inherits the constructor from a
6190 /// virtual base class (in which case it won't actually invoke it).
6191 std::pair<CXXConstructorDecl *, bool>
6192 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6193 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6194 if (It == InheritedFromBases.end())
6195 return std::make_pair(nullptr, false);
6196
6197 // This is an intermediary class.
6198 if (It->second)
6199 return std::make_pair(
6200 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6201 It->second->constructsVirtualBase());
6202
6203 // This is the base class from which the constructor was inherited.
6204 return std::make_pair(Ctor, false);
6205 }
6206};
6207
6208/// Is the special member function which would be selected to perform the
6209/// specified operation on the specified class type a constexpr constructor?
6210static bool
6211specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6212 Sema::CXXSpecialMember CSM, unsigned Quals,
6213 bool ConstRHS,
6214 CXXConstructorDecl *InheritedCtor = nullptr,
6215 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6216 // If we're inheriting a constructor, see if we need to call it for this base
6217 // class.
6218 if (InheritedCtor) {
6219 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6219, __extension__ __PRETTY_FUNCTION__))
;
6220 auto BaseCtor =
6221 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6222 if (BaseCtor)
6223 return BaseCtor->isConstexpr();
6224 }
6225
6226 if (CSM == Sema::CXXDefaultConstructor)
6227 return ClassDecl->hasConstexprDefaultConstructor();
6228
6229 Sema::SpecialMemberOverloadResult SMOR =
6230 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6231 if (!SMOR.getMethod())
6232 // A constructor we wouldn't select can't be "involved in initializing"
6233 // anything.
6234 return true;
6235 return SMOR.getMethod()->isConstexpr();
6236}
6237
6238/// Determine whether the specified special member function would be constexpr
6239/// if it were implicitly defined.
6240static bool defaultedSpecialMemberIsConstexpr(
6241 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6242 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6243 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6244 if (!S.getLangOpts().CPlusPlus11)
6245 return false;
6246
6247 // C++11 [dcl.constexpr]p4:
6248 // In the definition of a constexpr constructor [...]
6249 bool Ctor = true;
6250 switch (CSM) {
6251 case Sema::CXXDefaultConstructor:
6252 if (Inherited)
6253 break;
6254 // Since default constructor lookup is essentially trivial (and cannot
6255 // involve, for instance, template instantiation), we compute whether a
6256 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6257 //
6258 // This is important for performance; we need to know whether the default
6259 // constructor is constexpr to determine whether the type is a literal type.
6260 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6261
6262 case Sema::CXXCopyConstructor:
6263 case Sema::CXXMoveConstructor:
6264 // For copy or move constructors, we need to perform overload resolution.
6265 break;
6266
6267 case Sema::CXXCopyAssignment:
6268 case Sema::CXXMoveAssignment:
6269 if (!S.getLangOpts().CPlusPlus14)
6270 return false;
6271 // In C++1y, we need to perform overload resolution.
6272 Ctor = false;
6273 break;
6274
6275 case Sema::CXXDestructor:
6276 case Sema::CXXInvalid:
6277 return false;
6278 }
6279
6280 // -- if the class is a non-empty union, or for each non-empty anonymous
6281 // union member of a non-union class, exactly one non-static data member
6282 // shall be initialized; [DR1359]
6283 //
6284 // If we squint, this is guaranteed, since exactly one non-static data member
6285 // will be initialized (if the constructor isn't deleted), we just don't know
6286 // which one.
6287 if (Ctor && ClassDecl->isUnion())
6288 return CSM == Sema::CXXDefaultConstructor
6289 ? ClassDecl->hasInClassInitializer() ||
6290 !ClassDecl->hasVariantMembers()
6291 : true;
6292
6293 // -- the class shall not have any virtual base classes;
6294 if (Ctor && ClassDecl->getNumVBases())
6295 return false;
6296
6297 // C++1y [class.copy]p26:
6298 // -- [the class] is a literal type, and
6299 if (!Ctor && !ClassDecl->isLiteral())
6300 return false;
6301
6302 // -- every constructor involved in initializing [...] base class
6303 // sub-objects shall be a constexpr constructor;
6304 // -- the assignment operator selected to copy/move each direct base
6305 // class is a constexpr function, and
6306 for (const auto &B : ClassDecl->bases()) {
6307 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6308 if (!BaseType) continue;
6309
6310 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6311 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6312 InheritedCtor, Inherited))
6313 return false;
6314 }
6315
6316 // -- every constructor involved in initializing non-static data members
6317 // [...] shall be a constexpr constructor;
6318 // -- every non-static data member and base class sub-object shall be
6319 // initialized
6320 // -- for each non-static data member of X that is of class type (or array
6321 // thereof), the assignment operator selected to copy/move that member is
6322 // a constexpr function
6323 for (const auto *F : ClassDecl->fields()) {
6324 if (F->isInvalidDecl())
6325 continue;
6326 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6327 continue;
6328 QualType BaseType = S.Context.getBaseElementType(F->getType());
6329 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6330 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6331 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6332 BaseType.getCVRQualifiers(),
6333 ConstArg && !F->isMutable()))
6334 return false;
6335 } else if (CSM == Sema::CXXDefaultConstructor) {
6336 return false;
6337 }
6338 }
6339
6340 // All OK, it's constexpr!
6341 return true;
6342}
6343
6344static Sema::ImplicitExceptionSpecification
6345ComputeDefaultedSpecialMemberExceptionSpec(
6346 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6347 Sema::InheritedConstructorInfo *ICI);
6348
6349static Sema::ImplicitExceptionSpecification
6350computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6351 auto CSM = S.getSpecialMember(MD);
6352 if (CSM != Sema::CXXInvalid)
6353 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6354
6355 auto *CD = cast<CXXConstructorDecl>(MD);
6356 assert(CD->getInheritedConstructor() &&(static_cast <bool> (CD->getInheritedConstructor() &&
"only special members have implicit exception specs") ? void
(0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6357, __extension__ __PRETTY_FUNCTION__))
6357 "only special members have implicit exception specs")(static_cast <bool> (CD->getInheritedConstructor() &&
"only special members have implicit exception specs") ? void
(0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6357, __extension__ __PRETTY_FUNCTION__))
;
6358 Sema::InheritedConstructorInfo ICI(
6359 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6360 return ComputeDefaultedSpecialMemberExceptionSpec(
6361 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6362}
6363
6364static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6365 CXXMethodDecl *MD) {
6366 FunctionProtoType::ExtProtoInfo EPI;
6367
6368 // Build an exception specification pointing back at this member.
6369 EPI.ExceptionSpec.Type = EST_Unevaluated;
6370 EPI.ExceptionSpec.SourceDecl = MD;
6371
6372 // Set the calling convention to the default for C++ instance methods.
6373 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6374 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6375 /*IsCXXMethod=*/true));
6376 return EPI;
6377}
6378
6379void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6380 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6381 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6382 return;
6383
6384 // Evaluate the exception specification.
6385 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6386 auto ESI = IES.getExceptionSpec();
6387
6388 // Update the type of the special member to use it.
6389 UpdateExceptionSpec(MD, ESI);
6390
6391 // A user-provided destructor can be defined outside the class. When that
6392 // happens, be sure to update the exception specification on both
6393 // declarations.
6394 const FunctionProtoType *CanonicalFPT =
6395 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6396 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6397 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6398}
6399
6400void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6401 CXXRecordDecl *RD = MD->getParent();
6402 CXXSpecialMember CSM = getSpecialMember(MD);
6403
6404 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6405, __extension__ __PRETTY_FUNCTION__))
6405 "not an explicitly-defaulted special member")(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6405, __extension__ __PRETTY_FUNCTION__))
;
6406
6407 // Whether this was the first-declared instance of the constructor.
6408 // This affects whether we implicitly add an exception spec and constexpr.
6409 bool First = MD == MD->getCanonicalDecl();
6410
6411 bool HadError = false;
6412
6413 // C++11 [dcl.fct.def.default]p1:
6414 // A function that is explicitly defaulted shall
6415 // -- be a special member function (checked elsewhere),
6416 // -- have the same type (except for ref-qualifiers, and except that a
6417 // copy operation can take a non-const reference) as an implicit
6418 // declaration, and
6419 // -- not have default arguments.
6420 unsigned ExpectedParams = 1;
6421 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6422 ExpectedParams = 0;
6423 if (MD->getNumParams() != ExpectedParams) {
6424 // This also checks for default arguments: a copy or move constructor with a
6425 // default argument is classified as a default constructor, and assignment
6426 // operations and destructors can't have default arguments.
6427 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6428 << CSM << MD->getSourceRange();
6429 HadError = true;
6430 } else if (MD->isVariadic()) {
6431 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6432 << CSM << MD->getSourceRange();
6433 HadError = true;
6434 }
6435
6436 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6437
6438 bool CanHaveConstParam = false;
6439 if (CSM == CXXCopyConstructor)
6440 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6441 else if (CSM == CXXCopyAssignment)
6442 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6443
6444 QualType ReturnType = Context.VoidTy;
6445 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6446 // Check for return type matching.
6447 ReturnType = Type->getReturnType();
6448 QualType ExpectedReturnType =
6449 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6450 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6451 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6452 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6453 HadError = true;
6454 }
6455
6456 // A defaulted special member cannot have cv-qualifiers.
6457 if (Type->getTypeQuals()) {
6458 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6459 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6460 HadError = true;
6461 }
6462 }
6463
6464 // Check for parameter type matching.
6465 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6466 bool HasConstParam = false;
6467 if (ExpectedParams && ArgType->isReferenceType()) {
6468 // Argument must be reference to possibly-const T.
6469 QualType ReferentType = ArgType->getPointeeType();
6470 HasConstParam = ReferentType.isConstQualified();
6471
6472 if (ReferentType.isVolatileQualified()) {
6473 Diag(MD->getLocation(),
6474 diag::err_defaulted_special_member_volatile_param) << CSM;
6475 HadError = true;
6476 }
6477
6478 if (HasConstParam && !CanHaveConstParam) {
6479 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6480 Diag(MD->getLocation(),
6481 diag::err_defaulted_special_member_copy_const_param)
6482 << (CSM == CXXCopyAssignment);
6483 // FIXME: Explain why this special member can't be const.
6484 } else {
6485 Diag(MD->getLocation(),
6486 diag::err_defaulted_special_member_move_const_param)
6487 << (CSM == CXXMoveAssignment);
6488 }
6489 HadError = true;
6490 }
6491 } else if (ExpectedParams) {
6492 // A copy assignment operator can take its argument by value, but a
6493 // defaulted one cannot.
6494 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")(static_cast <bool> (CSM == CXXCopyAssignment &&
"unexpected non-ref argument") ? void (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6494, __extension__ __PRETTY_FUNCTION__))
;
6495 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6496 HadError = true;
6497 }
6498
6499 // C++11 [dcl.fct.def.default]p2:
6500 // An explicitly-defaulted function may be declared constexpr only if it
6501 // would have been implicitly declared as constexpr,
6502 // Do not apply this rule to members of class templates, since core issue 1358
6503 // makes such functions always instantiate to constexpr functions. For
6504 // functions which cannot be constexpr (for non-constructors in C++11 and for
6505 // destructors in C++1y), this is checked elsewhere.
6506 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6507 HasConstParam);
6508 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6509 : isa<CXXConstructorDecl>(MD)) &&
6510 MD->isConstexpr() && !Constexpr &&
6511 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6512 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6513 // FIXME: Explain why the special member can't be constexpr.
6514 HadError = true;
6515 }
6516
6517 // and may have an explicit exception-specification only if it is compatible
6518 // with the exception-specification on the implicit declaration.
6519 if (Type->hasExceptionSpec()) {
6520 // Delay the check if this is the first declaration of the special member,
6521 // since we may not have parsed some necessary in-class initializers yet.
6522 if (First) {
6523 // If the exception specification needs to be instantiated, do so now,
6524 // before we clobber it with an EST_Unevaluated specification below.
6525 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6526 InstantiateExceptionSpec(MD->getLocStart(), MD);
6527 Type = MD->getType()->getAs<FunctionProtoType>();
6528 }
6529 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6530 } else
6531 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6532 }
6533
6534 // If a function is explicitly defaulted on its first declaration,
6535 if (First) {
6536 // -- it is implicitly considered to be constexpr if the implicit
6537 // definition would be,
6538 MD->setConstexpr(Constexpr);
6539
6540 // -- it is implicitly considered to have the same exception-specification
6541 // as if it had been implicitly declared,
6542 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6543 EPI.ExceptionSpec.Type = EST_Unevaluated;
6544 EPI.ExceptionSpec.SourceDecl = MD;
6545 MD->setType(Context.getFunctionType(ReturnType,
6546 llvm::makeArrayRef(&ArgType,
6547 ExpectedParams),
6548 EPI));
6549 }
6550
6551 if (ShouldDeleteSpecialMember(MD, CSM)) {
6552 if (First) {
6553 SetDeclDeleted(MD, MD->getLocation());
6554 } else {
6555 // C++11 [dcl.fct.def.default]p4:
6556 // [For a] user-provided explicitly-defaulted function [...] if such a
6557 // function is implicitly defined as deleted, the program is ill-formed.
6558 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6559 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6560 HadError = true;
6561 }
6562 }
6563
6564 if (HadError)
6565 MD->setInvalidDecl();
6566}
6567
6568/// Check whether the exception specification provided for an
6569/// explicitly-defaulted special member matches the exception specification
6570/// that would have been generated for an implicit special member, per
6571/// C++11 [dcl.fct.def.default]p2.
6572void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6573 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6574 // If the exception specification was explicitly specified but hadn't been
6575 // parsed when the method was defaulted, grab it now.
6576 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5
Assuming the condition is false
6
Taking false branch
6577 SpecifiedType =
6578 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6579
6580 // Compute the implicit exception specification.
6581 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6582 /*IsCXXMethod=*/true);
6583 FunctionProtoType::ExtProtoInfo EPI(CC);
6584 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6585 EPI.ExceptionSpec = IES.getExceptionSpec();
6586 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6587 Context.getFunctionType(Context.VoidTy, None, EPI));
6588
6589 // Ensure that it matches.
6590 CheckEquivalentExceptionSpec(
6591 PDiag(diag::err_incorrect_defaulted_exception_spec)
7
Calling 'operator<<'
20
Returned allocated memory
6592 << getSpecialMember(MD), PDiag(),
21
Calling 'Sema::PDiag'
6593 ImplicitType, SourceLocation(),
6594 SpecifiedType, MD->getLocation());
6595}
6596
6597void Sema::CheckDelayedMemberExceptionSpecs() {
6598 decltype(DelayedExceptionSpecChecks) Checks;
6599 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6600
6601 std::swap(Checks, DelayedExceptionSpecChecks);
6602 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6603
6604 // Perform any deferred checking of exception specifications for virtual
6605 // destructors.
6606 for (auto &Check : Checks)
2
Assuming '__begin1' is equal to '__end1'
6607 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6608
6609 // Check that any explicitly-defaulted methods have exception specifications
6610 // compatible with their implicit exception specifications.
6611 for (auto &Spec : Specs)
3
Assuming '__begin1' is not equal to '__end1'
6612 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
4
Calling 'Sema::CheckExplicitlyDefaultedMemberExceptionSpec'
6613}
6614
6615namespace {
6616/// CRTP base class for visiting operations performed by a special member
6617/// function (or inherited constructor).
6618template<typename Derived>
6619struct SpecialMemberVisitor {
6620 Sema &S;
6621 CXXMethodDecl *MD;
6622 Sema::CXXSpecialMember CSM;
6623 Sema::InheritedConstructorInfo *ICI;
6624
6625 // Properties of the special member, computed for convenience.
6626 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6627
6628 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6629 Sema::InheritedConstructorInfo *ICI)
6630 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6631 switch (CSM) {
6632 case Sema::CXXDefaultConstructor:
6633 case Sema::CXXCopyConstructor:
6634 case Sema::CXXMoveConstructor:
6635 IsConstructor = true;
6636 break;
6637 case Sema::CXXCopyAssignment:
6638 case Sema::CXXMoveAssignment:
6639 IsAssignment = true;
6640 break;
6641 case Sema::CXXDestructor:
6642 break;
6643 case Sema::CXXInvalid:
6644 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6644)
;
6645 }
6646
6647 if (MD->getNumParams()) {
6648 if (const ReferenceType *RT =
6649 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6650 ConstArg = RT->getPointeeType().isConstQualified();
6651 }
6652 }
6653
6654 Derived &getDerived() { return static_cast<Derived&>(*this); }
6655
6656 /// Is this a "move" special member?
6657 bool isMove() const {
6658 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6659 }
6660
6661 /// Look up the corresponding special member in the given class.
6662 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6663 unsigned Quals, bool IsMutable) {
6664 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6665 ConstArg && !IsMutable);
6666 }
6667
6668 /// Look up the constructor for the specified base class to see if it's
6669 /// overridden due to this being an inherited constructor.
6670 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6671 if (!ICI)
6672 return {};
6673 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6673, __extension__ __PRETTY_FUNCTION__))
;
6674 auto *BaseCtor =
6675 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6676 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6677 return MD;
6678 return {};
6679 }
6680
6681 /// A base or member subobject.
6682 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6683
6684 /// Get the location to use for a subobject in diagnostics.
6685 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6686 // FIXME: For an indirect virtual base, the direct base leading to
6687 // the indirect virtual base would be a more useful choice.
6688 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6689 return B->getBaseTypeLoc();
6690 else
6691 return Subobj.get<FieldDecl*>()->getLocation();
6692 }
6693
6694 enum BasesToVisit {
6695 /// Visit all non-virtual (direct) bases.
6696 VisitNonVirtualBases,
6697 /// Visit all direct bases, virtual or not.
6698 VisitDirectBases,
6699 /// Visit all non-virtual bases, and all virtual bases if the class
6700 /// is not abstract.
6701 VisitPotentiallyConstructedBases,
6702 /// Visit all direct or virtual bases.
6703 VisitAllBases
6704 };
6705
6706 // Visit the bases and members of the class.
6707 bool visit(BasesToVisit Bases) {
6708 CXXRecordDecl *RD = MD->getParent();
6709
6710 if (Bases == VisitPotentiallyConstructedBases)
6711 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6712
6713 for (auto &B : RD->bases())
6714 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6715 getDerived().visitBase(&B))
6716 return true;
6717
6718 if (Bases == VisitAllBases)
6719 for (auto &B : RD->vbases())
6720 if (getDerived().visitBase(&B))
6721 return true;
6722
6723 for (auto *F : RD->fields())
6724 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6725 getDerived().visitField(F))
6726 return true;
6727
6728 return false;
6729 }
6730};
6731}
6732
6733namespace {
6734struct SpecialMemberDeletionInfo
6735 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6736 bool Diagnose;
6737
6738 SourceLocation Loc;
6739
6740 bool AllFieldsAreConst;
6741
6742 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6743 Sema::CXXSpecialMember CSM,
6744 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6745 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6746 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6747
6748 bool inUnion() const { return MD->getParent()->isUnion(); }
6749
6750 Sema::CXXSpecialMember getEffectiveCSM() {
6751 return ICI ? Sema::CXXInvalid : CSM;
6752 }
6753
6754 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6755 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6756
6757 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6758 bool shouldDeleteForField(FieldDecl *FD);
6759 bool shouldDeleteForAllConstMembers();
6760
6761 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6762 unsigned Quals);
6763 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6764 Sema::SpecialMemberOverloadResult SMOR,
6765 bool IsDtorCallInCtor);
6766
6767 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6768};
6769}
6770
6771/// Is the given special member inaccessible when used on the given
6772/// sub-object.
6773bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6774 CXXMethodDecl *target) {
6775 /// If we're operating on a base class, the object type is the
6776 /// type of this special member.
6777 QualType objectTy;
6778 AccessSpecifier access = target->getAccess();
6779 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6780 objectTy = S.Context.getTypeDeclType(MD->getParent());
6781 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6782
6783 // If we're operating on a field, the object type is the type of the field.
6784 } else {
6785 objectTy = S.Context.getTypeDeclType(target->getParent());
6786 }
6787
6788 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6789}
6790
6791/// Check whether we should delete a special member due to the implicit
6792/// definition containing a call to a special member of a subobject.
6793bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6794 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6795 bool IsDtorCallInCtor) {
6796 CXXMethodDecl *Decl = SMOR.getMethod();
6797 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6798
6799 int DiagKind = -1;
6800
6801 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6802 DiagKind = !Decl ? 0 : 1;
6803 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6804 DiagKind = 2;
6805 else if (!isAccessible(Subobj, Decl))
6806 DiagKind = 3;
6807 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6808 !Decl->isTrivial()) {
6809 // A member of a union must have a trivial corresponding special member.
6810 // As a weird special case, a destructor call from a union's constructor
6811 // must be accessible and non-deleted, but need not be trivial. Such a
6812 // destructor is never actually called, but is semantically checked as
6813 // if it were.
6814 DiagKind = 4;
6815 }
6816
6817 if (DiagKind == -1)
6818 return false;
6819
6820 if (Diagnose) {
6821 if (Field) {
6822 S.Diag(Field->getLocation(),
6823 diag::note_deleted_special_member_class_subobject)
6824 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6825 << Field << DiagKind << IsDtorCallInCtor;
6826 } else {
6827 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6828 S.Diag(Base->getLocStart(),
6829 diag::note_deleted_special_member_class_subobject)
6830 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6831 << Base->getType() << DiagKind << IsDtorCallInCtor;
6832 }
6833
6834 if (DiagKind == 1)
6835 S.NoteDeletedFunction(Decl);
6836 // FIXME: Explain inaccessibility if DiagKind == 3.
6837 }
6838
6839 return true;
6840}
6841
6842/// Check whether we should delete a special member function due to having a
6843/// direct or virtual base class or non-static data member of class type M.
6844bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6845 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6846 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6847 bool IsMutable = Field && Field->isMutable();
6848
6849 // C++11 [class.ctor]p5:
6850 // -- any direct or virtual base class, or non-static data member with no
6851 // brace-or-equal-initializer, has class type M (or array thereof) and
6852 // either M has no default constructor or overload resolution as applied
6853 // to M's default constructor results in an ambiguity or in a function
6854 // that is deleted or inaccessible
6855 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6856 // -- a direct or virtual base class B that cannot be copied/moved because
6857 // overload resolution, as applied to B's corresponding special member,
6858 // results in an ambiguity or a function that is deleted or inaccessible
6859 // from the defaulted special member
6860 // C++11 [class.dtor]p5:
6861 // -- any direct or virtual base class [...] has a type with a destructor
6862 // that is deleted or inaccessible
6863 if (!(CSM == Sema::CXXDefaultConstructor &&
6864 Field && Field->hasInClassInitializer()) &&
6865 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6866 false))
6867 return true;
6868
6869 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6870 // -- any direct or virtual base class or non-static data member has a
6871 // type with a destructor that is deleted or inaccessible
6872 if (IsConstructor) {
6873 Sema::SpecialMemberOverloadResult SMOR =
6874 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6875 false, false, false, false, false);
6876 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6877 return true;
6878 }
6879
6880 return false;
6881}
6882
6883/// Check whether we should delete a special member function due to the class
6884/// having a particular direct or virtual base class.
6885bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6886 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6887 // If program is correct, BaseClass cannot be null, but if it is, the error
6888 // must be reported elsewhere.
6889 if (!BaseClass)
6890 return false;
6891 // If we have an inheriting constructor, check whether we're calling an
6892 // inherited constructor instead of a default constructor.
6893 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6894 if (auto *BaseCtor = SMOR.getMethod()) {
6895 // Note that we do not check access along this path; other than that,
6896 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6897 // FIXME: Check that the base has a usable destructor! Sink this into
6898 // shouldDeleteForClassSubobject.
6899 if (BaseCtor->isDeleted() && Diagnose) {
6900 S.Diag(Base->getLocStart(),
6901 diag::note_deleted_special_member_class_subobject)
6902 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6903 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6904 S.NoteDeletedFunction(BaseCtor);
6905 }
6906 return BaseCtor->isDeleted();
6907 }
6908 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6909}
6910
6911/// Check whether we should delete a special member function due to the class
6912/// having a particular non-static data member.
6913bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6914 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6915 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6916
6917 if (CSM == Sema::CXXDefaultConstructor) {
6918 // For a default constructor, all references must be initialized in-class
6919 // and, if a union, it must have a non-const member.
6920 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6921 if (Diagnose)
6922 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6923 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6924 return true;
6925 }
6926 // C++11 [class.ctor]p5: any non-variant non-static data member of
6927 // const-qualified type (or array thereof) with no
6928 // brace-or-equal-initializer does not have a user-provided default
6929 // constructor.
6930 if (!inUnion() && FieldType.isConstQualified() &&
6931 !FD->hasInClassInitializer() &&
6932 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6933 if (Diagnose)
6934 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6935 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6936 return true;
6937 }
6938
6939 if (inUnion() && !FieldType.isConstQualified())
6940 AllFieldsAreConst = false;
6941 } else if (CSM == Sema::CXXCopyConstructor) {
6942 // For a copy constructor, data members must not be of rvalue reference
6943 // type.
6944 if (FieldType->isRValueReferenceType()) {
6945 if (Diagnose)
6946 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6947 << MD->getParent() << FD << FieldType;
6948 return true;
6949 }
6950 } else if (IsAssignment) {
6951 // For an assignment operator, data members must not be of reference type.
6952 if (FieldType->isReferenceType()) {
6953 if (Diagnose)
6954 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6955 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6956 return true;
6957 }
6958 if (!FieldRecord && FieldType.isConstQualified()) {
6959 // C++11 [class.copy]p23:
6960 // -- a non-static data member of const non-class type (or array thereof)
6961 if (Diagnose)
6962 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6963 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6964 return true;
6965 }
6966 }
6967
6968 if (FieldRecord) {
6969 // Some additional restrictions exist on the variant members.
6970 if (!inUnion() && FieldRecord->isUnion() &&
6971 FieldRecord->isAnonymousStructOrUnion()) {
6972 bool AllVariantFieldsAreConst = true;
6973
6974 // FIXME: Handle anonymous unions declared within anonymous unions.
6975 for (auto *UI : FieldRecord->fields()) {
6976 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6977
6978 if (!UnionFieldType.isConstQualified())
6979 AllVariantFieldsAreConst = false;
6980
6981 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6982 if (UnionFieldRecord &&
6983 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6984 UnionFieldType.getCVRQualifiers()))
6985 return true;
6986 }
6987
6988 // At least one member in each anonymous union must be non-const
6989 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6990 !FieldRecord->field_empty()) {
6991 if (Diagnose)
6992 S.Diag(FieldRecord->getLocation(),
6993 diag::note_deleted_default_ctor_all_const)
6994 << !!ICI << MD->getParent() << /*anonymous union*/1;
6995 return true;
6996 }
6997
6998 // Don't check the implicit member of the anonymous union type.
6999 // This is technically non-conformant, but sanity demands it.
7000 return false;
7001 }
7002
7003 if (shouldDeleteForClassSubobject(FieldRecord, FD,
7004 FieldType.getCVRQualifiers()))
7005 return true;
7006 }
7007
7008 return false;
7009}
7010
7011/// C++11 [class.ctor] p5:
7012/// A defaulted default constructor for a class X is defined as deleted if
7013/// X is a union and all of its variant members are of const-qualified type.
7014bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7015 // This is a silly definition, because it gives an empty union a deleted
7016 // default constructor. Don't do that.
7017 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7018 bool AnyFields = false;
7019 for (auto *F : MD->getParent()->fields())
7020 if ((AnyFields = !F->isUnnamedBitfield()))
7021 break;
7022 if (!AnyFields)
7023 return false;
7024 if (Diagnose)
7025 S.Diag(MD->getParent()->getLocation(),
7026 diag::note_deleted_default_ctor_all_const)
7027 << !!ICI << MD->getParent() << /*not anonymous union*/0;
7028 return true;
7029 }
7030 return false;
7031}
7032
7033/// Determine whether a defaulted special member function should be defined as
7034/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7035/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7036bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7037 InheritedConstructorInfo *ICI,
7038 bool Diagnose) {
7039 if (MD->isInvalidDecl())
7040 return false;
7041 CXXRecordDecl *RD = MD->getParent();
7042 assert(!RD->isDependentType() && "do deletion after instantiation")(static_cast <bool> (!RD->isDependentType() &&
"do deletion after instantiation") ? void (0) : __assert_fail
("!RD->isDependentType() && \"do deletion after instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7042, __extension__ __PRETTY_FUNCTION__))
;
7043 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7044 return false;
7045
7046 // C++11 [expr.lambda.prim]p19:
7047 // The closure type associated with a lambda-expression has a
7048 // deleted (8.4.3) default constructor and a deleted copy
7049 // assignment operator.
7050 if (RD->isLambda() &&
7051 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7052 if (Diagnose)
7053 Diag(RD->getLocation(), diag::note_lambda_decl);
7054 return true;
7055 }
7056
7057 // For an anonymous struct or union, the copy and assignment special members
7058 // will never be used, so skip the check. For an anonymous union declared at
7059 // namespace scope, the constructor and destructor are used.
7060 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7061 RD->isAnonymousStructOrUnion())
7062 return false;
7063
7064 // C++11 [class.copy]p7, p18:
7065 // If the class definition declares a move constructor or move assignment
7066 // operator, an implicitly declared copy constructor or copy assignment
7067 // operator is defined as deleted.
7068 if (MD->isImplicit() &&
7069 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7070 CXXMethodDecl *UserDeclaredMove = nullptr;
7071
7072 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7073 // deletion of the corresponding copy operation, not both copy operations.
7074 // MSVC 2015 has adopted the standards conforming behavior.
7075 bool DeletesOnlyMatchingCopy =
7076 getLangOpts().MSVCCompat &&
7077 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7078
7079 if (RD->hasUserDeclaredMoveConstructor() &&
7080 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7081 if (!Diagnose) return true;
7082
7083 // Find any user-declared move constructor.
7084 for (auto *I : RD->ctors()) {
7085 if (I->isMoveConstructor()) {
7086 UserDeclaredMove = I;
7087 break;
7088 }
7089 }
7090 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7090, __extension__ __PRETTY_FUNCTION__))
;
7091 } else if (RD->hasUserDeclaredMoveAssignment() &&
7092 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7093 if (!Diagnose) return true;
7094
7095 // Find any user-declared move assignment operator.
7096 for (auto *I : RD->methods()) {
7097 if (I->isMoveAssignmentOperator()) {
7098 UserDeclaredMove = I;
7099 break;
7100 }
7101 }
7102 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7102, __extension__ __PRETTY_FUNCTION__))
;
7103 }
7104
7105 if (UserDeclaredMove) {
7106 Diag(UserDeclaredMove->getLocation(),
7107 diag::note_deleted_copy_user_declared_move)
7108 << (CSM == CXXCopyAssignment) << RD
7109 << UserDeclaredMove->isMoveAssignmentOperator();
7110 return true;
7111 }
7112 }
7113
7114 // Do access control from the special member function
7115 ContextRAII MethodContext(*this, MD);
7116
7117 // C++11 [class.dtor]p5:
7118 // -- for a virtual destructor, lookup of the non-array deallocation function
7119 // results in an ambiguity or in a function that is deleted or inaccessible
7120 if (CSM == CXXDestructor && MD->isVirtual()) {
7121 FunctionDecl *OperatorDelete = nullptr;
7122 DeclarationName Name =
7123 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7124 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7125 OperatorDelete, /*Diagnose*/false)) {
7126 if (Diagnose)
7127 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7128 return true;
7129 }
7130 }
7131
7132 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7133
7134 // Per DR1611, do not consider virtual bases of constructors of abstract
7135 // classes, since we are not going to construct them.
7136 // Per DR1658, do not consider virtual bases of destructors of abstract
7137 // classes either.
7138 // Per DR2180, for assignment operators we only assign (and thus only
7139 // consider) direct bases.
7140 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7141 : SMI.VisitPotentiallyConstructedBases))
7142 return true;
7143
7144 if (SMI.shouldDeleteForAllConstMembers())
7145 return true;
7146
7147 if (getLangOpts().CUDA) {
7148 // We should delete the special member in CUDA mode if target inference
7149 // failed.
7150 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7151 Diagnose);
7152 }
7153
7154 return false;
7155}
7156
7157/// Perform lookup for a special member of the specified kind, and determine
7158/// whether it is trivial. If the triviality can be determined without the
7159/// lookup, skip it. This is intended for use when determining whether a
7160/// special member of a containing object is trivial, and thus does not ever
7161/// perform overload resolution for default constructors.
7162///
7163/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7164/// member that was most likely to be intended to be trivial, if any.
7165///
7166/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7167/// determine whether the special member is trivial.
7168static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7169 Sema::CXXSpecialMember CSM, unsigned Quals,
7170 bool ConstRHS,
7171 Sema::TrivialABIHandling TAH,
7172 CXXMethodDecl **Selected) {
7173 if (Selected)
7174 *Selected = nullptr;
7175
7176 switch (CSM) {
7177 case Sema::CXXInvalid:
7178 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7178)
;
7179
7180 case Sema::CXXDefaultConstructor:
7181 // C++11 [class.ctor]p5:
7182 // A default constructor is trivial if:
7183 // - all the [direct subobjects] have trivial default constructors
7184 //
7185 // Note, no overload resolution is performed in this case.
7186 if (RD->hasTrivialDefaultConstructor())
7187 return true;
7188
7189 if (Selected) {
7190 // If there's a default constructor which could have been trivial, dig it
7191 // out. Otherwise, if there's any user-provided default constructor, point
7192 // to that as an example of why there's not a trivial one.
7193 CXXConstructorDecl *DefCtor = nullptr;
7194 if (RD->needsImplicitDefaultConstructor())
7195 S.DeclareImplicitDefaultConstructor(RD);
7196 for (auto *CI : RD->ctors()) {
7197 if (!CI->isDefaultConstructor())
7198 continue;
7199 DefCtor = CI;
7200 if (!DefCtor->isUserProvided())
7201 break;
7202 }
7203
7204 *Selected = DefCtor;
7205 }
7206
7207 return false;
7208
7209 case Sema::CXXDestructor:
7210 // C++11 [class.dtor]p5:
7211 // A destructor is trivial if:
7212 // - all the direct [subobjects] have trivial destructors
7213 if (RD->hasTrivialDestructor() ||
7214 (TAH == Sema::TAH_ConsiderTrivialABI &&
7215 RD->hasTrivialDestructorForCall()))
7216 return true;
7217
7218 if (Selected) {
7219 if (RD->needsImplicitDestructor())
7220 S.DeclareImplicitDestructor(RD);
7221 *Selected = RD->getDestructor();
7222 }
7223
7224 return false;
7225
7226 case Sema::CXXCopyConstructor:
7227 // C++11 [class.copy]p12:
7228 // A copy constructor is trivial if:
7229 // - the constructor selected to copy each direct [subobject] is trivial
7230 if (RD->hasTrivialCopyConstructor() ||
7231 (TAH == Sema::TAH_ConsiderTrivialABI &&
7232 RD->hasTrivialCopyConstructorForCall())) {
7233 if (Quals == Qualifiers::Const)
7234 // We must either select the trivial copy constructor or reach an
7235 // ambiguity; no need to actually perform overload resolution.
7236 return true;
7237 } else if (!Selected) {
7238 return false;
7239 }
7240 // In C++98, we are not supposed to perform overload resolution here, but we
7241 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7242 // cases like B as having a non-trivial copy constructor:
7243 // struct A { template<typename T> A(T&); };
7244 // struct B { mutable A a; };
7245 goto NeedOverloadResolution;
7246
7247 case Sema::CXXCopyAssignment:
7248 // C++11 [class.copy]p25:
7249 // A copy assignment operator is trivial if:
7250 // - the assignment operator selected to copy each direct [subobject] is
7251 // trivial
7252 if (RD->hasTrivialCopyAssignment()) {
7253 if (Quals == Qualifiers::Const)
7254 return true;
7255 } else if (!Selected) {
7256 return false;
7257 }
7258 // In C++98, we are not supposed to perform overload resolution here, but we
7259 // treat that as a language defect.
7260 goto NeedOverloadResolution;
7261
7262 case Sema::CXXMoveConstructor:
7263 case Sema::CXXMoveAssignment:
7264 NeedOverloadResolution:
7265 Sema::SpecialMemberOverloadResult SMOR =
7266 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7267
7268 // The standard doesn't describe how to behave if the lookup is ambiguous.
7269 // We treat it as not making the member non-trivial, just like the standard
7270 // mandates for the default constructor. This should rarely matter, because
7271 // the member will also be deleted.
7272 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7273 return true;
7274
7275 if (!SMOR.getMethod()) {
7276 assert(SMOR.getKind() ==(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7277, __extension__ __PRETTY_FUNCTION__))
7277 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7277, __extension__ __PRETTY_FUNCTION__))
;
7278 return false;
7279 }
7280
7281 // We deliberately don't check if we found a deleted special member. We're
7282 // not supposed to!
7283 if (Selected)
7284 *Selected = SMOR.getMethod();
7285
7286 if (TAH == Sema::TAH_ConsiderTrivialABI &&
7287 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7288 return SMOR.getMethod()->isTrivialForCall();
7289 return SMOR.getMethod()->isTrivial();
7290 }
7291
7292 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7292)
;
7293}
7294
7295static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7296 for (auto *CI : RD->ctors())
7297 if (!CI->isImplicit())
7298 return CI;
7299
7300 // Look for constructor templates.
7301 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7302 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7303 if (CXXConstructorDecl *CD =
7304 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7305 return CD;
7306 }
7307
7308 return nullptr;
7309}
7310
7311/// The kind of subobject we are checking for triviality. The values of this
7312/// enumeration are used in diagnostics.
7313enum TrivialSubobjectKind {
7314 /// The subobject is a base class.
7315 TSK_BaseClass,
7316 /// The subobject is a non-static data member.
7317 TSK_Field,
7318 /// The object is actually the complete object.
7319 TSK_CompleteObject
7320};
7321
7322/// Check whether the special member selected for a given type would be trivial.
7323static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7324 QualType SubType, bool ConstRHS,
7325 Sema::CXXSpecialMember CSM,
7326 TrivialSubobjectKind Kind,
7327 Sema::TrivialABIHandling TAH, bool Diagnose) {
7328 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7329 if (!SubRD)
7330 return true;
7331
7332 CXXMethodDecl *Selected;
7333 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7334 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7335 return true;
7336
7337 if (Diagnose) {
7338 if (ConstRHS)
7339 SubType.addConst();
7340
7341 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7342 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7343 << Kind << SubType.getUnqualifiedType();
7344 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7345 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7346 } else if (!Selected)
7347 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7348 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7349 else if (Selected->isUserProvided()) {
7350 if (Kind == TSK_CompleteObject)
7351 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7352 << Kind << SubType.getUnqualifiedType() << CSM;
7353 else {
7354 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7355 << Kind << SubType.getUnqualifiedType() << CSM;
7356 S.Diag(Selected->getLocation(), diag::note_declared_at);
7357 }
7358 } else {
7359 if (Kind != TSK_CompleteObject)
7360 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7361 << Kind << SubType.getUnqualifiedType() << CSM;
7362
7363 // Explain why the defaulted or deleted special member isn't trivial.
7364 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7365 Diagnose);
7366 }
7367 }
7368
7369 return false;
7370}
7371
7372/// Check whether the members of a class type allow a special member to be
7373/// trivial.
7374static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7375 Sema::CXXSpecialMember CSM,
7376 bool ConstArg,
7377 Sema::TrivialABIHandling TAH,
7378 bool Diagnose) {
7379 for (const auto *FI : RD->fields()) {
7380 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7381 continue;
7382
7383 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7384
7385 // Pretend anonymous struct or union members are members of this class.
7386 if (FI->isAnonymousStructOrUnion()) {
7387 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7388 CSM, ConstArg, TAH, Diagnose))
7389 return false;
7390 continue;
7391 }
7392
7393 // C++11 [class.ctor]p5:
7394 // A default constructor is trivial if [...]
7395 // -- no non-static data member of its class has a
7396 // brace-or-equal-initializer
7397 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7398 if (Diagnose)
7399 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7400 return false;
7401 }
7402
7403 // Objective C ARC 4.3.5:
7404 // [...] nontrivally ownership-qualified types are [...] not trivially
7405 // default constructible, copy constructible, move constructible, copy
7406 // assignable, move assignable, or destructible [...]
7407 if (FieldType.hasNonTrivialObjCLifetime()) {
7408 if (Diagnose)
7409 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7410 << RD << FieldType.getObjCLifetime();
7411 return false;
7412 }
7413
7414 bool ConstRHS = ConstArg && !FI->isMutable();
7415 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7416 CSM, TSK_Field, TAH, Diagnose))
7417 return false;
7418 }
7419
7420 return true;
7421}
7422
7423/// Diagnose why the specified class does not have a trivial special member of
7424/// the given kind.
7425void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7426 QualType Ty = Context.getRecordType(RD);
7427
7428 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7429 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7430 TSK_CompleteObject, TAH_IgnoreTrivialABI,
7431 /*Diagnose*/true);
7432}
7433
7434/// Determine whether a defaulted or deleted special member function is trivial,
7435/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7436/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7437bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7438 TrivialABIHandling TAH, bool Diagnose) {
7439 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")(static_cast <bool> (!MD->isUserProvided() &&
CSM != CXXInvalid && "not special enough") ? void (0
) : __assert_fail ("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7439, __extension__ __PRETTY_FUNCTION__))
;
7440
7441 CXXRecordDecl *RD = MD->getParent();
7442
7443 bool ConstArg = false;
7444
7445 // C++11 [class.copy]p12, p25: [DR1593]
7446 // A [special member] is trivial if [...] its parameter-type-list is
7447 // equivalent to the parameter-type-list of an implicit declaration [...]
7448 switch (CSM) {
7449 case CXXDefaultConstructor:
7450 case CXXDestructor:
7451 // Trivial default constructors and destructors cannot have parameters.
7452 break;
7453
7454 case CXXCopyConstructor:
7455 case CXXCopyAssignment: {
7456 // Trivial copy operations always have const, non-volatile parameter types.
7457 ConstArg = true;
7458 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7459 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7460 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7461 if (Diagnose)
7462 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7463 << Param0->getSourceRange() << Param0->getType()
7464 << Context.getLValueReferenceType(
7465 Context.getRecordType(RD).withConst());
7466 return false;
7467 }
7468 break;
7469 }
7470
7471 case CXXMoveConstructor:
7472 case CXXMoveAssignment: {
7473 // Trivial move operations always have non-cv-qualified parameters.
7474 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7475 const RValueReferenceType *RT =
7476 Param0->getType()->getAs<RValueReferenceType>();
7477 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7478 if (Diagnose)
7479 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7480 << Param0->getSourceRange() << Param0->getType()
7481 << Context.getRValueReferenceType(Context.getRecordType(RD));
7482 return false;
7483 }
7484 break;
7485 }
7486
7487 case CXXInvalid:
7488 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7488)
;
7489 }
7490
7491 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7492 if (Diagnose)
7493 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7494 diag::note_nontrivial_default_arg)
7495 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7496 return false;
7497 }
7498 if (MD->isVariadic()) {
7499 if (Diagnose)
7500 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7501 return false;
7502 }
7503
7504 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7505 // A copy/move [constructor or assignment operator] is trivial if
7506 // -- the [member] selected to copy/move each direct base class subobject
7507 // is trivial
7508 //
7509 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7510 // A [default constructor or destructor] is trivial if
7511 // -- all the direct base classes have trivial [default constructors or
7512 // destructors]
7513 for (const auto &BI : RD->bases())
7514 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7515 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7516 return false;
7517
7518 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7519 // A copy/move [constructor or assignment operator] for a class X is
7520 // trivial if
7521 // -- for each non-static data member of X that is of class type (or array
7522 // thereof), the constructor selected to copy/move that member is
7523 // trivial
7524 //
7525 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7526 // A [default constructor or destructor] is trivial if
7527 // -- for all of the non-static data members of its class that are of class
7528 // type (or array thereof), each such class has a trivial [default
7529 // constructor or destructor]
7530 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7531 return false;
7532
7533 // C++11 [class.dtor]p5:
7534 // A destructor is trivial if [...]
7535 // -- the destructor is not virtual
7536 if (CSM == CXXDestructor && MD->isVirtual()) {
7537 if (Diagnose)
7538 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7539 return false;
7540 }
7541
7542 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7543 // A [special member] for class X is trivial if [...]
7544 // -- class X has no virtual functions and no virtual base classes
7545 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7546 if (!Diagnose)
7547 return false;
7548
7549 if (RD->getNumVBases()) {
7550 // Check for virtual bases. We already know that the corresponding
7551 // member in all bases is trivial, so vbases must all be direct.
7552 CXXBaseSpecifier &BS = *RD->vbases_begin();
7553 assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail
("BS.isVirtual()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7553, __extension__ __PRETTY_FUNCTION__))
;
7554 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7555 return false;
7556 }
7557
7558 // Must have a virtual method.
7559 for (const auto *MI : RD->methods()) {
7560 if (MI->isVirtual()) {
7561 SourceLocation MLoc = MI->getLocStart();
7562 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7563 return false;
7564 }
7565 }
7566
7567 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7567)
;
7568 }
7569
7570 // Looks like it's trivial!
7571 return true;
7572}
7573
7574namespace {
7575struct FindHiddenVirtualMethod {
7576 Sema *S;
7577 CXXMethodDecl *Method;
7578 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7579 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7580
7581private:
7582 /// Check whether any most overriden method from MD in Methods
7583 static bool CheckMostOverridenMethods(
7584 const CXXMethodDecl *MD,
7585 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7586 if (MD->size_overridden_methods() == 0)
7587 return Methods.count(MD->getCanonicalDecl());
7588 for (const CXXMethodDecl *O : MD->overridden_methods())
7589 if (CheckMostOverridenMethods(O, Methods))
7590 return true;
7591 return false;
7592 }
7593
7594public:
7595 /// Member lookup function that determines whether a given C++
7596 /// method overloads virtual methods in a base class without overriding any,
7597 /// to be used with CXXRecordDecl::lookupInBases().
7598 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7599 RecordDecl *BaseRecord =
7600 Specifier->getType()->getAs<RecordType>()->getDecl();
7601
7602 DeclarationName Name = Method->getDeclName();
7603 assert(Name.getNameKind() == DeclarationName::Identifier)(static_cast <bool> (Name.getNameKind() == DeclarationName
::Identifier) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7603, __extension__ __PRETTY_FUNCTION__))
;
7604
7605 bool foundSameNameMethod = false;
7606 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7607 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7608 Path.Decls = Path.Decls.slice(1)) {
7609 NamedDecl *D = Path.Decls.front();
7610 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7611 MD = MD->getCanonicalDecl();
7612 foundSameNameMethod = true;
7613 // Interested only in hidden virtual methods.
7614 if (!MD->isVirtual())
7615 continue;
7616 // If the method we are checking overrides a method from its base
7617 // don't warn about the other overloaded methods. Clang deviates from
7618 // GCC by only diagnosing overloads of inherited virtual functions that
7619 // do not override any other virtual functions in the base. GCC's
7620 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7621 // function from a base class. These cases may be better served by a
7622 // warning (not specific to virtual functions) on call sites when the
7623 // call would select a different function from the base class, were it
7624 // visible.
7625 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7626 if (!S->IsOverload(Method, MD, false))
7627 return true;
7628 // Collect the overload only if its hidden.
7629 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7630 overloadedMethods.push_back(MD);
7631 }
7632 }
7633
7634 if (foundSameNameMethod)
7635 OverloadedMethods.append(overloadedMethods.begin(),
7636 overloadedMethods.end());
7637 return foundSameNameMethod;
7638 }
7639};
7640} // end anonymous namespace
7641
7642/// \brief Add the most overriden methods from MD to Methods
7643static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7644 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7645 if (MD->size_overridden_methods() == 0)
7646 Methods.insert(MD->getCanonicalDecl());
7647 else
7648 for (const CXXMethodDecl *O : MD->overridden_methods())
7649 AddMostOverridenMethods(O, Methods);
7650}
7651
7652/// \brief Check if a method overloads virtual methods in a base class without
7653/// overriding any.
7654void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7655 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7656 if (!MD->getDeclName().isIdentifier())
7657 return;
7658
7659 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7660 /*bool RecordPaths=*/false,
7661 /*bool DetectVirtual=*/false);
7662 FindHiddenVirtualMethod FHVM;
7663 FHVM.Method = MD;
7664 FHVM.S = this;
7665
7666 // Keep the base methods that were overriden or introduced in the subclass
7667 // by 'using' in a set. A base method not in this set is hidden.
7668 CXXRecordDecl *DC = MD->getParent();
7669 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7670 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7671 NamedDecl *ND = *I;
7672 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7673 ND = shad->getTargetDecl();
7674 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7675 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7676 }
7677
7678 if (DC->lookupInBases(FHVM, Paths))
7679 OverloadedMethods = FHVM.OverloadedMethods;
7680}
7681
7682void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7683 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7684 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7685 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7686 PartialDiagnostic PD = PDiag(
7687 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7688 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7689 Diag(overloadedMD->getLocation(), PD);
7690 }
7691}
7692
7693/// \brief Diagnose methods which overload virtual methods in a base class
7694/// without overriding any.
7695void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7696 if (MD->isInvalidDecl())
7697 return;
7698
7699 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7700 return;
7701
7702 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7703 FindHiddenVirtualMethods(MD, OverloadedMethods);
7704 if (!OverloadedMethods.empty()) {
7705 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7706 << MD << (OverloadedMethods.size() > 1);
7707
7708 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7709 }
7710}
7711
7712void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7713 auto PrintDiagAndRemoveAttr = [&]() {
7714 // No diagnostics if this is a template instantiation.
7715 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7716 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7717 diag::ext_cannot_use_trivial_abi) << &RD;
7718 RD.dropAttr<TrivialABIAttr>();
7719 };
7720
7721 // Ill-formed if the struct has virtual functions.
7722 if (RD.isPolymorphic()) {
7723 PrintDiagAndRemoveAttr();
7724 return;
7725 }
7726
7727 for (const auto &B : RD.bases()) {
7728 // Ill-formed if the base class is non-trivial for the purpose of calls or a
7729 // virtual base.
7730 if ((!B.getType()->isDependentType() &&
7731 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7732 B.isVirtual()) {
7733 PrintDiagAndRemoveAttr();
7734 return;
7735 }
7736 }
7737
7738 for (const auto *FD : RD.fields()) {
7739 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7740 // non-trivial for the purpose of calls.
7741 QualType FT = FD->getType();
7742 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7743 PrintDiagAndRemoveAttr();
7744 return;
7745 }
7746
7747 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7748 if (!RT->isDependentType() &&
7749 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7750 PrintDiagAndRemoveAttr();
7751 return;
7752 }
7753 }
7754}
7755
7756void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7757 Decl *TagDecl,
7758 SourceLocation LBrac,
7759 SourceLocation RBrac,
7760 AttributeList *AttrList) {
7761 if (!TagDecl)
7762 return;
7763
7764 AdjustDeclIfTemplate(TagDecl);
7765
7766 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7767 if (l->getKind() != AttributeList::AT_Visibility)
7768 continue;
7769 l->setInvalid();
7770 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7771 l->getName();
7772 }
7773
7774 // See if trivial_abi has to be dropped.
7775 auto *RD = dyn_cast<CXXRecordDecl>(TagDecl);
7776 if (RD && RD->hasAttr<TrivialABIAttr>())
7777 checkIllFormedTrivialABIStruct(*RD);
7778
7779 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7780 // strict aliasing violation!
7781 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7782 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7783
7784 CheckCompletedCXXClass(RD);
7785}
7786
7787/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7788/// special functions, such as the default constructor, copy
7789/// constructor, or destructor, to the given C++ class (C++
7790/// [special]p1). This routine can only be executed just before the
7791/// definition of the class is complete.
7792void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7793 if (ClassDecl->needsImplicitDefaultConstructor()) {
7794 ++ASTContext::NumImplicitDefaultConstructors;
7795
7796 if (ClassDecl->hasInheritedConstructor())
7797 DeclareImplicitDefaultConstructor(ClassDecl);
7798 }
7799
7800 if (ClassDecl->needsImplicitCopyConstructor()) {
7801 ++ASTContext::NumImplicitCopyConstructors;
7802
7803 // If the properties or semantics of the copy constructor couldn't be
7804 // determined while the class was being declared, force a declaration
7805 // of it now.
7806 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7807 ClassDecl->hasInheritedConstructor())
7808 DeclareImplicitCopyConstructor(ClassDecl);
7809 // For the MS ABI we need to know whether the copy ctor is deleted. A
7810 // prerequisite for deleting the implicit copy ctor is that the class has a
7811 // move ctor or move assignment that is either user-declared or whose
7812 // semantics are inherited from a subobject. FIXME: We should provide a more
7813 // direct way for CodeGen to ask whether the constructor was deleted.
7814 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7815 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7816 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7817 ClassDecl->hasUserDeclaredMoveAssignment() ||
7818 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7819 DeclareImplicitCopyConstructor(ClassDecl);
7820 }
7821
7822 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7823 ++ASTContext::NumImplicitMoveConstructors;
7824
7825 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7826 ClassDecl->hasInheritedConstructor())
7827 DeclareImplicitMoveConstructor(ClassDecl);
7828 }
7829
7830 if (ClassDecl->needsImplicitCopyAssignment()) {
7831 ++ASTContext::NumImplicitCopyAssignmentOperators;
7832
7833 // If we have a dynamic class, then the copy assignment operator may be
7834 // virtual, so we have to declare it immediately. This ensures that, e.g.,
7835 // it shows up in the right place in the vtable and that we diagnose
7836 // problems with the implicit exception specification.
7837 if (ClassDecl->isDynamicClass() ||
7838 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7839 ClassDecl->hasInheritedAssignment())
7840 DeclareImplicitCopyAssignment(ClassDecl);
7841 }
7842
7843 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7844 ++ASTContext::NumImplicitMoveAssignmentOperators;
7845
7846 // Likewise for the move assignment operator.
7847 if (ClassDecl->isDynamicClass() ||
7848 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7849 ClassDecl->hasInheritedAssignment())
7850 DeclareImplicitMoveAssignment(ClassDecl);
7851 }
7852
7853 if (ClassDecl->needsImplicitDestructor()) {
7854 ++ASTContext::NumImplicitDestructors;
7855
7856 // If we have a dynamic class, then the destructor may be virtual, so we
7857 // have to declare the destructor immediately. This ensures that, e.g., it
7858 // shows up in the right place in the vtable and that we diagnose problems
7859 // with the implicit exception specification.
7860 if (ClassDecl->isDynamicClass() ||
7861 ClassDecl->needsOverloadResolutionForDestructor())
7862 DeclareImplicitDestructor(ClassDecl);
7863 }
7864}
7865
7866unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7867 if (!D)
7868 return 0;
7869
7870 // The order of template parameters is not important here. All names
7871 // get added to the same scope.
7872 SmallVector<TemplateParameterList *, 4> ParameterLists;
7873
7874 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7875 D = TD->getTemplatedDecl();
7876
7877 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7878 ParameterLists.push_back(PSD->getTemplateParameters());
7879
7880 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7881 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7882 ParameterLists.push_back(DD->getTemplateParameterList(i));
7883
7884 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7885 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7886 ParameterLists.push_back(FTD->getTemplateParameters());
7887 }
7888 }
7889
7890 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7891 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7892 ParameterLists.push_back(TD->getTemplateParameterList(i));
7893
7894 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7895 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7896 ParameterLists.push_back(CTD->getTemplateParameters());
7897 }
7898 }
7899
7900 unsigned Count = 0;
7901 for (TemplateParameterList *Params : ParameterLists) {
7902 if (Params->size() > 0)
7903 // Ignore explicit specializations; they don't contribute to the template
7904 // depth.
7905 ++Count;
7906 for (NamedDecl *Param : *Params) {
7907 if (Param->getDeclName()) {
7908 S->AddDecl(Param);
7909 IdResolver.AddDecl(Param);
7910 }
7911 }
7912 }
7913
7914 return Count;
7915}
7916
7917void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7918 if (!RecordD) return;
7919 AdjustDeclIfTemplate(RecordD);
7920 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7921 PushDeclContext(S, Record);
7922}
7923
7924void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7925 if (!RecordD) return;
7926 PopDeclContext();
7927}
7928
7929/// This is used to implement the constant expression evaluation part of the
7930/// attribute enable_if extension. There is nothing in standard C++ which would
7931/// require reentering parameters.
7932void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7933 if (!Param)
7934 return;
7935
7936 S->AddDecl(Param);
7937 if (Param->getDeclName())
7938 IdResolver.AddDecl(Param);
7939}
7940
7941/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7942/// parsing a top-level (non-nested) C++ class, and we are now
7943/// parsing those parts of the given Method declaration that could
7944/// not be parsed earlier (C++ [class.mem]p2), such as default
7945/// arguments. This action should enter the scope of the given
7946/// Method declaration as if we had just parsed the qualified method
7947/// name. However, it should not bring the parameters into scope;
7948/// that will be performed by ActOnDelayedCXXMethodParameter.
7949void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7950}
7951
7952/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7953/// C++ method declaration. We're (re-)introducing the given
7954/// function parameter into scope for use in parsing later parts of
7955/// the method declaration. For example, we could see an
7956/// ActOnParamDefaultArgument event for this parameter.
7957void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7958 if (!ParamD)
7959 return;
7960
7961 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7962
7963 // If this parameter has an unparsed default argument, clear it out
7964 // to make way for the parsed default argument.
7965 if (Param->hasUnparsedDefaultArg())
7966 Param->setDefaultArg(nullptr);
7967
7968 S->AddDecl(Param);
7969 if (Param->getDeclName())
7970 IdResolver.AddDecl(Param);
7971}
7972
7973/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7974/// processing the delayed method declaration for Method. The method
7975/// declaration is now considered finished. There may be a separate
7976/// ActOnStartOfFunctionDef action later (not necessarily
7977/// immediately!) for this method, if it was also defined inside the
7978/// class body.
7979void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7980 if (!MethodD)
7981 return;
7982
7983 AdjustDeclIfTemplate(MethodD);
7984
7985 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7986
7987 // Now that we have our default arguments, check the constructor
7988 // again. It could produce additional diagnostics or affect whether
7989 // the class has implicitly-declared destructors, among other
7990 // things.
7991 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7992 CheckConstructor(Constructor);
7993
7994 // Check the default arguments, which we may have added.
7995 if (!Method->isInvalidDecl())
7996 CheckCXXDefaultArguments(Method);
7997}
7998
7999/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8000/// the well-formedness of the constructor declarator @p D with type @p
8001/// R. If there are any errors in the declarator, this routine will
8002/// emit diagnostics and set the invalid bit to true. In any case, the type
8003/// will be updated to reflect a well-formed type for the constructor and
8004/// returned.
8005QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8006 StorageClass &SC) {
8007 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8008
8009 // C++ [class.ctor]p3:
8010 // A constructor shall not be virtual (10.3) or static (9.4). A
8011 // constructor can be invoked for a const, volatile or const
8012 // volatile object. A constructor shall not be declared const,
8013 // volatile, or const volatile (9.3.2).
8014 if (isVirtual) {
8015 if (!D.isInvalidType())
8016 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8017 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8018 << SourceRange(D.getIdentifierLoc());
8019 D.setInvalidType();
8020 }
8021 if (SC == SC_Static) {
8022 if (!D.isInvalidType())
8023 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8024 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8025 << SourceRange(D.getIdentifierLoc());
8026 D.setInvalidType();
8027 SC = SC_None;
8028 }
8029
8030 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8031 diagnoseIgnoredQualifiers(
8032 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8033 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8034 D.getDeclSpec().getRestrictSpecLoc(),
8035 D.getDeclSpec().getAtomicSpecLoc());
8036 D.setInvalidType();
8037 }
8038
8039 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8040 if (FTI.TypeQuals != 0) {
8041 if (FTI.TypeQuals & Qualifiers::Const)
8042 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8043 << "const" << SourceRange(D.getIdentifierLoc());
8044 if (FTI.TypeQuals & Qualifiers::Volatile)
8045 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8046 << "volatile" << SourceRange(D.getIdentifierLoc());
8047 if (FTI.TypeQuals & Qualifiers::Restrict)
8048 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
8049 << "restrict" << SourceRange(D.getIdentifierLoc());
8050 D.setInvalidType();
8051 }
8052
8053 // C++0x [class.ctor]p4:
8054 // A constructor shall not be declared with a ref-qualifier.
8055 if (FTI.hasRefQualifier()) {
8056 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8057 << FTI.RefQualifierIsLValueRef
8058 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8059 D.setInvalidType();
8060 }
8061
8062 // Rebuild the function type "R" without any type qualifiers (in
8063 // case any of the errors above fired) and with "void" as the
8064 // return type, since constructors don't have return types.
8065 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8066 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8067 return R;
8068
8069 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8070 EPI.TypeQuals = 0;
8071 EPI.RefQualifier = RQ_None;
8072
8073 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8074}
8075
8076/// CheckConstructor - Checks a fully-formed constructor for
8077/// well-formedness, issuing any diagnostics required. Returns true if
8078/// the constructor declarator is invalid.
8079void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8080 CXXRecordDecl *ClassDecl
8081 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8082 if (!ClassDecl)
8083 return Constructor->setInvalidDecl();
8084
8085 // C++ [class.copy]p3:
8086 // A declaration of a constructor for a class X is ill-formed if
8087 // its first parameter is of type (optionally cv-qualified) X and
8088 // either there are no other parameters or else all other
8089 // parameters have default arguments.
8090 if (!Constructor->isInvalidDecl() &&
8091 ((Constructor->getNumParams() == 1) ||
8092 (Constructor->getNumParams() > 1 &&
8093 Constructor->getParamDecl(1)->hasDefaultArg())) &&
8094 Constructor->getTemplateSpecializationKind()
8095 != TSK_ImplicitInstantiation) {
8096 QualType ParamType = Constructor->getParamDecl(0)->getType();
8097 QualType ClassTy = Context.getTagDeclType(ClassDecl);
8098 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8099 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8100 const char *ConstRef
8101 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8102 : " const &";
8103 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8104 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8105
8106 // FIXME: Rather that making the constructor invalid, we should endeavor
8107 // to fix the type.
8108 Constructor->setInvalidDecl();
8109 }
8110 }
8111}
8112
8113/// CheckDestructor - Checks a fully-formed destructor definition for
8114/// well-formedness, issuing any diagnostics required. Returns true
8115/// on error.
8116bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8117 CXXRecordDecl *RD = Destructor->getParent();
8118
8119 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8120 SourceLocation Loc;
8121
8122 if (!Destructor->isImplicit())
8123 Loc = Destructor->getLocation();
8124 else
8125 Loc = RD->getLocation();
8126
8127 // If we have a virtual destructor, look up the deallocation function
8128 if (FunctionDecl *OperatorDelete =
8129 FindDeallocationFunctionForDestructor(Loc, RD)) {
8130 Expr *ThisArg = nullptr;
8131
8132 // If the notional 'delete this' expression requires a non-trivial
8133 // conversion from 'this' to the type of a destroying operator delete's
8134 // first parameter, perform that conversion now.
8135 if (OperatorDelete->isDestroyingOperatorDelete()) {
8136 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8137 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8138 // C++ [class.dtor]p13:
8139 // ... as if for the expression 'delete this' appearing in a
8140 // non-virtual destructor of the destructor's class.
8141 ContextRAII SwitchContext(*this, Destructor);
8142 ExprResult This =
8143 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8144 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")(static_cast <bool> (!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? void (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8144, __extension__ __PRETTY_FUNCTION__))
;
8145 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8146 if (This.isInvalid()) {
8147 // FIXME: Register this as a context note so that it comes out
8148 // in the right order.
8149 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8150 return true;
8151 }
8152 ThisArg = This.get();
8153 }
8154 }
8155
8156 MarkFunctionReferenced(Loc, OperatorDelete);
8157 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8158 }
8159 }
8160
8161 return false;
8162}
8163
8164/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8165/// the well-formednes of the destructor declarator @p D with type @p
8166/// R. If there are any errors in the declarator, this routine will
8167/// emit diagnostics and set the declarator to invalid. Even if this happens,
8168/// will be updated to reflect a well-formed type for the destructor and
8169/// returned.
8170QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8171 StorageClass& SC) {
8172 // C++ [class.dtor]p1:
8173 // [...] A typedef-name that names a class is a class-name
8174 // (7.1.3); however, a typedef-name that names a class shall not
8175 // be used as the identifier in the declarator for a destructor
8176 // declaration.
8177 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8178 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8179 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8180 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8181 else if (const TemplateSpecializationType *TST =
8182 DeclaratorType->getAs<TemplateSpecializationType>())
8183 if (TST->isTypeAlias())
8184 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8185 << DeclaratorType << 1;
8186
8187 // C++ [class.dtor]p2:
8188 // A destructor is used to destroy objects of its class type. A
8189 // destructor takes no parameters, and no return type can be
8190 // specified for it (not even void). The address of a destructor
8191 // shall not be taken. A destructor shall not be static. A
8192 // destructor can be invoked for a const, volatile or const
8193 // volatile object. A destructor shall not be declared const,
8194 // volatile or const volatile (9.3.2).
8195 if (SC == SC_Static) {
8196 if (!D.isInvalidType())
8197 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8198 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8199 << SourceRange(D.getIdentifierLoc())
8200 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8201
8202 SC = SC_None;
8203 }
8204 if (!D.isInvalidType()) {
8205 // Destructors don't have return types, but the parser will
8206 // happily parse something like:
8207 //
8208 // class X {
8209 // float ~X();
8210 // };
8211 //
8212 // The return type will be eliminated later.
8213 if (D.getDeclSpec().hasTypeSpecifier())
8214 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8215 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8216 << SourceRange(D.getIdentifierLoc());
8217 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8218 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8219 SourceLocation(),
8220 D.getDeclSpec().getConstSpecLoc(),
8221 D.getDeclSpec().getVolatileSpecLoc(),
8222 D.getDeclSpec().getRestrictSpecLoc(),
8223 D.getDeclSpec().getAtomicSpecLoc());
8224 D.setInvalidType();
8225 }
8226 }
8227
8228 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8229 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8230 if (FTI.TypeQuals & Qualifiers::Const)
8231 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8232 << "const" << SourceRange(D.getIdentifierLoc());
8233 if (FTI.TypeQuals & Qualifiers::Volatile)
8234 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8235 << "volatile" << SourceRange(D.getIdentifierLoc());
8236 if (FTI.TypeQuals & Qualifiers::Restrict)
8237 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8238 << "restrict" << SourceRange(D.getIdentifierLoc());
8239 D.setInvalidType();
8240 }
8241
8242 // C++0x [class.dtor]p2:
8243 // A destructor shall not be declared with a ref-qualifier.
8244 if (FTI.hasRefQualifier()) {
8245 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8246 << FTI.RefQualifierIsLValueRef
8247 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8248 D.setInvalidType();
8249 }
8250
8251 // Make sure we don't have any parameters.
8252 if (FTIHasNonVoidParameters(FTI)) {
8253 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8254
8255 // Delete the parameters.
8256 FTI.freeParams();
8257 D.setInvalidType();
8258 }
8259
8260 // Make sure the destructor isn't variadic.
8261 if (FTI.isVariadic) {
8262 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8263 D.setInvalidType();
8264 }
8265
8266 // Rebuild the function type "R" without any type qualifiers or
8267 // parameters (in case any of the errors above fired) and with
8268 // "void" as the return type, since destructors don't have return
8269 // types.
8270 if (!D.isInvalidType())
8271 return R;
8272
8273 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8274 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8275 EPI.Variadic = false;
8276 EPI.TypeQuals = 0;
8277 EPI.RefQualifier = RQ_None;
8278 return Context.getFunctionType(Context.VoidTy, None, EPI);
8279}
8280
8281static void extendLeft(SourceRange &R, SourceRange Before) {
8282 if (Before.isInvalid())
8283 return;
8284 R.setBegin(Before.getBegin());
8285 if (R.getEnd().isInvalid())
8286 R.setEnd(Before.getEnd());
8287}
8288
8289static void extendRight(SourceRange &R, SourceRange After) {
8290 if (After.isInvalid())
8291 return;
8292 if (R.getBegin().isInvalid())
8293 R.setBegin(After.getBegin());
8294 R.setEnd(After.getEnd());
8295}
8296
8297/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8298/// well-formednes of the conversion function declarator @p D with
8299/// type @p R. If there are any errors in the declarator, this routine
8300/// will emit diagnostics and return true. Otherwise, it will return
8301/// false. Either way, the type @p R will be updated to reflect a
8302/// well-formed type for the conversion operator.
8303void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8304 StorageClass& SC) {
8305 // C++ [class.conv.fct]p1:
8306 // Neither parameter types nor return type can be specified. The
8307 // type of a conversion function (8.3.5) is "function taking no
8308 // parameter returning conversion-type-id."
8309 if (SC == SC_Static) {
8310 if (!D.isInvalidType())
8311 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8312 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8313 << D.getName().getSourceRange();
8314 D.setInvalidType();
8315 SC = SC_None;
8316 }
8317
8318 TypeSourceInfo *ConvTSI = nullptr;
8319 QualType ConvType =
8320 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8321
8322 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
8323 // Conversion functions don't have return types, but the parser will
8324 // happily parse something like:
8325 //
8326 // class X {
8327 // float operator bool();
8328 // };
8329 //
8330 // The return type will be changed later anyway.
8331 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8332 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8333 << SourceRange(D.getIdentifierLoc());
8334 D.setInvalidType();
8335 }
8336
8337 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8338
8339 // Make sure we don't have any parameters.
8340 if (Proto->getNumParams() > 0) {
8341 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8342
8343 // Delete the parameters.
8344 D.getFunctionTypeInfo().freeParams();
8345 D.setInvalidType();
8346 } else if (Proto->isVariadic()) {
8347 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8348 D.setInvalidType();
8349 }
8350
8351 // Diagnose "&operator bool()" and other such nonsense. This
8352 // is actually a gcc extension which we don't support.
8353 if (Proto->getReturnType() != ConvType) {
8354 bool NeedsTypedef = false;
8355 SourceRange Before, After;
8356
8357 // Walk the chunks and extract information on them for our diagnostic.
8358 bool PastFunctionChunk = false;
8359 for (auto &Chunk : D.type_objects()) {
8360 switch (Chunk.Kind) {
8361 case DeclaratorChunk::Function:
8362 if (!PastFunctionChunk) {
8363 if (Chunk.Fun.HasTrailingReturnType) {
8364 TypeSourceInfo *TRT = nullptr;
8365 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8366 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8367 }
8368 PastFunctionChunk = true;
8369 break;
8370 }
8371 LLVM_FALLTHROUGH[[clang::fallthrough]];
8372 case DeclaratorChunk::Array:
8373 NeedsTypedef = true;
8374 extendRight(After, Chunk.getSourceRange());
8375 break;
8376
8377 case DeclaratorChunk::Pointer:
8378 case DeclaratorChunk::BlockPointer:
8379 case DeclaratorChunk::Reference:
8380 case DeclaratorChunk::MemberPointer:
8381 case DeclaratorChunk::Pipe:
8382 extendLeft(Before, Chunk.getSourceRange());
8383 break;
8384
8385 case DeclaratorChunk::Paren:
8386 extendLeft(Before, Chunk.Loc);
8387 extendRight(After, Chunk.EndLoc);
8388 break;
8389 }
8390 }
8391
8392 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8393 After.isValid() ? After.getBegin() :
8394 D.getIdentifierLoc();
8395 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8396 DB << Before << After;
8397
8398 if (!NeedsTypedef) {
8399 DB << /*don't need a typedef*/0;
8400
8401 // If we can provide a correct fix-it hint, do so.
8402 if (After.isInvalid() && ConvTSI) {
8403 SourceLocation InsertLoc =
8404 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8405 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8406 << FixItHint::CreateInsertionFromRange(
8407 InsertLoc, CharSourceRange::getTokenRange(Before))
8408 << FixItHint::CreateRemoval(Before);
8409 }
8410 } else if (!Proto->getReturnType()->isDependentType()) {
8411 DB << /*typedef*/1 << Proto->getReturnType();
8412 } else if (getLangOpts().CPlusPlus11) {
8413 DB << /*alias template*/2 << Proto->getReturnType();
8414 } else {
8415 DB << /*might not be fixable*/3;
8416 }
8417
8418 // Recover by incorporating the other type chunks into the result type.
8419 // Note, this does *not* change the name of the function. This is compatible
8420 // with the GCC extension:
8421 // struct S { &operator int(); } s;
8422 // int &r = s.operator int(); // ok in GCC
8423 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8424 ConvType = Proto->getReturnType();
8425 }
8426
8427 // C++ [class.conv.fct]p4:
8428 // The conversion-type-id shall not represent a function type nor
8429 // an array type.
8430 if (ConvType->isArrayType()) {
8431 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8432 ConvType = Context.getPointerType(ConvType);
8433 D.setInvalidType();
8434 } else if (ConvType->isFunctionType()) {
8435 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8436 ConvType = Context.getPointerType(ConvType);
8437 D.setInvalidType();
8438 }
8439
8440 // Rebuild the function type "R" without any parameters (in case any
8441 // of the errors above fired) and with the conversion type as the
8442 // return type.
8443 if (D.isInvalidType())
8444 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8445
8446 // C++0x explicit conversion operators.
8447 if (D.getDeclSpec().isExplicitSpecified())
8448 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8449 getLangOpts().CPlusPlus11 ?
8450 diag::warn_cxx98_compat_explicit_conversion_functions :
8451 diag::ext_explicit_conversion_functions)
8452 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8453}
8454
8455/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8456/// the declaration of the given C++ conversion function. This routine
8457/// is responsible for recording the conversion function in the C++
8458/// class, if possible.
8459Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8460 assert(Conversion && "Expected to receive a conversion function declaration")(static_cast <bool> (Conversion && "Expected to receive a conversion function declaration"
) ? void (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8460, __extension__ __PRETTY_FUNCTION__))
;
8461
8462 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8463
8464 // Make sure we aren't redeclaring the conversion function.
8465 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8466
8467 // C++ [class.conv.fct]p1:
8468 // [...] A conversion function is never used to convert a
8469 // (possibly cv-qualified) object to the (possibly cv-qualified)
8470 // same object type (or a reference to it), to a (possibly
8471 // cv-qualified) base class of that type (or a reference to it),
8472 // or to (possibly cv-qualified) void.
8473 // FIXME: Suppress this warning if the conversion function ends up being a
8474 // virtual function that overrides a virtual function in a base class.
8475 QualType ClassType
8476 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8477 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8478 ConvType = ConvTypeRef->getPointeeType();
8479 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8480 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8481 /* Suppress diagnostics for instantiations. */;
8482 else if (ConvType->isRecordType()) {
8483 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8484 if (ConvType == ClassType)
8485 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8486 << ClassType;
8487 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8488 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8489 << ClassType << ConvType;
8490 } else if (ConvType->isVoidType()) {
8491 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8492 << ClassType << ConvType;
8493 }
8494
8495 if (FunctionTemplateDecl *ConversionTemplate
8496 = Conversion->getDescribedFunctionTemplate())
8497 return ConversionTemplate;
8498
8499 return Conversion;
8500}
8501
8502namespace {
8503/// Utility class to accumulate and print a diagnostic listing the invalid
8504/// specifier(s) on a declaration.
8505struct BadSpecifierDiagnoser {
8506 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8507 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8508 ~BadSpecifierDiagnoser() {
8509 Diagnostic << Specifiers;
8510 }
8511
8512 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8513 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8514 }
8515 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8516 return check(SpecLoc,
8517 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8518 }
8519 void check(SourceLocation SpecLoc, const char *Spec) {
8520 if (SpecLoc.isInvalid()) return;
8521 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8522 if (!Specifiers.empty()) Specifiers += " ";
8523 Specifiers += Spec;
8524 }
8525
8526 Sema &S;
8527 Sema::SemaDiagnosticBuilder Diagnostic;
8528 std::string Specifiers;
8529};
8530}
8531
8532/// Check the validity of a declarator that we parsed for a deduction-guide.
8533/// These aren't actually declarators in the grammar, so we need to check that
8534/// the user didn't specify any pieces that are not part of the deduction-guide
8535/// grammar.
8536void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8537 StorageClass &SC) {
8538 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8539 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8540 assert(GuidedTemplateDecl && "missing template decl for deduction guide")(static_cast <bool> (GuidedTemplateDecl && "missing template decl for deduction guide"
) ? void (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8540, __extension__ __PRETTY_FUNCTION__))
;
8541
8542 // C++ [temp.deduct.guide]p3:
8543 // A deduction-gide shall be declared in the same scope as the
8544 // corresponding class template.
8545 if (!CurContext->getRedeclContext()->Equals(
8546 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8547 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8548 << GuidedTemplateDecl;
8549 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8550 }
8551
8552 auto &DS = D.getMutableDeclSpec();
8553 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8554 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8555 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8556 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8557 BadSpecifierDiagnoser Diagnoser(
8558 *this, D.getIdentifierLoc(),
8559 diag::err_deduction_guide_invalid_specifier);
8560
8561 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8562 DS.ClearStorageClassSpecs();
8563 SC = SC_None;
8564
8565 // 'explicit' is permitted.
8566 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8567 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8568 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8569 DS.ClearConstexprSpec();
8570
8571 Diagnoser.check(DS.getConstSpecLoc(), "const");
8572 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8573 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8574 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8575 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8576 DS.ClearTypeQualifiers();
8577
8578 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8579 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8580 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8581 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8582 DS.ClearTypeSpecType();
8583 }
8584
8585 if (D.isInvalidType())
8586 return;
8587
8588 // Check the declarator is simple enough.
8589 bool FoundFunction = false;
8590 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8591 if (Chunk.Kind == DeclaratorChunk::Paren)
8592 continue;
8593 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8594 Diag(D.getDeclSpec().getLocStart(),
8595 diag::err_deduction_guide_with_complex_decl)
8596 << D.getSourceRange();
8597 break;
8598 }
8599 if (!Chunk.Fun.hasTrailingReturnType()) {
8600 Diag(D.getName().getLocStart(),
8601 diag::err_deduction_guide_no_trailing_return_type);
8602 break;
8603 }
8604
8605 // Check that the return type is written as a specialization of
8606 // the template specified as the deduction-guide's name.
8607 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8608 TypeSourceInfo *TSI = nullptr;
8609 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8610 assert(TSI && "deduction guide has valid type but invalid return type?")(static_cast <bool> (TSI && "deduction guide has valid type but invalid return type?"
) ? void (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8610, __extension__ __PRETTY_FUNCTION__))
;
8611 bool AcceptableReturnType = false;
8612 bool MightInstantiateToSpecialization = false;
8613 if (auto RetTST =
8614 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8615 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8616 bool TemplateMatches =
8617 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8618 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8619 AcceptableReturnType = true;
8620 else {
8621 // This could still instantiate to the right type, unless we know it
8622 // names the wrong class template.
8623 auto *TD = SpecifiedName.getAsTemplateDecl();
8624 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8625 !TemplateMatches);
8626 }
8627 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8628 MightInstantiateToSpecialization = true;
8629 }
8630
8631 if (!AcceptableReturnType) {
8632 Diag(TSI->getTypeLoc().getLocStart(),
8633 diag::err_deduction_guide_bad_trailing_return_type)
8634 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8635 << TSI->getTypeLoc().getSourceRange();
8636 }
8637
8638 // Keep going to check that we don't have any inner declarator pieces (we
8639 // could still have a function returning a pointer to a function).
8640 FoundFunction = true;
8641 }
8642
8643 if (D.isFunctionDefinition())
8644 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8645}
8646
8647//===----------------------------------------------------------------------===//
8648// Namespace Handling
8649//===----------------------------------------------------------------------===//
8650
8651/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8652/// reopened.
8653static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8654 SourceLocation Loc,
8655 IdentifierInfo *II, bool *IsInline,
8656 NamespaceDecl *PrevNS) {
8657 assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline()
) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8657, __extension__ __PRETTY_FUNCTION__))
;
8658
8659 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8660 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8661 // inline namespaces, with the intention of bringing names into namespace std.
8662 //
8663 // We support this just well enough to get that case working; this is not
8664 // sufficient to support reopening namespaces as inline in general.
8665 if (*IsInline && II && II->getName().startswith("__atomic") &&
8666 S.getSourceManager().isInSystemHeader(Loc)) {
8667 // Mark all prior declarations of the namespace as inline.
8668 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8669 NS = NS->getPreviousDecl())
8670 NS->setInline(*IsInline);
8671 // Patch up the lookup table for the containing namespace. This isn't really
8672 // correct, but it's good enough for this particular case.
8673 for (auto *I : PrevNS->decls())
8674 if (auto *ND = dyn_cast<NamedDecl>(I))
8675 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8676 return;
8677 }
8678
8679 if (PrevNS->isInline())
8680 // The user probably just forgot the 'inline', so suggest that it
8681 // be added back.
8682 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8683 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8684 else
8685 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8686
8687 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8688 *IsInline = PrevNS->isInline();
8689}
8690
8691/// ActOnStartNamespaceDef - This is called at the start of a namespace
8692/// definition.
8693Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8694 SourceLocation InlineLoc,
8695 SourceLocation NamespaceLoc,
8696 SourceLocation IdentLoc,
8697 IdentifierInfo *II,
8698 SourceLocation LBrace,
8699 AttributeList *AttrList,
8700 UsingDirectiveDecl *&UD) {
8701 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8702 // For anonymous namespace, take the location of the left brace.
8703 SourceLocation Loc = II ? IdentLoc : LBrace;
8704 bool IsInline = InlineLoc.isValid();
8705 bool IsInvalid = false;
8706 bool IsStd = false;
8707 bool AddToKnown = false;
8708 Scope *DeclRegionScope = NamespcScope->getParent();
8709
8710 NamespaceDecl *PrevNS = nullptr;
8711 if (II) {
8712 // C++ [namespace.def]p2:
8713 // The identifier in an original-namespace-definition shall not
8714 // have been previously defined in the declarative region in
8715 // which the original-namespace-definition appears. The
8716 // identifier in an original-namespace-definition is the name of
8717 // the namespace. Subsequently in that declarative region, it is
8718 // treated as an original-namespace-name.
8719 //
8720 // Since namespace names are unique in their scope, and we don't
8721 // look through using directives, just look for any ordinary names
8722 // as if by qualified name lookup.
8723 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8724 ForExternalRedeclaration);
8725 LookupQualifiedName(R, CurContext->getRedeclContext());
8726 NamedDecl *PrevDecl =
8727 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8728 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8729
8730 if (PrevNS) {
8731 // This is an extended namespace definition.
8732 if (IsInline != PrevNS->isInline())
8733 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8734 &IsInline, PrevNS);
8735 } else if (PrevDecl) {
8736 // This is an invalid name redefinition.
8737 Diag(Loc, diag::err_redefinition_different_kind)
8738 << II;
8739 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8740 IsInvalid = true;
8741 // Continue on to push Namespc as current DeclContext and return it.
8742 } else if (II->isStr("std") &&
8743 CurContext->getRedeclContext()->isTranslationUnit()) {
8744 // This is the first "real" definition of the namespace "std", so update
8745 // our cache of the "std" namespace to point at this definition.
8746 PrevNS = getStdNamespace();
8747 IsStd = true;
8748 AddToKnown = !IsInline;
8749 } else {
8750 // We've seen this namespace for the first time.
8751 AddToKnown = !IsInline;
8752 }
8753 } else {
8754 // Anonymous namespaces.
8755
8756 // Determine whether the parent already has an anonymous namespace.
8757 DeclContext *Parent = CurContext->getRedeclContext();
8758 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8759 PrevNS = TU->getAnonymousNamespace();
8760 } else {
8761 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8762 PrevNS = ND->getAnonymousNamespace();
8763 }
8764
8765 if (PrevNS && IsInline != PrevNS->isInline())
8766 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8767 &IsInline, PrevNS);
8768 }
8769
8770 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8771 StartLoc, Loc, II, PrevNS);
8772 if (IsInvalid)
8773 Namespc->setInvalidDecl();
8774
8775 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8776 AddPragmaAttributes(DeclRegionScope, Namespc);
8777
8778 // FIXME: Should we be merging attributes?
8779 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8780 PushNamespaceVisibilityAttr(Attr, Loc);
8781
8782 if (IsStd)
8783 StdNamespace = Namespc;
8784 if (AddToKnown)
8785 KnownNamespaces[Namespc] = false;
8786
8787 if (II) {
8788 PushOnScopeChains(Namespc, DeclRegionScope);
8789 } else {
8790 // Link the anonymous namespace into its parent.
8791 DeclContext *Parent = CurContext->getRedeclContext();
8792 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8793 TU->setAnonymousNamespace(Namespc);
8794 } else {
8795 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8796 }
8797
8798 CurContext->addDecl(Namespc);
8799
8800 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8801 // behaves as if it were replaced by
8802 // namespace unique { /* empty body */ }
8803 // using namespace unique;
8804 // namespace unique { namespace-body }
8805 // where all occurrences of 'unique' in a translation unit are
8806 // replaced by the same identifier and this identifier differs
8807 // from all other identifiers in the entire program.
8808
8809 // We just create the namespace with an empty name and then add an
8810 // implicit using declaration, just like the standard suggests.
8811 //
8812 // CodeGen enforces the "universally unique" aspect by giving all
8813 // declarations semantically contained within an anonymous
8814 // namespace internal linkage.
8815
8816 if (!PrevNS) {
8817 UD = UsingDirectiveDecl::Create(Context, Parent,
8818 /* 'using' */ LBrace,
8819 /* 'namespace' */ SourceLocation(),
8820 /* qualifier */ NestedNameSpecifierLoc(),
8821 /* identifier */ SourceLocation(),
8822 Namespc,
8823 /* Ancestor */ Parent);
8824 UD->setImplicit();
8825 Parent->addDecl(UD);
8826 }
8827 }
8828
8829 ActOnDocumentableDecl(Namespc);
8830
8831 // Although we could have an invalid decl (i.e. the namespace name is a
8832 // redefinition), push it as current DeclContext and try to continue parsing.
8833 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8834 // for the namespace has the declarations that showed up in that particular
8835 // namespace definition.
8836 PushDeclContext(NamespcScope, Namespc);
8837 return Namespc;
8838}
8839
8840/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8841/// is a namespace alias, returns the namespace it points to.
8842static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8843 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8844 return AD->getNamespace();
8845 return dyn_cast_or_null<NamespaceDecl>(D);
8846}
8847
8848/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8849/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8850void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8851 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8852 assert(Namespc && "Invalid parameter, expected NamespaceDecl")(static_cast <bool> (Namespc && "Invalid parameter, expected NamespaceDecl"
) ? void (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8852, __extension__ __PRETTY_FUNCTION__))
;
8853 Namespc->setRBraceLoc(RBrace);
8854 PopDeclContext();
8855 if (Namespc->hasAttr<VisibilityAttr>())
8856 PopPragmaVisibility(true, RBrace);
8857}
8858
8859CXXRecordDecl *Sema::getStdBadAlloc() const {
8860 return cast_or_null<CXXRecordDecl>(
8861 StdBadAlloc.get(Context.getExternalSource()));
8862}
8863
8864EnumDecl *Sema::getStdAlignValT() const {
8865 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8866}
8867
8868NamespaceDecl *Sema::getStdNamespace() const {
8869 return cast_or_null<NamespaceDecl>(
8870 StdNamespace.get(Context.getExternalSource()));
8871}
8872
8873NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8874 if (!StdExperimentalNamespaceCache) {
8875 if (auto Std = getStdNamespace()) {
8876 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8877 SourceLocation(), LookupNamespaceName);
8878 if (!LookupQualifiedName(Result, Std) ||
8879 !(StdExperimentalNamespaceCache =
8880 Result.getAsSingle<NamespaceDecl>()))
8881 Result.suppressDiagnostics();
8882 }
8883 }
8884 return StdExperimentalNamespaceCache;
8885}
8886
8887/// \brief Retrieve the special "std" namespace, which may require us to
8888/// implicitly define the namespace.
8889NamespaceDecl *Sema::getOrCreateStdNamespace() {
8890 if (!StdNamespace) {
8891 // The "std" namespace has not yet been defined, so build one implicitly.
8892 StdNamespace = NamespaceDecl::Create(Context,
8893 Context.getTranslationUnitDecl(),
8894 /*Inline=*/false,
8895 SourceLocation(), SourceLocation(),
8896 &PP.getIdentifierTable().get("std"),
8897 /*PrevDecl=*/nullptr);
8898 getStdNamespace()->setImplicit(true);
8899 }
8900
8901 return getStdNamespace();
8902}
8903
8904bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8905 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8906, __extension__ __PRETTY_FUNCTION__))
8906 "Looking for std::initializer_list outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8906, __extension__ __PRETTY_FUNCTION__))
;
8907
8908 // We're looking for implicit instantiations of
8909 // template <typename E> class std::initializer_list.
8910
8911 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8912 return false;
8913
8914 ClassTemplateDecl *Template = nullptr;
8915 const TemplateArgument *Arguments = nullptr;
8916
8917 if (const RecordType *RT = Ty->getAs<RecordType>()) {
8918
8919 ClassTemplateSpecializationDecl *Specialization =
8920 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8921 if (!Specialization)
8922 return false;
8923
8924 Template = Specialization->getSpecializedTemplate();
8925 Arguments = Specialization->getTemplateArgs().data();
8926 } else if (const TemplateSpecializationType *TST =
8927 Ty->getAs<TemplateSpecializationType>()) {
8928 Template = dyn_cast_or_null<ClassTemplateDecl>(
8929 TST->getTemplateName().getAsTemplateDecl());
8930 Arguments = TST->getArgs();
8931 }
8932 if (!Template)
8933 return false;
8934
8935 if (!StdInitializerList) {
8936 // Haven't recognized std::initializer_list yet, maybe this is it.
8937 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8938 if (TemplateClass->getIdentifier() !=
8939 &PP.getIdentifierTable().get("initializer_list") ||
8940 !getStdNamespace()->InEnclosingNamespaceSetOf(
8941 TemplateClass->getDeclContext()))
8942 return false;
8943 // This is a template called std::initializer_list, but is it the right
8944 // template?
8945 TemplateParameterList *Params = Template->getTemplateParameters();
8946 if (Params->getMinRequiredArguments() != 1)
8947 return false;
8948 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8949 return false;
8950
8951 // It's the right template.
8952 StdInitializerList = Template;
8953 }
8954
8955 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8956 return false;
8957
8958 // This is an instance of std::initializer_list. Find the argument type.
8959 if (Element)
8960 *Element = Arguments[0].getAsType();
8961 return true;
8962}
8963
8964static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8965 NamespaceDecl *Std = S.getStdNamespace();
8966 if (!Std) {
8967 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8968 return nullptr;
8969 }
8970
8971 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8972 Loc, Sema::LookupOrdinaryName);
8973 if (!S.LookupQualifiedName(Result, Std)) {
8974 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8975 return nullptr;
8976 }
8977 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8978 if (!Template) {
8979 Result.suppressDiagnostics();
8980 // We found something weird. Complain about the first thing we found.
8981 NamedDecl *Found = *Result.begin();
8982 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8983 return nullptr;
8984 }
8985
8986 // We found some template called std::initializer_list. Now verify that it's
8987 // correct.
8988 TemplateParameterList *Params = Template->getTemplateParameters();
8989 if (Params->getMinRequiredArguments() != 1 ||
8990 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8991 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8992 return nullptr;
8993 }
8994
8995 return Template;
8996}
8997
8998QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8999 if (!StdInitializerList) {
9000 StdInitializerList = LookupStdInitializerList(*this, Loc);
9001 if (!StdInitializerList)
9002 return QualType();
9003 }
9004
9005 TemplateArgumentListInfo Args(Loc, Loc);
9006 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9007 Context.getTrivialTypeSourceInfo(Element,
9008 Loc)));
9009 return Context.getCanonicalType(
9010 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9011}
9012
9013bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9014 // C++ [dcl.init.list]p2:
9015 // A constructor is an initializer-list constructor if its first parameter
9016 // is of type std::initializer_list<E> or reference to possibly cv-qualified
9017 // std::initializer_list<E> for some type E, and either there are no other
9018 // parameters or else all other parameters have default arguments.
9019 if (Ctor->getNumParams() < 1 ||
9020 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9021 return false;
9022
9023 QualType ArgType = Ctor->getParamDecl(0)->getType();
9024 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9025 ArgType = RT->getPointeeType().getUnqualifiedType();
9026
9027 return isStdInitializerList(ArgType, nullptr);
9028}
9029
9030/// \brief Determine whether a using statement is in a context where it will be
9031/// apply in all contexts.
9032static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9033 switch (CurContext->getDeclKind()) {
9034 case Decl::TranslationUnit:
9035 return true;
9036 case Decl::LinkageSpec:
9037 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9038 default:
9039 return false;
9040 }
9041}
9042
9043namespace {
9044
9045// Callback to only accept typo corrections that are namespaces.
9046class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9047public:
9048 bool ValidateCandidate(const TypoCorrection &candidate) override {
9049 if (NamedDecl *ND = candidate.getCorrectionDecl())
9050 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9051 return false;
9052 }
9053};
9054
9055}
9056
9057static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9058 CXXScopeSpec &SS,
9059 SourceLocation IdentLoc,
9060 IdentifierInfo *Ident) {
9061 R.clear();
9062 if (TypoCorrection Corrected =
9063 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9064 llvm::make_unique<NamespaceValidatorCCC>(),
9065 Sema::CTK_ErrorRecovery)) {
9066 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9067 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9068 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9069 Ident->getName().equals(CorrectedStr);
9070 S.diagnoseTypo(Corrected,
9071 S.PDiag(diag::err_using_directive_member_suggest)
9072 << Ident << DC << DroppedSpecifier << SS.getRange(),
9073 S.PDiag(diag::note_namespace_defined_here));
9074 } else {
9075 S.diagnoseTypo(Corrected,
9076 S.PDiag(diag::err_using_directive_suggest) << Ident,
9077 S.PDiag(diag::note_namespace_defined_here));
9078 }
9079 R.addDecl(Corrected.getFoundDecl());
9080 return true;
9081 }
9082 return false;
9083}
9084
9085Decl *Sema::ActOnUsingDirective(Scope *S,
9086 SourceLocation UsingLoc,
9087 SourceLocation NamespcLoc,
9088 CXXScopeSpec &SS,
9089 SourceLocation IdentLoc,
9090 IdentifierInfo *NamespcName,
9091 AttributeList *AttrList) {
9092 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9092, __extension__ __PRETTY_FUNCTION__))
;
9093 assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName."
) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9093, __extension__ __PRETTY_FUNCTION__))
;
9094 assert(IdentLoc.isValid() && "Invalid NamespceName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid NamespceName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9094, __extension__ __PRETTY_FUNCTION__))
;
9095
9096 // This can only happen along a recovery path.
9097 while (S->isTemplateParamScope())
9098 S = S->getParent();
9099 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9099, __extension__ __PRETTY_FUNCTION__))
;
9100
9101 UsingDirectiveDecl *UDir = nullptr;
9102 NestedNameSpecifier *Qualifier = nullptr;
9103 if (SS.isSet())
9104 Qualifier = SS.getScopeRep();
9105
9106 // Lookup namespace name.
9107 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9108 LookupParsedName(R, S, &SS);
9109 if (R.isAmbiguous())
9110 return nullptr;
9111
9112 if (R.empty()) {
9113 R.clear();
9114 // Allow "using namespace std;" or "using namespace ::std;" even if
9115 // "std" hasn't been defined yet, for GCC compatibility.
9116 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9117 NamespcName->isStr("std")) {
9118 Diag(IdentLoc, diag::ext_using_undefined_std);
9119 R.addDecl(getOrCreateStdNamespace());
9120 R.resolveKind();
9121 }
9122 // Otherwise, attempt typo correction.
9123 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9124 }
9125
9126 if (!R.empty()) {
9127 NamedDecl *Named = R.getRepresentativeDecl();
9128 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9129 assert(NS && "expected namespace decl")(static_cast <bool> (NS && "expected namespace decl"
) ? void (0) : __assert_fail ("NS && \"expected namespace decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9129, __extension__ __PRETTY_FUNCTION__))
;
9130
9131 // The use of a nested name specifier may trigger deprecation warnings.
9132 DiagnoseUseOfDecl(Named, IdentLoc);
9133
9134 // C++ [namespace.udir]p1:
9135 // A using-directive specifies that the names in the nominated
9136 // namespace can be used in the scope in which the
9137 // using-directive appears after the using-directive. During
9138 // unqualified name lookup (3.4.1), the names appear as if they
9139 // were declared in the nearest enclosing namespace which
9140 // contains both the using-directive and the nominated
9141 // namespace. [Note: in this context, "contains" means "contains
9142 // directly or indirectly". ]
9143
9144 // Find enclosing context containing both using-directive and
9145 // nominated namespace.
9146 DeclContext *CommonAncestor = NS;
9147 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9148 CommonAncestor = CommonAncestor->getParent();
9149
9150 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9151 SS.getWithLocInContext(Context),
9152 IdentLoc, Named, CommonAncestor);
9153
9154 if (IsUsingDirectiveInToplevelContext(CurContext) &&
9155 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9156 Diag(IdentLoc, diag::warn_using_directive_in_header);
9157 }
9158
9159 PushUsingDirective(S, UDir);
9160 } else {
9161 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9162 }
9163
9164 if (UDir)
9165 ProcessDeclAttributeList(S, UDir, AttrList);
9166
9167 return UDir;
9168}
9169
9170void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9171 // If the scope has an associated entity and the using directive is at
9172 // namespace or translation unit scope, add the UsingDirectiveDecl into
9173 // its lookup structure so qualified name lookup can find it.
9174 DeclContext *Ctx = S->getEntity();
9175 if (Ctx && !Ctx->isFunctionOrMethod())
9176 Ctx->addDecl(UDir);
9177 else
9178 // Otherwise, it is at block scope. The using-directives will affect lookup
9179 // only to the end of the scope.
9180 S->PushUsingDirective(UDir);
9181}
9182
9183
9184Decl *Sema::ActOnUsingDeclaration(Scope *S,
9185 AccessSpecifier AS,
9186 SourceLocation UsingLoc,
9187 SourceLocation TypenameLoc,
9188 CXXScopeSpec &SS,
9189 UnqualifiedId &Name,
9190 SourceLocation EllipsisLoc,
9191 AttributeList *AttrList) {
9192 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9192, __extension__ __PRETTY_FUNCTION__))
;
9193
9194 if (SS.isEmpty()) {
9195 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
9196 return nullptr;
9197 }
9198
9199 switch (Name.getKind()) {
9200 case UnqualifiedIdKind::IK_ImplicitSelfParam:
9201 case UnqualifiedIdKind::IK_Identifier:
9202 case UnqualifiedIdKind::IK_OperatorFunctionId:
9203 case UnqualifiedIdKind::IK_LiteralOperatorId:
9204 case UnqualifiedIdKind::IK_ConversionFunctionId:
9205 break;
9206
9207 case UnqualifiedIdKind::IK_ConstructorName:
9208 case UnqualifiedIdKind::IK_ConstructorTemplateId:
9209 // C++11 inheriting constructors.
9210 Diag(Name.getLocStart(),
9211 getLangOpts().CPlusPlus11 ?
9212 diag::warn_cxx98_compat_using_decl_constructor :
9213 diag::err_using_decl_constructor)
9214 << SS.getRange();
9215
9216 if (getLangOpts().CPlusPlus11) break;
9217
9218 return nullptr;
9219
9220 case UnqualifiedIdKind::IK_DestructorName:
9221 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9222 << SS.getRange();
9223 return nullptr;
9224
9225 case UnqualifiedIdKind::IK_TemplateId:
9226 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9227 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9228 return nullptr;
9229
9230 case UnqualifiedIdKind::IK_DeductionGuideName:
9231 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9231)
;
9232 }
9233
9234 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9235 DeclarationName TargetName = TargetNameInfo.getName();
9236 if (!TargetName)
9237 return nullptr;
9238
9239 // Warn about access declarations.
9240 if (UsingLoc.isInvalid()) {
9241 Diag(Name.getLocStart(),
9242 getLangOpts().CPlusPlus11 ? diag::err_access_decl
9243 : diag::warn_access_decl_deprecated)
9244 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9245 }
9246
9247 if (EllipsisLoc.isInvalid()) {
9248 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9249 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9250 return nullptr;
9251 } else {
9252 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9253 !TargetNameInfo.containsUnexpandedParameterPack()) {
9254 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9255 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9256 EllipsisLoc = SourceLocation();
9257 }
9258 }
9259
9260 NamedDecl *UD =
9261 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9262 SS, TargetNameInfo, EllipsisLoc, AttrList,
9263 /*IsInstantiation*/false);
9264 if (UD)
9265 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9266
9267 return UD;
9268}
9269
9270/// \brief Determine whether a using declaration considers the given
9271/// declarations as "equivalent", e.g., if they are redeclarations of
9272/// the same entity or are both typedefs of the same type.
9273static bool
9274IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9275 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9276 return true;
9277
9278 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9279 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9280 return Context.hasSameType(TD1->getUnderlyingType(),
9281 TD2->getUnderlyingType());
9282
9283 return false;
9284}
9285
9286
9287/// Determines whether to create a using shadow decl for a particular
9288/// decl, given the set of decls existing prior to this using lookup.
9289bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9290 const LookupResult &Previous,
9291 UsingShadowDecl *&PrevShadow) {
9292 // Diagnose finding a decl which is not from a base class of the
9293 // current class. We do this now because there are cases where this
9294 // function will silently decide not to build a shadow decl, which
9295 // will pre-empt further diagnostics.
9296 //
9297 // We don't need to do this in C++11 because we do the check once on
9298 // the qualifier.
9299 //
9300 // FIXME: diagnose the following if we care enough:
9301 // struct A { int foo; };
9302 // struct B : A { using A::foo; };
9303 // template <class T> struct C : A {};
9304 // template <class T> struct D : C<T> { using B::foo; } // <---
9305 // This is invalid (during instantiation) in C++03 because B::foo
9306 // resolves to the using decl in B, which is not a base class of D<T>.
9307 // We can't diagnose it immediately because C<T> is an unknown
9308 // specialization. The UsingShadowDecl in D<T> then points directly
9309 // to A::foo, which will look well-formed when we instantiate.
9310 // The right solution is to not collapse the shadow-decl chain.
9311 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9312 DeclContext *OrigDC = Orig->getDeclContext();
9313
9314 // Handle enums and anonymous structs.
9315 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9316 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9317 while (OrigRec->isAnonymousStructOrUnion())
9318 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9319
9320 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9321 if (OrigDC == CurContext) {
9322 Diag(Using->getLocation(),
9323 diag::err_using_decl_nested_name_specifier_is_current_class)
9324 << Using->getQualifierLoc().getSourceRange();
9325 Diag(Orig->getLocation(), diag::note_using_decl_target);
9326 Using->setInvalidDecl();
9327 return true;
9328 }
9329
9330 Diag(Using->getQualifierLoc().getBeginLoc(),
9331 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9332 << Using->getQualifier()
9333 << cast<CXXRecordDecl>(CurContext)
9334 << Using->getQualifierLoc().getSourceRange();
9335 Diag(Orig->getLocation(), diag::note_using_decl_target);
9336 Using->setInvalidDecl();
9337 return true;
9338 }
9339 }
9340
9341 if (Previous.empty()) return false;
9342
9343 NamedDecl *Target = Orig;
9344 if (isa<UsingShadowDecl>(Target))
9345 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9346
9347 // If the target happens to be one of the previous declarations, we
9348 // don't have a conflict.
9349 //
9350 // FIXME: but we might be increasing its access, in which case we
9351 // should redeclare it.
9352 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9353 bool FoundEquivalentDecl = false;
9354 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9355 I != E; ++I) {
9356 NamedDecl *D = (*I)->getUnderlyingDecl();
9357 // We can have UsingDecls in our Previous results because we use the same
9358 // LookupResult for checking whether the UsingDecl itself is a valid
9359 // redeclaration.
9360 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9361 continue;
9362
9363 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9364 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9365 PrevShadow = Shadow;
9366 FoundEquivalentDecl = true;
9367 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9368 // We don't conflict with an existing using shadow decl of an equivalent
9369 // declaration, but we're not a redeclaration of it.
9370 FoundEquivalentDecl = true;
9371 }
9372
9373 if (isVisible(D))
9374 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9375 }
9376
9377 if (FoundEquivalentDecl)
9378 return false;
9379
9380 if (FunctionDecl *FD = Target->getAsFunction()) {
9381 NamedDecl *OldDecl = nullptr;
9382 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9383 /*IsForUsingDecl*/ true)) {
9384 case Ovl_Overload:
9385 return false;
9386
9387 case Ovl_NonFunction:
9388 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9389 break;
9390
9391 // We found a decl with the exact signature.
9392 case Ovl_Match:
9393 // If we're in a record, we want to hide the target, so we
9394 // return true (without a diagnostic) to tell the caller not to
9395 // build a shadow decl.
9396 if (CurContext->isRecord())
9397 return true;
9398
9399 // If we're not in a record, this is an error.
9400 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9401 break;
9402 }
9403
9404 Diag(Target->getLocation(), diag::note_using_decl_target);
9405 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9406 Using->setInvalidDecl();
9407 return true;
9408 }
9409
9410 // Target is not a function.
9411
9412 if (isa<TagDecl>(Target)) {
9413 // No conflict between a tag and a non-tag.
9414 if (!Tag) return false;
9415
9416 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9417 Diag(Target->getLocation(), diag::note_using_decl_target);
9418 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9419 Using->setInvalidDecl();
9420 return true;
9421 }
9422
9423 // No conflict between a tag and a non-tag.
9424 if (!NonTag) return false;
9425
9426 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9427 Diag(Target->getLocation(), diag::note_using_decl_target);
9428 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9429 Using->setInvalidDecl();
9430 return true;
9431}
9432
9433/// Determine whether a direct base class is a virtual base class.
9434static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9435 if (!Derived->getNumVBases())
9436 return false;
9437 for (auto &B : Derived->bases())
9438 if (B.getType()->getAsCXXRecordDecl() == Base)
9439 return B.isVirtual();
9440 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9440)
;
9441}
9442
9443/// Builds a shadow declaration corresponding to a 'using' declaration.
9444UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9445 UsingDecl *UD,
9446 NamedDecl *Orig,
9447 UsingShadowDecl *PrevDecl) {
9448 // If we resolved to another shadow declaration, just coalesce them.
9449 NamedDecl *Target = Orig;
9450 if (isa<UsingShadowDecl>(Target)) {
9451 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9452 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")(static_cast <bool> (!isa<UsingShadowDecl>(Target
) && "nested shadow declaration") ? void (0) : __assert_fail
("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9452, __extension__ __PRETTY_FUNCTION__))
;
9453 }
9454
9455 NamedDecl *NonTemplateTarget = Target;
9456 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9457 NonTemplateTarget = TargetTD->getTemplatedDecl();
9458
9459 UsingShadowDecl *Shadow;
9460 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9461 bool IsVirtualBase =
9462 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9463 UD->getQualifier()->getAsRecordDecl());
9464 Shadow = ConstructorUsingShadowDecl::Create(
9465 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9466 } else {
9467 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9468 Target);
9469 }
9470 UD->addShadowDecl(Shadow);
9471
9472 Shadow->setAccess(UD->getAccess());
9473 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9474 Shadow->setInvalidDecl();
9475
9476 Shadow->setPreviousDecl(PrevDecl);
9477
9478 if (S)
9479 PushOnScopeChains(Shadow, S);
9480 else
9481 CurContext->addDecl(Shadow);
9482
9483
9484 return Shadow;
9485}
9486
9487/// Hides a using shadow declaration. This is required by the current
9488/// using-decl implementation when a resolvable using declaration in a
9489/// class is followed by a declaration which would hide or override
9490/// one or more of the using decl's targets; for example:
9491///
9492/// struct Base { void foo(int); };
9493/// struct Derived : Base {
9494/// using Base::foo;
9495/// void foo(int);
9496/// };
9497///
9498/// The governing language is C++03 [namespace.udecl]p12:
9499///
9500/// When a using-declaration brings names from a base class into a
9501/// derived class scope, member functions in the derived class
9502/// override and/or hide member functions with the same name and
9503/// parameter types in a base class (rather than conflicting).
9504///
9505/// There are two ways to implement this:
9506/// (1) optimistically create shadow decls when they're not hidden
9507/// by existing declarations, or
9508/// (2) don't create any shadow decls (or at least don't make them
9509/// visible) until we've fully parsed/instantiated the class.
9510/// The problem with (1) is that we might have to retroactively remove
9511/// a shadow decl, which requires several O(n) operations because the
9512/// decl structures are (very reasonably) not designed for removal.
9513/// (2) avoids this but is very fiddly and phase-dependent.
9514void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9515 if (Shadow->getDeclName().getNameKind() ==
9516 DeclarationName::CXXConversionFunctionName)
9517 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9518
9519 // Remove it from the DeclContext...
9520 Shadow->getDeclContext()->removeDecl(Shadow);
9521
9522 // ...and the scope, if applicable...
9523 if (S) {
9524 S->RemoveDecl(Shadow);
9525 IdResolver.RemoveDecl(Shadow);
9526 }
9527
9528 // ...and the using decl.
9529 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9530
9531 // TODO: complain somehow if Shadow was used. It shouldn't
9532 // be possible for this to happen, because...?
9533}
9534
9535/// Find the base specifier for a base class with the given type.
9536static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9537 QualType DesiredBase,
9538 bool &AnyDependentBases) {
9539 // Check whether the named type is a direct base class.
9540 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9541 for (auto &Base : Derived->bases()) {
9542 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9543 if (CanonicalDesiredBase == BaseType)
9544 return &Base;
9545 if (BaseType->isDependentType())
9546 AnyDependentBases = true;
9547 }
9548 return nullptr;
9549}
9550
9551namespace {
9552class UsingValidatorCCC : public CorrectionCandidateCallback {
9553public:
9554 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9555 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9556 : HasTypenameKeyword(HasTypenameKeyword),
9557 IsInstantiation(IsInstantiation), OldNNS(NNS),
9558 RequireMemberOf(RequireMemberOf) {}
9559
9560 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9561 NamedDecl *ND = Candidate.getCorrectionDecl();
9562
9563 // Keywords are not valid here.
9564 if (!ND || isa<NamespaceDecl>(ND))
9565 return false;
9566
9567 // Completely unqualified names are invalid for a 'using' declaration.
9568 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9569 return false;
9570
9571 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9572 // reject.
9573
9574 if (RequireMemberOf) {
9575 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9576 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9577 // No-one ever wants a using-declaration to name an injected-class-name
9578 // of a base class, unless they're declaring an inheriting constructor.
9579 ASTContext &Ctx = ND->getASTContext();
9580 if (!Ctx.getLangOpts().CPlusPlus11)
9581 return false;
9582 QualType FoundType = Ctx.getRecordType(FoundRecord);
9583
9584 // Check that the injected-class-name is named as a member of its own
9585 // type; we don't want to suggest 'using Derived::Base;', since that
9586 // means something else.
9587 NestedNameSpecifier *Specifier =
9588 Candidate.WillReplaceSpecifier()
9589 ? Candidate.getCorrectionSpecifier()
9590 : OldNNS;
9591 if (!Specifier->getAsType() ||
9592 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9593 return false;
9594
9595 // Check that this inheriting constructor declaration actually names a
9596 // direct base class of the current class.
9597 bool AnyDependentBases = false;
9598 if (!findDirectBaseWithType(RequireMemberOf,
9599 Ctx.getRecordType(FoundRecord),
9600 AnyDependentBases) &&
9601 !AnyDependentBases)
9602 return false;
9603 } else {
9604 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9605 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9606 return false;
9607
9608 // FIXME: Check that the base class member is accessible?
9609 }
9610 } else {
9611 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9612 if (FoundRecord && FoundRecord->isInjectedClassName())
9613 return false;
9614 }
9615
9616 if (isa<TypeDecl>(ND))
9617 return HasTypenameKeyword || !IsInstantiation;
9618
9619 return !HasTypenameKeyword;
9620 }
9621
9622private:
9623 bool HasTypenameKeyword;
9624 bool IsInstantiation;
9625 NestedNameSpecifier *OldNNS;
9626 CXXRecordDecl *RequireMemberOf;
9627};
9628} // end anonymous namespace
9629
9630/// Builds a using declaration.
9631///
9632/// \param IsInstantiation - Whether this call arises from an
9633/// instantiation of an unresolved using declaration. We treat
9634/// the lookup differently for these declarations.
9635NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9636 SourceLocation UsingLoc,
9637 bool HasTypenameKeyword,
9638 SourceLocation TypenameLoc,
9639 CXXScopeSpec &SS,
9640 DeclarationNameInfo NameInfo,
9641 SourceLocation EllipsisLoc,
9642 AttributeList *AttrList,
9643 bool IsInstantiation) {
9644 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9644, __extension__ __PRETTY_FUNCTION__))
;
9645 SourceLocation IdentLoc = NameInfo.getLoc();
9646 assert(IdentLoc.isValid() && "Invalid TargetName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid TargetName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9646, __extension__ __PRETTY_FUNCTION__))
;
9647
9648 // FIXME: We ignore attributes for now.
9649
9650 // For an inheriting constructor declaration, the name of the using
9651 // declaration is the name of a constructor in this class, not in the
9652 // base class.
9653 DeclarationNameInfo UsingName = NameInfo;
9654 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9655 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9656 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9657 Context.getCanonicalType(Context.getRecordType(RD))));
9658
9659 // Do the redeclaration lookup in the current scope.
9660 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9661 ForVisibleRedeclaration);
9662 Previous.setHideTags(false);
9663 if (S) {
9664 LookupName(Previous, S);
9665
9666 // It is really dumb that we have to do this.
9667 LookupResult::Filter F = Previous.makeFilter();
9668 while (F.hasNext()) {
9669 NamedDecl *D = F.next();
9670 if (!isDeclInScope(D, CurContext, S))
9671 F.erase();
9672 // If we found a local extern declaration that's not ordinarily visible,
9673 // and this declaration is being added to a non-block scope, ignore it.
9674 // We're only checking for scope conflicts here, not also for violations
9675 // of the linkage rules.
9676 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9677 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9678 F.erase();
9679 }
9680 F.done();
9681 } else {
9682 assert(IsInstantiation && "no scope in non-instantiation")(static_cast <bool> (IsInstantiation && "no scope in non-instantiation"
) ? void (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9682, __extension__ __PRETTY_FUNCTION__))
;
9683 if (CurContext->isRecord())
9684 LookupQualifiedName(Previous, CurContext);
9685 else {
9686 // No redeclaration check is needed here; in non-member contexts we
9687 // diagnosed all possible conflicts with other using-declarations when
9688 // building the template:
9689 //
9690 // For a dependent non-type using declaration, the only valid case is
9691 // if we instantiate to a single enumerator. We check for conflicts
9692 // between shadow declarations we introduce, and we check in the template
9693 // definition for conflicts between a non-type using declaration and any
9694 // other declaration, which together covers all cases.
9695 //
9696 // A dependent typename using declaration will never successfully
9697 // instantiate, since it will always name a class member, so we reject
9698 // that in the template definition.
9699 }
9700 }
9701
9702 // Check for invalid redeclarations.
9703 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9704 SS, IdentLoc, Previous))
9705 return nullptr;
9706
9707 // Check for bad qualifiers.
9708 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9709 IdentLoc))
9710 return nullptr;
9711
9712 DeclContext *LookupContext = computeDeclContext(SS);
9713 NamedDecl *D;
9714 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9715 if (!LookupContext || EllipsisLoc.isValid()) {
9716 if (HasTypenameKeyword) {
9717 // FIXME: not all declaration name kinds are legal here
9718 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9719 UsingLoc, TypenameLoc,
9720 QualifierLoc,
9721 IdentLoc, NameInfo.getName(),
9722 EllipsisLoc);
9723 } else {
9724 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9725 QualifierLoc, NameInfo, EllipsisLoc);
9726 }
9727 D->setAccess(AS);
9728 CurContext->addDecl(D);
9729 return D;
9730 }
9731
9732 auto Build = [&](bool Invalid) {
9733 UsingDecl *UD =
9734 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9735 UsingName, HasTypenameKeyword);
9736 UD->setAccess(AS);
9737 CurContext->addDecl(UD);
9738 UD->setInvalidDecl(Invalid);
9739 return UD;
9740 };
9741 auto BuildInvalid = [&]{ return Build(true); };
9742 auto BuildValid = [&]{ return Build(false); };
9743
9744 if (RequireCompleteDeclContext(SS, LookupContext))
9745 return BuildInvalid();
9746
9747 // Look up the target name.
9748 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9749
9750 // Unlike most lookups, we don't always want to hide tag
9751 // declarations: tag names are visible through the using declaration
9752 // even if hidden by ordinary names, *except* in a dependent context
9753 // where it's important for the sanity of two-phase lookup.
9754 if (!IsInstantiation)
9755 R.setHideTags(false);
9756
9757 // For the purposes of this lookup, we have a base object type
9758 // equal to that of the current context.
9759 if (CurContext->isRecord()) {
9760 R.setBaseObjectType(
9761 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9762 }
9763
9764 LookupQualifiedName(R, LookupContext);
9765
9766 // Try to correct typos if possible. If constructor name lookup finds no
9767 // results, that means the named class has no explicit constructors, and we
9768 // suppressed declaring implicit ones (probably because it's dependent or
9769 // invalid).
9770 if (R.empty() &&
9771 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9772 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9773 // it will believe that glibc provides a ::gets in cases where it does not,
9774 // and will try to pull it into namespace std with a using-declaration.
9775 // Just ignore the using-declaration in that case.
9776 auto *II = NameInfo.getName().getAsIdentifierInfo();
9777 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9778 CurContext->isStdNamespace() &&
9779 isa<TranslationUnitDecl>(LookupContext) &&
9780 getSourceManager().isInSystemHeader(UsingLoc))
9781 return nullptr;
9782 if (TypoCorrection Corrected = CorrectTypo(
9783 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9784 llvm::make_unique<UsingValidatorCCC>(
9785 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9786 dyn_cast<CXXRecordDecl>(CurContext)),
9787 CTK_ErrorRecovery)) {
9788 // We reject candidates where DroppedSpecifier == true, hence the
9789 // literal '0' below.
9790 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9791 << NameInfo.getName() << LookupContext << 0
9792 << SS.getRange());
9793
9794 // If we picked a correction with no attached Decl we can't do anything
9795 // useful with it, bail out.
9796 NamedDecl *ND = Corrected.getCorrectionDecl();
9797 if (!ND)
9798 return BuildInvalid();
9799
9800 // If we corrected to an inheriting constructor, handle it as one.
9801 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9802 if (RD && RD->isInjectedClassName()) {
9803 // The parent of the injected class name is the class itself.
9804 RD = cast<CXXRecordDecl>(RD->getParent());
9805
9806 // Fix up the information we'll use to build the using declaration.
9807 if (Corrected.WillReplaceSpecifier()) {
9808 NestedNameSpecifierLocBuilder Builder;
9809 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9810 QualifierLoc.getSourceRange());
9811 QualifierLoc = Builder.getWithLocInContext(Context);
9812 }
9813
9814 // In this case, the name we introduce is the name of a derived class
9815 // constructor.
9816 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9817 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9818 Context.getCanonicalType(Context.getRecordType(CurClass))));
9819 UsingName.setNamedTypeInfo(nullptr);
9820 for (auto *Ctor : LookupConstructors(RD))
9821 R.addDecl(Ctor);
9822 R.resolveKind();
9823 } else {
9824 // FIXME: Pick up all the declarations if we found an overloaded
9825 // function.
9826 UsingName.setName(ND->getDeclName());
9827 R.addDecl(ND);
9828 }
9829 } else {
9830 Diag(IdentLoc, diag::err_no_member)
9831 << NameInfo.getName() << LookupContext << SS.getRange();
9832 return BuildInvalid();
9833 }
9834 }
9835
9836 if (R.isAmbiguous())
9837 return BuildInvalid();
9838
9839 if (HasTypenameKeyword) {
9840 // If we asked for a typename and got a non-type decl, error out.
9841 if (!R.getAsSingle<TypeDecl>()) {
9842 Diag(IdentLoc, diag::err_using_typename_non_type);
9843 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9844 Diag((*I)->getUnderlyingDecl()->getLocation(),
9845 diag::note_using_decl_target);
9846 return BuildInvalid();
9847 }
9848 } else {
9849 // If we asked for a non-typename and we got a type, error out,
9850 // but only if this is an instantiation of an unresolved using
9851 // decl. Otherwise just silently find the type name.
9852 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9853 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9854 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9855 return BuildInvalid();
9856 }
9857 }
9858
9859 // C++14 [namespace.udecl]p6:
9860 // A using-declaration shall not name a namespace.
9861 if (R.getAsSingle<NamespaceDecl>()) {
9862 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9863 << SS.getRange();
9864 return BuildInvalid();
9865 }
9866
9867 // C++14 [namespace.udecl]p7:
9868 // A using-declaration shall not name a scoped enumerator.
9869 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9870 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9871 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9872 << SS.getRange();
9873 return BuildInvalid();
9874 }
9875 }
9876
9877 UsingDecl *UD = BuildValid();
9878
9879 // Some additional rules apply to inheriting constructors.
9880 if (UsingName.getName().getNameKind() ==
9881 DeclarationName::CXXConstructorName) {
9882 // Suppress access diagnostics; the access check is instead performed at the
9883 // point of use for an inheriting constructor.
9884 R.suppressDiagnostics();
9885 if (CheckInheritingConstructorUsingDecl(UD))
9886 return UD;
9887 }
9888
9889 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9890 UsingShadowDecl *PrevDecl = nullptr;
9891 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9892 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9893 }
9894
9895 return UD;
9896}
9897
9898NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9899 ArrayRef<NamedDecl *> Expansions) {
9900 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9902, __extension__ __PRETTY_FUNCTION__))
9901 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9902, __extension__ __PRETTY_FUNCTION__))
9902 isa<UsingPackDecl>(InstantiatedFrom))(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9902, __extension__ __PRETTY_FUNCTION__))
;
9903
9904 auto *UPD =
9905 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9906 UPD->setAccess(InstantiatedFrom->getAccess());
9907 CurContext->addDecl(UPD);
9908 return UPD;
9909}
9910
9911/// Additional checks for a using declaration referring to a constructor name.
9912bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9913 assert(!UD->hasTypename() && "expecting a constructor name")(static_cast <bool> (!UD->hasTypename() && "expecting a constructor name"
) ? void (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9913, __extension__ __PRETTY_FUNCTION__))
;
9914
9915 const Type *SourceType = UD->getQualifier()->getAsType();
9916 assert(SourceType &&(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9917, __extension__ __PRETTY_FUNCTION__))
9917 "Using decl naming constructor doesn't have type in scope spec.")(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9917, __extension__ __PRETTY_FUNCTION__))
;
9918 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9919
9920 // Check whether the named type is a direct base class.
9921 bool AnyDependentBases = false;
9922 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9923 AnyDependentBases);
9924 if (!Base && !AnyDependentBases) {
9925 Diag(UD->getUsingLoc(),
9926 diag::err_using_decl_constructor_not_in_direct_base)
9927 << UD->getNameInfo().getSourceRange()
9928 << QualType(SourceType, 0) << TargetClass;
9929 UD->setInvalidDecl();
9930 return true;
9931 }
9932
9933 if (Base)
9934 Base->setInheritConstructors();
9935
9936 return false;
9937}
9938
9939/// Checks that the given using declaration is not an invalid
9940/// redeclaration. Note that this is checking only for the using decl
9941/// itself, not for any ill-formedness among the UsingShadowDecls.
9942bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9943 bool HasTypenameKeyword,
9944 const CXXScopeSpec &SS,
9945 SourceLocation NameLoc,
9946 const LookupResult &Prev) {
9947 NestedNameSpecifier *Qual = SS.getScopeRep();
9948
9949 // C++03 [namespace.udecl]p8:
9950 // C++0x [namespace.udecl]p10:
9951 // A using-declaration is a declaration and can therefore be used
9952 // repeatedly where (and only where) multiple declarations are
9953 // allowed.
9954 //
9955 // That's in non-member contexts.
9956 if (!CurContext->getRedeclContext()->isRecord()) {
9957 // A dependent qualifier outside a class can only ever resolve to an
9958 // enumeration type. Therefore it conflicts with any other non-type
9959 // declaration in the same scope.
9960 // FIXME: How should we check for dependent type-type conflicts at block
9961 // scope?
9962 if (Qual->isDependent() && !HasTypenameKeyword) {
9963 for (auto *D : Prev) {
9964 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9965 bool OldCouldBeEnumerator =
9966 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9967 Diag(NameLoc,
9968 OldCouldBeEnumerator ? diag::err_redefinition
9969 : diag::err_redefinition_different_kind)
9970 << Prev.getLookupName();
9971 Diag(D->getLocation(), diag::note_previous_definition);
9972 return true;
9973 }
9974 }
9975 }
9976 return false;
9977 }
9978
9979 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9980 NamedDecl *D = *I;
9981
9982 bool DTypename;
9983 NestedNameSpecifier *DQual;
9984 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9985 DTypename = UD->hasTypename();
9986 DQual = UD->getQualifier();
9987 } else if (UnresolvedUsingValueDecl *UD
9988 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9989 DTypename = false;
9990 DQual = UD->getQualifier();
9991 } else if (UnresolvedUsingTypenameDecl *UD
9992 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9993 DTypename = true;
9994 DQual = UD->getQualifier();
9995 } else continue;
9996
9997 // using decls differ if one says 'typename' and the other doesn't.
9998 // FIXME: non-dependent using decls?
9999 if (HasTypenameKeyword != DTypename) continue;
10000
10001 // using decls differ if they name different scopes (but note that
10002 // template instantiation can cause this check to trigger when it
10003 // didn't before instantiation).
10004 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10005 Context.getCanonicalNestedNameSpecifier(DQual))
10006 continue;
10007
10008 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10009 Diag(D->getLocation(), diag::note_using_decl) << 1;
10010 return true;
10011 }
10012
10013 return false;
10014}
10015
10016
10017/// Checks that the given nested-name qualifier used in a using decl
10018/// in the current context is appropriately related to the current
10019/// scope. If an error is found, diagnoses it and returns true.
10020bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10021 bool HasTypename,
10022 const CXXScopeSpec &SS,
10023 const DeclarationNameInfo &NameInfo,
10024 SourceLocation NameLoc) {
10025 DeclContext *NamedContext = computeDeclContext(SS);
10026
10027 if (!CurContext->isRecord()) {
10028 // C++03 [namespace.udecl]p3:
10029 // C++0x [namespace.udecl]p8:
10030 // A using-declaration for a class member shall be a member-declaration.
10031
10032 // If we weren't able to compute a valid scope, it might validly be a
10033 // dependent class scope or a dependent enumeration unscoped scope. If
10034 // we have a 'typename' keyword, the scope must resolve to a class type.
10035 if ((HasTypename && !NamedContext) ||
10036 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10037 auto *RD = NamedContext
10038 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10039 : nullptr;
10040 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10041 RD = nullptr;
10042
10043 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10044 << SS.getRange();
10045
10046 // If we have a complete, non-dependent source type, try to suggest a
10047 // way to get the same effect.
10048 if (!RD)
10049 return true;
10050
10051 // Find what this using-declaration was referring to.
10052 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10053 R.setHideTags(false);
10054 R.suppressDiagnostics();
10055 LookupQualifiedName(R, RD);
10056
10057 if (R.getAsSingle<TypeDecl>()) {
10058 if (getLangOpts().CPlusPlus11) {
10059 // Convert 'using X::Y;' to 'using Y = X::Y;'.
10060 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10061 << 0 // alias declaration
10062 << FixItHint::CreateInsertion(SS.getBeginLoc(),
10063 NameInfo.getName().getAsString() +
10064 " = ");
10065 } else {
10066 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10067 SourceLocation InsertLoc =
10068 getLocForEndOfToken(NameInfo.getLocEnd());
10069 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10070 << 1 // typedef declaration
10071 << FixItHint::CreateReplacement(UsingLoc, "typedef")
10072 << FixItHint::CreateInsertion(
10073 InsertLoc, " " + NameInfo.getName().getAsString());
10074 }
10075 } else if (R.getAsSingle<VarDecl>()) {
10076 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10077 // repeating the type of the static data member here.
10078 FixItHint FixIt;
10079 if (getLangOpts().CPlusPlus11) {
10080 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10081 FixIt = FixItHint::CreateReplacement(
10082 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10083 }
10084
10085 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10086 << 2 // reference declaration
10087 << FixIt;
10088 } else if (R.getAsSingle<EnumConstantDecl>()) {
10089 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10090 // repeating the type of the enumeration here, and we can't do so if
10091 // the type is anonymous.
10092 FixItHint FixIt;
10093 if (getLangOpts().CPlusPlus11) {
10094 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10095 FixIt = FixItHint::CreateReplacement(
10096 UsingLoc,
10097 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10098 }
10099
10100 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10101 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10102 << FixIt;
10103 }
10104 return true;
10105 }
10106
10107 // Otherwise, this might be valid.
10108 return false;
10109 }
10110
10111 // The current scope is a record.
10112
10113 // If the named context is dependent, we can't decide much.
10114 if (!NamedContext) {
10115 // FIXME: in C++0x, we can diagnose if we can prove that the
10116 // nested-name-specifier does not refer to a base class, which is
10117 // still possible in some cases.
10118
10119 // Otherwise we have to conservatively report that things might be
10120 // okay.
10121 return false;
10122 }
10123
10124 if (!NamedContext->isRecord()) {
10125 // Ideally this would point at the last name in the specifier,
10126 // but we don't have that level of source info.
10127 Diag(SS.getRange().getBegin(),
10128 diag::err_using_decl_nested_name_specifier_is_not_class)
10129 << SS.getScopeRep() << SS.getRange();
10130 return true;
10131 }
10132
10133 if (!NamedContext->isDependentContext() &&
10134 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10135 return true;
10136
10137 if (getLangOpts().CPlusPlus11) {
10138 // C++11 [namespace.udecl]p3:
10139 // In a using-declaration used as a member-declaration, the
10140 // nested-name-specifier shall name a base class of the class
10141 // being defined.
10142
10143 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10144 cast<CXXRecordDecl>(NamedContext))) {
10145 if (CurContext == NamedContext) {
10146 Diag(NameLoc,
10147 diag::err_using_decl_nested_name_specifier_is_current_class)
10148 << SS.getRange();
10149 return true;
10150 }
10151
10152 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10153 Diag(SS.getRange().getBegin(),
10154 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10155 << SS.getScopeRep()
10156 << cast<CXXRecordDecl>(CurContext)
10157 << SS.getRange();
10158 }
10159 return true;
10160 }
10161
10162 return false;
10163 }
10164
10165 // C++03 [namespace.udecl]p4:
10166 // A using-declaration used as a member-declaration shall refer
10167 // to a member of a base class of the class being defined [etc.].
10168
10169 // Salient point: SS doesn't have to name a base class as long as
10170 // lookup only finds members from base classes. Therefore we can
10171 // diagnose here only if we can prove that that can't happen,
10172 // i.e. if the class hierarchies provably don't intersect.
10173
10174 // TODO: it would be nice if "definitely valid" results were cached
10175 // in the UsingDecl and UsingShadowDecl so that these checks didn't
10176 // need to be repeated.
10177
10178 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10179 auto Collect = [&Bases](const CXXRecordDecl *Base) {
10180 Bases.insert(Base);
10181 return true;
10182 };
10183
10184 // Collect all bases. Return false if we find a dependent base.
10185 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10186 return false;
10187
10188 // Returns true if the base is dependent or is one of the accumulated base
10189 // classes.
10190 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10191 return !Bases.count(Base);
10192 };
10193
10194 // Return false if the class has a dependent base or if it or one
10195 // of its bases is present in the base set of the current context.
10196 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10197 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10198 return false;
10199
10200 Diag(SS.getRange().getBegin(),
10201 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10202 << SS.getScopeRep()
10203 << cast<CXXRecordDecl>(CurContext)
10204 << SS.getRange();
10205
10206 return true;
10207}
10208
10209Decl *Sema::ActOnAliasDeclaration(Scope *S,
10210 AccessSpecifier AS,
10211 MultiTemplateParamsArg TemplateParamLists,
10212 SourceLocation UsingLoc,
10213 UnqualifiedId &Name,
10214 AttributeList *AttrList,
10215 TypeResult Type,
10216 Decl *DeclFromDeclSpec) {
10217 // Skip up to the relevant declaration scope.
10218 while (S->isTemplateParamScope())
10219 S = S->getParent();
10220 assert((S->getFlags() & Scope::DeclScope) &&(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10221, __extension__ __PRETTY_FUNCTION__))
10221 "got alias-declaration outside of declaration scope")(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10221, __extension__ __PRETTY_FUNCTION__))
;
10222
10223 if (Type.isInvalid())
10224 return nullptr;
10225
10226 bool Invalid = false;
10227 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10228 TypeSourceInfo *TInfo = nullptr;
10229 GetTypeFromParser(Type.get(), &TInfo);
10230
10231 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10232 return nullptr;
10233
10234 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10235 UPPC_DeclarationType)) {
10236 Invalid = true;
10237 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10238 TInfo->getTypeLoc().getBeginLoc());
10239 }
10240
10241 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10242 TemplateParamLists.size()
10243 ? forRedeclarationInCurContext()
10244 : ForVisibleRedeclaration);
10245 LookupName(Previous, S);
10246
10247 // Warn about shadowing the name of a template parameter.
10248 if (Previous.isSingleResult() &&
10249 Previous.getFoundDecl()->isTemplateParameter()) {
10250 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10251 Previous.clear();
10252 }
10253
10254 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&(static_cast <bool> (Name.Kind == UnqualifiedIdKind::IK_Identifier
&& "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10255, __extension__ __PRETTY_FUNCTION__))
10255 "name in alias declaration must be an identifier")(static_cast <bool> (Name.Kind == UnqualifiedIdKind::IK_Identifier
&& "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10255, __extension__ __PRETTY_FUNCTION__))
;
10256 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10257 Name.StartLocation,
10258 Name.Identifier, TInfo);
10259
10260 NewTD->setAccess(AS);
10261
10262 if (Invalid)
10263 NewTD->setInvalidDecl();
10264
10265 ProcessDeclAttributeList(S, NewTD, AttrList);
10266 AddPragmaAttributes(S, NewTD);
10267
10268 CheckTypedefForVariablyModifiedType(S, NewTD);
10269 Invalid |= NewTD->isInvalidDecl();
10270
10271 bool Redeclaration = false;
10272
10273 NamedDecl *NewND;
10274 if (TemplateParamLists.size()) {
10275 TypeAliasTemplateDecl *OldDecl = nullptr;
10276 TemplateParameterList *OldTemplateParams = nullptr;
10277
10278 if (TemplateParamLists.size() != 1) {
10279 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10280 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10281 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10282 }
10283 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10284
10285 // Check that we can declare a template here.
10286 if (CheckTemplateDeclScope(S, TemplateParams))
10287 return nullptr;
10288
10289 // Only consider previous declarations in the same scope.
10290 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10291 /*ExplicitInstantiationOrSpecialization*/false);
10292 if (!Previous.empty()) {
10293 Redeclaration = true;
10294
10295 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10296 if (!OldDecl && !Invalid) {
10297 Diag(UsingLoc, diag::err_redefinition_different_kind)
10298 << Name.Identifier;
10299
10300 NamedDecl *OldD = Previous.getRepresentativeDecl();
10301 if (OldD->getLocation().isValid())
10302 Diag(OldD->getLocation(), diag::note_previous_definition);
10303
10304 Invalid = true;
10305 }
10306
10307 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10308 if (TemplateParameterListsAreEqual(TemplateParams,
10309 OldDecl->getTemplateParameters(),
10310 /*Complain=*/true,
10311 TPL_TemplateMatch))
10312 OldTemplateParams = OldDecl->getTemplateParameters();
10313 else
10314 Invalid = true;
10315
10316 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10317 if (!Invalid &&
10318 !Context.hasSameType(OldTD->getUnderlyingType(),
10319 NewTD->getUnderlyingType())) {
10320 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10321 // but we can't reasonably accept it.
10322 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10323 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10324 if (OldTD->getLocation().isValid())
10325 Diag(OldTD->getLocation(), diag::note_previous_definition);
10326 Invalid = true;
10327 }
10328 }
10329 }
10330
10331 // Merge any previous default template arguments into our parameters,
10332 // and check the parameter list.
10333 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10334 TPC_TypeAliasTemplate))
10335 return nullptr;
10336
10337 TypeAliasTemplateDecl *NewDecl =
10338 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10339 Name.Identifier, TemplateParams,
10340 NewTD);
10341 NewTD->setDescribedAliasTemplate(NewDecl);
10342
10343 NewDecl->setAccess(AS);
10344
10345 if (Invalid)
10346 NewDecl->setInvalidDecl();
10347 else if (OldDecl) {
10348 NewDecl->setPreviousDecl(OldDecl);
10349 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10350 }
10351
10352 NewND = NewDecl;
10353 } else {
10354 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10355 setTagNameForLinkagePurposes(TD, NewTD);
10356 handleTagNumbering(TD, S);
10357 }
10358 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10359 NewND = NewTD;
10360 }
10361
10362 PushOnScopeChains(NewND, S);
10363 ActOnDocumentableDecl(NewND);
10364 return NewND;
10365}
10366
10367Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10368 SourceLocation AliasLoc,
10369 IdentifierInfo *Alias, CXXScopeSpec &SS,
10370 SourceLocation IdentLoc,
10371 IdentifierInfo *Ident) {
10372
10373 // Lookup the namespace name.
10374 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10375 LookupParsedName(R, S, &SS);
10376
10377 if (R.isAmbiguous())
10378 return nullptr;
10379
10380 if (R.empty()) {
10381 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10382 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10383 return nullptr;
10384 }
10385 }
10386 assert(!R.isAmbiguous() && !R.empty())(static_cast <bool> (!R.isAmbiguous() && !R.empty
()) ? void (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10386, __extension__ __PRETTY_FUNCTION__))
;
10387 NamedDecl *ND = R.getRepresentativeDecl();
10388
10389 // Check if we have a previous declaration with the same name.
10390 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10391 ForVisibleRedeclaration);
10392 LookupName(PrevR, S);
10393
10394 // Check we're not shadowing a template parameter.
10395 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10396 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10397 PrevR.clear();
10398 }
10399
10400 // Filter out any other lookup result from an enclosing scope.
10401 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10402 /*AllowInlineNamespace*/false);
10403
10404 // Find the previous declaration and check that we can redeclare it.
10405 NamespaceAliasDecl *Prev = nullptr;
10406 if (PrevR.isSingleResult()) {
10407 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10408 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10409 // We already have an alias with the same name that points to the same
10410 // namespace; check that it matches.
10411 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10412 Prev = AD;
10413 } else if (isVisible(PrevDecl)) {
10414 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10415 << Alias;
10416 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10417 << AD->getNamespace();
10418 return nullptr;
10419 }
10420 } else if (isVisible(PrevDecl)) {
10421 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10422 ? diag::err_redefinition
10423 : diag::err_redefinition_different_kind;
10424 Diag(AliasLoc, DiagID) << Alias;
10425 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10426 return nullptr;
10427 }
10428 }
10429
10430 // The use of a nested name specifier may trigger deprecation warnings.
10431 DiagnoseUseOfDecl(ND, IdentLoc);
10432
10433 NamespaceAliasDecl *AliasDecl =
10434 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10435 Alias, SS.getWithLocInContext(Context),
10436 IdentLoc, ND);
10437 if (Prev)
10438 AliasDecl->setPreviousDecl(Prev);
10439
10440 PushOnScopeChains(AliasDecl, S);
10441 return AliasDecl;
10442}
10443
10444namespace {
10445struct SpecialMemberExceptionSpecInfo
10446 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10447 SourceLocation Loc;
10448 Sema::ImplicitExceptionSpecification ExceptSpec;
10449
10450 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10451 Sema::CXXSpecialMember CSM,
10452 Sema::InheritedConstructorInfo *ICI,
10453 SourceLocation Loc)
10454 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10455
10456 bool visitBase(CXXBaseSpecifier *Base);
10457 bool visitField(FieldDecl *FD);
10458
10459 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10460 unsigned Quals);
10461
10462 void visitSubobjectCall(Subobject Subobj,
10463 Sema::SpecialMemberOverloadResult SMOR);
10464};
10465}
10466
10467bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10468 auto *RT = Base->getType()->getAs<RecordType>();
10469 if (!RT)
10470 return false;
10471
10472 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10473 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10474 if (auto *BaseCtor = SMOR.getMethod()) {
10475 visitSubobjectCall(Base, BaseCtor);
10476 return false;
10477 }
10478
10479 visitClassSubobject(BaseClass, Base, 0);
10480 return false;
10481}
10482
10483bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10484 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10485 Expr *E = FD->getInClassInitializer();
10486 if (!E)
10487 // FIXME: It's a little wasteful to build and throw away a
10488 // CXXDefaultInitExpr here.
10489 // FIXME: We should have a single context note pointing at Loc, and
10490 // this location should be MD->getLocation() instead, since that's
10491 // the location where we actually use the default init expression.
10492 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10493 if (E)
10494 ExceptSpec.CalledExpr(E);
10495 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10496 ->getAs<RecordType>()) {
10497 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10498 FD->getType().getCVRQualifiers());
10499 }
10500 return false;
10501}
10502
10503void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10504 Subobject Subobj,
10505 unsigned Quals) {
10506 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10507 bool IsMutable = Field && Field->isMutable();
10508 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10509}
10510
10511void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10512 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10513 // Note, if lookup fails, it doesn't matter what exception specification we
10514 // choose because the special member will be deleted.
10515 if (CXXMethodDecl *MD = SMOR.getMethod())
10516 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10517}
10518
10519static Sema::ImplicitExceptionSpecification
10520ComputeDefaultedSpecialMemberExceptionSpec(
10521 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10522 Sema::InheritedConstructorInfo *ICI) {
10523 CXXRecordDecl *ClassDecl = MD->getParent();
10524
10525 // C++ [except.spec]p14:
10526 // An implicitly declared special member function (Clause 12) shall have an
10527 // exception-specification. [...]
10528 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10529 if (ClassDecl->isInvalidDecl())
10530 return Info.ExceptSpec;
10531
10532 // C++1z [except.spec]p7:
10533 // [Look for exceptions thrown by] a constructor selected [...] to
10534 // initialize a potentially constructed subobject,
10535 // C++1z [except.spec]p8:
10536 // The exception specification for an implicitly-declared destructor, or a
10537 // destructor without a noexcept-specifier, is potentially-throwing if and
10538 // only if any of the destructors for any of its potentially constructed
10539 // subojects is potentially throwing.
10540 // FIXME: We respect the first rule but ignore the "potentially constructed"
10541 // in the second rule to resolve a core issue (no number yet) that would have
10542 // us reject:
10543 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10544 // struct B : A {};
10545 // struct C : B { void f(); };
10546 // ... due to giving B::~B() a non-throwing exception specification.
10547 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10548 : Info.VisitAllBases);
10549
10550 return Info.ExceptSpec;
10551}
10552
10553namespace {
10554/// RAII object to register a special member as being currently declared.
10555struct DeclaringSpecialMember {
10556 Sema &S;
10557 Sema::SpecialMemberDecl D;
10558 Sema::ContextRAII SavedContext;
10559 bool WasAlreadyBeingDeclared;
10560
10561 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10562 : S(S), D(RD, CSM), SavedContext(S, RD) {
10563 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10564 if (WasAlreadyBeingDeclared)
10565 // This almost never happens, but if it does, ensure that our cache
10566 // doesn't contain a stale result.
10567 S.SpecialMemberCache.clear();
10568 else {
10569 // Register a note to be produced if we encounter an error while
10570 // declaring the special member.
10571 Sema::CodeSynthesisContext Ctx;
10572 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10573 // FIXME: We don't have a location to use here. Using the class's
10574 // location maintains the fiction that we declare all special members
10575 // with the class, but (1) it's not clear that lying about that helps our
10576 // users understand what's going on, and (2) there may be outer contexts
10577 // on the stack (some of which are relevant) and printing them exposes
10578 // our lies.
10579 Ctx.PointOfInstantiation = RD->getLocation();
10580 Ctx.Entity = RD;
10581 Ctx.SpecialMember = CSM;
10582 S.pushCodeSynthesisContext(Ctx);
10583 }
10584 }
10585 ~DeclaringSpecialMember() {
10586 if (!WasAlreadyBeingDeclared) {
10587 S.SpecialMembersBeingDeclared.erase(D);
10588 S.popCodeSynthesisContext();
10589 }
10590 }
10591
10592 /// \brief Are we already trying to declare this special member?
10593 bool isAlreadyBeingDeclared() const {
10594 return WasAlreadyBeingDeclared;
10595 }
10596};
10597}
10598
10599void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10600 // Look up any existing declarations, but don't trigger declaration of all
10601 // implicit special members with this name.
10602 DeclarationName Name = FD->getDeclName();
10603 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10604 ForExternalRedeclaration);
10605 for (auto *D : FD->getParent()->lookup(Name))
10606 if (auto *Acceptable = R.getAcceptableDecl(D))
10607 R.addDecl(Acceptable);
10608 R.resolveKind();
10609 R.suppressDiagnostics();
10610
10611 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10612}
10613
10614CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10615 CXXRecordDecl *ClassDecl) {
10616 // C++ [class.ctor]p5:
10617 // A default constructor for a class X is a constructor of class X
10618 // that can be called without an argument. If there is no
10619 // user-declared constructor for class X, a default constructor is
10620 // implicitly declared. An implicitly-declared default constructor
10621 // is an inline public member of its class.
10622 assert(ClassDecl->needsImplicitDefaultConstructor() &&(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10623, __extension__ __PRETTY_FUNCTION__))
10623 "Should not build implicit default constructor!")(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10623, __extension__ __PRETTY_FUNCTION__))
;
10624
10625 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10626 if (DSM.isAlreadyBeingDeclared())
10627 return nullptr;
10628
10629 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10630 CXXDefaultConstructor,
10631 false);
10632
10633 // Create the actual constructor declaration.
10634 CanQualType ClassType
10635 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10636 SourceLocation ClassLoc = ClassDecl->getLocation();
10637 DeclarationName Name
10638 = Context.DeclarationNames.getCXXConstructorName(ClassType);
10639 DeclarationNameInfo NameInfo(Name, ClassLoc);
10640 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10641 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10642 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10643 /*isImplicitlyDeclared=*/true, Constexpr);
10644 DefaultCon->setAccess(AS_public);
10645 DefaultCon->setDefaulted();
10646
10647 if (getLangOpts().CUDA) {
10648 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10649 DefaultCon,
10650 /* ConstRHS */ false,
10651 /* Diagnose */ false);
10652 }
10653
10654 // Build an exception specification pointing back at this constructor.
10655 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10656 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10657
10658 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10659 // constructors is easy to compute.
10660 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10661
10662 // Note that we have declared this constructor.
10663 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10664
10665 Scope *S = getScopeForContext(ClassDecl);
10666 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10667
10668 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10669 SetDeclDeleted(DefaultCon, ClassLoc);
10670
10671 if (S)
10672 PushOnScopeChains(DefaultCon, S, false);
10673 ClassDecl->addDecl(DefaultCon);
10674
10675 return DefaultCon;
10676}
10677
10678void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10679 CXXConstructorDecl *Constructor) {
10680 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10683, __extension__ __PRETTY_FUNCTION__))
10681 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10683, __extension__ __PRETTY_FUNCTION__))
10682 !Constructor->isDeleted()) &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10683, __extension__ __PRETTY_FUNCTION__))
10683 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10683, __extension__ __PRETTY_FUNCTION__))
;
10684 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10685 return;
10686
10687 CXXRecordDecl *ClassDecl = Constructor->getParent();
10688 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10688, __extension__ __PRETTY_FUNCTION__))
;
10689
10690 SynthesizedFunctionScope Scope(*this, Constructor);
10691
10692 // The exception specification is needed because we are defining the
10693 // function.
10694 ResolveExceptionSpec(CurrentLocation,
10695 Constructor->getType()->castAs<FunctionProtoType>());
10696 MarkVTableUsed(CurrentLocation, ClassDecl);
10697
10698 // Add a context note for diagnostics produced after this point.
10699 Scope.addContextNote(CurrentLocation);
10700
10701 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10702 Constructor->setInvalidDecl();
10703 return;
10704 }
10705
10706 SourceLocation Loc = Constructor->getLocEnd().isValid()
10707 ? Constructor->getLocEnd()
10708 : Constructor->getLocation();
10709 Constructor->setBody(new (Context) CompoundStmt(Loc));
10710 Constructor->markUsed(Context);
10711
10712 if (ASTMutationListener *L = getASTMutationListener()) {
10713 L->CompletedImplicitDefinition(Constructor);
10714 }
10715
10716 DiagnoseUninitializedFields(*this, Constructor);
10717}
10718
10719void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10720 // Perform any delayed checks on exception specifications.
10721 CheckDelayedMemberExceptionSpecs();
1
Calling 'Sema::CheckDelayedMemberExceptionSpecs'
10722}
10723
10724/// Find or create the fake constructor we synthesize to model constructing an
10725/// object of a derived class via a constructor of a base class.
10726CXXConstructorDecl *
10727Sema::findInheritingConstructor(SourceLocation Loc,
10728 CXXConstructorDecl *BaseCtor,
10729 ConstructorUsingShadowDecl *Shadow) {
10730 CXXRecordDecl *Derived = Shadow->getParent();
10731 SourceLocation UsingLoc = Shadow->getLocation();
10732
10733 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10734 // For now we use the name of the base class constructor as a member of the
10735 // derived class to indicate a (fake) inherited constructor name.
10736 DeclarationName Name = BaseCtor->getDeclName();
10737
10738 // Check to see if we already have a fake constructor for this inherited
10739 // constructor call.
10740 for (NamedDecl *Ctor : Derived->lookup(Name))
10741 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10742 ->getInheritedConstructor()
10743 .getConstructor(),
10744 BaseCtor))
10745 return cast<CXXConstructorDecl>(Ctor);
10746
10747 DeclarationNameInfo NameInfo(Name, UsingLoc);
10748 TypeSourceInfo *TInfo =
10749 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10750 FunctionProtoTypeLoc ProtoLoc =
10751 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10752
10753 // Check the inherited constructor is valid and find the list of base classes
10754 // from which it was inherited.
10755 InheritedConstructorInfo ICI(*this, Loc, Shadow);
10756
10757 bool Constexpr =
10758 BaseCtor->isConstexpr() &&
10759 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10760 false, BaseCtor, &ICI);
10761
10762 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10763 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10764 BaseCtor->isExplicit(), /*Inline=*/true,
10765 /*ImplicitlyDeclared=*/true, Constexpr,
10766 InheritedConstructor(Shadow, BaseCtor));
10767 if (Shadow->isInvalidDecl())
10768 DerivedCtor->setInvalidDecl();
10769
10770 // Build an unevaluated exception specification for this fake constructor.
10771 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10772 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10773 EPI.ExceptionSpec.Type = EST_Unevaluated;
10774 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10775 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10776 FPT->getParamTypes(), EPI));
10777
10778 // Build the parameter declarations.
10779 SmallVector<ParmVarDecl *, 16> ParamDecls;
10780 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10781 TypeSourceInfo *TInfo =
10782 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10783 ParmVarDecl *PD = ParmVarDecl::Create(
10784 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10785 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10786 PD->setScopeInfo(0, I);
10787 PD->setImplicit();
10788 // Ensure attributes are propagated onto parameters (this matters for
10789 // format, pass_object_size, ...).
10790 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10791 ParamDecls.push_back(PD);
10792 ProtoLoc.setParam(I, PD);
10793 }
10794
10795 // Set up the new constructor.
10796 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")(static_cast <bool> (!BaseCtor->isDeleted() &&
"should not use deleted constructor") ? void (0) : __assert_fail
("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10796, __extension__ __PRETTY_FUNCTION__))
;
10797 DerivedCtor->setAccess(BaseCtor->getAccess());
10798 DerivedCtor->setParams(ParamDecls);
10799 Derived->addDecl(DerivedCtor);
10800
10801 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10802 SetDeclDeleted(DerivedCtor, UsingLoc);
10803
10804 return DerivedCtor;
10805}
10806
10807void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10808 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10809 Ctor->getInheritedConstructor().getShadowDecl());
10810 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10811 /*Diagnose*/true);
10812}
10813
10814void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10815 CXXConstructorDecl *Constructor) {
10816 CXXRecordDecl *ClassDecl = Constructor->getParent();
10817 assert(Constructor->getInheritedConstructor() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10819, __extension__ __PRETTY_FUNCTION__))
10818 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10819, __extension__ __PRETTY_FUNCTION__))
10819 !Constructor->isDeleted())(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10819, __extension__ __PRETTY_FUNCTION__))
;
10820 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10821 return;
10822
10823 // Initializations are performed "as if by a defaulted default constructor",
10824 // so enter the appropriate scope.
10825 SynthesizedFunctionScope Scope(*this, Constructor);
10826
10827 // The exception specification is needed because we are defining the
10828 // function.
10829 ResolveExceptionSpec(CurrentLocation,
10830 Constructor->getType()->castAs<FunctionProtoType>());
10831 MarkVTableUsed(CurrentLocation, ClassDecl);
10832
10833 // Add a context note for diagnostics produced after this point.
10834 Scope.addContextNote(CurrentLocation);
10835
10836 ConstructorUsingShadowDecl *Shadow =
10837 Constructor->getInheritedConstructor().getShadowDecl();
10838 CXXConstructorDecl *InheritedCtor =
10839 Constructor->getInheritedConstructor().getConstructor();
10840
10841 // [class.inhctor.init]p1:
10842 // initialization proceeds as if a defaulted default constructor is used to
10843 // initialize the D object and each base class subobject from which the
10844 // constructor was inherited
10845
10846 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10847 CXXRecordDecl *RD = Shadow->getParent();
10848 SourceLocation InitLoc = Shadow->getLocation();
10849
10850 // Build explicit initializers for all base classes from which the
10851 // constructor was inherited.
10852 SmallVector<CXXCtorInitializer*, 8> Inits;
10853 for (bool VBase : {false, true}) {
10854 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10855 if (B.isVirtual() != VBase)
10856 continue;
10857
10858 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10859 if (!BaseRD)
10860 continue;
10861
10862 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10863 if (!BaseCtor.first)
10864 continue;
10865
10866 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10867 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10868 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10869
10870 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10871 Inits.push_back(new (Context) CXXCtorInitializer(
10872 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10873 SourceLocation()));
10874 }
10875 }
10876
10877 // We now proceed as if for a defaulted default constructor, with the relevant
10878 // initializers replaced.
10879
10880 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
10881 Constructor->setInvalidDecl();
10882 return;
10883 }
10884
10885 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10886 Constructor->markUsed(Context);
10887
10888 if (ASTMutationListener *L = getASTMutationListener()) {
10889 L->CompletedImplicitDefinition(Constructor);
10890 }
10891
10892 DiagnoseUninitializedFields(*this, Constructor);
10893}
10894
10895CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10896 // C++ [class.dtor]p2:
10897 // If a class has no user-declared destructor, a destructor is
10898 // declared implicitly. An implicitly-declared destructor is an
10899 // inline public member of its class.
10900 assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10900, __extension__ __PRETTY_FUNCTION__))
;
10901
10902 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10903 if (DSM.isAlreadyBeingDeclared())
10904 return nullptr;
10905
10906 // Create the actual destructor declaration.
10907 CanQualType ClassType
10908 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10909 SourceLocation ClassLoc = ClassDecl->getLocation();
10910 DeclarationName Name
10911 = Context.DeclarationNames.getCXXDestructorName(ClassType);
10912 DeclarationNameInfo NameInfo(Name, ClassLoc);
10913 CXXDestructorDecl *Destructor
10914 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10915 QualType(), nullptr, /*isInline=*/true,
10916 /*isImplicitlyDeclared=*/true);
10917 Destructor->setAccess(AS_public);
10918 Destructor->setDefaulted();
10919
10920 if (getLangOpts().CUDA) {
10921 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10922 Destructor,
10923 /* ConstRHS */ false,
10924 /* Diagnose */ false);
10925 }
10926
10927 // Build an exception specification pointing back at this destructor.
10928 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10929 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10930
10931 // We don't need to use SpecialMemberIsTrivial here; triviality for
10932 // destructors is easy to compute.
10933 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10934 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
10935 ClassDecl->hasTrivialDestructorForCall());
10936
10937 // Note that we have declared this destructor.
10938 ++ASTContext::NumImplicitDestructorsDeclared;
10939
10940 Scope *S = getScopeForContext(ClassDecl);
10941 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10942
10943 // We can't check whether an implicit destructor is deleted before we complete
10944 // the definition of the class, because its validity depends on the alignment
10945 // of the class. We'll check this from ActOnFields once the class is complete.
10946 if (ClassDecl->isCompleteDefinition() &&
10947 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10948 SetDeclDeleted(Destructor, ClassLoc);
10949
10950 // Introduce this destructor into its scope.
10951 if (S)
10952 PushOnScopeChains(Destructor, S, false);
10953 ClassDecl->addDecl(Destructor);
10954
10955 return Destructor;
10956}
10957
10958void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10959 CXXDestructorDecl *Destructor) {
10960 assert((Destructor->isDefaulted() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10963, __extension__ __PRETTY_FUNCTION__))
10961 !Destructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10963, __extension__ __PRETTY_FUNCTION__))
10962 !Destructor->isDeleted()) &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10963, __extension__ __PRETTY_FUNCTION__))
10963 "DefineImplicitDestructor - call it for implicit default dtor")(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10963, __extension__ __PRETTY_FUNCTION__))
;
10964 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
10965 return;
10966
10967 CXXRecordDecl *ClassDecl = Destructor->getParent();
10968 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")(static_cast <bool> (ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10968, __extension__ __PRETTY_FUNCTION__))
;
10969
10970 SynthesizedFunctionScope Scope(*this, Destructor);
10971
10972 // The exception specification is needed because we are defining the
10973 // function.
10974 ResolveExceptionSpec(CurrentLocation,
10975 Destructor->getType()->castAs<FunctionProtoType>());
10976 MarkVTableUsed(CurrentLocation, ClassDecl);
10977
10978 // Add a context note for diagnostics produced after this point.
10979 Scope.addContextNote(CurrentLocation);
10980
10981 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10982 Destructor->getParent());
10983
10984 if (CheckDestructor(Destructor)) {
10985 Destructor->setInvalidDecl();
10986 return;
10987 }
10988
10989 SourceLocation Loc = Destructor->getLocEnd().isValid()
10990 ? Destructor->getLocEnd()
10991 : Destructor->getLocation();
10992 Destructor->setBody(new (Context) CompoundStmt(Loc));
10993 Destructor->markUsed(Context);
10994
10995 if (ASTMutationListener *L = getASTMutationListener()) {
10996 L->CompletedImplicitDefinition(Destructor);
10997 }
10998}
10999
11000/// \brief Perform any semantic analysis which needs to be delayed until all
11001/// pending class member declarations have been parsed.
11002void Sema::ActOnFinishCXXMemberDecls() {
11003 // If the context is an invalid C++ class, just suppress these checks.
11004 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11005 if (Record->isInvalidDecl()) {
11006 DelayedDefaultedMemberExceptionSpecs.clear();
11007 DelayedExceptionSpecChecks.clear();
11008 return;
11009 }
11010 checkForMultipleExportedDefaultConstructors(*this, Record);
11011 }
11012}
11013
11014void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11015 referenceDLLExportedClassMethods();
11016}
11017
11018void Sema::referenceDLLExportedClassMethods() {
11019 if (!DelayedDllExportClasses.empty()) {
11020 // Calling ReferenceDllExportedMembers might cause the current function to
11021 // be called again, so use a local copy of DelayedDllExportClasses.
11022 SmallVector<CXXRecordDecl *, 4> WorkList;
11023 std::swap(DelayedDllExportClasses, WorkList);
11024 for (CXXRecordDecl *Class : WorkList)
11025 ReferenceDllExportedMembers(*this, Class);
11026 }
11027}
11028
11029void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
11030 CXXDestructorDecl *Destructor) {
11031 assert(getLangOpts().CPlusPlus11 &&(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11032, __extension__ __PRETTY_FUNCTION__))
11032 "adjusting dtor exception specs was introduced in c++11")(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11032, __extension__ __PRETTY_FUNCTION__))
;
11033
11034 // C++11 [class.dtor]p3:
11035 // A declaration of a destructor that does not have an exception-
11036 // specification is implicitly considered to have the same exception-
11037 // specification as an implicit declaration.
11038 const FunctionProtoType *DtorType = Destructor->getType()->
11039 getAs<FunctionProtoType>();
11040 if (DtorType->hasExceptionSpec())
11041 return;
11042
11043 // Replace the destructor's type, building off the existing one. Fortunately,
11044 // the only thing of interest in the destructor type is its extended info.
11045 // The return and arguments are fixed.
11046 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11047 EPI.ExceptionSpec.Type = EST_Unevaluated;
11048 EPI.ExceptionSpec.SourceDecl = Destructor;
11049 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11050
11051 // FIXME: If the destructor has a body that could throw, and the newly created
11052 // spec doesn't allow exceptions, we should emit a warning, because this
11053 // change in behavior can break conforming C++03 programs at runtime.
11054 // However, we don't have a body or an exception specification yet, so it
11055 // needs to be done somewhere else.
11056}
11057
11058namespace {
11059/// \brief An abstract base class for all helper classes used in building the
11060// copy/move operators. These classes serve as factory functions and help us
11061// avoid using the same Expr* in the AST twice.
11062class ExprBuilder {
11063 ExprBuilder(const ExprBuilder&) = delete;
11064 ExprBuilder &operator=(const ExprBuilder&) = delete;
11065
11066protected:
11067 static Expr *assertNotNull(Expr *E) {
11068 assert(E && "Expression construction must not fail.")(static_cast <bool> (E && "Expression construction must not fail."
) ? void (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11068, __extension__ __PRETTY_FUNCTION__))
;
11069 return E;
11070 }
11071
11072public:
11073 ExprBuilder() {}
11074 virtual ~ExprBuilder() {}
11075
11076 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11077};
11078
11079class RefBuilder: public ExprBuilder {
11080 VarDecl *Var;
11081 QualType VarType;
11082
11083public:
11084 Expr *build(Sema &S, SourceLocation Loc) const override {
11085 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11086 }
11087
11088 RefBuilder(VarDecl *Var, QualType VarType)
11089 : Var(Var), VarType(VarType) {}
11090};
11091
11092class ThisBuilder: public ExprBuilder {
11093public:
11094 Expr *build(Sema &S, SourceLocation Loc) const override {
11095 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11096 }
11097};
11098
11099class CastBuilder: public ExprBuilder {
11100 const ExprBuilder &Builder;
11101 QualType Type;
11102 ExprValueKind Kind;
11103 const CXXCastPath &Path;
11104
11105public:
11106 Expr *build(Sema &S, SourceLocation Loc) const override {
11107 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11108 CK_UncheckedDerivedToBase, Kind,
11109 &Path).get());
11110 }
11111
11112 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11113 const CXXCastPath &Path)
11114 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11115};
11116
11117class DerefBuilder: public ExprBuilder {
11118 const ExprBuilder &Builder;
11119
11120public:
11121 Expr *build(Sema &S, SourceLocation Loc) const override {
11122 return assertNotNull(
11123 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11124 }
11125
11126 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11127};
11128
11129class MemberBuilder: public ExprBuilder {
11130 const ExprBuilder &Builder;
11131 QualType Type;
11132 CXXScopeSpec SS;
11133 bool IsArrow;
11134 LookupResult &MemberLookup;
11135
11136public:
11137 Expr *build(Sema &S, SourceLocation Loc) const override {
11138 return assertNotNull(S.BuildMemberReferenceExpr(
11139 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11140 nullptr, MemberLookup, nullptr, nullptr).get());
11141 }
11142
11143 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11144 LookupResult &MemberLookup)
11145 : Builder(Builder), Type(Type), IsArrow(IsArrow),
11146 MemberLookup(MemberLookup) {}
11147};
11148
11149class MoveCastBuilder: public ExprBuilder {
11150 const ExprBuilder &Builder;
11151
11152public:
11153 Expr *build(Sema &S, SourceLocation Loc) const override {
11154 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11155 }
11156
11157 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11158};
11159
11160class LvalueConvBuilder: public ExprBuilder {
11161 const ExprBuilder &Builder;
11162
11163public:
11164 Expr *build(Sema &S, SourceLocation Loc) const override {
11165 return assertNotNull(
11166 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11167 }
11168
11169 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11170};
11171
11172class SubscriptBuilder: public ExprBuilder {
11173 const ExprBuilder &Base;
11174 const ExprBuilder &Index;
11175
11176public:
11177 Expr *build(Sema &S, SourceLocation Loc) const override {
11178 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11179 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11180 }
11181
11182 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11183 : Base(Base), Index(Index) {}
11184};
11185
11186} // end anonymous namespace
11187
11188/// When generating a defaulted copy or move assignment operator, if a field
11189/// should be copied with __builtin_memcpy rather than via explicit assignments,
11190/// do so. This optimization only applies for arrays of scalars, and for arrays
11191/// of class type where the selected copy/move-assignment operator is trivial.
11192static StmtResult
11193buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11194 const ExprBuilder &ToB, const ExprBuilder &FromB) {
11195 // Compute the size of the memory buffer to be copied.
11196 QualType SizeType = S.Context.getSizeType();
11197 llvm::APInt Size(S.Context.getTypeSize(SizeType),
11198 S.Context.getTypeSizeInChars(T).getQuantity());
11199
11200 // Take the address of the field references for "from" and "to". We
11201 // directly construct UnaryOperators here because semantic analysis
11202 // does not permit us to take the address of an xvalue.
11203 Expr *From = FromB.build(S, Loc);
11204 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11205 S.Context.getPointerType(From->getType()),
11206 VK_RValue, OK_Ordinary, Loc, false);
11207 Expr *To = ToB.build(S, Loc);
11208 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11209 S.Context.getPointerType(To->getType()),
11210 VK_RValue, OK_Ordinary, Loc, false);
11211
11212 const Type *E = T->getBaseElementTypeUnsafe();
11213 bool NeedsCollectableMemCpy =
11214 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11215
11216 // Create a reference to the __builtin_objc_memmove_collectable function
11217 StringRef MemCpyName = NeedsCollectableMemCpy ?
11218 "__builtin_objc_memmove_collectable" :
11219 "__builtin_memcpy";
11220 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11221 Sema::LookupOrdinaryName);
11222 S.LookupName(R, S.TUScope, true);
11223
11224 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11225 if (!MemCpy)
11226 // Something went horribly wrong earlier, and we will have complained
11227 // about it.
11228 return StmtError();
11229
11230 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11231 VK_RValue, Loc, nullptr);
11232 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? void (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11232, __extension__ __PRETTY_FUNCTION__))
;
11233
11234 Expr *CallArgs[] = {
11235 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11236 };
11237 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11238 Loc, CallArgs, Loc);
11239
11240 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11240, __extension__ __PRETTY_FUNCTION__))
;
11241 return Call.getAs<Stmt>();
11242}
11243
11244/// \brief Builds a statement that copies/moves the given entity from \p From to
11245/// \c To.
11246///
11247/// This routine is used to copy/move the members of a class with an
11248/// implicitly-declared copy/move assignment operator. When the entities being
11249/// copied are arrays, this routine builds for loops to copy them.
11250///
11251/// \param S The Sema object used for type-checking.
11252///
11253/// \param Loc The location where the implicit copy/move is being generated.
11254///
11255/// \param T The type of the expressions being copied/moved. Both expressions
11256/// must have this type.
11257///
11258/// \param To The expression we are copying/moving to.
11259///
11260/// \param From The expression we are copying/moving from.
11261///
11262/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11263/// Otherwise, it's a non-static member subobject.
11264///
11265/// \param Copying Whether we're copying or moving.
11266///
11267/// \param Depth Internal parameter recording the depth of the recursion.
11268///
11269/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11270/// if a memcpy should be used instead.
11271static StmtResult
11272buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11273 const ExprBuilder &To, const ExprBuilder &From,
11274 bool CopyingBaseSubobject, bool Copying,
11275 unsigned Depth = 0) {
11276 // C++11 [class.copy]p28:
11277 // Each subobject is assigned in the manner appropriate to its type:
11278 //
11279 // - if the subobject is of class type, as if by a call to operator= with
11280 // the subobject as the object expression and the corresponding
11281 // subobject of x as a single function argument (as if by explicit
11282 // qualification; that is, ignoring any possible virtual overriding
11283 // functions in more derived classes);
11284 //
11285 // C++03 [class.copy]p13:
11286 // - if the subobject is of class type, the copy assignment operator for
11287 // the class is used (as if by explicit qualification; that is,
11288 // ignoring any possible virtual overriding functions in more derived
11289 // classes);
11290 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11291 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11292
11293 // Look for operator=.
11294 DeclarationName Name
11295 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11296 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11297 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11298
11299 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11300 // operator.
11301 if (!S.getLangOpts().CPlusPlus11) {
11302 LookupResult::Filter F = OpLookup.makeFilter();
11303 while (F.hasNext()) {
11304 NamedDecl *D = F.next();
11305 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11306 if (Method->isCopyAssignmentOperator() ||
11307 (!Copying && Method->isMoveAssignmentOperator()))
11308 continue;
11309
11310 F.erase();
11311 }
11312 F.done();
11313 }
11314
11315 // Suppress the protected check (C++ [class.protected]) for each of the
11316 // assignment operators we found. This strange dance is required when
11317 // we're assigning via a base classes's copy-assignment operator. To
11318 // ensure that we're getting the right base class subobject (without
11319 // ambiguities), we need to cast "this" to that subobject type; to
11320 // ensure that we don't go through the virtual call mechanism, we need
11321 // to qualify the operator= name with the base class (see below). However,
11322 // this means that if the base class has a protected copy assignment
11323 // operator, the protected member access check will fail. So, we
11324 // rewrite "protected" access to "public" access in this case, since we
11325 // know by construction that we're calling from a derived class.
11326 if (CopyingBaseSubobject) {
11327 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11328 L != LEnd; ++L) {
11329 if (L.getAccess() == AS_protected)
11330 L.setAccess(AS_public);
11331 }
11332 }
11333
11334 // Create the nested-name-specifier that will be used to qualify the
11335 // reference to operator=; this is required to suppress the virtual
11336 // call mechanism.
11337 CXXScopeSpec SS;
11338 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11339 SS.MakeTrivial(S.Context,
11340 NestedNameSpecifier::Create(S.Context, nullptr, false,
11341 CanonicalT),
11342 Loc);
11343
11344 // Create the reference to operator=.
11345 ExprResult OpEqualRef
11346 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11347 SS, /*TemplateKWLoc=*/SourceLocation(),
11348 /*FirstQualifierInScope=*/nullptr,
11349 OpLookup,
11350 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11351 /*SuppressQualifierCheck=*/true);
11352 if (OpEqualRef.isInvalid())
11353 return StmtError();
11354
11355 // Build the call to the assignment operator.
11356
11357 Expr *FromInst = From.build(S, Loc);
11358 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11359 OpEqualRef.getAs<Expr>(),
11360 Loc, FromInst, Loc);
11361 if (Call.isInvalid())
11362 return StmtError();
11363
11364 // If we built a call to a trivial 'operator=' while copying an array,
11365 // bail out. We'll replace the whole shebang with a memcpy.
11366 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11367 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11368 return StmtResult((Stmt*)nullptr);
11369
11370 // Convert to an expression-statement, and clean up any produced
11371 // temporaries.
11372 return S.ActOnExprStmt(Call);
11373 }
11374
11375 // - if the subobject is of scalar type, the built-in assignment
11376 // operator is used.
11377 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11378 if (!ArrayTy) {
11379 ExprResult Assignment = S.CreateBuiltinBinOp(
11380 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11381 if (Assignment.isInvalid())
11382 return StmtError();
11383 return S.ActOnExprStmt(Assignment);
11384 }
11385
11386 // - if the subobject is an array, each element is assigned, in the
11387 // manner appropriate to the element type;
11388
11389 // Construct a loop over the array bounds, e.g.,
11390 //
11391 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11392 //
11393 // that will copy each of the array elements.
11394 QualType SizeType = S.Context.getSizeType();
11395
11396 // Create the iteration variable.
11397 IdentifierInfo *IterationVarName = nullptr;
11398 {
11399 SmallString<8> Str;
11400 llvm::raw_svector_ostream OS(Str);
11401 OS << "__i" << Depth;
11402 IterationVarName = &S.Context.Idents.get(OS.str());
11403 }
11404 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11405 IterationVarName, SizeType,
11406 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11407 SC_None);
11408
11409 // Initialize the iteration variable to zero.
11410 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11411 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11412
11413 // Creates a reference to the iteration variable.
11414 RefBuilder IterationVarRef(IterationVar, SizeType);
11415 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11416
11417 // Create the DeclStmt that holds the iteration variable.
11418 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11419
11420 // Subscript the "from" and "to" expressions with the iteration variable.
11421 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11422 MoveCastBuilder FromIndexMove(FromIndexCopy);
11423 const ExprBuilder *FromIndex;
11424 if (Copying)
11425 FromIndex = &FromIndexCopy;
11426 else
11427 FromIndex = &FromIndexMove;
11428
11429 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11430
11431 // Build the copy/move for an individual element of the array.
11432 StmtResult Copy =
11433 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11434 ToIndex, *FromIndex, CopyingBaseSubobject,
11435 Copying, Depth + 1);
11436 // Bail out if copying fails or if we determined that we should use memcpy.
11437 if (Copy.isInvalid() || !Copy.get())
11438 return Copy;
11439
11440 // Create the comparison against the array bound.
11441 llvm::APInt Upper
11442 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11443 Expr *Comparison
11444 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11445 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11446 BO_NE, S.Context.BoolTy,
11447 VK_RValue, OK_Ordinary, Loc, FPOptions());
11448
11449 // Create the pre-increment of the iteration variable. We can determine
11450 // whether the increment will overflow based on the value of the array
11451 // bound.
11452 Expr *Increment = new (S.Context)
11453 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11454 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11455
11456 // Construct the loop that copies all elements of this array.
11457 return S.ActOnForStmt(
11458 Loc, Loc, InitStmt,
11459 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11460 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11461}
11462
11463static StmtResult
11464buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11465 const ExprBuilder &To, const ExprBuilder &From,
11466 bool CopyingBaseSubobject, bool Copying) {
11467 // Maybe we should use a memcpy?
11468 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11469 T.isTriviallyCopyableType(S.Context))
11470 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11471
11472 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11473 CopyingBaseSubobject,
11474 Copying, 0));
11475
11476 // If we ended up picking a trivial assignment operator for an array of a
11477 // non-trivially-copyable class type, just emit a memcpy.
11478 if (!Result.isInvalid() && !Result.get())
11479 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11480
11481 return Result;
11482}
11483
11484CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11485 // Note: The following rules are largely analoguous to the copy
11486 // constructor rules. Note that virtual bases are not taken into account
11487 // for determining the argument type of the operator. Note also that
11488 // operators taking an object instead of a reference are allowed.
11489 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11489, __extension__ __PRETTY_FUNCTION__))
;
11490
11491 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11492 if (DSM.isAlreadyBeingDeclared())
11493 return nullptr;
11494
11495 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11496 QualType RetType = Context.getLValueReferenceType(ArgType);
11497 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11498 if (Const)
11499 ArgType = ArgType.withConst();
11500 ArgType = Context.getLValueReferenceType(ArgType);
11501
11502 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11503 CXXCopyAssignment,
11504 Const);
11505
11506 // An implicitly-declared copy assignment operator is an inline public
11507 // member of its class.
11508 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11509 SourceLocation ClassLoc = ClassDecl->getLocation();
11510 DeclarationNameInfo NameInfo(Name, ClassLoc);
11511 CXXMethodDecl *CopyAssignment =
11512 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11513 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11514 /*isInline=*/true, Constexpr, SourceLocation());
11515 CopyAssignment->setAccess(AS_public);
11516 CopyAssignment->setDefaulted();
11517 CopyAssignment->setImplicit();
11518
11519 if (getLangOpts().CUDA) {
11520 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11521 CopyAssignment,
11522 /* ConstRHS */ Const,
11523 /* Diagnose */ false);
11524 }
11525
11526 // Build an exception specification pointing back at this member.
11527 FunctionProtoType::ExtProtoInfo EPI =
11528 getImplicitMethodEPI(*this, CopyAssignment);
11529 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11530
11531 // Add the parameter to the operator.
11532 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11533 ClassLoc, ClassLoc,
11534 /*Id=*/nullptr, ArgType,
11535 /*TInfo=*/nullptr, SC_None,
11536 nullptr);
11537 CopyAssignment->setParams(FromParam);
11538
11539 CopyAssignment->setTrivial(
11540 ClassDecl->needsOverloadResolutionForCopyAssignment()
11541 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11542 : ClassDecl->hasTrivialCopyAssignment());
11543
11544 // Note that we have added this copy-assignment operator.
11545 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11546
11547 Scope *S = getScopeForContext(ClassDecl);
11548 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11549
11550 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11551 SetDeclDeleted(CopyAssignment, ClassLoc);
11552
11553 if (S)
11554 PushOnScopeChains(CopyAssignment, S, false);
11555 ClassDecl->addDecl(CopyAssignment);
11556
11557 return CopyAssignment;
11558}
11559
11560/// Diagnose an implicit copy operation for a class which is odr-used, but
11561/// which is deprecated because the class has a user-declared copy constructor,
11562/// copy assignment operator, or destructor.
11563static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11564 assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0
) : __assert_fail ("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11564, __extension__ __PRETTY_FUNCTION__))
;
11565
11566 CXXRecordDecl *RD = CopyOp->getParent();
11567 CXXMethodDecl *UserDeclaredOperation = nullptr;
11568
11569 // In Microsoft mode, assignment operations don't affect constructors and
11570 // vice versa.
11571 if (RD->hasUserDeclaredDestructor()) {
11572 UserDeclaredOperation = RD->getDestructor();
11573 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11574 RD->hasUserDeclaredCopyConstructor() &&
11575 !S.getLangOpts().MSVCCompat) {
11576 // Find any user-declared copy constructor.
11577 for (auto *I : RD->ctors()) {
11578 if (I->isCopyConstructor()) {
11579 UserDeclaredOperation = I;
11580 break;
11581 }
11582 }
11583 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11583, __extension__ __PRETTY_FUNCTION__))
;
11584 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11585 RD->hasUserDeclaredCopyAssignment() &&
11586 !S.getLangOpts().MSVCCompat) {
11587 // Find any user-declared move assignment operator.
11588 for (auto *I : RD->methods()) {
11589 if (I->isCopyAssignmentOperator()) {
11590 UserDeclaredOperation = I;
11591 break;
11592 }
11593 }
11594 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11594, __extension__ __PRETTY_FUNCTION__))
;
11595 }
11596
11597 if (UserDeclaredOperation) {
11598 S.Diag(UserDeclaredOperation->getLocation(),
11599 diag::warn_deprecated_copy_operation)
11600 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11601 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11602 }
11603}
11604
11605void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11606 CXXMethodDecl *CopyAssignOperator) {
11607 assert((CopyAssignOperator->isDefaulted() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11612, __extension__ __PRETTY_FUNCTION__))
11608 CopyAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11612, __extension__ __PRETTY_FUNCTION__))
11609 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11612, __extension__ __PRETTY_FUNCTION__))
11610 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11612, __extension__ __PRETTY_FUNCTION__))
11611 !CopyAssignOperator->isDeleted()) &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11612, __extension__ __PRETTY_FUNCTION__))
11612 "DefineImplicitCopyAssignment called for wrong function")(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11612, __extension__ __PRETTY_FUNCTION__))
;
11613 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11614 return;
11615
11616 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11617 if (ClassDecl->isInvalidDecl()) {
11618 CopyAssignOperator->setInvalidDecl();
11619 return;
11620 }
11621
11622 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11623
11624 // The exception specification is needed because we are defining the
11625 // function.
11626 ResolveExceptionSpec(CurrentLocation,
11627 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11628
11629 // Add a context note for diagnostics produced after this point.
11630 Scope.addContextNote(CurrentLocation);
11631
11632 // C++11 [class.copy]p18:
11633 // The [definition of an implicitly declared copy assignment operator] is
11634 // deprecated if the class has a user-declared copy constructor or a
11635 // user-declared destructor.
11636 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11637 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11638
11639 // C++0x [class.copy]p30:
11640 // The implicitly-defined or explicitly-defaulted copy assignment operator
11641 // for a non-union class X performs memberwise copy assignment of its
11642 // subobjects. The direct base classes of X are assigned first, in the
11643 // order of their declaration in the base-specifier-list, and then the
11644 // immediate non-static data members of X are assigned, in the order in
11645 // which they were declared in the class definition.
11646
11647 // The statements that form the synthesized function body.
11648 SmallVector<Stmt*, 8> Statements;
11649
11650 // The parameter for the "other" object, which we are copying from.
11651 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11652 Qualifiers OtherQuals = Other->getType().getQualifiers();
11653 QualType OtherRefType = Other->getType();
11654 if (const LValueReferenceType *OtherRef
11655 = OtherRefType->getAs<LValueReferenceType>()) {
11656 OtherRefType = OtherRef->getPointeeType();
11657 OtherQuals = OtherRefType.getQualifiers();
11658 }
11659
11660 // Our location for everything implicitly-generated.
11661 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11662 ? CopyAssignOperator->getLocEnd()
11663 : CopyAssignOperator->getLocation();
11664
11665 // Builds a DeclRefExpr for the "other" object.
11666 RefBuilder OtherRef(Other, OtherRefType);
11667
11668 // Builds the "this" pointer.
11669 ThisBuilder This;
11670
11671 // Assign base classes.
11672 bool Invalid = false;
11673 for (auto &Base : ClassDecl->bases()) {
11674 // Form the assignment:
11675 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11676 QualType BaseType = Base.getType().getUnqualifiedType();
11677 if (!BaseType->isRecordType()) {
11678 Invalid = true;
11679 continue;
11680 }
11681
11682 CXXCastPath BasePath;
11683 BasePath.push_back(&Base);
11684
11685 // Construct the "from" expression, which is an implicit cast to the
11686 // appropriately-qualified base type.
11687 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11688 VK_LValue, BasePath);
11689
11690 // Dereference "this".
11691 DerefBuilder DerefThis(This);
11692 CastBuilder To(DerefThis,
11693 Context.getCVRQualifiedType(
11694 BaseType, CopyAssignOperator->getTypeQualifiers()),
11695 VK_LValue, BasePath);
11696
11697 // Build the copy.
11698 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11699 To, From,
11700 /*CopyingBaseSubobject=*/true,
11701 /*Copying=*/true);
11702 if (Copy.isInvalid()) {
11703 CopyAssignOperator->setInvalidDecl();
11704 return;
11705 }
11706
11707 // Success! Record the copy.
11708 Statements.push_back(Copy.getAs<Expr>());
11709 }
11710
11711 // Assign non-static members.
11712 for (auto *Field : ClassDecl->fields()) {
11713 // FIXME: We should form some kind of AST representation for the implied
11714 // memcpy in a union copy operation.
11715 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11716 continue;
11717
11718 if (Field->isInvalidDecl()) {
11719 Invalid = true;
11720 continue;
11721 }
11722
11723 // Check for members of reference type; we can't copy those.
11724 if (Field->getType()->isReferenceType()) {
11725 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11726 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11727 Diag(Field->getLocation(), diag::note_declared_at);
11728 Invalid = true;
11729 continue;
11730 }
11731
11732 // Check for members of const-qualified, non-class type.
11733 QualType BaseType = Context.getBaseElementType(Field->getType());
11734 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11735 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11736 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11737 Diag(Field->getLocation(), diag::note_declared_at);
11738 Invalid = true;
11739 continue;
11740 }
11741
11742 // Suppress assigning zero-width bitfields.
11743 if (Field->isZeroLengthBitField(Context))
11744 continue;
11745
11746 QualType FieldType = Field->getType().getNonReferenceType();
11747 if (FieldType->isIncompleteArrayType()) {
11748 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11749, __extension__ __PRETTY_FUNCTION__))
11749 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11749, __extension__ __PRETTY_FUNCTION__))
;
11750 continue;
11751 }
11752
11753 // Build references to the field in the object we're copying from and to.
11754 CXXScopeSpec SS; // Intentionally empty
11755 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11756 LookupMemberName);
11757 MemberLookup.addDecl(Field);
11758 MemberLookup.resolveKind();
11759
11760 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11761
11762 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11763
11764 // Build the copy of this field.
11765 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11766 To, From,
11767 /*CopyingBaseSubobject=*/false,
11768 /*Copying=*/true);
11769 if (Copy.isInvalid()) {
11770 CopyAssignOperator->setInvalidDecl();
11771 return;
11772 }
11773
11774 // Success! Record the copy.
11775 Statements.push_back(Copy.getAs<Stmt>());
11776 }
11777
11778 if (!Invalid) {
11779 // Add a "return *this;"
11780 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11781
11782 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11783 if (Return.isInvalid())
11784 Invalid = true;
11785 else
11786 Statements.push_back(Return.getAs<Stmt>());
11787 }
11788
11789 if (Invalid) {
11790 CopyAssignOperator->setInvalidDecl();
11791 return;
11792 }
11793
11794 StmtResult Body;
11795 {
11796 CompoundScopeRAII CompoundScope(*this);
11797 Body = ActOnCompoundStmt(Loc, Loc, Statements,
11798 /*isStmtExpr=*/false);
11799 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11799, __extension__ __PRETTY_FUNCTION__))
;
11800 }
11801 CopyAssignOperator->setBody(Body.getAs<Stmt>());
11802 CopyAssignOperator->markUsed(Context);
11803
11804 if (ASTMutationListener *L = getASTMutationListener()) {
11805 L->CompletedImplicitDefinition(CopyAssignOperator);
11806 }
11807}
11808
11809CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11810 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11810, __extension__ __PRETTY_FUNCTION__))
;
11811
11812 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11813 if (DSM.isAlreadyBeingDeclared())
11814 return nullptr;
11815
11816 // Note: The following rules are largely analoguous to the move
11817 // constructor rules.
11818
11819 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11820 QualType RetType = Context.getLValueReferenceType(ArgType);
11821 ArgType = Context.getRValueReferenceType(ArgType);
11822
11823 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11824 CXXMoveAssignment,
11825 false);
11826
11827 // An implicitly-declared move assignment operator is an inline public
11828 // member of its class.
11829 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11830 SourceLocation ClassLoc = ClassDecl->getLocation();
11831 DeclarationNameInfo NameInfo(Name, ClassLoc);
11832 CXXMethodDecl *MoveAssignment =
11833 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11834 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11835 /*isInline=*/true, Constexpr, SourceLocation());
11836 MoveAssignment->setAccess(AS_public);
11837 MoveAssignment->setDefaulted();
11838 MoveAssignment->setImplicit();
11839
11840 if (getLangOpts().CUDA) {
11841 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11842 MoveAssignment,
11843 /* ConstRHS */ false,
11844 /* Diagnose */ false);
11845 }
11846
11847 // Build an exception specification pointing back at this member.
11848 FunctionProtoType::ExtProtoInfo EPI =
11849 getImplicitMethodEPI(*this, MoveAssignment);
11850 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11851
11852 // Add the parameter to the operator.
11853 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11854 ClassLoc, ClassLoc,
11855 /*Id=*/nullptr, ArgType,
11856 /*TInfo=*/nullptr, SC_None,
11857 nullptr);
11858 MoveAssignment->setParams(FromParam);
11859
11860 MoveAssignment->setTrivial(
11861 ClassDecl->needsOverloadResolutionForMoveAssignment()
11862 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11863 : ClassDecl->hasTrivialMoveAssignment());
11864
11865 // Note that we have added this copy-assignment operator.
11866 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11867
11868 Scope *S = getScopeForContext(ClassDecl);
11869 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11870
11871 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11872 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11873 SetDeclDeleted(MoveAssignment, ClassLoc);
11874 }
11875
11876 if (S)
11877 PushOnScopeChains(MoveAssignment, S, false);
11878 ClassDecl->addDecl(MoveAssignment);
11879
11880 return MoveAssignment;
11881}
11882
11883/// Check if we're implicitly defining a move assignment operator for a class
11884/// with virtual bases. Such a move assignment might move-assign the virtual
11885/// base multiple times.
11886static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11887 SourceLocation CurrentLocation) {
11888 assert(!Class->isDependentContext() && "should not define dependent move")(static_cast <bool> (!Class->isDependentContext() &&
"should not define dependent move") ? void (0) : __assert_fail
("!Class->isDependentContext() && \"should not define dependent move\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11888, __extension__ __PRETTY_FUNCTION__))
;
11889
11890 // Only a virtual base could get implicitly move-assigned multiple times.
11891 // Only a non-trivial move assignment can observe this. We only want to
11892 // diagnose if we implicitly define an assignment operator that assigns
11893 // two base classes, both of which move-assign the same virtual base.
11894 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11895 Class->getNumBases() < 2)
11896 return;
11897
11898 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11899 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11900 VBaseMap VBases;
11901
11902 for (auto &BI : Class->bases()) {
11903 Worklist.push_back(&BI);
11904 while (!Worklist.empty()) {
11905 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11906 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11907
11908 // If the base has no non-trivial move assignment operators,
11909 // we don't care about moves from it.
11910 if (!Base->hasNonTrivialMoveAssignment())
11911 continue;
11912
11913 // If there's nothing virtual here, skip it.
11914 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11915 continue;
11916
11917 // If we're not actually going to call a move assignment for this base,
11918 // or the selected move assignment is trivial, skip it.
11919 Sema::SpecialMemberOverloadResult SMOR =
11920 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11921 /*ConstArg*/false, /*VolatileArg*/false,
11922 /*RValueThis*/true, /*ConstThis*/false,
11923 /*VolatileThis*/false);
11924 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11925 !SMOR.getMethod()->isMoveAssignmentOperator())
11926 continue;
11927
11928 if (BaseSpec->isVirtual()) {
11929 // We're going to move-assign this virtual base, and its move
11930 // assignment operator is not trivial. If this can happen for
11931 // multiple distinct direct bases of Class, diagnose it. (If it
11932 // only happens in one base, we'll diagnose it when synthesizing
11933 // that base class's move assignment operator.)
11934 CXXBaseSpecifier *&Existing =
11935 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11936 .first->second;
11937 if (Existing && Existing != &BI) {
11938 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11939 << Class << Base;
11940 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11941 << (Base->getCanonicalDecl() ==
11942 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11943 << Base << Existing->getType() << Existing->getSourceRange();
11944 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11945 << (Base->getCanonicalDecl() ==
11946 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11947 << Base << BI.getType() << BaseSpec->getSourceRange();
11948
11949 // Only diagnose each vbase once.
11950 Existing = nullptr;
11951 }
11952 } else {
11953 // Only walk over bases that have defaulted move assignment operators.
11954 // We assume that any user-provided move assignment operator handles
11955 // the multiple-moves-of-vbase case itself somehow.
11956 if (!SMOR.getMethod()->isDefaulted())
11957 continue;
11958
11959 // We're going to move the base classes of Base. Add them to the list.
11960 for (auto &BI : Base->bases())
11961 Worklist.push_back(&BI);
11962 }
11963 }
11964 }
11965}
11966
11967void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11968 CXXMethodDecl *MoveAssignOperator) {
11969 assert((MoveAssignOperator->isDefaulted() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11974, __extension__ __PRETTY_FUNCTION__))
11970 MoveAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11974, __extension__ __PRETTY_FUNCTION__))
11971 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11974, __extension__ __PRETTY_FUNCTION__))
11972 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11974, __extension__ __PRETTY_FUNCTION__))
11973 !MoveAssignOperator->isDeleted()) &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11974, __extension__ __PRETTY_FUNCTION__))
11974 "DefineImplicitMoveAssignment called for wrong function")(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11974, __extension__ __PRETTY_FUNCTION__))
;
11975 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
11976 return;
11977
11978 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11979 if (ClassDecl->isInvalidDecl()) {
11980 MoveAssignOperator->setInvalidDecl();
11981 return;
11982 }
11983
11984 // C++0x [class.copy]p28:
11985 // The implicitly-defined or move assignment operator for a non-union class
11986 // X performs memberwise move assignment of its subobjects. The direct base
11987 // classes of X are assigned first, in the order of their declaration in the
11988 // base-specifier-list, and then the immediate non-static data members of X
11989 // are assigned, in the order in which they were declared in the class
11990 // definition.
11991
11992 // Issue a warning if our implicit move assignment operator will move
11993 // from a virtual base more than once.
11994 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11995
11996 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11997
11998 // The exception specification is needed because we are defining the
11999 // function.
12000 ResolveExceptionSpec(CurrentLocation,
12001 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12002
12003 // Add a context note for diagnostics produced after this point.
12004 Scope.addContextNote(CurrentLocation);
12005
12006 // The statements that form the synthesized function body.
12007 SmallVector<Stmt*, 8> Statements;
12008
12009 // The parameter for the "other" object, which we are move from.
12010 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12011 QualType OtherRefType = Other->getType()->
12012 getAs<RValueReferenceType>()->getPointeeType();
12013 assert(!OtherRefType.getQualifiers() &&(static_cast <bool> (!OtherRefType.getQualifiers() &&
"Bad argument type of defaulted move assignment") ? void (0)
: __assert_fail ("!OtherRefType.getQualifiers() && \"Bad argument type of defaulted move assignment\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12014, __extension__ __PRETTY_FUNCTION__))
12014 "Bad argument type of defaulted move assignment")(static_cast <bool> (!OtherRefType.getQualifiers() &&
"Bad argument type of defaulted move assignment") ? void (0)
: __assert_fail ("!OtherRefType.getQualifiers() && \"Bad argument type of defaulted move assignment\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12014, __extension__ __PRETTY_FUNCTION__))
;
12015
12016 // Our location for everything implicitly-generated.
12017 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
12018 ? MoveAssignOperator->getLocEnd()
12019 : MoveAssignOperator->getLocation();
12020
12021 // Builds a reference to the "other" object.
12022 RefBuilder OtherRef(Other, OtherRefType);
12023 // Cast to rvalue.
12024 MoveCastBuilder MoveOther(OtherRef);
12025
12026 // Builds the "this" pointer.
12027 ThisBuilder This;
12028
12029 // Assign base classes.
12030 bool Invalid = false;
12031 for (auto &Base : ClassDecl->bases()) {
12032 // C++11 [class.copy]p28:
12033 // It is unspecified whether subobjects representing virtual base classes
12034 // are assigned more than once by the implicitly-defined copy assignment
12035 // operator.
12036 // FIXME: Do not assign to a vbase that will be assigned by some other base
12037 // class. For a move-assignment, this can result in the vbase being moved
12038 // multiple times.
12039
12040 // Form the assignment:
12041 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12042 QualType BaseType = Base.getType().getUnqualifiedType();
12043 if (!BaseType->isRecordType()) {
12044 Invalid = true;
12045 continue;
12046 }
12047
12048 CXXCastPath BasePath;
12049 BasePath.push_back(&Base);
12050
12051 // Construct the "from" expression, which is an implicit cast to the
12052 // appropriately-qualified base type.
12053 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12054
12055 // Dereference "this".
12056 DerefBuilder DerefThis(This);
12057
12058 // Implicitly cast "this" to the appropriately-qualified base type.
12059 CastBuilder To(DerefThis,
12060 Context.getCVRQualifiedType(
12061 BaseType, MoveAssignOperator->getTypeQualifiers()),
12062 VK_LValue, BasePath);
12063
12064 // Build the move.
12065 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12066 To, From,
12067 /*CopyingBaseSubobject=*/true,
12068 /*Copying=*/false);
12069 if (Move.isInvalid()) {
12070 MoveAssignOperator->setInvalidDecl();
12071 return;
12072 }
12073
12074 // Success! Record the move.
12075 Statements.push_back(Move.getAs<Expr>());
12076 }
12077
12078 // Assign non-static members.
12079 for (auto *Field : ClassDecl->fields()) {
12080 // FIXME: We should form some kind of AST representation for the implied
12081 // memcpy in a union copy operation.
12082 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12083 continue;
12084
12085 if (Field->isInvalidDecl()) {
12086 Invalid = true;
12087 continue;
12088 }
12089
12090 // Check for members of reference type; we can't move those.
12091 if (Field->getType()->isReferenceType()) {
12092 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12093 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12094 Diag(Field->getLocation(), diag::note_declared_at);
12095 Invalid = true;
12096 continue;
12097 }
12098
12099 // Check for members of const-qualified, non-class type.
12100 QualType BaseType = Context.getBaseElementType(Field->getType());
12101 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12102 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12103 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12104 Diag(Field->getLocation(), diag::note_declared_at);
12105 Invalid = true;
12106 continue;
12107 }
12108
12109 // Suppress assigning zero-width bitfields.
12110 if (Field->isZeroLengthBitField(Context))
12111 continue;
12112
12113 QualType FieldType = Field->getType().getNonReferenceType();
12114 if (FieldType->isIncompleteArrayType()) {
12115 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12116, __extension__ __PRETTY_FUNCTION__))
12116 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12116, __extension__ __PRETTY_FUNCTION__))
;
12117 continue;
12118 }
12119
12120 // Build references to the field in the object we're copying from and to.
12121 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12122 LookupMemberName);
12123 MemberLookup.addDecl(Field);
12124 MemberLookup.resolveKind();
12125 MemberBuilder From(MoveOther, OtherRefType,
12126 /*IsArrow=*/false, MemberLookup);
12127 MemberBuilder To(This, getCurrentThisType(),
12128 /*IsArrow=*/true, MemberLookup);
12129
12130 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12132, __extension__ __PRETTY_FUNCTION__))
12131 "Member reference with rvalue base must be rvalue except for reference "(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12132, __extension__ __PRETTY_FUNCTION__))
12132 "members, which aren't allowed for move assignment.")(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12132, __extension__ __PRETTY_FUNCTION__))
;
12133
12134 // Build the move of this field.
12135 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12136 To, From,
12137 /*CopyingBaseSubobject=*/false,
12138 /*Copying=*/false);
12139 if (Move.isInvalid()) {
12140 MoveAssignOperator->setInvalidDecl();
12141 return;
12142 }
12143
12144 // Success! Record the copy.
12145 Statements.push_back(Move.getAs<Stmt>());
12146 }
12147
12148 if (!Invalid) {
12149 // Add a "return *this;"
12150 ExprResult ThisObj =
12151 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12152
12153 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12154 if (Return.isInvalid())
12155 Invalid = true;
12156 else
12157 Statements.push_back(Return.getAs<Stmt>());
12158 }
12159
12160 if (Invalid) {
12161 MoveAssignOperator->setInvalidDecl();
12162 return;
12163 }
12164
12165 StmtResult Body;
12166 {
12167 CompoundScopeRAII CompoundScope(*this);
12168 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12169 /*isStmtExpr=*/false);
12170 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12170, __extension__ __PRETTY_FUNCTION__))
;
12171 }
12172 MoveAssignOperator->setBody(Body.getAs<Stmt>());
12173 MoveAssignOperator->markUsed(Context);
12174
12175 if (ASTMutationListener *L = getASTMutationListener()) {
12176 L->CompletedImplicitDefinition(MoveAssignOperator);
12177 }
12178}
12179
12180CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12181 CXXRecordDecl *ClassDecl) {
12182 // C++ [class.copy]p4:
12183 // If the class definition does not explicitly declare a copy
12184 // constructor, one is declared implicitly.
12185 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12185, __extension__ __PRETTY_FUNCTION__))
;
12186
12187 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12188 if (DSM.isAlreadyBeingDeclared())
12189 return nullptr;
12190
12191 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12192 QualType ArgType = ClassType;
12193 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12194 if (Const)
12195 ArgType = ArgType.withConst();
12196 ArgType = Context.getLValueReferenceType(ArgType);
12197
12198 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12199 CXXCopyConstructor,
12200 Const);
12201
12202 DeclarationName Name
12203 = Context.DeclarationNames.getCXXConstructorName(
12204 Context.getCanonicalType(ClassType));
12205 SourceLocation ClassLoc = ClassDecl->getLocation();
12206 DeclarationNameInfo NameInfo(Name, ClassLoc);
12207
12208 // An implicitly-declared copy constructor is an inline public
12209 // member of its class.
12210 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12211 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12212 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12213 Constexpr);
12214 CopyConstructor->setAccess(AS_public);
12215 CopyConstructor->setDefaulted();
12216
12217 if (getLangOpts().CUDA) {
12218 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12219 CopyConstructor,
12220 /* ConstRHS */ Const,
12221 /* Diagnose */ false);
12222 }
12223
12224 // Build an exception specification pointing back at this member.
12225 FunctionProtoType::ExtProtoInfo EPI =
12226 getImplicitMethodEPI(*this, CopyConstructor);
12227 CopyConstructor->setType(
12228 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12229
12230 // Add the parameter to the constructor.
12231 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12232 ClassLoc, ClassLoc,
12233 /*IdentifierInfo=*/nullptr,
12234 ArgType, /*TInfo=*/nullptr,
12235 SC_None, nullptr);
12236 CopyConstructor->setParams(FromParam);
12237
12238 CopyConstructor->setTrivial(
12239 ClassDecl->needsOverloadResolutionForCopyConstructor()
12240 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12241 : ClassDecl->hasTrivialCopyConstructor());
12242
12243 CopyConstructor->setTrivialForCall(
12244 ClassDecl->hasAttr<TrivialABIAttr>() ||
12245 (ClassDecl->needsOverloadResolutionForCopyConstructor()
12246 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12247 TAH_ConsiderTrivialABI)
12248 : ClassDecl->hasTrivialCopyConstructorForCall()));
12249
12250 // Note that we have declared this constructor.
12251 ++ASTContext::NumImplicitCopyConstructorsDeclared;
12252
12253 Scope *S = getScopeForContext(ClassDecl);
12254 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12255
12256 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12257 ClassDecl->setImplicitCopyConstructorIsDeleted();
12258 SetDeclDeleted(CopyConstructor, ClassLoc);
12259 }
12260
12261 if (S)
12262 PushOnScopeChains(CopyConstructor, S, false);
12263 ClassDecl->addDecl(CopyConstructor);
12264
12265 return CopyConstructor;
12266}
12267
12268void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12269 CXXConstructorDecl *CopyConstructor) {
12270 assert((CopyConstructor->isDefaulted() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12274, __extension__ __PRETTY_FUNCTION__))
12271 CopyConstructor->isCopyConstructor() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12274, __extension__ __PRETTY_FUNCTION__))
12272 !CopyConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12274, __extension__ __PRETTY_FUNCTION__))
12273 !CopyConstructor->isDeleted()) &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12274, __extension__ __PRETTY_FUNCTION__))
12274 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12274, __extension__ __PRETTY_FUNCTION__))
;
12275 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12276 return;
12277
12278 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12279 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12279, __extension__ __PRETTY_FUNCTION__))
;
12280
12281 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12282
12283 // The exception specification is needed because we are defining the
12284 // function.
12285 ResolveExceptionSpec(CurrentLocation,
12286 CopyConstructor->getType()->castAs<FunctionProtoType>());
12287 MarkVTableUsed(CurrentLocation, ClassDecl);
12288
12289 // Add a context note for diagnostics produced after this point.
12290 Scope.addContextNote(CurrentLocation);
12291
12292 // C++11 [class.copy]p7:
12293 // The [definition of an implicitly declared copy constructor] is
12294 // deprecated if the class has a user-declared copy assignment operator
12295 // or a user-declared destructor.
12296 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12297 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12298
12299 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12300 CopyConstructor->setInvalidDecl();
12301 } else {
12302 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12303 ? CopyConstructor->getLocEnd()
12304 : CopyConstructor->getLocation();
12305 Sema::CompoundScopeRAII CompoundScope(*this);
12306 CopyConstructor->setBody(
12307 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12308 CopyConstructor->markUsed(Context);
12309 }
12310
12311 if (ASTMutationListener *L = getASTMutationListener()) {
12312 L->CompletedImplicitDefinition(CopyConstructor);
12313 }
12314}
12315
12316CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12317 CXXRecordDecl *ClassDecl) {
12318 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12318, __extension__ __PRETTY_FUNCTION__))
;
12319
12320 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12321 if (DSM.isAlreadyBeingDeclared())
12322 return nullptr;
12323
12324 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12325 QualType ArgType = Context.getRValueReferenceType(ClassType);
12326
12327 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12328 CXXMoveConstructor,
12329 false);
12330
12331 DeclarationName Name
12332 = Context.DeclarationNames.getCXXConstructorName(
12333 Context.getCanonicalType(ClassType));
12334 SourceLocation ClassLoc = ClassDecl->getLocation();
12335 DeclarationNameInfo NameInfo(Name, ClassLoc);
12336
12337 // C++11 [class.copy]p11:
12338 // An implicitly-declared copy/move constructor is an inline public
12339 // member of its class.
12340 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12341 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12342 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12343 Constexpr);
12344 MoveConstructor->setAccess(AS_public);
12345 MoveConstructor->setDefaulted();
12346
12347 if (getLangOpts().CUDA) {
12348 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12349 MoveConstructor,
12350 /* ConstRHS */ false,
12351 /* Diagnose */ false);
12352 }
12353
12354 // Build an exception specification pointing back at this member.
12355 FunctionProtoType::ExtProtoInfo EPI =
12356 getImplicitMethodEPI(*this, MoveConstructor);
12357 MoveConstructor->setType(
12358 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12359
12360 // Add the parameter to the constructor.
12361 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12362 ClassLoc, ClassLoc,
12363 /*IdentifierInfo=*/nullptr,
12364 ArgType, /*TInfo=*/nullptr,
12365 SC_None, nullptr);
12366 MoveConstructor->setParams(FromParam);
12367
12368 MoveConstructor->setTrivial(
12369 ClassDecl->needsOverloadResolutionForMoveConstructor()
12370 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12371 : ClassDecl->hasTrivialMoveConstructor());
12372
12373 MoveConstructor->setTrivialForCall(
12374 ClassDecl->hasAttr<TrivialABIAttr>() ||
12375 (ClassDecl->needsOverloadResolutionForMoveConstructor()
12376 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12377 TAH_ConsiderTrivialABI)
12378 : ClassDecl->hasTrivialMoveConstructorForCall()));
12379
12380 // Note that we have declared this constructor.
12381 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12382
12383 Scope *S = getScopeForContext(ClassDecl);
12384 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12385
12386 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12387 ClassDecl->setImplicitMoveConstructorIsDeleted();
12388 SetDeclDeleted(MoveConstructor, ClassLoc);
12389 }
12390
12391 if (S)
12392 PushOnScopeChains(MoveConstructor, S, false);
12393 ClassDecl->addDecl(MoveConstructor);
12394
12395 return MoveConstructor;
12396}
12397
12398void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12399 CXXConstructorDecl *MoveConstructor) {
12400 assert((MoveConstructor->isDefaulted() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12404, __extension__ __PRETTY_FUNCTION__))
12401 MoveConstructor->isMoveConstructor() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12404, __extension__ __PRETTY_FUNCTION__))
12402 !MoveConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12404, __extension__ __PRETTY_FUNCTION__))
12403 !MoveConstructor->isDeleted()) &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12404, __extension__ __PRETTY_FUNCTION__))
12404 "DefineImplicitMoveConstructor - call it for implicit move ctor")(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12404, __extension__ __PRETTY_FUNCTION__))
;
12405 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12406 return;
12407
12408 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12409 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12409, __extension__ __PRETTY_FUNCTION__))
;
12410
12411 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12412
12413 // The exception specification is needed because we are defining the
12414 // function.
12415 ResolveExceptionSpec(CurrentLocation,
12416 MoveConstructor->getType()->castAs<FunctionProtoType>());
12417 MarkVTableUsed(CurrentLocation, ClassDecl);
12418
12419 // Add a context note for diagnostics produced after this point.
12420 Scope.addContextNote(CurrentLocation);
12421
12422 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12423 MoveConstructor->setInvalidDecl();
12424 } else {
12425 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12426 ? MoveConstructor->getLocEnd()
12427 : MoveConstructor->getLocation();
12428 Sema::CompoundScopeRAII CompoundScope(*this);
12429 MoveConstructor->setBody(ActOnCompoundStmt(
12430 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12431 MoveConstructor->markUsed(Context);
12432 }
12433
12434 if (ASTMutationListener *L = getASTMutationListener()) {
12435 L->CompletedImplicitDefinition(MoveConstructor);
12436 }
12437}
12438
12439bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12440 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12441}
12442
12443void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12444 SourceLocation CurrentLocation,
12445 CXXConversionDecl *Conv) {
12446 SynthesizedFunctionScope Scope(*this, Conv);
12447 assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12447, __extension__ __PRETTY_FUNCTION__))
;
12448
12449 CXXRecordDecl *Lambda = Conv->getParent();
12450 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12451 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12452
12453 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12454 CallOp = InstantiateFunctionDeclaration(
12455 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12456 if (!CallOp)
12457 return;
12458
12459 Invoker = InstantiateFunctionDeclaration(
12460 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12461 if (!Invoker)
12462 return;
12463 }
12464
12465 if (CallOp->isInvalidDecl())
12466 return;
12467
12468 // Mark the call operator referenced (and add to pending instantiations
12469 // if necessary).
12470 // For both the conversion and static-invoker template specializations
12471 // we construct their body's in this function, so no need to add them
12472 // to the PendingInstantiations.
12473 MarkFunctionReferenced(CurrentLocation, CallOp);
12474
12475 // Fill in the __invoke function with a dummy implementation. IR generation
12476 // will fill in the actual details. Update its type in case it contained
12477 // an 'auto'.
12478 Invoker->markUsed(Context);
12479 Invoker->setReferenced();
12480 Invoker->setType(Conv->getReturnType()->getPointeeType());
12481 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12482
12483 // Construct the body of the conversion function { return __invoke; }.
12484 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12485 VK_LValue, Conv->getLocation()).get();
12486 assert(FunctionRef && "Can't refer to __invoke function?")(static_cast <bool> (FunctionRef && "Can't refer to __invoke function?"
) ? void (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12486, __extension__ __PRETTY_FUNCTION__))
;
12487 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12488 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12489 Conv->getLocation()));
12490 Conv->markUsed(Context);
12491 Conv->setReferenced();
12492
12493 if (ASTMutationListener *L = getASTMutationListener()) {
12494 L->CompletedImplicitDefinition(Conv);
12495 L->CompletedImplicitDefinition(Invoker);
12496 }
12497}
12498
12499
12500
12501void Sema::DefineImplicitLambdaToBlockPointerConversion(
12502 SourceLocation CurrentLocation,
12503 CXXConversionDecl *Conv)
12504{
12505 assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda
()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12505, __extension__ __PRETTY_FUNCTION__))
;
12506
12507 SynthesizedFunctionScope Scope(*this, Conv);
12508
12509 // Copy-initialize the lambda object as needed to capture it.
12510 Expr *This = ActOnCXXThis(CurrentLocation).get();
12511 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12512
12513 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12514 Conv->getLocation(),
12515 Conv, DerefThis);
12516
12517 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12518 // behavior. Note that only the general conversion function does this
12519 // (since it's unusable otherwise); in the case where we inline the
12520 // block literal, it has block literal lifetime semantics.
12521 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12522 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12523 CK_CopyAndAutoreleaseBlockObject,
12524 BuildBlock.get(), nullptr, VK_RValue);
12525
12526 if (BuildBlock.isInvalid()) {
12527 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12528 Conv->setInvalidDecl();
12529 return;
12530 }
12531
12532 // Create the return statement that returns the block from the conversion
12533 // function.
12534 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12535 if (Return.isInvalid()) {
12536 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12537 Conv->setInvalidDecl();
12538 return;
12539 }
12540
12541 // Set the body of the conversion function.
12542 Stmt *ReturnS = Return.get();
12543 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12544 Conv->getLocation()));
12545 Conv->markUsed(Context);
12546
12547 // We're done; notify the mutation listener, if any.
12548 if (ASTMutationListener *L = getASTMutationListener()) {
12549 L->CompletedImplicitDefinition(Conv);
12550 }
12551}
12552
12553/// \brief Determine whether the given list arguments contains exactly one
12554/// "real" (non-default) argument.
12555static bool hasOneRealArgument(MultiExprArg Args) {
12556 switch (Args.size()) {
12557 case 0:
12558 return false;
12559
12560 default:
12561 if (!Args[1]->isDefaultArgument())
12562 return false;
12563
12564 LLVM_FALLTHROUGH[[clang::fallthrough]];
12565 case 1:
12566 return !Args[0]->isDefaultArgument();
12567 }
12568
12569 return false;
12570}
12571
12572ExprResult
12573Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12574 NamedDecl *FoundDecl,
12575 CXXConstructorDecl *Constructor,
12576 MultiExprArg ExprArgs,
12577 bool HadMultipleCandidates,
12578 bool IsListInitialization,
12579 bool IsStdInitListInitialization,
12580 bool RequiresZeroInit,
12581 unsigned ConstructKind,
12582 SourceRange ParenRange) {
12583 bool Elidable = false;
12584
12585 // C++0x [class.copy]p34:
12586 // When certain criteria are met, an implementation is allowed to
12587 // omit the copy/move construction of a class object, even if the
12588 // copy/move constructor and/or destructor for the object have
12589 // side effects. [...]
12590 // - when a temporary class object that has not been bound to a
12591 // reference (12.2) would be copied/moved to a class object
12592 // with the same cv-unqualified type, the copy/move operation
12593 // can be omitted by constructing the temporary object
12594 // directly into the target of the omitted copy/move
12595 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12596 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12597 Expr *SubExpr = ExprArgs[0];
12598 Elidable = SubExpr->isTemporaryObject(
12599 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12600 }
12601
12602 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12603 FoundDecl, Constructor,
12604 Elidable, ExprArgs, HadMultipleCandidates,
12605 IsListInitialization,
12606 IsStdInitListInitialization, RequiresZeroInit,
12607 ConstructKind, ParenRange);
12608}
12609
12610ExprResult
12611Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12612 NamedDecl *FoundDecl,
12613 CXXConstructorDecl *Constructor,
12614 bool Elidable,
12615 MultiExprArg ExprArgs,
12616 bool HadMultipleCandidates,
12617 bool IsListInitialization,
12618 bool IsStdInitListInitialization,
12619 bool RequiresZeroInit,
12620 unsigned ConstructKind,
12621 SourceRange ParenRange) {
12622 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12623 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12624 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12625 return ExprError();
12626 }
12627
12628 return BuildCXXConstructExpr(
12629 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12630 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12631 RequiresZeroInit, ConstructKind, ParenRange);
12632}
12633
12634/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12635/// including handling of its default argument expressions.
12636ExprResult
12637Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12638 CXXConstructorDecl *Constructor,
12639 bool Elidable,
12640 MultiExprArg ExprArgs,
12641 bool HadMultipleCandidates,
12642 bool IsListInitialization,
12643 bool IsStdInitListInitialization,
12644 bool RequiresZeroInit,
12645 unsigned ConstructKind,
12646 SourceRange ParenRange) {
12647 assert(declaresSameEntity((static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12650, __extension__ __PRETTY_FUNCTION__))
12648 Constructor->getParent(),(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12650, __extension__ __PRETTY_FUNCTION__))
12649 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12650, __extension__ __PRETTY_FUNCTION__))
12650 "given constructor for wrong type")(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12650, __extension__ __PRETTY_FUNCTION__))
;
12651 MarkFunctionReferenced(ConstructLoc, Constructor);
12652 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12653 return ExprError();
12654
12655 return CXXConstructExpr::Create(
12656 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12657 ExprArgs, HadMultipleCandidates, IsListInitialization,
12658 IsStdInitListInitialization, RequiresZeroInit,
12659 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12660 ParenRange);
12661}
12662
12663ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12664 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12664, __extension__ __PRETTY_FUNCTION__))
;
12665
12666 // If we already have the in-class initializer nothing needs to be done.
12667 if (Field->getInClassInitializer())
12668 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12669
12670 // If we might have already tried and failed to instantiate, don't try again.
12671 if (Field->isInvalidDecl())
12672 return ExprError();
12673
12674 // Maybe we haven't instantiated the in-class initializer. Go check the
12675 // pattern FieldDecl to see if it has one.
12676 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12677
12678 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12679 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12680 DeclContext::lookup_result Lookup =
12681 ClassPattern->lookup(Field->getDeclName());
12682
12683 // Lookup can return at most two results: the pattern for the field, or the
12684 // injected class name of the parent record. No other member can have the
12685 // same name as the field.
12686 // In modules mode, lookup can return multiple results (coming from
12687 // different modules).
12688 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&(static_cast <bool> ((getLangOpts().Modules || (!Lookup
.empty() && Lookup.size() <= 2)) && "more than two lookup results for field name"
) ? void (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12689, __extension__ __PRETTY_FUNCTION__))
12689 "more than two lookup results for field name")(static_cast <bool> ((getLangOpts().Modules || (!Lookup
.empty() && Lookup.size() <= 2)) && "more than two lookup results for field name"
) ? void (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12689, __extension__ __PRETTY_FUNCTION__))
;
12690 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12691 if (!Pattern) {
12692 assert(isa<CXXRecordDecl>(Lookup[0]) &&(static_cast <bool> (isa<CXXRecordDecl>(Lookup[0]
) && "cannot have other non-field member with same name"
) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12693, __extension__ __PRETTY_FUNCTION__))
12693 "cannot have other non-field member with same name")(static_cast <bool> (isa<CXXRecordDecl>(Lookup[0]
) && "cannot have other non-field member with same name"
) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12693, __extension__ __PRETTY_FUNCTION__))
;
12694 for (auto L : Lookup)
12695 if (isa<FieldDecl>(L)) {
12696 Pattern = cast<FieldDecl>(L);
12697 break;
12698 }
12699 assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!"
) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12699, __extension__ __PRETTY_FUNCTION__))
;
12700 }
12701
12702 if (!Pattern->hasInClassInitializer() ||
12703 InstantiateInClassInitializer(Loc, Field, Pattern,
12704 getTemplateInstantiationArgs(Field))) {
12705 // Don't diagnose this again.
12706 Field->setInvalidDecl();
12707 return ExprError();
12708 }
12709 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12710 }
12711
12712 // DR1351:
12713 // If the brace-or-equal-initializer of a non-static data member
12714 // invokes a defaulted default constructor of its class or of an
12715 // enclosing class in a potentially evaluated subexpression, the
12716 // program is ill-formed.
12717 //
12718 // This resolution is unworkable: the exception specification of the
12719 // default constructor can be needed in an unevaluated context, in
12720 // particular, in the operand of a noexcept-expression, and we can be
12721 // unable to compute an exception specification for an enclosed class.
12722 //
12723 // Any attempt to resolve the exception specification of a defaulted default
12724 // constructor before the initializer is lexically complete will ultimately
12725 // come here at which point we can diagnose it.
12726 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12727 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12728 << OutermostClass << Field;
12729 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12730 // Recover by marking the field invalid, unless we're in a SFINAE context.
12731 if (!isSFINAEContext())
12732 Field->setInvalidDecl();
12733 return ExprError();
12734}
12735
12736void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12737 if (VD->isInvalidDecl()) return;
12738
12739 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12740 if (ClassDecl->isInvalidDecl()) return;
12741 if (ClassDecl->hasIrrelevantDestructor()) return;
12742 if (ClassDecl->isDependentContext()) return;
12743
12744 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12745 MarkFunctionReferenced(VD->getLocation(), Destructor);
12746 CheckDestructorAccess(VD->getLocation(), Destructor,
12747 PDiag(diag::err_access_dtor_var)
12748 << VD->getDeclName()
12749 << VD->getType());
12750 DiagnoseUseOfDecl(Destructor, VD->getLocation());
12751
12752 if (Destructor->isTrivial()) return;
12753 if (!VD->hasGlobalStorage()) return;
12754
12755 // Emit warning for non-trivial dtor in global scope (a real global,
12756 // class-static, function-static).
12757 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12758
12759 // TODO: this should be re-enabled for static locals by !CXAAtExit
12760 if (!VD->isStaticLocal())
12761 Diag(VD->getLocation(), diag::warn_global_destructor);
12762}
12763
12764/// \brief Given a constructor and the set of arguments provided for the
12765/// constructor, convert the arguments and add any required default arguments
12766/// to form a proper call to this constructor.
12767///
12768/// \returns true if an error occurred, false otherwise.
12769bool
12770Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12771 MultiExprArg ArgsPtr,
12772 SourceLocation Loc,
12773 SmallVectorImpl<Expr*> &ConvertedArgs,
12774 bool AllowExplicit,
12775 bool IsListInitialization) {
12776 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12777 unsigned NumArgs = ArgsPtr.size();
12778 Expr **Args = ArgsPtr.data();
12779
12780 const FunctionProtoType *Proto
12781 = Constructor->getType()->getAs<FunctionProtoType>();
12782 assert(Proto && "Constructor without a prototype?")(static_cast <bool> (Proto && "Constructor without a prototype?"
) ? void (0) : __assert_fail ("Proto && \"Constructor without a prototype?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12782, __extension__ __PRETTY_FUNCTION__))
;
12783 unsigned NumParams = Proto->getNumParams();
12784
12785 // If too few arguments are available, we'll fill in the rest with defaults.
12786 if (NumArgs < NumParams)
12787 ConvertedArgs.reserve(NumParams);
12788 else
12789 ConvertedArgs.reserve(NumArgs);
12790
12791 VariadicCallType CallType =
12792 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12793 SmallVector<Expr *, 8> AllArgs;
12794 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12795 Proto, 0,
12796 llvm::makeArrayRef(Args, NumArgs),
12797 AllArgs,
12798 CallType, AllowExplicit,
12799 IsListInitialization);
12800 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12801
12802 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12803
12804 CheckConstructorCall(Constructor,
12805 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12806 Proto, Loc);
12807
12808 return Invalid;
12809}
12810
12811static inline bool
12812CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12813 const FunctionDecl *FnDecl) {
12814 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12815 if (isa<NamespaceDecl>(DC)) {
12816 return SemaRef.Diag(FnDecl->getLocation(),
12817 diag::err_operator_new_delete_declared_in_namespace)
12818 << FnDecl->getDeclName();
12819 }
12820
12821 if (isa<TranslationUnitDecl>(DC) &&
12822 FnDecl->getStorageClass() == SC_Static) {
12823 return SemaRef.Diag(FnDecl->getLocation(),
12824 diag::err_operator_new_delete_declared_static)
12825 << FnDecl->getDeclName();
12826 }
12827
12828 return false;
12829}
12830
12831static inline bool
12832CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12833 CanQualType ExpectedResultType,
12834 CanQualType ExpectedFirstParamType,
12835 unsigned DependentParamTypeDiag,
12836 unsigned InvalidParamTypeDiag) {
12837 QualType ResultType =
12838 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12839
12840 // Check that the result type is not dependent.
12841 if (ResultType->isDependentType())
12842 return SemaRef.Diag(FnDecl->getLocation(),
12843 diag::err_operator_new_delete_dependent_result_type)
12844 << FnDecl->getDeclName() << ExpectedResultType;
12845
12846 // Check that the result type is what we expect.
12847 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12848 return SemaRef.Diag(FnDecl->getLocation(),
12849 diag::err_operator_new_delete_invalid_result_type)
12850 << FnDecl->getDeclName() << ExpectedResultType;
12851
12852 // A function template must have at least 2 parameters.
12853 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12854 return SemaRef.Diag(FnDecl->getLocation(),
12855 diag::err_operator_new_delete_template_too_few_parameters)
12856 << FnDecl->getDeclName();
12857
12858 // The function decl must have at least 1 parameter.
12859 if (FnDecl->getNumParams() == 0)
12860 return SemaRef.Diag(FnDecl->getLocation(),
12861 diag::err_operator_new_delete_too_few_parameters)
12862 << FnDecl->getDeclName();
12863
12864 // Check the first parameter type is not dependent.
12865 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12866 if (FirstParamType->isDependentType())
12867 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12868 << FnDecl->getDeclName() << ExpectedFirstParamType;
12869
12870 // Check that the first parameter type is what we expect.
12871 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12872 ExpectedFirstParamType)
12873 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12874 << FnDecl->getDeclName() << ExpectedFirstParamType;
12875
12876 return false;
12877}
12878
12879static bool
12880CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12881 // C++ [basic.stc.dynamic.allocation]p1:
12882 // A program is ill-formed if an allocation function is declared in a
12883 // namespace scope other than global scope or declared static in global
12884 // scope.
12885 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12886 return true;
12887
12888 CanQualType SizeTy =
12889 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12890
12891 // C++ [basic.stc.dynamic.allocation]p1:
12892 // The return type shall be void*. The first parameter shall have type
12893 // std::size_t.
12894 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12895 SizeTy,
12896 diag::err_operator_new_dependent_param_type,
12897 diag::err_operator_new_param_type))
12898 return true;
12899
12900 // C++ [basic.stc.dynamic.allocation]p1:
12901 // The first parameter shall not have an associated default argument.
12902 if (FnDecl->getParamDecl(0)->hasDefaultArg())
12903 return SemaRef.Diag(FnDecl->getLocation(),
12904 diag::err_operator_new_default_arg)
12905 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12906
12907 return false;
12908}
12909
12910static bool
12911CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12912 // C++ [basic.stc.dynamic.deallocation]p1:
12913 // A program is ill-formed if deallocation functions are declared in a
12914 // namespace scope other than global scope or declared static in global
12915 // scope.
12916 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12917 return true;
12918
12919 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
12920
12921 // C++ P0722:
12922 // Within a class C, the first parameter of a destroying operator delete
12923 // shall be of type C *. The first parameter of any other deallocation
12924 // function shall be of type void *.
12925 CanQualType ExpectedFirstParamType =
12926 MD && MD->isDestroyingOperatorDelete()
12927 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
12928 SemaRef.Context.getRecordType(MD->getParent())))
12929 : SemaRef.Context.VoidPtrTy;
12930
12931 // C++ [basic.stc.dynamic.deallocation]p2:
12932 // Each deallocation function shall return void
12933 if (CheckOperatorNewDeleteTypes(
12934 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
12935 diag::err_operator_delete_dependent_param_type,
12936 diag::err_operator_delete_param_type))
12937 return true;
12938
12939 // C++ P0722:
12940 // A destroying operator delete shall be a usual deallocation function.
12941 if (MD && !MD->getParent()->isDependentContext() &&
12942 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
12943 SemaRef.Diag(MD->getLocation(),
12944 diag::err_destroying_operator_delete_not_usual);
12945 return true;
12946 }
12947
12948 return false;
12949}
12950
12951/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12952/// of this overloaded operator is well-formed. If so, returns false;
12953/// otherwise, emits appropriate diagnostics and returns true.
12954bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12955 assert(FnDecl && FnDecl->isOverloadedOperator() &&(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12956, __extension__ __PRETTY_FUNCTION__))
12956 "Expected an overloaded operator declaration")(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12956, __extension__ __PRETTY_FUNCTION__))
;
12957
12958 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12959
12960 // C++ [over.oper]p5:
12961 // The allocation and deallocation functions, operator new,
12962 // operator new[], operator delete and operator delete[], are
12963 // described completely in 3.7.3. The attributes and restrictions
12964 // found in the rest of this subclause do not apply to them unless
12965 // explicitly stated in 3.7.3.
12966 if (Op == OO_Delete || Op == OO_Array_Delete)
12967 return CheckOperatorDeleteDeclaration(*this, FnDecl);
12968
12969 if (Op == OO_New || Op == OO_Array_New)
12970 return CheckOperatorNewDeclaration(*this, FnDecl);
12971
12972 // C++ [over.oper]p6:
12973 // An operator function shall either be a non-static member
12974 // function or be a non-member function and have at least one
12975 // parameter whose type is a class, a reference to a class, an
12976 // enumeration, or a reference to an enumeration.
12977 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12978 if (MethodDecl->isStatic())
12979 return Diag(FnDecl->getLocation(),
12980 diag::err_operator_overload_static) << FnDecl->getDeclName();
12981 } else {
12982 bool ClassOrEnumParam = false;
12983 for (auto Param : FnDecl->parameters()) {
12984 QualType ParamType = Param->getType().getNonReferenceType();
12985 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12986 ParamType->isEnumeralType()) {
12987 ClassOrEnumParam = true;
12988 break;
12989 }
12990 }
12991
12992 if (!ClassOrEnumParam)
12993 return Diag(FnDecl->getLocation(),
12994 diag::err_operator_overload_needs_class_or_enum)
12995 << FnDecl->getDeclName();
12996 }
12997
12998 // C++ [over.oper]p8:
12999 // An operator function cannot have default arguments (8.3.6),
13000 // except where explicitly stated below.
13001 //
13002 // Only the function-call operator allows default arguments
13003 // (C++ [over.call]p1).
13004 if (Op != OO_Call) {
13005 for (auto Param : FnDecl->parameters()) {
13006 if (Param->hasDefaultArg())
13007 return Diag(Param->getLocation(),
13008 diag::err_operator_overload_default_arg)
13009 << FnDecl->getDeclName() << Param->getDefaultArgRange();
13010 }
13011 }
13012
13013 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13014 { false, false, false }
13015#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13016 , { Unary, Binary, MemberOnly }
13017#include "clang/Basic/OperatorKinds.def"
13018 };
13019
13020 bool CanBeUnaryOperator = OperatorUses[Op][0];
13021 bool CanBeBinaryOperator = OperatorUses[Op][1];
13022 bool MustBeMemberOperator = OperatorUses[Op][2];
13023
13024 // C++ [over.oper]p8:
13025 // [...] Operator functions cannot have more or fewer parameters
13026 // than the number required for the corresponding operator, as
13027 // described in the rest of this subclause.
13028 unsigned NumParams = FnDecl->getNumParams()
13029 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13030 if (Op != OO_Call &&
13031 ((NumParams == 1 && !CanBeUnaryOperator) ||
13032 (NumParams == 2 && !CanBeBinaryOperator) ||
13033 (NumParams < 1) || (NumParams > 2))) {
13034 // We have the wrong number of parameters.
13035 unsigned ErrorKind;
13036 if (CanBeUnaryOperator && CanBeBinaryOperator) {
13037 ErrorKind = 2; // 2 -> unary or binary.
13038 } else if (CanBeUnaryOperator) {
13039 ErrorKind = 0; // 0 -> unary
13040 } else {
13041 assert(CanBeBinaryOperator &&(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13042, __extension__ __PRETTY_FUNCTION__))
13042 "All non-call overloaded operators are unary or binary!")(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13042, __extension__ __PRETTY_FUNCTION__))
;
13043 ErrorKind = 1; // 1 -> binary
13044 }
13045
13046 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13047 << FnDecl->getDeclName() << NumParams << ErrorKind;
13048 }
13049
13050 // Overloaded operators other than operator() cannot be variadic.
13051 if (Op != OO_Call &&
13052 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13053 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13054 << FnDecl->getDeclName();
13055 }
13056
13057 // Some operators must be non-static member functions.
13058 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13059 return Diag(FnDecl->getLocation(),
13060 diag::err_operator_overload_must_be_member)
13061 << FnDecl->getDeclName();
13062 }
13063
13064 // C++ [over.inc]p1:
13065 // The user-defined function called operator++ implements the
13066 // prefix and postfix ++ operator. If this function is a member
13067 // function with no parameters, or a non-member function with one
13068 // parameter of class or enumeration type, it defines the prefix
13069 // increment operator ++ for objects of that type. If the function
13070 // is a member function with one parameter (which shall be of type
13071 // int) or a non-member function with two parameters (the second
13072 // of which shall be of type int), it defines the postfix
13073 // increment operator ++ for objects of that type.
13074 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13075 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13076 QualType ParamType = LastParam->getType();
13077
13078 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13079 !ParamType->isDependentType())
13080 return Diag(LastParam->getLocation(),
13081 diag::err_operator_overload_post_incdec_must_be_int)
13082 << LastParam->getType() << (Op == OO_MinusMinus);
13083 }
13084
13085 return false;
13086}
13087
13088static bool
13089checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13090 FunctionTemplateDecl *TpDecl) {
13091 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13092
13093 // Must have one or two template parameters.
13094 if (TemplateParams->size() == 1) {
13095 NonTypeTemplateParmDecl *PmDecl =
13096 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13097
13098 // The template parameter must be a char parameter pack.
13099 if (PmDecl && PmDecl->isTemplateParameterPack() &&
13100 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13101 return false;
13102
13103 } else if (TemplateParams->size() == 2) {
13104 TemplateTypeParmDecl *PmType =
13105 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13106 NonTypeTemplateParmDecl *PmArgs =
13107 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13108
13109 // The second template parameter must be a parameter pack with the
13110 // first template parameter as its type.
13111 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13112 PmArgs->isTemplateParameterPack()) {
13113 const TemplateTypeParmType *TArgs =
13114 PmArgs->getType()->getAs<TemplateTypeParmType>();
13115 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13116 TArgs->getIndex() == PmType->getIndex()) {
13117 if (!SemaRef.inTemplateInstantiation())
13118 SemaRef.Diag(TpDecl->getLocation(),
13119 diag::ext_string_literal_operator_template);
13120 return false;
13121 }
13122 }
13123 }
13124
13125 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13126 diag::err_literal_operator_template)
13127 << TpDecl->getTemplateParameters()->getSourceRange();
13128 return true;
13129}
13130
13131/// CheckLiteralOperatorDeclaration - Check whether the declaration
13132/// of this literal operator function is well-formed. If so, returns
13133/// false; otherwise, emits appropriate diagnostics and returns true.
13134bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13135 if (isa<CXXMethodDecl>(FnDecl)) {
13136 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13137 << FnDecl->getDeclName();
13138 return true;
13139 }
13140
13141 if (FnDecl->isExternC()) {
13142 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13143 if (const LinkageSpecDecl *LSD =
13144 FnDecl->getDeclContext()->getExternCContext())
13145 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13146 return true;
13147 }
13148
13149 // This might be the definition of a literal operator template.
13150 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13151
13152 // This might be a specialization of a literal operator template.
13153 if (!TpDecl)
13154 TpDecl = FnDecl->getPrimaryTemplate();
13155
13156 // template <char...> type operator "" name() and
13157 // template <class T, T...> type operator "" name() are the only valid
13158 // template signatures, and the only valid signatures with no parameters.
13159 if (TpDecl) {
13160 if (FnDecl->param_size() != 0) {
13161 Diag(FnDecl->getLocation(),
13162 diag::err_literal_operator_template_with_params);
13163 return true;
13164 }
13165
13166 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13167 return true;
13168
13169 } else if (FnDecl->param_size() == 1) {
13170 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13171
13172 QualType ParamType = Param->getType().getUnqualifiedType();
13173
13174 // Only unsigned long long int, long double, any character type, and const
13175 // char * are allowed as the only parameters.
13176 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13177 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13178 Context.hasSameType(ParamType, Context.CharTy) ||
13179 Context.hasSameType(ParamType, Context.WideCharTy) ||
13180 Context.hasSameType(ParamType, Context.Char16Ty) ||
13181 Context.hasSameType(ParamType, Context.Char32Ty)) {
13182 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13183 QualType InnerType = Ptr->getPointeeType();
13184
13185 // Pointer parameter must be a const char *.
13186 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13187 Context.CharTy) &&
13188 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13189 Diag(Param->getSourceRange().getBegin(),
13190 diag::err_literal_operator_param)
13191 << ParamType << "'const char *'" << Param->getSourceRange();
13192 return true;
13193 }
13194
13195 } else if (ParamType->isRealFloatingType()) {
13196 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13197 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13198 return true;
13199
13200 } else if (ParamType->isIntegerType()) {
13201 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13202 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13203 return true;
13204
13205 } else {
13206 Diag(Param->getSourceRange().getBegin(),
13207 diag::err_literal_operator_invalid_param)
13208 << ParamType << Param->getSourceRange();
13209 return true;
13210 }
13211
13212 } else if (FnDecl->param_size() == 2) {
13213 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13214
13215 // First, verify that the first parameter is correct.
13216
13217 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13218
13219 // Two parameter function must have a pointer to const as a
13220 // first parameter; let's strip those qualifiers.
13221 const PointerType *PT = FirstParamType->getAs<PointerType>();
13222
13223 if (!PT) {
13224 Diag((*Param)->getSourceRange().getBegin(),
13225 diag::err_literal_operator_param)
13226 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13227 return true;
13228 }
13229
13230 QualType PointeeType = PT->getPointeeType();
13231 // First parameter must be const
13232 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13233 Diag((*Param)->getSourceRange().getBegin(),
13234 diag::err_literal_operator_param)
13235 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13236 return true;
13237 }
13238
13239 QualType InnerType = PointeeType.getUnqualifiedType();
13240 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
13241 // are allowed as the first parameter to a two-parameter function
13242 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13243 Context.hasSameType(InnerType, Context.WideCharTy) ||
13244 Context.hasSameType(InnerType, Context.Char16Ty) ||
13245 Context.hasSameType(InnerType, Context.Char32Ty))) {
13246 Diag((*Param)->getSourceRange().getBegin(),
13247 diag::err_literal_operator_param)
13248 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13249 return true;
13250 }
13251
13252 // Move on to the second and final parameter.
13253 ++Param;
13254
13255 // The second parameter must be a std::size_t.
13256 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13257 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13258 Diag((*Param)->getSourceRange().getBegin(),
13259 diag::err_literal_operator_param)
13260 << SecondParamType << Context.getSizeType()
13261 << (*Param)->getSourceRange();
13262 return true;
13263 }
13264 } else {
13265 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13266 return true;
13267 }
13268
13269 // Parameters are good.
13270
13271 // A parameter-declaration-clause containing a default argument is not
13272 // equivalent to any of the permitted forms.
13273 for (auto Param : FnDecl->parameters()) {
13274 if (Param->hasDefaultArg()) {
13275 Diag(Param->getDefaultArgRange().getBegin(),
13276 diag::err_literal_operator_default_argument)
13277 << Param->getDefaultArgRange();
13278 break;
13279 }
13280 }
13281
13282 StringRef LiteralName
13283 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13284 if (LiteralName[0] != '_' &&
13285 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13286 // C++11 [usrlit.suffix]p1:
13287 // Literal suffix identifiers that do not start with an underscore
13288 // are reserved for future standardization.
13289 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13290 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13291 }
13292
13293 return false;
13294}
13295
13296/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13297/// linkage specification, including the language and (if present)
13298/// the '{'. ExternLoc is the location of the 'extern', Lang is the
13299/// language string literal. LBraceLoc, if valid, provides the location of
13300/// the '{' brace. Otherwise, this linkage specification does not
13301/// have any braces.
13302Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13303 Expr *LangStr,
13304 SourceLocation LBraceLoc) {
13305 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13306 if (!Lit->isAscii()) {
13307 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13308 << LangStr->getSourceRange();
13309 return nullptr;
13310 }
13311
13312 StringRef Lang = Lit->getString();
13313 LinkageSpecDecl::LanguageIDs Language;
13314 if (Lang == "C")
13315 Language = LinkageSpecDecl::lang_c;
13316 else if (Lang == "C++")
13317 Language = LinkageSpecDecl::lang_cxx;
13318 else {
13319 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13320 << LangStr->getSourceRange();
13321 return nullptr;
13322 }
13323
13324 // FIXME: Add all the various semantics of linkage specifications
13325
13326 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13327 LangStr->getExprLoc(), Language,
13328 LBraceLoc.isValid());
13329 CurContext->addDecl(D);
13330 PushDeclContext(S, D);
13331 return D;
13332}
13333
13334/// ActOnFinishLinkageSpecification - Complete the definition of
13335/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13336/// valid, it's the position of the closing '}' brace in a linkage
13337/// specification that uses braces.
13338Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13339 Decl *LinkageSpec,
13340 SourceLocation RBraceLoc) {
13341 if (RBraceLoc.isValid()) {
13342 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13343 LSDecl->setRBraceLoc(RBraceLoc);
13344 }
13345 PopDeclContext();
13346 return LinkageSpec;
13347}
13348
13349Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13350 AttributeList *AttrList,
13351 SourceLocation SemiLoc) {
13352 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13353 // Attribute declarations appertain to empty declaration so we handle
13354 // them here.
13355 if (AttrList)
13356 ProcessDeclAttributeList(S, ED, AttrList);
13357
13358 CurContext->addDecl(ED);
13359 return ED;
13360}
13361
13362/// \brief Perform semantic analysis for the variable declaration that
13363/// occurs within a C++ catch clause, returning the newly-created
13364/// variable.
13365VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13366 TypeSourceInfo *TInfo,
13367 SourceLocation StartLoc,
13368 SourceLocation Loc,
13369 IdentifierInfo *Name) {
13370 bool Invalid = false;
13371 QualType ExDeclType = TInfo->getType();
13372
13373 // Arrays and functions decay.
13374 if (ExDeclType->isArrayType())
13375 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13376 else if (ExDeclType->isFunctionType())
13377 ExDeclType = Context.getPointerType(ExDeclType);
13378
13379 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13380 // The exception-declaration shall not denote a pointer or reference to an
13381 // incomplete type, other than [cv] void*.
13382 // N2844 forbids rvalue references.
13383 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13384 Diag(Loc, diag::err_catch_rvalue_ref);
13385 Invalid = true;
13386 }
13387
13388 if (ExDeclType->isVariablyModifiedType()) {
13389 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13390 Invalid = true;
13391 }
13392
13393 QualType BaseType = ExDeclType;
13394 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13395 unsigned DK = diag::err_catch_incomplete;
13396 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13397 BaseType = Ptr->getPointeeType();
13398 Mode = 1;
13399 DK = diag::err_catch_incomplete_ptr;
13400 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13401 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13402 BaseType = Ref->getPointeeType();
13403 Mode = 2;
13404 DK = diag::err_catch_incomplete_ref;
13405 }
13406 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13407 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13408 Invalid = true;
13409
13410 if (!Invalid && !ExDeclType->isDependentType() &&
13411 RequireNonAbstractType(Loc, ExDeclType,
13412 diag::err_abstract_type_in_decl,
13413 AbstractVariableType))
13414 Invalid = true;
13415
13416 // Only the non-fragile NeXT runtime currently supports C++ catches
13417 // of ObjC types, and no runtime supports catching ObjC types by value.
13418 if (!Invalid && getLangOpts().ObjC1) {
13419 QualType T = ExDeclType;
13420 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13421 T = RT->getPointeeType();
13422
13423 if (T->isObjCObjectType()) {
13424 Diag(Loc, diag::err_objc_object_catch);
13425 Invalid = true;
13426 } else if (T->isObjCObjectPointerType()) {
13427 // FIXME: should this be a test for macosx-fragile specifically?
13428 if (getLangOpts().ObjCRuntime.isFragile())
13429 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13430 }
13431 }
13432
13433 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13434 ExDeclType, TInfo, SC_None);
13435 ExDecl->setExceptionVariable(true);
13436
13437 // In ARC, infer 'retaining' for variables of retainable type.
13438 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13439 Invalid = true;
13440
13441 if (!Invalid && !ExDeclType->isDependentType()) {
13442 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13443 // Insulate this from anything else we might currently be parsing.
13444 EnterExpressionEvaluationContext scope(
13445 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13446
13447 // C++ [except.handle]p16:
13448 // The object declared in an exception-declaration or, if the
13449 // exception-declaration does not specify a name, a temporary (12.2) is
13450 // copy-initialized (8.5) from the exception object. [...]
13451 // The object is destroyed when the handler exits, after the destruction
13452 // of any automatic objects initialized within the handler.
13453 //
13454 // We just pretend to initialize the object with itself, then make sure
13455 // it can be destroyed later.
13456 QualType initType = Context.getExceptionObjectType(ExDeclType);
13457
13458 InitializedEntity entity =
13459 InitializedEntity::InitializeVariable(ExDecl);
13460 InitializationKind initKind =
13461 InitializationKind::CreateCopy(Loc, SourceLocation());
13462
13463 Expr *opaqueValue =
13464 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13465 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13466 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13467 if (result.isInvalid())
13468 Invalid = true;
13469 else {
13470 // If the constructor used was non-trivial, set this as the
13471 // "initializer".
13472 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13473 if (!construct->getConstructor()->isTrivial()) {
13474 Expr *init = MaybeCreateExprWithCleanups(construct);
13475 ExDecl->setInit(init);
13476 }
13477
13478 // And make sure it's destructable.
13479 FinalizeVarWithDestructor(ExDecl, recordType);
13480 }
13481 }
13482 }
13483
13484 if (Invalid)
13485 ExDecl->setInvalidDecl();
13486
13487 return ExDecl;
13488}
13489
13490/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13491/// handler.
13492Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13493 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13494 bool Invalid = D.isInvalidType();
13495
13496 // Check for unexpanded parameter packs.
13497 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13498 UPPC_ExceptionType)) {
13499 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13500 D.getIdentifierLoc());
13501 Invalid = true;
13502 }
13503
13504 IdentifierInfo *II = D.getIdentifier();
13505 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13506 LookupOrdinaryName,
13507 ForVisibleRedeclaration)) {
13508 // The scope should be freshly made just for us. There is just no way
13509 // it contains any previous declaration, except for function parameters in
13510 // a function-try-block's catch statement.
13511 assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void
(0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13511, __extension__ __PRETTY_FUNCTION__))
;
13512 if (isDeclInScope(PrevDecl, CurContext, S)) {
13513 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13514 << D.getIdentifier();
13515 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13516 Invalid = true;
13517 } else if (PrevDecl->isTemplateParameter())
13518 // Maybe we will complain about the shadowed template parameter.
13519 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13520 }
13521
13522 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13523 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13524 << D.getCXXScopeSpec().getRange();
13525 Invalid = true;
13526 }
13527
13528 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13529 D.getLocStart(),
13530 D.getIdentifierLoc(),
13531 D.getIdentifier());
13532 if (Invalid)
13533 ExDecl->setInvalidDecl();
13534
13535 // Add the exception declaration into this scope.
13536 if (II)
13537 PushOnScopeChains(ExDecl, S);
13538 else
13539 CurContext->addDecl(ExDecl);
13540
13541 ProcessDeclAttributes(S, ExDecl, D);
13542 return ExDecl;
13543}
13544
13545Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13546 Expr *AssertExpr,
13547 Expr *AssertMessageExpr,
13548 SourceLocation RParenLoc) {
13549 StringLiteral *AssertMessage =
13550 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13551
13552 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13553 return nullptr;
13554
13555 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13556 AssertMessage, RParenLoc, false);
13557}
13558
13559Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13560 Expr *AssertExpr,
13561 StringLiteral *AssertMessage,
13562 SourceLocation RParenLoc,
13563 bool Failed) {
13564 assert(AssertExpr != nullptr && "Expected non-null condition")(static_cast <bool> (AssertExpr != nullptr && "Expected non-null condition"
) ? void (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13564, __extension__ __PRETTY_FUNCTION__))
;
13565 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13566 !Failed) {
13567 // In a static_assert-declaration, the constant-expression shall be a
13568 // constant expression that can be contextually converted to bool.
13569 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13570 if (Converted.isInvalid())
13571 Failed = true;
13572
13573 llvm::APSInt Cond;
13574 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13575 diag::err_static_assert_expression_is_not_constant,
13576 /*AllowFold=*/false).isInvalid())
13577 Failed = true;
13578
13579 if (!Failed && !Cond) {
13580 SmallString<256> MsgBuffer;
13581 llvm::raw_svector_ostream Msg(MsgBuffer);
13582 if (AssertMessage)
13583 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13584
13585 Expr *InnerCond = nullptr;
13586 std::string InnerCondDescription;
13587 std::tie(InnerCond, InnerCondDescription) =
13588 findFailedBooleanCondition(Converted.get(),
13589 /*AllowTopLevelCond=*/false);
13590 if (InnerCond) {
13591 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13592 << InnerCondDescription << !AssertMessage
13593 << Msg.str() << InnerCond->getSourceRange();
13594 } else {
13595 Diag(StaticAssertLoc, diag::err_static_assert_failed)
13596 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13597 }
13598 Failed = true;
13599 }
13600 }
13601
13602 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13603 /*DiscardedValue*/false,
13604 /*IsConstexpr*/true);
13605 if (FullAssertExpr.isInvalid())
13606 Failed = true;
13607 else
13608 AssertExpr = FullAssertExpr.get();
13609
13610 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13611 AssertExpr, AssertMessage, RParenLoc,
13612 Failed);
13613
13614 CurContext->addDecl(Decl);
13615 return Decl;
13616}
13617
13618/// \brief Perform semantic analysis of the given friend type declaration.
13619///
13620/// \returns A friend declaration that.
13621FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13622 SourceLocation FriendLoc,
13623 TypeSourceInfo *TSInfo) {
13624 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")(static_cast <bool> (TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? void (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13624, __extension__ __PRETTY_FUNCTION__))
;
13625
13626 QualType T = TSInfo->getType();
13627 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13628
13629 // C++03 [class.friend]p2:
13630 // An elaborated-type-specifier shall be used in a friend declaration
13631 // for a class.*
13632 //
13633 // * The class-key of the elaborated-type-specifier is required.
13634 if (!CodeSynthesisContexts.empty()) {
13635 // Do not complain about the form of friend template types during any kind
13636 // of code synthesis. For template instantiation, we will have complained
13637 // when the template was defined.
13638 } else {
13639 if (!T->isElaboratedTypeSpecifier()) {
13640 // If we evaluated the type to a record type, suggest putting
13641 // a tag in front.
13642 if (const RecordType *RT = T->getAs<RecordType>()) {
13643 RecordDecl *RD = RT->getDecl();
13644
13645 SmallString<16> InsertionText(" ");
13646 InsertionText += RD->getKindName();
13647
13648 Diag(TypeRange.getBegin(),
13649 getLangOpts().CPlusPlus11 ?
13650 diag::warn_cxx98_compat_unelaborated_friend_type :
13651 diag::ext_unelaborated_friend_type)
13652 << (unsigned) RD->getTagKind()
13653 << T
13654 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13655 InsertionText);
13656 } else {
13657 Diag(FriendLoc,
13658 getLangOpts().CPlusPlus11 ?
13659 diag::warn_cxx98_compat_nonclass_type_friend :
13660 diag::ext_nonclass_type_friend)
13661 << T
13662 << TypeRange;
13663 }
13664 } else if (T->getAs<EnumType>()) {
13665 Diag(FriendLoc,
13666 getLangOpts().CPlusPlus11 ?
13667 diag::warn_cxx98_compat_enum_friend :
13668 diag::ext_enum_friend)
13669 << T
13670 << TypeRange;
13671 }
13672
13673 // C++11 [class.friend]p3:
13674 // A friend declaration that does not declare a function shall have one
13675 // of the following forms:
13676 // friend elaborated-type-specifier ;
13677 // friend simple-type-specifier ;
13678 // friend typename-specifier ;
13679 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13680 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13681 }
13682
13683 // If the type specifier in a friend declaration designates a (possibly
13684 // cv-qualified) class type, that class is declared as a friend; otherwise,
13685 // the friend declaration is ignored.
13686 return FriendDecl::Create(Context, CurContext,
13687 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13688 FriendLoc);
13689}
13690
13691/// Handle a friend tag declaration where the scope specifier was
13692/// templated.
13693Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13694 unsigned TagSpec, SourceLocation TagLoc,
13695 CXXScopeSpec &SS,
13696 IdentifierInfo *Name,
13697 SourceLocation NameLoc,
13698 AttributeList *Attr,
13699 MultiTemplateParamsArg TempParamLists) {
13700 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13701
13702 bool IsMemberSpecialization = false;
13703 bool Invalid = false;
13704
13705 if (TemplateParameterList *TemplateParams =
13706 MatchTemplateParametersToScopeSpecifier(
13707 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13708 IsMemberSpecialization, Invalid)) {
13709 if (TemplateParams->size() > 0) {
13710 // This is a declaration of a class template.
13711 if (Invalid)
13712 return nullptr;
13713
13714 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13715 NameLoc, Attr, TemplateParams, AS_public,
13716 /*ModulePrivateLoc=*/SourceLocation(),
13717 FriendLoc, TempParamLists.size() - 1,
13718 TempParamLists.data()).get();
13719 } else {
13720 // The "template<>" header is extraneous.
13721 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13722 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13723 IsMemberSpecialization = true;
13724 }
13725 }
13726
13727 if (Invalid) return nullptr;
13728
13729 bool isAllExplicitSpecializations = true;
13730 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13731 if (TempParamLists[I]->size()) {
13732 isAllExplicitSpecializations = false;
13733 break;
13734 }
13735 }
13736
13737 // FIXME: don't ignore attributes.
13738
13739 // If it's explicit specializations all the way down, just forget
13740 // about the template header and build an appropriate non-templated
13741 // friend. TODO: for source fidelity, remember the headers.
13742 if (isAllExplicitSpecializations) {
13743 if (SS.isEmpty()) {
13744 bool Owned = false;
13745 bool IsDependent = false;
13746 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13747 Attr, AS_public,
13748 /*ModulePrivateLoc=*/SourceLocation(),
13749 MultiTemplateParamsArg(), Owned, IsDependent,
13750 /*ScopedEnumKWLoc=*/SourceLocation(),
13751 /*ScopedEnumUsesClassTag=*/false,
13752 /*UnderlyingType=*/TypeResult(),
13753 /*IsTypeSpecifier=*/false,
13754 /*IsTemplateParamOrArg=*/false);
13755 }
13756
13757 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13758 ElaboratedTypeKeyword Keyword
13759 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13760 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13761 *Name, NameLoc);
13762 if (T.isNull())
13763 return nullptr;
13764
13765 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13766 if (isa<DependentNameType>(T)) {
13767 DependentNameTypeLoc TL =
13768 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13769 TL.setElaboratedKeywordLoc(TagLoc);
13770 TL.setQualifierLoc(QualifierLoc);
13771 TL.setNameLoc(NameLoc);
13772 } else {
13773 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13774 TL.setElaboratedKeywordLoc(TagLoc);
13775 TL.setQualifierLoc(QualifierLoc);
13776 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13777 }
13778
13779 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13780 TSI, FriendLoc, TempParamLists);
13781 Friend->setAccess(AS_public);
13782 CurContext->addDecl(Friend);
13783 return Friend;
13784 }
13785
13786 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")(static_cast <bool> (SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? void (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13786, __extension__ __PRETTY_FUNCTION__))
;
13787
13788
13789
13790 // Handle the case of a templated-scope friend class. e.g.
13791 // template <class T> class A<T>::B;
13792 // FIXME: we don't support these right now.
13793 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13794 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13795 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13796 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13797 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13798 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13799 TL.setElaboratedKeywordLoc(TagLoc);
13800 TL.setQualifierLoc(SS.getWithLocInContext(Context));
13801 TL.setNameLoc(NameLoc);
13802
13803 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13804 TSI, FriendLoc, TempParamLists);
13805 Friend->setAccess(AS_public);
13806 Friend->setUnsupportedFriend(true);
13807 CurContext->addDecl(Friend);
13808 return Friend;
13809}
13810
13811
13812/// Handle a friend type declaration. This works in tandem with
13813/// ActOnTag.
13814///
13815/// Notes on friend class templates:
13816///
13817/// We generally treat friend class declarations as if they were
13818/// declaring a class. So, for example, the elaborated type specifier
13819/// in a friend declaration is required to obey the restrictions of a
13820/// class-head (i.e. no typedefs in the scope chain), template
13821/// parameters are required to match up with simple template-ids, &c.
13822/// However, unlike when declaring a template specialization, it's
13823/// okay to refer to a template specialization without an empty
13824/// template parameter declaration, e.g.
13825/// friend class A<T>::B<unsigned>;
13826/// We permit this as a special case; if there are any template
13827/// parameters present at all, require proper matching, i.e.
13828/// template <> template \<class T> friend class A<int>::B;
13829Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13830 MultiTemplateParamsArg TempParams) {
13831 SourceLocation Loc = DS.getLocStart();
13832
13833 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13833, __extension__ __PRETTY_FUNCTION__))
;
13834 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13834, __extension__ __PRETTY_FUNCTION__))
;
13835
13836 // Try to convert the decl specifier to a type. This works for
13837 // friend templates because ActOnTag never produces a ClassTemplateDecl
13838 // for a TUK_Friend.
13839 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
13840 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13841 QualType T = TSI->getType();
13842 if (TheDeclarator.isInvalidType())
13843 return nullptr;
13844
13845 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13846 return nullptr;
13847
13848 // This is definitely an error in C++98. It's probably meant to
13849 // be forbidden in C++0x, too, but the specification is just
13850 // poorly written.
13851 //
13852 // The problem is with declarations like the following:
13853 // template <T> friend A<T>::foo;
13854 // where deciding whether a class C is a friend or not now hinges
13855 // on whether there exists an instantiation of A that causes
13856 // 'foo' to equal C. There are restrictions on class-heads
13857 // (which we declare (by fiat) elaborated friend declarations to
13858 // be) that makes this tractable.
13859 //
13860 // FIXME: handle "template <> friend class A<T>;", which
13861 // is possibly well-formed? Who even knows?
13862 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13863 Diag(Loc, diag::err_tagless_friend_type_template)
13864 << DS.getSourceRange();
13865 return nullptr;
13866 }
13867
13868 // C++98 [class.friend]p1: A friend of a class is a function
13869 // or class that is not a member of the class . . .
13870 // This is fixed in DR77, which just barely didn't make the C++03
13871 // deadline. It's also a very silly restriction that seriously
13872 // affects inner classes and which nobody else seems to implement;
13873 // thus we never diagnose it, not even in -pedantic.
13874 //
13875 // But note that we could warn about it: it's always useless to
13876 // friend one of your own members (it's not, however, worthless to
13877 // friend a member of an arbitrary specialization of your template).
13878
13879 Decl *D;
13880 if (!TempParams.empty())
13881 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13882 TempParams,
13883 TSI,
13884 DS.getFriendSpecLoc());
13885 else
13886 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13887
13888 if (!D)
13889 return nullptr;
13890
13891 D->setAccess(AS_public);
13892 CurContext->addDecl(D);
13893
13894 return D;
13895}
13896
13897NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13898 MultiTemplateParamsArg TemplateParams) {
13899 const DeclSpec &DS = D.getDeclSpec();
13900
13901 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13901, __extension__ __PRETTY_FUNCTION__))
;
13902 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13902, __extension__ __PRETTY_FUNCTION__))
;
13903
13904 SourceLocation Loc = D.getIdentifierLoc();
13905 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13906
13907 // C++ [class.friend]p1
13908 // A friend of a class is a function or class....
13909 // Note that this sees through typedefs, which is intended.
13910 // It *doesn't* see through dependent types, which is correct
13911 // according to [temp.arg.type]p3:
13912 // If a declaration acquires a function type through a
13913 // type dependent on a template-parameter and this causes
13914 // a declaration that does not use the syntactic form of a
13915 // function declarator to have a function type, the program
13916 // is ill-formed.
13917 if (!TInfo->getType()->isFunctionType()) {
13918 Diag(Loc, diag::err_unexpected_friend);
13919
13920 // It might be worthwhile to try to recover by creating an
13921 // appropriate declaration.
13922 return nullptr;
13923 }
13924
13925 // C++ [namespace.memdef]p3
13926 // - If a friend declaration in a non-local class first declares a
13927 // class or function, the friend class or function is a member
13928 // of the innermost enclosing namespace.
13929 // - The name of the friend is not found by simple name lookup
13930 // until a matching declaration is provided in that namespace
13931 // scope (either before or after the class declaration granting
13932 // friendship).
13933 // - If a friend function is called, its name may be found by the
13934 // name lookup that considers functions from namespaces and
13935 // classes associated with the types of the function arguments.
13936 // - When looking for a prior declaration of a class or a function
13937 // declared as a friend, scopes outside the innermost enclosing
13938 // namespace scope are not considered.
13939
13940 CXXScopeSpec &SS = D.getCXXScopeSpec();
13941 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13942 DeclarationName Name = NameInfo.getName();
13943 assert(Name)(static_cast <bool> (Name) ? void (0) : __assert_fail (
"Name", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13943, __extension__ __PRETTY_FUNCTION__))
;
13944
13945 // Check for unexpanded parameter packs.
13946 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13947 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13948 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13949 return nullptr;
13950
13951 // The context we found the declaration in, or in which we should
13952 // create the declaration.
13953 DeclContext *DC;
13954 Scope *DCScope = S;
13955 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13956 ForExternalRedeclaration);
13957
13958 // There are five cases here.
13959 // - There's no scope specifier and we're in a local class. Only look
13960 // for functions declared in the immediately-enclosing block scope.
13961 // We recover from invalid scope qualifiers as if they just weren't there.
13962 FunctionDecl *FunctionContainingLocalClass = nullptr;
13963 if ((SS.isInvalid() || !SS.isSet()) &&
13964 (FunctionContainingLocalClass =
13965 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13966 // C++11 [class.friend]p11:
13967 // If a friend declaration appears in a local class and the name
13968 // specified is an unqualified name, a prior declaration is
13969 // looked up without considering scopes that are outside the
13970 // innermost enclosing non-class scope. For a friend function
13971 // declaration, if there is no prior declaration, the program is
13972 // ill-formed.
13973
13974 // Find the innermost enclosing non-class scope. This is the block
13975 // scope containing the local class definition (or for a nested class,
13976 // the outer local class).
13977 DCScope = S->getFnParent();
13978
13979 // Look up the function name in the scope.
13980 Previous.clear(LookupLocalFriendName);
13981 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13982
13983 if (!Previous.empty()) {
13984 // All possible previous declarations must have the same context:
13985 // either they were declared at block scope or they are members of
13986 // one of the enclosing local classes.
13987 DC = Previous.getRepresentativeDecl()->getDeclContext();
13988 } else {
13989 // This is ill-formed, but provide the context that we would have
13990 // declared the function in, if we were permitted to, for error recovery.
13991 DC = FunctionContainingLocalClass;
13992 }
13993 adjustContextForLocalExternDecl(DC);
13994
13995 // C++ [class.friend]p6:
13996 // A function can be defined in a friend declaration of a class if and
13997 // only if the class is a non-local class (9.8), the function name is
13998 // unqualified, and the function has namespace scope.
13999 if (D.isFunctionDefinition()) {
14000 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14001 }
14002
14003 // - There's no scope specifier, in which case we just go to the
14004 // appropriate scope and look for a function or function template
14005 // there as appropriate.
14006 } else if (SS.isInvalid() || !SS.isSet()) {
14007 // C++11 [namespace.memdef]p3:
14008 // If the name in a friend declaration is neither qualified nor
14009 // a template-id and the declaration is a function or an
14010 // elaborated-type-specifier, the lookup to determine whether
14011 // the entity has been previously declared shall not consider
14012 // any scopes outside the innermost enclosing namespace.
14013 bool isTemplateId =
14014 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14015
14016 // Find the appropriate context according to the above.
14017 DC = CurContext;
14018
14019 // Skip class contexts. If someone can cite chapter and verse
14020 // for this behavior, that would be nice --- it's what GCC and
14021 // EDG do, and it seems like a reasonable intent, but the spec
14022 // really only says that checks for unqualified existing
14023 // declarations should stop at the nearest enclosing namespace,
14024 // not that they should only consider the nearest enclosing
14025 // namespace.
14026 while (DC->isRecord())
14027 DC = DC->getParent();
14028
14029 DeclContext *LookupDC = DC;
14030 while (LookupDC->isTransparentContext())
14031 LookupDC = LookupDC->getParent();
14032
14033 while (true) {
14034 LookupQualifiedName(Previous, LookupDC);
14035
14036 if (!Previous.empty()) {
14037 DC = LookupDC;
14038 break;
14039 }
14040
14041 if (isTemplateId) {
14042 if (isa<TranslationUnitDecl>(LookupDC)) break;
14043 } else {
14044 if (LookupDC->isFileContext()) break;
14045 }
14046 LookupDC = LookupDC->getParent();
14047 }
14048
14049 DCScope = getScopeForDeclContext(S, DC);
14050
14051 // - There's a non-dependent scope specifier, in which case we
14052 // compute it and do a previous lookup there for a function
14053 // or function template.
14054 } else if (!SS.getScopeRep()->isDependent()) {
14055 DC = computeDeclContext(SS);
14056 if (!DC) return nullptr;
14057
14058 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14059
14060 LookupQualifiedName(Previous, DC);
14061
14062 // Ignore things found implicitly in the wrong scope.
14063 // TODO: better diagnostics for this case. Suggesting the right
14064 // qualified scope would be nice...
14065 LookupResult::Filter F = Previous.makeFilter();
14066 while (F.hasNext()) {
14067 NamedDecl *D = F.next();
14068 if (!DC->InEnclosingNamespaceSetOf(
14069 D->getDeclContext()->getRedeclContext()))
14070 F.erase();
14071 }
14072 F.done();
14073
14074 if (Previous.empty()) {
14075 D.setInvalidType();
14076 Diag(Loc, diag::err_qualified_friend_not_found)
14077 << Name << TInfo->getType();
14078 return nullptr;
14079 }
14080
14081 // C++ [class.friend]p1: A friend of a class is a function or
14082 // class that is not a member of the class . . .
14083 if (DC->Equals(CurContext))
14084 Diag(DS.getFriendSpecLoc(),
14085 getLangOpts().CPlusPlus11 ?
14086 diag::warn_cxx98_compat_friend_is_member :
14087 diag::err_friend_is_member);
14088
14089 if (D.isFunctionDefinition()) {
14090 // C++ [class.friend]p6:
14091 // A function can be defined in a friend declaration of a class if and
14092 // only if the class is a non-local class (9.8), the function name is
14093 // unqualified, and the function has namespace scope.
14094 SemaDiagnosticBuilder DB
14095 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14096
14097 DB << SS.getScopeRep();
14098 if (DC->isFileContext())
14099 DB << FixItHint::CreateRemoval(SS.getRange());
14100 SS.clear();
14101 }
14102
14103 // - There's a scope specifier that does not match any template
14104 // parameter lists, in which case we use some arbitrary context,
14105 // create a method or method template, and wait for instantiation.
14106 // - There's a scope specifier that does match some template
14107 // parameter lists, which we don't handle right now.
14108 } else {
14109 if (D.isFunctionDefinition()) {
14110 // C++ [class.friend]p6:
14111 // A function can be defined in a friend declaration of a class if and
14112 // only if the class is a non-local class (9.8), the function name is
14113 // unqualified, and the function has namespace scope.
14114 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14115 << SS.getScopeRep();
14116 }
14117
14118 DC = CurContext;
14119 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"friend declaration not in class?") ? void (0) : __assert_fail
("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14119, __extension__ __PRETTY_FUNCTION__))
;
14120 }
14121
14122 if (!DC->isRecord()) {
14123 int DiagArg = -1;
14124 switch (D.getName().getKind()) {
14125 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14126 case UnqualifiedIdKind::IK_ConstructorName:
14127 DiagArg = 0;
14128 break;
14129 case UnqualifiedIdKind::IK_DestructorName:
14130 DiagArg = 1;
14131 break;
14132 case UnqualifiedIdKind::IK_ConversionFunctionId:
14133 DiagArg = 2;
14134 break;
14135 case UnqualifiedIdKind::IK_DeductionGuideName:
14136 DiagArg = 3;
14137 break;
14138 case UnqualifiedIdKind::IK_Identifier:
14139 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14140 case UnqualifiedIdKind::IK_LiteralOperatorId:
14141 case UnqualifiedIdKind::IK_OperatorFunctionId:
14142 case UnqualifiedIdKind::IK_TemplateId:
14143 break;
14144 }
14145 // This implies that it has to be an operator or function.
14146 if (DiagArg >= 0) {
14147 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14148 return nullptr;
14149 }
14150 }
14151
14152 // FIXME: This is an egregious hack to cope with cases where the scope stack
14153 // does not contain the declaration context, i.e., in an out-of-line
14154 // definition of a class.
14155 Scope FakeDCScope(S, Scope::DeclScope, Diags);
14156 if (!DCScope) {
14157 FakeDCScope.setEntity(DC);
14158 DCScope = &FakeDCScope;
14159 }
14160
14161 bool AddToScope = true;
14162 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14163 TemplateParams, AddToScope);
14164 if (!ND) return nullptr;
14165
14166 assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext
) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14166, __extension__ __PRETTY_FUNCTION__))
;
14167
14168 // If we performed typo correction, we might have added a scope specifier
14169 // and changed the decl context.
14170 DC = ND->getDeclContext();
14171
14172 // Add the function declaration to the appropriate lookup tables,
14173 // adjusting the redeclarations list as necessary. We don't
14174 // want to do this yet if the friending class is dependent.
14175 //
14176 // Also update the scope-based lookup if the target context's
14177 // lookup context is in lexical scope.
14178 if (!CurContext->isDependentContext()) {
14179 DC = DC->getRedeclContext();
14180 DC->makeDeclVisibleInContext(ND);
14181 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14182 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14183 }
14184
14185 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14186 D.getIdentifierLoc(), ND,
14187 DS.getFriendSpecLoc());
14188 FrD->setAccess(AS_public);
14189 CurContext->addDecl(FrD);
14190
14191 if (ND->isInvalidDecl()) {
14192 FrD->setInvalidDecl();
14193 } else {
14194 if (DC->isRecord()) CheckFriendAccess(ND);
14195
14196 FunctionDecl *FD;
14197 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14198 FD = FTD->getTemplatedDecl();
14199 else
14200 FD = cast<FunctionDecl>(ND);
14201
14202 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14203 // default argument expression, that declaration shall be a definition
14204 // and shall be the only declaration of the function or function
14205 // template in the translation unit.
14206 if (functionDeclHasDefaultArgument(FD)) {
14207 // We can't look at FD->getPreviousDecl() because it may not have been set
14208 // if we're in a dependent context. If the function is known to be a
14209 // redeclaration, we will have narrowed Previous down to the right decl.
14210 if (D.isRedeclaration()) {
14211 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14212 Diag(Previous.getRepresentativeDecl()->getLocation(),
14213 diag::note_previous_declaration);
14214 } else if (!D.isFunctionDefinition())
14215 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14216 }
14217
14218 // Mark templated-scope function declarations as unsupported.
14219 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14220 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14221 << SS.getScopeRep() << SS.getRange()
14222 << cast<CXXRecordDecl>(CurContext);
14223 FrD->setUnsupportedFriend(true);
14224 }
14225 }
14226
14227 return ND;
14228}
14229
14230void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14231 AdjustDeclIfTemplate(Dcl);
14232
14233 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14234 if (!Fn) {
14235 Diag(DelLoc, diag::err_deleted_non_function);
14236 return;
14237 }
14238
14239 // Deleted function does not have a body.
14240 Fn->setWillHaveBody(false);
14241
14242 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14243 // Don't consider the implicit declaration we generate for explicit
14244 // specializations. FIXME: Do not generate these implicit declarations.
14245 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14246 Prev->getPreviousDecl()) &&
14247 !Prev->isDefined()) {
14248 Diag(DelLoc, diag::err_deleted_decl_not_first);
14249 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14250 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14251 : diag::note_previous_declaration);
14252 }
14253 // If the declaration wasn't the first, we delete the function anyway for
14254 // recovery.
14255 Fn = Fn->getCanonicalDecl();
14256 }
14257
14258 // dllimport/dllexport cannot be deleted.
14259 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14260 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14261 Fn->setInvalidDecl();
14262 }
14263
14264 if (Fn->isDeleted())
14265 return;
14266
14267 // See if we're deleting a function which is already known to override a
14268 // non-deleted virtual function.
14269 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14270 bool IssuedDiagnostic = false;
14271 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14272 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14273 if (!IssuedDiagnostic) {
14274 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14275 IssuedDiagnostic = true;
14276 }
14277 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14278 }
14279 }
14280 // If this function was implicitly deleted because it was defaulted,
14281 // explain why it was deleted.
14282 if (IssuedDiagnostic && MD->isDefaulted())
14283 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14284 /*Diagnose*/true);
14285 }
14286
14287 // C++11 [basic.start.main]p3:
14288 // A program that defines main as deleted [...] is ill-formed.
14289 if (Fn->isMain())
14290 Diag(DelLoc, diag::err_deleted_main);
14291
14292 // C++11 [dcl.fct.def.delete]p4:
14293 // A deleted function is implicitly inline.
14294 Fn->setImplicitlyInline();
14295 Fn->setDeletedAsWritten();
14296}
14297
14298void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14299 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14300
14301 if (MD) {
14302 if (MD->getParent()->isDependentType()) {
14303 MD->setDefaulted();
14304 MD->setExplicitlyDefaulted();
14305 return;
14306 }
14307
14308 CXXSpecialMember Member = getSpecialMember(MD);
14309 if (Member == CXXInvalid) {
14310 if (!MD->isInvalidDecl())
14311 Diag(DefaultLoc, diag::err_default_special_members);
14312 return;
14313 }
14314
14315 MD->setDefaulted();
14316 MD->setExplicitlyDefaulted();
14317
14318 // Unset that we will have a body for this function. We might not,
14319 // if it turns out to be trivial, and we don't need this marking now
14320 // that we've marked it as defaulted.
14321 MD->setWillHaveBody(false);
14322
14323 // If this definition appears within the record, do the checking when
14324 // the record is complete.
14325 const FunctionDecl *Primary = MD;
14326 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14327 // Ask the template instantiation pattern that actually had the
14328 // '= default' on it.
14329 Primary = Pattern;
14330
14331 // If the method was defaulted on its first declaration, we will have
14332 // already performed the checking in CheckCompletedCXXClass. Such a
14333 // declaration doesn't trigger an implicit definition.
14334 if (Primary->getCanonicalDecl()->isDefaulted())
14335 return;
14336
14337 CheckExplicitlyDefaultedSpecialMember(MD);
14338
14339 if (!MD->isInvalidDecl())
14340 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14341 } else {
14342 Diag(DefaultLoc, diag::err_default_special_members);
14343 }
14344}
14345
14346static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14347 for (Stmt *SubStmt : S->children()) {
14348 if (!SubStmt)
14349 continue;
14350 if (isa<ReturnStmt>(SubStmt))
14351 Self.Diag(SubStmt->getLocStart(),
14352 diag::err_return_in_constructor_handler);
14353 if (!isa<Expr>(SubStmt))
14354 SearchForReturnInStmt(Self, SubStmt);
14355 }
14356}
14357
14358void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14359 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14360 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14361 SearchForReturnInStmt(*this, Handler);
14362 }
14363}
14364
14365bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14366 const CXXMethodDecl *Old) {
14367 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14368 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14369
14370 if (OldFT->hasExtParameterInfos()) {
14371 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14372 // A parameter of the overriding method should be annotated with noescape
14373 // if the corresponding parameter of the overridden method is annotated.
14374 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14375 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14376 Diag(New->getParamDecl(I)->getLocation(),
14377 diag::warn_overriding_method_missing_noescape);
14378 Diag(Old->getParamDecl(I)->getLocation(),
14379 diag::note_overridden_marked_noescape);
14380 }
14381 }
14382
14383 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14384
14385 // If the calling conventions match, everything is fine
14386 if (NewCC == OldCC)
14387 return false;
14388
14389 // If the calling conventions mismatch because the new function is static,
14390 // suppress the calling convention mismatch error; the error about static
14391 // function override (err_static_overrides_virtual from
14392 // Sema::CheckFunctionDeclaration) is more clear.
14393 if (New->getStorageClass() == SC_Static)
14394 return false;
14395
14396 Diag(New->getLocation(),
14397 diag::err_conflicting_overriding_cc_attributes)
14398 << New->getDeclName() << New->getType() << Old->getType();
14399 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14400 return true;
14401}
14402
14403bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14404 const CXXMethodDecl *Old) {
14405 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14406 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14407
14408 if (Context.hasSameType(NewTy, OldTy) ||
14409 NewTy->isDependentType() || OldTy->isDependentType())
14410 return false;
14411
14412 // Check if the return types are covariant
14413 QualType NewClassTy, OldClassTy;
14414
14415 /// Both types must be pointers or references to classes.
14416 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14417 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14418 NewClassTy = NewPT->getPointeeType();
14419 OldClassTy = OldPT->getPointeeType();
14420 }
14421 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14422 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14423 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14424 NewClassTy = NewRT->getPointeeType();
14425 OldClassTy = OldRT->getPointeeType();
14426 }
14427 }
14428 }
14429
14430 // The return types aren't either both pointers or references to a class type.
14431 if (NewClassTy.isNull()) {
14432 Diag(New->getLocation(),
14433 diag::err_different_return_type_for_overriding_virtual_function)
14434 << New->getDeclName() << NewTy << OldTy
14435 << New->getReturnTypeSourceRange();
14436 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14437 << Old->getReturnTypeSourceRange();
14438
14439 return true;
14440 }
14441
14442 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14443 // C++14 [class.virtual]p8:
14444 // If the class type in the covariant return type of D::f differs from
14445 // that of B::f, the class type in the return type of D::f shall be
14446 // complete at the point of declaration of D::f or shall be the class
14447 // type D.
14448 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14449 if (!RT->isBeingDefined() &&
14450 RequireCompleteType(New->getLocation(), NewClassTy,
14451 diag::err_covariant_return_incomplete,
14452 New->getDeclName()))
14453 return true;
14454 }
14455
14456 // Check if the new class derives from the old class.
14457 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14458 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14459 << New->getDeclName() << NewTy << OldTy
14460 << New->getReturnTypeSourceRange();
14461 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14462 << Old->getReturnTypeSourceRange();
14463 return true;
14464 }
14465
14466 // Check if we the conversion from derived to base is valid.
14467 if (CheckDerivedToBaseConversion(
14468 NewClassTy, OldClassTy,
14469 diag::err_covariant_return_inaccessible_base,
14470 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14471 New->getLocation(), New->getReturnTypeSourceRange(),
14472 New->getDeclName(), nullptr)) {
14473 // FIXME: this note won't trigger for delayed access control
14474 // diagnostics, and it's impossible to get an undelayed error
14475 // here from access control during the original parse because
14476 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14477 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14478 << Old->getReturnTypeSourceRange();
14479 return true;
14480 }
14481 }
14482
14483 // The qualifiers of the return types must be the same.
14484 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14485 Diag(New->getLocation(),
14486 diag::err_covariant_return_type_different_qualifications)
14487 << New->getDeclName() << NewTy << OldTy
14488 << New->getReturnTypeSourceRange();
14489 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14490 << Old->getReturnTypeSourceRange();
14491 return true;
14492 }
14493
14494
14495 // The new class type must have the same or less qualifiers as the old type.
14496 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14497 Diag(New->getLocation(),
14498 diag::err_covariant_return_type_class_type_more_qualified)
14499 << New->getDeclName() << NewTy << OldTy
14500 << New->getReturnTypeSourceRange();
14501 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14502 << Old->getReturnTypeSourceRange();
14503 return true;
14504 }
14505
14506 return false;
14507}
14508
14509/// \brief Mark the given method pure.
14510///
14511/// \param Method the method to be marked pure.
14512///
14513/// \param InitRange the source range that covers the "0" initializer.
14514bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14515 SourceLocation EndLoc = InitRange.getEnd();
14516 if (EndLoc.isValid())
14517 Method->setRangeEnd(EndLoc);
14518
14519 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14520 Method->setPure();
14521 return false;
14522 }
14523
14524 if (!Method->isInvalidDecl())
14525 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14526 << Method->getDeclName() << InitRange;
14527 return true;
14528}
14529
14530void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14531 if (D->getFriendObjectKind())
14532 Diag(D->getLocation(), diag::err_pure_friend);
14533 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14534 CheckPureMethod(M, ZeroLoc);
14535 else
14536 Diag(D->getLocation(), diag::err_illegal_initializer);
14537}
14538
14539/// \brief Determine whether the given declaration is a global variable or
14540/// static data member.
14541static bool isNonlocalVariable(const Decl *D) {
14542 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14543 return Var->hasGlobalStorage();
14544
14545 return false;
14546}
14547
14548/// Invoked when we are about to parse an initializer for the declaration
14549/// 'Dcl'.
14550///
14551/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14552/// static data member of class X, names should be looked up in the scope of
14553/// class X. If the declaration had a scope specifier, a scope will have
14554/// been created and passed in for this purpose. Otherwise, S will be null.
14555void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14556 // If there is no declaration, there was an error parsing it.
14557 if (!D || D->isInvalidDecl())
14558 return;
14559
14560 // We will always have a nested name specifier here, but this declaration
14561 // might not be out of line if the specifier names the current namespace:
14562 // extern int n;
14563 // int ::n = 0;
14564 if (S && D->isOutOfLine())
14565 EnterDeclaratorContext(S, D->getDeclContext());
14566
14567 // If we are parsing the initializer for a static data member, push a
14568 // new expression evaluation context that is associated with this static
14569 // data member.
14570 if (isNonlocalVariable(D))
14571 PushExpressionEvaluationContext(
14572 ExpressionEvaluationContext::PotentiallyEvaluated, D);
14573}
14574
14575/// Invoked after we are finished parsing an initializer for the declaration D.
14576void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14577 // If there is no declaration, there was an error parsing it.
14578 if (!D || D->isInvalidDecl())
14579 return;
14580
14581 if (isNonlocalVariable(D))
14582 PopExpressionEvaluationContext();
14583
14584 if (S && D->isOutOfLine())
14585 ExitDeclaratorContext(S);
14586}
14587
14588/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14589/// C++ if/switch/while/for statement.
14590/// e.g: "if (int x = f()) {...}"
14591DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14592 // C++ 6.4p2:
14593 // The declarator shall not specify a function or an array.
14594 // The type-specifier-seq shall not contain typedef and shall not declare a
14595 // new class or enumeration.
14596 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14597, __extension__ __PRETTY_FUNCTION__))
14597 "Parser allowed 'typedef' as storage class of condition decl.")(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14597, __extension__ __PRETTY_FUNCTION__))
;
14598
14599 Decl *Dcl = ActOnDeclarator(S, D);
14600 if (!Dcl)
14601 return true;
14602
14603 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14604 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14605 << D.getSourceRange();
14606 return true;
14607 }
14608
14609 return Dcl;
14610}
14611
14612void Sema::LoadExternalVTableUses() {
14613 if (!ExternalSource)
14614 return;
14615
14616 SmallVector<ExternalVTableUse, 4> VTables;
14617 ExternalSource->ReadUsedVTables(VTables);
14618 SmallVector<VTableUse, 4> NewUses;
14619 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14620 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14621 = VTablesUsed.find(VTables[I].Record);
14622 // Even if a definition wasn't required before, it may be required now.
14623 if (Pos != VTablesUsed.end()) {
14624 if (!Pos->second && VTables[I].DefinitionRequired)
14625 Pos->second = true;
14626 continue;
14627 }
14628
14629 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14630 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14631 }
14632
14633 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14634}
14635
14636void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14637 bool DefinitionRequired) {
14638 // Ignore any vtable uses in unevaluated operands or for classes that do
14639 // not have a vtable.
14640 if (!Class->isDynamicClass() || Class->isDependentContext() ||
14641 CurContext->isDependentContext() || isUnevaluatedContext())
14642 return;
14643
14644 // Try to insert this class into the map.
14645 LoadExternalVTableUses();
14646 Class = Class->getCanonicalDecl();
14647 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14648 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14649 if (!Pos.second) {
14650 // If we already had an entry, check to see if we are promoting this vtable
14651 // to require a definition. If so, we need to reappend to the VTableUses
14652 // list, since we may have already processed the first entry.
14653 if (DefinitionRequired && !Pos.first->second) {
14654 Pos.first->second = true;
14655 } else {
14656 // Otherwise, we can early exit.
14657 return;
14658 }
14659 } else {
14660 // The Microsoft ABI requires that we perform the destructor body
14661 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14662 // the deleting destructor is emitted with the vtable, not with the
14663 // destructor definition as in the Itanium ABI.
14664 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14665 CXXDestructorDecl *DD = Class->getDestructor();
14666 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14667 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14668 // If this is an out-of-line declaration, marking it referenced will
14669 // not do anything. Manually call CheckDestructor to look up operator
14670 // delete().
14671 ContextRAII SavedContext(*this, DD);
14672 CheckDestructor(DD);
14673 } else {
14674 MarkFunctionReferenced(Loc, Class->getDestructor());
14675 }
14676 }
14677 }
14678 }
14679
14680 // Local classes need to have their virtual members marked
14681 // immediately. For all other classes, we mark their virtual members
14682 // at the end of the translation unit.
14683 if (Class->isLocalClass())
14684 MarkVirtualMembersReferenced(Loc, Class);
14685 else
14686 VTableUses.push_back(std::make_pair(Class, Loc));
14687}
14688
14689bool Sema::DefineUsedVTables() {
14690 LoadExternalVTableUses();
14691 if (VTableUses.empty())
14692 return false;
14693
14694 // Note: The VTableUses vector could grow as a result of marking
14695 // the members of a class as "used", so we check the size each
14696 // time through the loop and prefer indices (which are stable) to
14697 // iterators (which are not).
14698 bool DefinedAnything = false;
14699 for (unsigned I = 0; I != VTableUses.size(); ++I) {
14700 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14701 if (!Class)
14702 continue;
14703 TemplateSpecializationKind ClassTSK =
14704 Class->getTemplateSpecializationKind();
14705
14706 SourceLocation Loc = VTableUses[I].second;
14707
14708 bool DefineVTable = true;
14709
14710 // If this class has a key function, but that key function is
14711 // defined in another translation unit, we don't need to emit the
14712 // vtable even though we're using it.
14713 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14714 if (KeyFunction && !KeyFunction->hasBody()) {
14715 // The key function is in another translation unit.
14716 DefineVTable = false;
14717 TemplateSpecializationKind TSK =
14718 KeyFunction->getTemplateSpecializationKind();
14719 assert(TSK != TSK_ExplicitInstantiationDefinition &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14721, __extension__ __PRETTY_FUNCTION__))
14720 TSK != TSK_ImplicitInstantiation &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14721, __extension__ __PRETTY_FUNCTION__))
14721 "Instantiations don't have key functions")(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14721, __extension__ __PRETTY_FUNCTION__))
;
14722 (void)TSK;
14723 } else if (!KeyFunction) {
14724 // If we have a class with no key function that is the subject
14725 // of an explicit instantiation declaration, suppress the
14726 // vtable; it will live with the explicit instantiation
14727 // definition.
14728 bool IsExplicitInstantiationDeclaration =
14729 ClassTSK == TSK_ExplicitInstantiationDeclaration;
14730 for (auto R : Class->redecls()) {
14731 TemplateSpecializationKind TSK
14732 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14733 if (TSK == TSK_ExplicitInstantiationDeclaration)
14734 IsExplicitInstantiationDeclaration = true;
14735 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14736 IsExplicitInstantiationDeclaration = false;
14737 break;
14738 }
14739 }
14740
14741 if (IsExplicitInstantiationDeclaration)
14742 DefineVTable = false;
14743 }
14744
14745 // The exception specifications for all virtual members may be needed even
14746 // if we are not providing an authoritative form of the vtable in this TU.
14747 // We may choose to emit it available_externally anyway.
14748 if (!DefineVTable) {
14749 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14750 continue;
14751 }
14752
14753 // Mark all of the virtual members of this class as referenced, so
14754 // that we can build a vtable. Then, tell the AST consumer that a
14755 // vtable for this class is required.
14756 DefinedAnything = true;
14757 MarkVirtualMembersReferenced(Loc, Class);
14758 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
14759 if (VTablesUsed[Canonical])
14760 Consumer.HandleVTable(Class);
14761
14762 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14763 // no key function or the key function is inlined. Don't warn in C++ ABIs
14764 // that lack key functions, since the user won't be able to make one.
14765 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14766 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14767 const FunctionDecl *KeyFunctionDef = nullptr;
14768 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14769 KeyFunctionDef->isInlined())) {
14770 Diag(Class->getLocation(),
14771 ClassTSK == TSK_ExplicitInstantiationDefinition
14772 ? diag::warn_weak_template_vtable
14773 : diag::warn_weak_vtable)
14774 << Class;
14775 }
14776 }
14777 }
14778 VTableUses.clear();
14779
14780 return DefinedAnything;
14781}
14782
14783void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14784 const CXXRecordDecl *RD) {
14785 for (const auto *I : RD->methods())
14786 if (I->isVirtual() && !I->isPure())
14787 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14788}
14789
14790void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14791 const CXXRecordDecl *RD) {
14792 // Mark all functions which will appear in RD's vtable as used.
14793 CXXFinalOverriderMap FinalOverriders;
14794 RD->getFinalOverriders(FinalOverriders);
14795 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14796 E = FinalOverriders.end();
14797 I != E; ++I) {
14798 for (OverridingMethods::const_iterator OI = I->second.begin(),
14799 OE = I->second.end();
14800 OI != OE; ++OI) {
14801 assert(OI->second.size() > 0 && "no final overrider")(static_cast <bool> (OI->second.size() > 0 &&
"no final overrider") ? void (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14801, __extension__ __PRETTY_FUNCTION__))
;
14802 CXXMethodDecl *Overrider = OI->second.front().Method;
14803
14804 // C++ [basic.def.odr]p2:
14805 // [...] A virtual member function is used if it is not pure. [...]
14806 if (!Overrider->isPure())
14807 MarkFunctionReferenced(Loc, Overrider);
14808 }
14809 }
14810
14811 // Only classes that have virtual bases need a VTT.
14812 if (RD->getNumVBases() == 0)
14813 return;
14814
14815 for (const auto &I : RD->bases()) {
14816 const CXXRecordDecl *Base =
14817 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14818 if (Base->getNumVBases() == 0)
14819 continue;
14820 MarkVirtualMembersReferenced(Loc, Base);
14821 }
14822}
14823
14824/// SetIvarInitializers - This routine builds initialization ASTs for the
14825/// Objective-C implementation whose ivars need be initialized.
14826void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14827 if (!getLangOpts().CPlusPlus)
14828 return;
14829 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14830 SmallVector<ObjCIvarDecl*, 8> ivars;
14831 CollectIvarsToConstructOrDestruct(OID, ivars);
14832 if (ivars.empty())
14833 return;
14834 SmallVector<CXXCtorInitializer*, 32> AllToInit;
14835 for (unsigned i = 0; i < ivars.size(); i++) {
14836 FieldDecl *Field = ivars[i];
14837 if (Field->isInvalidDecl())
14838 continue;
14839
14840 CXXCtorInitializer *Member;
14841 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14842 InitializationKind InitKind =
14843 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14844
14845 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14846 ExprResult MemberInit =
14847 InitSeq.Perform(*this, InitEntity, InitKind, None);
14848 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14849 // Note, MemberInit could actually come back empty if no initialization
14850 // is required (e.g., because it would call a trivial default constructor)
14851 if (!MemberInit.get() || MemberInit.isInvalid())
14852 continue;
14853
14854 Member =
14855 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14856 SourceLocation(),
14857 MemberInit.getAs<Expr>(),
14858 SourceLocation());
14859 AllToInit.push_back(Member);
14860
14861 // Be sure that the destructor is accessible and is marked as referenced.
14862 if (const RecordType *RecordTy =
14863 Context.getBaseElementType(Field->getType())
14864 ->getAs<RecordType>()) {
14865 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14866 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14867 MarkFunctionReferenced(Field->getLocation(), Destructor);
14868 CheckDestructorAccess(Field->getLocation(), Destructor,
14869 PDiag(diag::err_access_dtor_ivar)
14870 << Context.getBaseElementType(Field->getType()));
14871 }
14872 }
14873 }
14874 ObjCImplementation->setIvarInitializers(Context,
14875 AllToInit.data(), AllToInit.size());
14876 }
14877}
14878
14879static
14880void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14881 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14882 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14883 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14884 Sema &S) {
14885 if (Ctor->isInvalidDecl())
14886 return;
14887
14888 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14889
14890 // Target may not be determinable yet, for instance if this is a dependent
14891 // call in an uninstantiated template.
14892 if (Target) {
14893 const FunctionDecl *FNTarget = nullptr;
14894 (void)Target->hasBody(FNTarget);
14895 Target = const_cast<CXXConstructorDecl*>(
14896 cast_or_null<CXXConstructorDecl>(FNTarget));
14897 }
14898
14899 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14900 // Avoid dereferencing a null pointer here.
14901 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14902
14903 if (!Current.insert(Canonical).second)
14904 return;
14905
14906 // We know that beyond here, we aren't chaining into a cycle.
14907 if (!Target || !Target->isDelegatingConstructor() ||
14908 Target->isInvalidDecl() || Valid.count(TCanonical)) {
14909 Valid.insert(Current.begin(), Current.end());
14910 Current.clear();
14911 // We've hit a cycle.
14912 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14913 Current.count(TCanonical)) {
14914 // If we haven't diagnosed this cycle yet, do so now.
14915 if (!Invalid.count(TCanonical)) {
14916 S.Diag((*Ctor->init_begin())->getSourceLocation(),
14917 diag::warn_delegating_ctor_cycle)
14918 << Ctor;
14919
14920 // Don't add a note for a function delegating directly to itself.
14921 if (TCanonical != Canonical)
14922 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14923
14924 CXXConstructorDecl *C = Target;
14925 while (C->getCanonicalDecl() != Canonical) {
14926 const FunctionDecl *FNTarget = nullptr;
14927 (void)C->getTargetConstructor()->hasBody(FNTarget);
14928 assert(FNTarget && "Ctor cycle through bodiless function")(static_cast <bool> (FNTarget && "Ctor cycle through bodiless function"
) ? void (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14928, __extension__ __PRETTY_FUNCTION__))
;
14929
14930 C = const_cast<CXXConstructorDecl*>(
14931 cast<CXXConstructorDecl>(FNTarget));
14932 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14933 }
14934 }
14935
14936 Invalid.insert(Current.begin(), Current.end());
14937 Current.clear();
14938 } else {
14939 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14940 }
14941}
14942
14943
14944void Sema::CheckDelegatingCtorCycles() {
14945 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14946
14947 for (DelegatingCtorDeclsType::iterator
14948 I = DelegatingCtorDecls.begin(ExternalSource),
14949 E = DelegatingCtorDecls.end();
14950 I != E; ++I)
14951 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14952
14953 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14954 CE = Invalid.end();
14955 CI != CE; ++CI)
14956 (*CI)->setInvalidDecl();
14957}
14958
14959namespace {
14960 /// \brief AST visitor that finds references to the 'this' expression.
14961 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14962 Sema &S;
14963
14964 public:
14965 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14966
14967 bool VisitCXXThisExpr(CXXThisExpr *E) {
14968 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14969 << E->isImplicit();
14970 return false;
14971 }
14972 };
14973}
14974
14975bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14976 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14977 if (!TSInfo)
14978 return false;
14979
14980 TypeLoc TL = TSInfo->getTypeLoc();
14981 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14982 if (!ProtoTL)
14983 return false;
14984
14985 // C++11 [expr.prim.general]p3:
14986 // [The expression this] shall not appear before the optional
14987 // cv-qualifier-seq and it shall not appear within the declaration of a
14988 // static member function (although its type and value category are defined
14989 // within a static member function as they are within a non-static member
14990 // function). [ Note: this is because declaration matching does not occur
14991 // until the complete declarator is known. - end note ]
14992 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14993 FindCXXThisExpr Finder(*this);
14994
14995 // If the return type came after the cv-qualifier-seq, check it now.
14996 if (Proto->hasTrailingReturn() &&
14997 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14998 return true;
14999
15000 // Check the exception specification.
15001 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15002 return true;
15003
15004 return checkThisInStaticMemberFunctionAttributes(Method);
15005}
15006
15007bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15008 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15009 if (!TSInfo)
15010 return false;
15011
15012 TypeLoc TL = TSInfo->getTypeLoc();
15013 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15014 if (!ProtoTL)
15015 return false;
15016
15017 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15018 FindCXXThisExpr Finder(*this);
15019
15020 switch (Proto->getExceptionSpecType()) {
15021 case EST_Unparsed:
15022 case EST_Uninstantiated:
15023 case EST_Unevaluated:
15024 case EST_BasicNoexcept:
15025 case EST_DynamicNone:
15026 case EST_MSAny:
15027 case EST_None:
15028 break;
15029
15030 case EST_ComputedNoexcept:
15031 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15032 return true;
15033 LLVM_FALLTHROUGH[[clang::fallthrough]];
15034
15035 case EST_Dynamic:
15036 for (const auto &E : Proto->exceptions()) {
15037 if (!Finder.TraverseType(E))
15038 return true;
15039 }
15040 break;
15041 }
15042
15043 return false;
15044}
15045
15046bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15047 FindCXXThisExpr Finder(*this);
15048
15049 // Check attributes.
15050 for (const auto *A : Method->attrs()) {
15051 // FIXME: This should be emitted by tblgen.
15052 Expr *Arg = nullptr;
15053 ArrayRef<Expr *> Args;
15054 if (const auto *G = dyn_cast<GuardedByAttr>(A))
15055 Arg = G->getArg();
15056 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15057 Arg = G->getArg();
15058 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15059 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15060 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15061 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15062 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15063 Arg = ETLF->getSuccessValue();
15064 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15065 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15066 Arg = STLF->getSuccessValue();
15067 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15068 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15069 Arg = LR->getArg();
15070 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15071 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15072 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15073 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15074 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15075 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15076 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15077 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15078 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15079 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15080
15081 if (Arg && !Finder.TraverseStmt(Arg))
15082 return true;
15083
15084 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15085 if (!Finder.TraverseStmt(Args[I]))
15086 return true;
15087 }
15088 }
15089
15090 return false;
15091}
15092
15093void Sema::checkExceptionSpecification(
15094 bool IsTopLevel, ExceptionSpecificationType EST,
15095 ArrayRef<ParsedType> DynamicExceptions,
15096 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15097 SmallVectorImpl<QualType> &Exceptions,
15098 FunctionProtoType::ExceptionSpecInfo &ESI) {
15099 Exceptions.clear();
15100 ESI.Type = EST;
15101 if (EST == EST_Dynamic) {
15102 Exceptions.reserve(DynamicExceptions.size());
15103 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15104 // FIXME: Preserve type source info.
15105 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15106
15107 if (IsTopLevel) {
15108 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15109 collectUnexpandedParameterPacks(ET, Unexpanded);
15110 if (!Unexpanded.empty()) {
15111 DiagnoseUnexpandedParameterPacks(
15112 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15113 Unexpanded);
15114 continue;
15115 }
15116 }
15117
15118 // Check that the type is valid for an exception spec, and
15119 // drop it if not.
15120 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15121 Exceptions.push_back(ET);
15122 }
15123 ESI.Exceptions = Exceptions;
15124 return;
15125 }
15126
15127 if (EST == EST_ComputedNoexcept) {
15128 // If an error occurred, there's no expression here.
15129 if (NoexceptExpr) {
15130 assert((NoexceptExpr->isTypeDependent() ||(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15133, __extension__ __PRETTY_FUNCTION__))
15131 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15133, __extension__ __PRETTY_FUNCTION__))
15132 Context.BoolTy) &&(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15133, __extension__ __PRETTY_FUNCTION__))
15133 "Parser should have made sure that the expression is boolean")(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15133, __extension__ __PRETTY_FUNCTION__))
;
15134 if (IsTopLevel && NoexceptExpr &&
15135 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15136 ESI.Type = EST_BasicNoexcept;
15137 return;
15138 }
15139
15140 if (!NoexceptExpr->isValueDependent()) {
15141 ExprResult Result = VerifyIntegerConstantExpression(
15142 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression,
15143 /*AllowFold*/ false);
15144 if (Result.isInvalid()) {
15145 ESI.Type = EST_BasicNoexcept;
15146 return;
15147 }
15148 NoexceptExpr = Result.get();
15149 }
15150 ESI.NoexceptExpr = NoexceptExpr;
15151 }
15152 return;
15153 }
15154}
15155
15156void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15157 ExceptionSpecificationType EST,
15158 SourceRange SpecificationRange,
15159 ArrayRef<ParsedType> DynamicExceptions,
15160 ArrayRef<SourceRange> DynamicExceptionRanges,
15161 Expr *NoexceptExpr) {
15162 if (!MethodD)
15163 return;
15164
15165 // Dig out the method we're referring to.
15166 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15167 MethodD = FunTmpl->getTemplatedDecl();
15168
15169 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15170 if (!Method)
15171 return;
15172
15173 // Check the exception specification.
15174 llvm::SmallVector<QualType, 4> Exceptions;
15175 FunctionProtoType::ExceptionSpecInfo ESI;
15176 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15177 DynamicExceptionRanges, NoexceptExpr, Exceptions,
15178 ESI);
15179
15180 // Update the exception specification on the function type.
15181 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15182
15183 if (Method->isStatic())
15184 checkThisInStaticMemberFunctionExceptionSpec(Method);
15185
15186 if (Method->isVirtual()) {
15187 // Check overrides, which we previously had to delay.
15188 for (const CXXMethodDecl *O : Method->overridden_methods())
15189 CheckOverridingFunctionExceptionSpec(Method, O);
15190 }
15191}
15192
15193/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15194///
15195MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15196 SourceLocation DeclStart,
15197 Declarator &D, Expr *BitWidth,
15198 InClassInitStyle InitStyle,
15199 AccessSpecifier AS,
15200 AttributeList *MSPropertyAttr) {
15201 IdentifierInfo *II = D.getIdentifier();
15202 if (!II) {
15203 Diag(DeclStart, diag::err_anonymous_property);
15204 return nullptr;
15205 }
15206 SourceLocation Loc = D.getIdentifierLoc();
15207
15208 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15209 QualType T = TInfo->getType();
15210 if (getLangOpts().CPlusPlus) {
15211 CheckExtraCXXDefaultArguments(D);
15212
15213 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15214 UPPC_DataMemberType)) {
15215 D.setInvalidType();
15216 T = Context.IntTy;
15217 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15218 }
15219 }
15220
15221 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15222
15223 if (D.getDeclSpec().isInlineSpecified())
15224 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15225 << getLangOpts().CPlusPlus17;
15226 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15227 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15228 diag::err_invalid_thread)
15229 << DeclSpec::getSpecifierName(TSCS);
15230
15231 // Check to see if this name was declared as a member previously
15232 NamedDecl *PrevDecl = nullptr;
15233 LookupResult Previous(*this, II, Loc, LookupMemberName,
15234 ForVisibleRedeclaration);
15235 LookupName(Previous, S);
15236 switch (Previous.getResultKind()) {
15237 case LookupResult::Found:
15238 case LookupResult::FoundUnresolvedValue:
15239 PrevDecl = Previous.getAsSingle<NamedDecl>();
15240 break;
15241
15242 case LookupResult::FoundOverloaded:
15243 PrevDecl = Previous.getRepresentativeDecl();
15244 break;
15245
15246 case LookupResult::NotFound:
15247 case LookupResult::NotFoundInCurrentInstantiation:
15248 case LookupResult::Ambiguous:
15249 break;
15250 }
15251
15252 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15253 // Maybe we will complain about the shadowed template parameter.
15254 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15255 // Just pretend that we didn't see the previous declaration.
15256 PrevDecl = nullptr;
15257 }
15258
15259 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15260 PrevDecl = nullptr;
15261
15262 SourceLocation TSSL = D.getLocStart();
15263 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15264 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15265 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15266 ProcessDeclAttributes(TUScope, NewPD, D);
15267 NewPD->setAccess(AS);
15268
15269 if (NewPD->isInvalidDecl())
15270 Record->setInvalidDecl();
15271
15272 if (D.getDeclSpec().isModulePrivateSpecified())
15273 NewPD->setModulePrivate();
15274
15275 if (NewPD->isInvalidDecl() && PrevDecl) {
15276 // Don't introduce NewFD into scope; there's already something
15277 // with the same name in the same scope.
15278 } else if (II) {
15279 PushOnScopeChains(NewPD, S);
15280 } else
15281 Record->addDecl(NewPD);
15282
15283 return NewPD;
15284}

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h

1//===- PartialDiagnostic.h - Diagnostic "closures" --------------*- C++ -*-===//
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/// \file
11/// \brief Implements a partial diagnostic that can be emitted anwyhere
12/// in a DiagnosticBuilder stream.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
17#define LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
18
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include <cassert>
25#include <cstdint>
26#include <string>
27#include <type_traits>
28#include <utility>
29
30namespace clang {
31
32class DeclContext;
33class IdentifierInfo;
34
35class PartialDiagnostic {
36public:
37 enum {
38 // The MaxArguments and MaxFixItHints member enum values from
39 // DiagnosticsEngine are private but DiagnosticsEngine declares
40 // PartialDiagnostic a friend. These enum values are redeclared
41 // here so that the nested Storage class below can access them.
42 MaxArguments = DiagnosticsEngine::MaxArguments
43 };
44
45 struct Storage {
46 enum {
47 /// \brief The maximum number of arguments we can hold. We
48 /// currently only support up to 10 arguments (%0-%9).
49 ///
50 /// A single diagnostic with more than that almost certainly has to
51 /// be simplified anyway.
52 MaxArguments = PartialDiagnostic::MaxArguments
53 };
54
55 /// \brief The number of entries in Arguments.
56 unsigned char NumDiagArgs = 0;
57
58 /// \brief Specifies for each argument whether it is in DiagArgumentsStr
59 /// or in DiagArguments.
60 unsigned char DiagArgumentsKind[MaxArguments];
61
62 /// \brief The values for the various substitution positions.
63 ///
64 /// This is used when the argument is not an std::string. The specific value
65 /// is mangled into an intptr_t and the interpretation depends on exactly
66 /// what sort of argument kind it is.
67 intptr_t DiagArgumentsVal[MaxArguments];
68
69 /// \brief The values for the various substitution positions that have
70 /// string arguments.
71 std::string DiagArgumentsStr[MaxArguments];
72
73 /// \brief The list of ranges added to this diagnostic.
74 SmallVector<CharSourceRange, 8> DiagRanges;
75
76 /// \brief If valid, provides a hint with some code to insert, remove, or
77 /// modify at a particular position.
78 SmallVector<FixItHint, 6> FixItHints;
79
80 Storage() = default;
81 };
82
83 /// \brief An allocator for Storage objects, which uses a small cache to
84 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
85 class StorageAllocator {
86 static const unsigned NumCached = 16;
87 Storage Cached[NumCached];
88 Storage *FreeList[NumCached];
89 unsigned NumFreeListEntries;
90
91 public:
92 StorageAllocator();
93 ~StorageAllocator();
94
95 /// \brief Allocate new storage.
96 Storage *Allocate() {
97 if (NumFreeListEntries == 0)
14
Assuming the condition is true
15
Taking true branch
98 return new Storage;
16
Memory is allocated
99
100 Storage *Result = FreeList[--NumFreeListEntries];
101 Result->NumDiagArgs = 0;
102 Result->DiagRanges.clear();
103 Result->FixItHints.clear();
104 return Result;
105 }
106
107 /// \brief Free the given storage object.
108 void Deallocate(Storage *S) {
109 if (S >= Cached && S <= Cached + NumCached) {
110 FreeList[NumFreeListEntries++] = S;
111 return;
112 }
113
114 delete S;
115 }
116 };
117
118private:
119 // NOTE: Sema assumes that PartialDiagnostic is location-invariant
120 // in the sense that its bits can be safely memcpy'ed and destructed
121 // in the new location.
122
123 /// \brief The diagnostic ID.
124 mutable unsigned DiagID = 0;
125
126 /// \brief Storage for args and ranges.
127 mutable Storage *DiagStorage = nullptr;
128
129 /// \brief Allocator used to allocate storage for this diagnostic.
130 StorageAllocator *Allocator = nullptr;
131
132 /// \brief Retrieve storage for this particular diagnostic.
133 Storage *getStorage() const {
134 if (DiagStorage)
11
Taking false branch
135 return DiagStorage;
136
137 if (Allocator)
12
Taking true branch
138 DiagStorage = Allocator->Allocate();
13
Calling 'StorageAllocator::Allocate'
17
Returned allocated memory
139 else {
140 assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))(static_cast <bool> (Allocator != reinterpret_cast<StorageAllocator
*>(~uintptr_t(0))) ? void (0) : __assert_fail ("Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 140, __extension__ __PRETTY_FUNCTION__))
;
141 DiagStorage = new Storage;
142 }
143 return DiagStorage;
144 }
145
146 void freeStorage() {
147 if (!DiagStorage)
148 return;
149
150 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
151 // (typically so we have the flexibility of passing a more complex
152 // diagnostic into the callee, but that does not commonly occur).
153 //
154 // Split this out into a slow function for silly compilers (*cough*) which
155 // can't do decent partial inlining.
156 freeStorageSlow();
157 }
158
159 void freeStorageSlow() {
160 if (Allocator)
161 Allocator->Deallocate(DiagStorage);
162 else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
163 delete DiagStorage;
164 DiagStorage = nullptr;
165 }
166
167 void AddSourceRange(const CharSourceRange &R) const {
168 if (!DiagStorage)
169 DiagStorage = getStorage();
170
171 DiagStorage->DiagRanges.push_back(R);
172 }
173
174 void AddFixItHint(const FixItHint &Hint) const {
175 if (Hint.isNull())
176 return;
177
178 if (!DiagStorage)
179 DiagStorage = getStorage();
180
181 DiagStorage->FixItHints.push_back(Hint);
182 }
183
184public:
185 struct NullDiagnostic {};
186
187 /// \brief Create a null partial diagnostic, which cannot carry a payload,
188 /// and only exists to be swapped with a real partial diagnostic.
189 PartialDiagnostic(NullDiagnostic) {}
190
191 PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator)
192 : DiagID(DiagID), Allocator(&Allocator) {}
193
194 PartialDiagnostic(const PartialDiagnostic &Other)
195 : DiagID(Other.DiagID), Allocator(Other.Allocator) {
196 if (Other.DiagStorage) {
197 DiagStorage = getStorage();
198 *DiagStorage = *Other.DiagStorage;
199 }
200 }
201
202 PartialDiagnostic(PartialDiagnostic &&Other)
203 : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage),
204 Allocator(Other.Allocator) {
23
Potential leak of memory pointed to by field 'DiagStorage'
205 Other.DiagStorage = nullptr;
206 }
207
208 PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)
209 : DiagID(Other.DiagID), DiagStorage(DiagStorage),
210 Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) {
211 if (Other.DiagStorage)
212 *this->DiagStorage = *Other.DiagStorage;
213 }
214
215 PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator)
216 : DiagID(Other.getID()), Allocator(&Allocator) {
217 // Copy arguments.
218 for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) {
219 if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string)
220 AddString(Other.getArgStdStr(I));
221 else
222 AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I));
223 }
224
225 // Copy source ranges.
226 for (unsigned I = 0, N = Other.getNumRanges(); I != N; ++I)
227 AddSourceRange(Other.getRange(I));
228
229 // Copy fix-its.
230 for (unsigned I = 0, N = Other.getNumFixItHints(); I != N; ++I)
231 AddFixItHint(Other.getFixItHint(I));
232 }
233
234 PartialDiagnostic &operator=(const PartialDiagnostic &Other) {
235 DiagID = Other.DiagID;
236 if (Other.DiagStorage) {
237 if (!DiagStorage)
238 DiagStorage = getStorage();
239
240 *DiagStorage = *Other.DiagStorage;
241 } else {
242 freeStorage();
243 }
244
245 return *this;
246 }
247
248 PartialDiagnostic &operator=(PartialDiagnostic &&Other) {
249 freeStorage();
250
251 DiagID = Other.DiagID;
252 DiagStorage = Other.DiagStorage;
253 Allocator = Other.Allocator;
254
255 Other.DiagStorage = nullptr;
256 return *this;
257 }
258
259 ~PartialDiagnostic() {
260 freeStorage();
261 }
262
263 void swap(PartialDiagnostic &PD) {
264 std::swap(DiagID, PD.DiagID);
265 std::swap(DiagStorage, PD.DiagStorage);
266 std::swap(Allocator, PD.Allocator);
267 }
268
269 unsigned getDiagID() const { return DiagID; }
270
271 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
272 if (!DiagStorage)
9
Taking true branch
273 DiagStorage = getStorage();
10
Calling 'PartialDiagnostic::getStorage'
18
Returned allocated memory
274
275 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 276, __extension__ __PRETTY_FUNCTION__))
276 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
278 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
279 }
280
281 void AddString(StringRef V) const {
282 if (!DiagStorage)
283 DiagStorage = getStorage();
284
285 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 286, __extension__ __PRETTY_FUNCTION__))
286 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs]
288 = DiagnosticsEngine::ak_std_string;
289 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = V;
290 }
291
292 void Emit(const DiagnosticBuilder &DB) const {
293 if (!DiagStorage)
294 return;
295
296 // Add all arguments.
297 for (unsigned i = 0, e = DiagStorage->NumDiagArgs; i != e; ++i) {
298 if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]
299 == DiagnosticsEngine::ak_std_string)
300 DB.AddString(DiagStorage->DiagArgumentsStr[i]);
301 else
302 DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i],
303 (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]);
304 }
305
306 // Add all ranges.
307 for (const CharSourceRange &Range : DiagStorage->DiagRanges)
308 DB.AddSourceRange(Range);
309
310 // Add all fix-its.
311 for (const FixItHint &Fix : DiagStorage->FixItHints)
312 DB.AddFixItHint(Fix);
313 }
314
315 void EmitToString(DiagnosticsEngine &Diags,
316 SmallVectorImpl<char> &Buf) const {
317 // FIXME: It should be possible to render a diagnostic to a string without
318 // messing with the state of the diagnostics engine.
319 DiagnosticBuilder DB(Diags.Report(getDiagID()));
320 Emit(DB);
321 DB.FlushCounts();
322 Diagnostic(&Diags).FormatDiagnostic(Buf);
323 DB.Clear();
324 Diags.Clear();
325 }
326
327 /// \brief Clear out this partial diagnostic, giving it a new diagnostic ID
328 /// and removing all of its arguments, ranges, and fix-it hints.
329 void Reset(unsigned DiagID = 0) {
330 this->DiagID = DiagID;
331 freeStorage();
332 }
333
334 bool hasStorage() const { return DiagStorage != nullptr; }
335
336 /// Retrieve the string argument at the given index.
337 StringRef getStringArg(unsigned I) {
338 assert(DiagStorage && "No diagnostic storage?")(static_cast <bool> (DiagStorage && "No diagnostic storage?"
) ? void (0) : __assert_fail ("DiagStorage && \"No diagnostic storage?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 338, __extension__ __PRETTY_FUNCTION__))
;
339 assert(I < DiagStorage->NumDiagArgs && "Not enough diagnostic args")(static_cast <bool> (I < DiagStorage->NumDiagArgs
&& "Not enough diagnostic args") ? void (0) : __assert_fail
("I < DiagStorage->NumDiagArgs && \"Not enough diagnostic args\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 339, __extension__ __PRETTY_FUNCTION__))
;
340 assert(DiagStorage->DiagArgumentsKind[I](static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 341, __extension__ __PRETTY_FUNCTION__))
341 == DiagnosticsEngine::ak_std_string && "Not a string arg")(static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 341, __extension__ __PRETTY_FUNCTION__))
;
342 return DiagStorage->DiagArgumentsStr[I];
343 }
344
345 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
346 unsigned I) {
347 PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
348 return PD;
349 }
350
351 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
352 int I) {
353 PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
8
Calling 'PartialDiagnostic::AddTaggedVal'
19
Returned allocated memory
354 return PD;
355 }
356
357 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
358 const char *S) {
359 PD.AddTaggedVal(reinterpret_cast<intptr_t>(S),
360 DiagnosticsEngine::ak_c_string);
361 return PD;
362 }
363
364 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
365 StringRef S) {
366
367 PD.AddString(S);
368 return PD;
369 }
370
371 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
372 const IdentifierInfo *II) {
373 PD.AddTaggedVal(reinterpret_cast<intptr_t>(II),
374 DiagnosticsEngine::ak_identifierinfo);
375 return PD;
376 }
377
378 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
379 // so that we only match those arguments that are (statically) DeclContexts;
380 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
381 // match.
382 template<typename T>
383 friend inline
384 typename std::enable_if<std::is_same<T, DeclContext>::value,
385 const PartialDiagnostic &>::type
386 operator<<(const PartialDiagnostic &PD, T *DC) {
387 PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
388 DiagnosticsEngine::ak_declcontext);
389 return PD;
390 }
391
392 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
393 SourceRange R) {
394 PD.AddSourceRange(CharSourceRange::getTokenRange(R));
395 return PD;
396 }
397
398 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
399 const CharSourceRange &R) {
400 PD.AddSourceRange(R);
401 return PD;
402 }
403
404 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
405 const FixItHint &Hint) {
406 PD.AddFixItHint(Hint);
407 return PD;
408 }
409};
410
411inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
412 const PartialDiagnostic &PD) {
413 PD.Emit(DB);
414 return DB;
415}
416
417/// \brief A partial diagnostic along with the source location where this
418/// diagnostic occurs.
419using PartialDiagnosticAt = std::pair<SourceLocation, PartialDiagnostic>;
420
421} // namespace clang
422
423#endif // LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h

1//===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
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 provides common API and #includes for the internal
11// implementation of Sema.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
16#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
17
18#include "clang/AST/ASTContext.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Sema.h"
21#include "clang/Sema/SemaDiagnostic.h"
22
23namespace clang {
24
25inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
26 return PartialDiagnostic(DiagID, Context.getDiagAllocator());
22
Calling move constructor for 'PartialDiagnostic'
27}
28
29inline bool
30FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
31 return FTI.NumParams == 1 && !FTI.isVariadic &&
32 FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
33 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
34}
35
36inline bool
37FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
38 // Assume FTI is well-formed.
39 return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
40}
41
42// This requires the variable to be non-dependent and the initializer
43// to not be value dependent.
44inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) {
45 const VarDecl *DefVD = nullptr;
46 return !isa<ParmVarDecl>(Var) &&
47 Var->isUsableInConstantExpressions(Context) &&
48 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE();
49}
50
51// Helper function to check whether D's attributes match current CUDA mode.
52// Decls with mismatched attributes and related diagnostics may have to be
53// ignored during this CUDA compilation pass.
54inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
55 if (!LangOpts.CUDA || !D)
56 return true;
57 bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
58 D->hasAttr<CUDASharedAttr>() ||
59 D->hasAttr<CUDAGlobalAttr>();
60 return isDeviceSideDecl == LangOpts.CUDAIsDevice;
61}
62
63// Directly mark a variable odr-used. Given a choice, prefer to use
64// MarkVariableReferenced since it does additional checks and then
65// calls MarkVarDeclODRUsed.
66// If the variable must be captured:
67// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
68// - else capture it in the DeclContext that maps to the
69// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
70inline void MarkVarDeclODRUsed(VarDecl *Var,
71 SourceLocation Loc, Sema &SemaRef,
72 const unsigned *const FunctionScopeIndexToStopAt) {
73 // Keep track of used but undefined variables.
74 // FIXME: We shouldn't suppress this warning for static data members.
75 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
76 (!Var->isExternallyVisible() || Var->isInline() ||
77 SemaRef.isExternalWithNoLinkageType(Var)) &&
78 !(Var->isStaticDataMember() && Var->hasInit())) {
79 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
80 if (old.isInvalid())
81 old = Loc;
82 }
83 QualType CaptureType, DeclRefType;
84 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
85 /*EllipsisLoc*/ SourceLocation(),
86 /*BuildAndDiagnose*/ true,
87 CaptureType, DeclRefType,
88 FunctionScopeIndexToStopAt);
89
90 Var->markUsed(SemaRef.Context);
91}
92
93/// Return a DLL attribute from the declaration.
94inline InheritableAttr *getDLLAttr(Decl *D) {
95 assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&(static_cast <bool> (!(D->hasAttr<DLLImportAttr>
() && D->hasAttr<DLLExportAttr>()) &&
"A declaration cannot be both dllimport and dllexport.") ? void
(0) : __assert_fail ("!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) && \"A declaration cannot be both dllimport and dllexport.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h"
, 96, __extension__ __PRETTY_FUNCTION__))
96 "A declaration cannot be both dllimport and dllexport.")(static_cast <bool> (!(D->hasAttr<DLLImportAttr>
() && D->hasAttr<DLLExportAttr>()) &&
"A declaration cannot be both dllimport and dllexport.") ? void
(0) : __assert_fail ("!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) && \"A declaration cannot be both dllimport and dllexport.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h"
, 96, __extension__ __PRETTY_FUNCTION__))
;
97 if (auto *Import = D->getAttr<DLLImportAttr>())
98 return Import;
99 if (auto *Export = D->getAttr<DLLExportAttr>())
100 return Export;
101 return nullptr;
102}
103
104class TypoCorrectionConsumer : public VisibleDeclConsumer {
105 typedef SmallVector<TypoCorrection, 1> TypoResultList;
106 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
107 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
108
109public:
110 TypoCorrectionConsumer(Sema &SemaRef,
111 const DeclarationNameInfo &TypoName,
112 Sema::LookupNameKind LookupKind,
113 Scope *S, CXXScopeSpec *SS,
114 std::unique_ptr<CorrectionCandidateCallback> CCC,
115 DeclContext *MemberContext,
116 bool EnteringContext)
117 : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
118 SavedTCIndex(0), SemaRef(SemaRef), S(S),
119 SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
120 CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
121 Result(SemaRef, TypoName, LookupKind),
122 Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
123 EnteringContext(EnteringContext), SearchNamespaces(false) {
124 Result.suppressDiagnostics();
125 // Arrange for ValidatedCorrections[0] to always be an empty correction.
126 ValidatedCorrections.push_back(TypoCorrection());
127 }
128
129 bool includeHiddenDecls() const override { return true; }
130
131 // Methods for adding potential corrections to the consumer.
132 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
133 bool InBaseClass) override;
134 void FoundName(StringRef Name);
135 void addKeywordResult(StringRef Keyword);
136 void addCorrection(TypoCorrection Correction);
137
138 bool empty() const {
139 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
140 }
141
142 /// \brief Return the list of TypoCorrections for the given identifier from
143 /// the set of corrections that have the closest edit distance, if any.
144 TypoResultList &operator[](StringRef Name) {
145 return CorrectionResults.begin()->second[Name];
146 }
147
148 /// \brief Return the edit distance of the corrections that have the
149 /// closest/best edit distance from the original typop.
150 unsigned getBestEditDistance(bool Normalized) {
151 if (CorrectionResults.empty())
152 return (std::numeric_limits<unsigned>::max)();
153
154 unsigned BestED = CorrectionResults.begin()->first;
155 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
156 }
157
158 /// \brief Set-up method to add to the consumer the set of namespaces to use
159 /// in performing corrections to nested name specifiers. This method also
160 /// implicitly adds all of the known classes in the current AST context to the
161 /// to the consumer for correcting nested name specifiers.
162 void
163 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
164
165 /// \brief Return the next typo correction that passes all internal filters
166 /// and is deemed valid by the consumer's CorrectionCandidateCallback,
167 /// starting with the corrections that have the closest edit distance. An
168 /// empty TypoCorrection is returned once no more viable corrections remain
169 /// in the consumer.
170 const TypoCorrection &getNextCorrection();
171
172 /// \brief Get the last correction returned by getNextCorrection().
173 const TypoCorrection &getCurrentCorrection() {
174 return CurrentTCIndex < ValidatedCorrections.size()
175 ? ValidatedCorrections[CurrentTCIndex]
176 : ValidatedCorrections[0]; // The empty correction.
177 }
178
179 /// \brief Return the next typo correction like getNextCorrection, but keep
180 /// the internal state pointed to the current correction (i.e. the next time
181 /// getNextCorrection is called, it will return the same correction returned
182 /// by peekNextcorrection).
183 const TypoCorrection &peekNextCorrection() {
184 auto Current = CurrentTCIndex;
185 const TypoCorrection &TC = getNextCorrection();
186 CurrentTCIndex = Current;
187 return TC;
188 }
189
190 /// \brief Reset the consumer's position in the stream of viable corrections
191 /// (i.e. getNextCorrection() will return each of the previously returned
192 /// corrections in order before returning any new corrections).
193 void resetCorrectionStream() {
194 CurrentTCIndex = 0;
195 }
196
197 /// \brief Return whether the end of the stream of corrections has been
198 /// reached.
199 bool finished() {
200 return CorrectionResults.empty() &&
201 CurrentTCIndex >= ValidatedCorrections.size();
202 }
203
204 /// \brief Save the current position in the correction stream (overwriting any
205 /// previously saved position).
206 void saveCurrentPosition() {
207 SavedTCIndex = CurrentTCIndex;
208 }
209
210 /// \brief Restore the saved position in the correction stream.
211 void restoreSavedPosition() {
212 CurrentTCIndex = SavedTCIndex;
213 }
214
215 ASTContext &getContext() const { return SemaRef.Context; }
216 const LookupResult &getLookupResult() const { return Result; }
217
218 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
219 const CXXScopeSpec *getSS() const { return SS.get(); }
220 Scope *getScope() const { return S; }
221 CorrectionCandidateCallback *getCorrectionValidator() const {
222 return CorrectionValidator.get();
223 }
224
225private:
226 class NamespaceSpecifierSet {
227 struct SpecifierInfo {
228 DeclContext* DeclCtx;
229 NestedNameSpecifier* NameSpecifier;
230 unsigned EditDistance;
231 };
232
233 typedef SmallVector<DeclContext*, 4> DeclContextList;
234 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
235
236 ASTContext &Context;
237 DeclContextList CurContextChain;
238 std::string CurNameSpecifier;
239 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
240 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
241
242 std::map<unsigned, SpecifierInfoList> DistanceMap;
243
244 /// \brief Helper for building the list of DeclContexts between the current
245 /// context and the top of the translation unit
246 static DeclContextList buildContextChain(DeclContext *Start);
247
248 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
249 NestedNameSpecifier *&NNS);
250
251 public:
252 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
253 CXXScopeSpec *CurScopeSpec);
254
255 /// \brief Add the DeclContext (a namespace or record) to the set, computing
256 /// the corresponding NestedNameSpecifier and its distance in the process.
257 void addNameSpecifier(DeclContext *Ctx);
258
259 /// \brief Provides flat iteration over specifiers, sorted by distance.
260 class iterator
261 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
262 SpecifierInfo> {
263 /// Always points to the last element in the distance map.
264 const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
265 /// Iterator on the distance map.
266 std::map<unsigned, SpecifierInfoList>::iterator Outer;
267 /// Iterator on an element in the distance map.
268 SpecifierInfoList::iterator Inner;
269
270 public:
271 iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
272 : OuterBack(std::prev(Set.DistanceMap.end())),
273 Outer(Set.DistanceMap.begin()),
274 Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
275 assert(!Set.DistanceMap.empty())(static_cast <bool> (!Set.DistanceMap.empty()) ? void (
0) : __assert_fail ("!Set.DistanceMap.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/SemaInternal.h"
, 275, __extension__ __PRETTY_FUNCTION__))
;
276 }
277
278 iterator &operator++() {
279 ++Inner;
280 if (Inner == Outer->second.end() && Outer != OuterBack) {
281 ++Outer;
282 Inner = Outer->second.begin();
283 }
284 return *this;
285 }
286
287 SpecifierInfo &operator*() { return *Inner; }
288 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
289 };
290
291 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
292 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
293 };
294
295 void addName(StringRef Name, NamedDecl *ND,
296 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
297
298 /// \brief Find any visible decls for the given typo correction candidate.
299 /// If none are found, it to the set of candidates for which qualified lookups
300 /// will be performed to find possible nested name specifier changes.
301 bool resolveCorrection(TypoCorrection &Candidate);
302
303 /// \brief Perform qualified lookups on the queued set of typo correction
304 /// candidates and add the nested name specifier changes to each candidate if
305 /// a lookup succeeds (at which point the candidate will be returned to the
306 /// main pool of potential corrections).
307 void performQualifiedLookups();
308
309 /// \brief The name written that is a typo in the source.
310 IdentifierInfo *Typo;
311
312 /// \brief The results found that have the smallest edit distance
313 /// found (so far) with the typo name.
314 ///
315 /// The pointer value being set to the current DeclContext indicates
316 /// whether there is a keyword with this name.
317 TypoEditDistanceMap CorrectionResults;
318
319 SmallVector<TypoCorrection, 4> ValidatedCorrections;
320 size_t CurrentTCIndex;
321 size_t SavedTCIndex;
322
323 Sema &SemaRef;
324 Scope *S;
325 std::unique_ptr<CXXScopeSpec> SS;
326 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
327 DeclContext *MemberContext;
328 LookupResult Result;
329 NamespaceSpecifierSet Namespaces;
330 SmallVector<TypoCorrection, 2> QualifiedResults;
331 bool EnteringContext;
332 bool SearchNamespaces;
333};
334
335inline Sema::TypoExprState::TypoExprState() {}
336
337inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
338 *this = std::move(other);
339}
340
341inline Sema::TypoExprState &Sema::TypoExprState::
342operator=(Sema::TypoExprState &&other) noexcept {
343 Consumer = std::move(other.Consumer);
344 DiagHandler = std::move(other.DiagHandler);
345 RecoveryHandler = std::move(other.RecoveryHandler);
346 return *this;
347}
348
349} // end namespace clang
350
351#endif