File: | tools/clang/lib/Sema/SemaDeclCXX.cpp |
Warning: | line 4208, column 43 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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 | ||||
46 | using namespace clang; | |||
47 | ||||
48 | //===----------------------------------------------------------------------===// | |||
49 | // CheckDefaultArgumentVisitor | |||
50 | //===----------------------------------------------------------------------===// | |||
51 | ||||
52 | namespace { | |||
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~svn326246/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 | ||||
151 | void | |||
152 | Sema::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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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 | ||||
222 | void 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 | ||||
251 | bool | |||
252 | Sema::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. | |||
300 | void | |||
301 | Sema::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. | |||
346 | void 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. | |||
359 | void 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. | |||
378 | void 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 | ||||
423 | static 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. | |||
438 | bool 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~svn326246/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 | ||||
689 | NamedDecl * | |||
690 | Sema::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~svn326246/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 | ||||
848 | static 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 | ||||
874 | static 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 | ||||
889 | static 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 | ||||
897 | static 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 | ||||
906 | static 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 | ||||
919 | static 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 | ||||
933 | static 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~svn326246/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 | ||||
990 | static TemplateArgumentLoc | |||
991 | getTrivialIntegralTemplateArgument(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 | ||||
997 | static TemplateArgumentLoc | |||
998 | getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { | |||
999 | return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); | |||
1000 | } | |||
1001 | ||||
1002 | namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } | |||
1003 | ||||
1004 | static 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. | |||
1052 | static 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 | ||||
1080 | namespace { | |||
1081 | struct 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 | ||||
1095 | static 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++. | |||
1220 | static 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 | ||||
1301 | static 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~svn326246/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 | ||||
1393 | void 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. | |||
1467 | void 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~svn326246/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~svn326246/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]. | |||
1507 | void 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. | |||
1559 | static 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. | |||
1583 | static 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~svn326246/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. | |||
1598 | bool 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. | |||
1658 | static 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. | |||
1772 | static 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. | |||
1810 | static bool | |||
1811 | CheckConstexprFunctionStmt(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. | |||
1929 | bool 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~svn326246/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. | |||
2068 | bool 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~svn326246/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. | |||
2087 | bool 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~svn326246/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. | |||
2112 | static 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. | |||
2146 | CXXBaseSpecifier * | |||
2147 | Sema::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~svn326246/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~svn326246/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~svn326246/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. | |||
2274 | BaseResult | |||
2275 | Sema::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. | |||
2327 | typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; | |||
2328 | ||||
2329 | /// \brief Recursively add the bases of Type. Don't add Type itself. | |||
2330 | static void | |||
2331 | NoteIndirectBases(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. | |||
2352 | bool 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->getName() | |||
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~svn326246/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~svn326246/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. | |||
2460 | void 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. | |||
2471 | bool 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. | |||
2498 | bool 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 | ||||
2517 | static 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 | ||||
2536 | void 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~svn326246/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~svn326246/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. | |||
2554 | bool | |||
2555 | Sema::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~svn326246/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 | ||||
2636 | bool | |||
2637 | Sema::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 | |||
2660 | std::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. | |||
2684 | bool 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~svn326246/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. | |||
2696 | void 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 | ||||
2764 | void 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. | |||
2792 | bool 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 | ||||
2805 | static 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 | ||||
2815 | static 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. | |||
2823 | void 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~svn326246/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~svn326246/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~svn326246/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.getAsString() << RD->getName() << Base->getName(); | |||
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). | |||
2877 | NamedDecl * | |||
2878 | Sema::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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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 | else | |||
3056 | Diag(D.getIdentifierLoc(), diag::err_member_qualification) | |||
3057 | << Name << SS.getRange(); | |||
3058 | ||||
3059 | SS.clear(); | |||
3060 | } | |||
3061 | ||||
3062 | if (MSPropertyAttr) { | |||
3063 | Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, | |||
3064 | BitWidth, InitStyle, AS, MSPropertyAttr); | |||
3065 | if (!Member) | |||
3066 | return nullptr; | |||
3067 | isInstField = false; | |||
3068 | } else { | |||
3069 | Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, | |||
3070 | BitWidth, InitStyle, AS); | |||
3071 | if (!Member) | |||
3072 | return nullptr; | |||
3073 | } | |||
3074 | ||||
3075 | CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); | |||
3076 | } else { | |||
3077 | Member = HandleDeclarator(S, D, TemplateParameterLists); | |||
3078 | if (!Member) | |||
3079 | return nullptr; | |||
3080 | ||||
3081 | // Non-instance-fields can't have a bitfield. | |||
3082 | if (BitWidth) { | |||
3083 | if (Member->isInvalidDecl()) { | |||
3084 | // don't emit another diagnostic. | |||
3085 | } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { | |||
3086 | // C++ 9.6p3: A bit-field shall not be a static member. | |||
3087 | // "static member 'A' cannot be a bit-field" | |||
3088 | Diag(Loc, diag::err_static_not_bitfield) | |||
3089 | << Name << BitWidth->getSourceRange(); | |||
3090 | } else if (isa<TypedefDecl>(Member)) { | |||
3091 | // "typedef member 'x' cannot be a bit-field" | |||
3092 | Diag(Loc, diag::err_typedef_not_bitfield) | |||
3093 | << Name << BitWidth->getSourceRange(); | |||
3094 | } else { | |||
3095 | // A function typedef ("typedef int f(); f a;"). | |||
3096 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | |||
3097 | Diag(Loc, diag::err_not_integral_type_bitfield) | |||
3098 | << Name << cast<ValueDecl>(Member)->getType() | |||
3099 | << BitWidth->getSourceRange(); | |||
3100 | } | |||
3101 | ||||
3102 | BitWidth = nullptr; | |||
3103 | Member->setInvalidDecl(); | |||
3104 | } | |||
3105 | ||||
3106 | Member->setAccess(AS); | |||
3107 | ||||
3108 | // If we have declared a member function template or static data member | |||
3109 | // template, set the access of the templated declaration as well. | |||
3110 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) | |||
3111 | FunTmpl->getTemplatedDecl()->setAccess(AS); | |||
3112 | else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) | |||
3113 | VarTmpl->getTemplatedDecl()->setAccess(AS); | |||
3114 | } | |||
3115 | ||||
3116 | if (VS.isOverrideSpecified()) | |||
3117 | Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); | |||
3118 | if (VS.isFinalSpecified()) | |||
3119 | Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, | |||
3120 | VS.isFinalSpelledSealed())); | |||
3121 | ||||
3122 | if (VS.getLastLocation().isValid()) { | |||
3123 | // Update the end location of a method that has a virt-specifiers. | |||
3124 | if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) | |||
3125 | MD->setRangeEnd(VS.getLastLocation()); | |||
3126 | } | |||
3127 | ||||
3128 | CheckOverrideControl(Member); | |||
3129 | ||||
3130 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3130, __extension__ __PRETTY_FUNCTION__)); | |||
3131 | ||||
3132 | if (isInstField) { | |||
3133 | FieldDecl *FD = cast<FieldDecl>(Member); | |||
3134 | FieldCollector->Add(FD); | |||
3135 | ||||
3136 | if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { | |||
3137 | // Remember all explicit private FieldDecls that have a name, no side | |||
3138 | // effects and are not part of a dependent type declaration. | |||
3139 | if (!FD->isImplicit() && FD->getDeclName() && | |||
3140 | FD->getAccess() == AS_private && | |||
3141 | !FD->hasAttr<UnusedAttr>() && | |||
3142 | !FD->getParent()->isDependentContext() && | |||
3143 | !InitializationHasSideEffects(*FD)) | |||
3144 | UnusedPrivateFields.insert(FD); | |||
3145 | } | |||
3146 | } | |||
3147 | ||||
3148 | return Member; | |||
3149 | } | |||
3150 | ||||
3151 | namespace { | |||
3152 | class UninitializedFieldVisitor | |||
3153 | : public EvaluatedExprVisitor<UninitializedFieldVisitor> { | |||
3154 | Sema &S; | |||
3155 | // List of Decls to generate a warning on. Also remove Decls that become | |||
3156 | // initialized. | |||
3157 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls; | |||
3158 | // List of base classes of the record. Classes are removed after their | |||
3159 | // initializers. | |||
3160 | llvm::SmallPtrSetImpl<QualType> &BaseClasses; | |||
3161 | // Vector of decls to be removed from the Decl set prior to visiting the | |||
3162 | // nodes. These Decls may have been initialized in the prior initializer. | |||
3163 | llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; | |||
3164 | // If non-null, add a note to the warning pointing back to the constructor. | |||
3165 | const CXXConstructorDecl *Constructor; | |||
3166 | // Variables to hold state when processing an initializer list. When | |||
3167 | // InitList is true, special case initialization of FieldDecls matching | |||
3168 | // InitListFieldDecl. | |||
3169 | bool InitList; | |||
3170 | FieldDecl *InitListFieldDecl; | |||
3171 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | |||
3172 | ||||
3173 | public: | |||
3174 | typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; | |||
3175 | UninitializedFieldVisitor(Sema &S, | |||
3176 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls, | |||
3177 | llvm::SmallPtrSetImpl<QualType> &BaseClasses) | |||
3178 | : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), | |||
3179 | Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} | |||
3180 | ||||
3181 | // Returns true if the use of ME is not an uninitialized use. | |||
3182 | bool IsInitListMemberExprInitialized(MemberExpr *ME, | |||
3183 | bool CheckReferenceOnly) { | |||
3184 | llvm::SmallVector<FieldDecl*, 4> Fields; | |||
3185 | bool ReferenceField = false; | |||
3186 | while (ME) { | |||
3187 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
3188 | if (!FD) | |||
3189 | return false; | |||
3190 | Fields.push_back(FD); | |||
3191 | if (FD->getType()->isReferenceType()) | |||
3192 | ReferenceField = true; | |||
3193 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); | |||
3194 | } | |||
3195 | ||||
3196 | // Binding a reference to an unintialized field is not an | |||
3197 | // uninitialized use. | |||
3198 | if (CheckReferenceOnly && !ReferenceField) | |||
3199 | return true; | |||
3200 | ||||
3201 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | |||
3202 | // Discard the first field since it is the field decl that is being | |||
3203 | // initialized. | |||
3204 | for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { | |||
3205 | UsedFieldIndex.push_back((*I)->getFieldIndex()); | |||
3206 | } | |||
3207 | ||||
3208 | for (auto UsedIter = UsedFieldIndex.begin(), | |||
3209 | UsedEnd = UsedFieldIndex.end(), | |||
3210 | OrigIter = InitFieldIndex.begin(), | |||
3211 | OrigEnd = InitFieldIndex.end(); | |||
3212 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | |||
3213 | if (*UsedIter < *OrigIter) | |||
3214 | return true; | |||
3215 | if (*UsedIter > *OrigIter) | |||
3216 | break; | |||
3217 | } | |||
3218 | ||||
3219 | return false; | |||
3220 | } | |||
3221 | ||||
3222 | void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, | |||
3223 | bool AddressOf) { | |||
3224 | if (isa<EnumConstantDecl>(ME->getMemberDecl())) | |||
3225 | return; | |||
3226 | ||||
3227 | // FieldME is the inner-most MemberExpr that is not an anonymous struct | |||
3228 | // or union. | |||
3229 | MemberExpr *FieldME = ME; | |||
3230 | ||||
3231 | bool AllPODFields = FieldME->getType().isPODType(S.Context); | |||
3232 | ||||
3233 | Expr *Base = ME; | |||
3234 | while (MemberExpr *SubME = | |||
3235 | dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { | |||
3236 | ||||
3237 | if (isa<VarDecl>(SubME->getMemberDecl())) | |||
3238 | return; | |||
3239 | ||||
3240 | if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) | |||
3241 | if (!FD->isAnonymousStructOrUnion()) | |||
3242 | FieldME = SubME; | |||
3243 | ||||
3244 | if (!FieldME->getType().isPODType(S.Context)) | |||
3245 | AllPODFields = false; | |||
3246 | ||||
3247 | Base = SubME->getBase(); | |||
3248 | } | |||
3249 | ||||
3250 | if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) | |||
3251 | return; | |||
3252 | ||||
3253 | if (AddressOf && AllPODFields) | |||
3254 | return; | |||
3255 | ||||
3256 | ValueDecl* FoundVD = FieldME->getMemberDecl(); | |||
3257 | ||||
3258 | if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { | |||
3259 | while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { | |||
3260 | BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); | |||
3261 | } | |||
3262 | ||||
3263 | if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { | |||
3264 | QualType T = BaseCast->getType(); | |||
3265 | if (T->isPointerType() && | |||
3266 | BaseClasses.count(T->getPointeeType())) { | |||
3267 | S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) | |||
3268 | << T->getPointeeType() << FoundVD; | |||
3269 | } | |||
3270 | } | |||
3271 | } | |||
3272 | ||||
3273 | if (!Decls.count(FoundVD)) | |||
3274 | return; | |||
3275 | ||||
3276 | const bool IsReference = FoundVD->getType()->isReferenceType(); | |||
3277 | ||||
3278 | if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { | |||
3279 | // Special checking for initializer lists. | |||
3280 | if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { | |||
3281 | return; | |||
3282 | } | |||
3283 | } else { | |||
3284 | // Prevent double warnings on use of unbounded references. | |||
3285 | if (CheckReferenceOnly && !IsReference) | |||
3286 | return; | |||
3287 | } | |||
3288 | ||||
3289 | unsigned diag = IsReference | |||
3290 | ? diag::warn_reference_field_is_uninit | |||
3291 | : diag::warn_field_is_uninit; | |||
3292 | S.Diag(FieldME->getExprLoc(), diag) << FoundVD; | |||
3293 | if (Constructor) | |||
3294 | S.Diag(Constructor->getLocation(), | |||
3295 | diag::note_uninit_in_this_constructor) | |||
3296 | << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); | |||
3297 | ||||
3298 | } | |||
3299 | ||||
3300 | void HandleValue(Expr *E, bool AddressOf) { | |||
3301 | E = E->IgnoreParens(); | |||
3302 | ||||
3303 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
3304 | HandleMemberExpr(ME, false /*CheckReferenceOnly*/, | |||
3305 | AddressOf /*AddressOf*/); | |||
3306 | return; | |||
3307 | } | |||
3308 | ||||
3309 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
3310 | Visit(CO->getCond()); | |||
3311 | HandleValue(CO->getTrueExpr(), AddressOf); | |||
3312 | HandleValue(CO->getFalseExpr(), AddressOf); | |||
3313 | return; | |||
3314 | } | |||
3315 | ||||
3316 | if (BinaryConditionalOperator *BCO = | |||
3317 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
3318 | Visit(BCO->getCond()); | |||
3319 | HandleValue(BCO->getFalseExpr(), AddressOf); | |||
3320 | return; | |||
3321 | } | |||
3322 | ||||
3323 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
3324 | HandleValue(OVE->getSourceExpr(), AddressOf); | |||
3325 | return; | |||
3326 | } | |||
3327 | ||||
3328 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
3329 | switch (BO->getOpcode()) { | |||
3330 | default: | |||
3331 | break; | |||
3332 | case(BO_PtrMemD): | |||
3333 | case(BO_PtrMemI): | |||
3334 | HandleValue(BO->getLHS(), AddressOf); | |||
3335 | Visit(BO->getRHS()); | |||
3336 | return; | |||
3337 | case(BO_Comma): | |||
3338 | Visit(BO->getLHS()); | |||
3339 | HandleValue(BO->getRHS(), AddressOf); | |||
3340 | return; | |||
3341 | } | |||
3342 | } | |||
3343 | ||||
3344 | Visit(E); | |||
3345 | } | |||
3346 | ||||
3347 | void CheckInitListExpr(InitListExpr *ILE) { | |||
3348 | InitFieldIndex.push_back(0); | |||
3349 | for (auto Child : ILE->children()) { | |||
3350 | if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { | |||
3351 | CheckInitListExpr(SubList); | |||
3352 | } else { | |||
3353 | Visit(Child); | |||
3354 | } | |||
3355 | ++InitFieldIndex.back(); | |||
3356 | } | |||
3357 | InitFieldIndex.pop_back(); | |||
3358 | } | |||
3359 | ||||
3360 | void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, | |||
3361 | FieldDecl *Field, const Type *BaseClass) { | |||
3362 | // Remove Decls that may have been initialized in the previous | |||
3363 | // initializer. | |||
3364 | for (ValueDecl* VD : DeclsToRemove) | |||
3365 | Decls.erase(VD); | |||
3366 | DeclsToRemove.clear(); | |||
3367 | ||||
3368 | Constructor = FieldConstructor; | |||
3369 | InitListExpr *ILE = dyn_cast<InitListExpr>(E); | |||
3370 | ||||
3371 | if (ILE && Field) { | |||
3372 | InitList = true; | |||
3373 | InitListFieldDecl = Field; | |||
3374 | InitFieldIndex.clear(); | |||
3375 | CheckInitListExpr(ILE); | |||
3376 | } else { | |||
3377 | InitList = false; | |||
3378 | Visit(E); | |||
3379 | } | |||
3380 | ||||
3381 | if (Field) | |||
3382 | Decls.erase(Field); | |||
3383 | if (BaseClass) | |||
3384 | BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); | |||
3385 | } | |||
3386 | ||||
3387 | void VisitMemberExpr(MemberExpr *ME) { | |||
3388 | // All uses of unbounded reference fields will warn. | |||
3389 | HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); | |||
3390 | } | |||
3391 | ||||
3392 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
3393 | if (E->getCastKind() == CK_LValueToRValue) { | |||
3394 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | |||
3395 | return; | |||
3396 | } | |||
3397 | ||||
3398 | Inherited::VisitImplicitCastExpr(E); | |||
3399 | } | |||
3400 | ||||
3401 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
3402 | if (E->getConstructor()->isCopyConstructor()) { | |||
3403 | Expr *ArgExpr = E->getArg(0); | |||
3404 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | |||
3405 | if (ILE->getNumInits() == 1) | |||
3406 | ArgExpr = ILE->getInit(0); | |||
3407 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | |||
3408 | if (ICE->getCastKind() == CK_NoOp) | |||
3409 | ArgExpr = ICE->getSubExpr(); | |||
3410 | HandleValue(ArgExpr, false /*AddressOf*/); | |||
3411 | return; | |||
3412 | } | |||
3413 | Inherited::VisitCXXConstructExpr(E); | |||
3414 | } | |||
3415 | ||||
3416 | void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { | |||
3417 | Expr *Callee = E->getCallee(); | |||
3418 | if (isa<MemberExpr>(Callee)) { | |||
3419 | HandleValue(Callee, false /*AddressOf*/); | |||
3420 | for (auto Arg : E->arguments()) | |||
3421 | Visit(Arg); | |||
3422 | return; | |||
3423 | } | |||
3424 | ||||
3425 | Inherited::VisitCXXMemberCallExpr(E); | |||
3426 | } | |||
3427 | ||||
3428 | void VisitCallExpr(CallExpr *E) { | |||
3429 | // Treat std::move as a use. | |||
3430 | if (E->isCallToStdMove()) { | |||
3431 | HandleValue(E->getArg(0), /*AddressOf=*/false); | |||
3432 | return; | |||
3433 | } | |||
3434 | ||||
3435 | Inherited::VisitCallExpr(E); | |||
3436 | } | |||
3437 | ||||
3438 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
3439 | Expr *Callee = E->getCallee(); | |||
3440 | ||||
3441 | if (isa<UnresolvedLookupExpr>(Callee)) | |||
3442 | return Inherited::VisitCXXOperatorCallExpr(E); | |||
3443 | ||||
3444 | Visit(Callee); | |||
3445 | for (auto Arg : E->arguments()) | |||
3446 | HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); | |||
3447 | } | |||
3448 | ||||
3449 | void VisitBinaryOperator(BinaryOperator *E) { | |||
3450 | // If a field assignment is detected, remove the field from the | |||
3451 | // uninitiailized field set. | |||
3452 | if (E->getOpcode() == BO_Assign) | |||
3453 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) | |||
3454 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) | |||
3455 | if (!FD->getType()->isReferenceType()) | |||
3456 | DeclsToRemove.push_back(FD); | |||
3457 | ||||
3458 | if (E->isCompoundAssignmentOp()) { | |||
3459 | HandleValue(E->getLHS(), false /*AddressOf*/); | |||
3460 | Visit(E->getRHS()); | |||
3461 | return; | |||
3462 | } | |||
3463 | ||||
3464 | Inherited::VisitBinaryOperator(E); | |||
3465 | } | |||
3466 | ||||
3467 | void VisitUnaryOperator(UnaryOperator *E) { | |||
3468 | if (E->isIncrementDecrementOp()) { | |||
3469 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | |||
3470 | return; | |||
3471 | } | |||
3472 | if (E->getOpcode() == UO_AddrOf) { | |||
3473 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { | |||
3474 | HandleValue(ME->getBase(), true /*AddressOf*/); | |||
3475 | return; | |||
3476 | } | |||
3477 | } | |||
3478 | ||||
3479 | Inherited::VisitUnaryOperator(E); | |||
3480 | } | |||
3481 | }; | |||
3482 | ||||
3483 | // Diagnose value-uses of fields to initialize themselves, e.g. | |||
3484 | // foo(foo) | |||
3485 | // where foo is not also a parameter to the constructor. | |||
3486 | // Also diagnose across field uninitialized use such as | |||
3487 | // x(y), y(x) | |||
3488 | // TODO: implement -Wuninitialized and fold this into that framework. | |||
3489 | static void DiagnoseUninitializedFields( | |||
3490 | Sema &SemaRef, const CXXConstructorDecl *Constructor) { | |||
3491 | ||||
3492 | if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, | |||
3493 | Constructor->getLocation())) { | |||
3494 | return; | |||
3495 | } | |||
3496 | ||||
3497 | if (Constructor->isInvalidDecl()) | |||
3498 | return; | |||
3499 | ||||
3500 | const CXXRecordDecl *RD = Constructor->getParent(); | |||
3501 | ||||
3502 | if (RD->getDescribedClassTemplate()) | |||
3503 | return; | |||
3504 | ||||
3505 | // Holds fields that are uninitialized. | |||
3506 | llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; | |||
3507 | ||||
3508 | // At the beginning, all fields are uninitialized. | |||
3509 | for (auto *I : RD->decls()) { | |||
3510 | if (auto *FD = dyn_cast<FieldDecl>(I)) { | |||
3511 | UninitializedFields.insert(FD); | |||
3512 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { | |||
3513 | UninitializedFields.insert(IFD->getAnonField()); | |||
3514 | } | |||
3515 | } | |||
3516 | ||||
3517 | llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; | |||
3518 | for (auto I : RD->bases()) | |||
3519 | UninitializedBaseClasses.insert(I.getType().getCanonicalType()); | |||
3520 | ||||
3521 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | |||
3522 | return; | |||
3523 | ||||
3524 | UninitializedFieldVisitor UninitializedChecker(SemaRef, | |||
3525 | UninitializedFields, | |||
3526 | UninitializedBaseClasses); | |||
3527 | ||||
3528 | for (const auto *FieldInit : Constructor->inits()) { | |||
3529 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | |||
3530 | break; | |||
3531 | ||||
3532 | Expr *InitExpr = FieldInit->getInit(); | |||
3533 | if (!InitExpr) | |||
3534 | continue; | |||
3535 | ||||
3536 | if (CXXDefaultInitExpr *Default = | |||
3537 | dyn_cast<CXXDefaultInitExpr>(InitExpr)) { | |||
3538 | InitExpr = Default->getExpr(); | |||
3539 | if (!InitExpr) | |||
3540 | continue; | |||
3541 | // In class initializers will point to the constructor. | |||
3542 | UninitializedChecker.CheckInitializer(InitExpr, Constructor, | |||
3543 | FieldInit->getAnyMember(), | |||
3544 | FieldInit->getBaseClass()); | |||
3545 | } else { | |||
3546 | UninitializedChecker.CheckInitializer(InitExpr, nullptr, | |||
3547 | FieldInit->getAnyMember(), | |||
3548 | FieldInit->getBaseClass()); | |||
3549 | } | |||
3550 | } | |||
3551 | } | |||
3552 | } // namespace | |||
3553 | ||||
3554 | /// \brief Enter a new C++ default initializer scope. After calling this, the | |||
3555 | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if | |||
3556 | /// parsing or instantiating the initializer failed. | |||
3557 | void Sema::ActOnStartCXXInClassMemberInitializer() { | |||
3558 | // Create a synthetic function scope to represent the call to the constructor | |||
3559 | // that notionally surrounds a use of this initializer. | |||
3560 | PushFunctionScope(); | |||
3561 | } | |||
3562 | ||||
3563 | /// \brief This is invoked after parsing an in-class initializer for a | |||
3564 | /// non-static C++ class member, and after instantiating an in-class initializer | |||
3565 | /// in a class template. Such actions are deferred until the class is complete. | |||
3566 | void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, | |||
3567 | SourceLocation InitLoc, | |||
3568 | Expr *InitExpr) { | |||
3569 | // Pop the notional constructor scope we created earlier. | |||
3570 | PopFunctionScopeInfo(nullptr, D); | |||
3571 | ||||
3572 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
3573 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3574, __extension__ __PRETTY_FUNCTION__)) | |||
3574 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3574, __extension__ __PRETTY_FUNCTION__)); | |||
3575 | ||||
3576 | if (!InitExpr) { | |||
3577 | D->setInvalidDecl(); | |||
3578 | if (FD) | |||
3579 | FD->removeInClassInitializer(); | |||
3580 | return; | |||
3581 | } | |||
3582 | ||||
3583 | if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { | |||
3584 | FD->setInvalidDecl(); | |||
3585 | FD->removeInClassInitializer(); | |||
3586 | return; | |||
3587 | } | |||
3588 | ||||
3589 | ExprResult Init = InitExpr; | |||
3590 | if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { | |||
3591 | InitializedEntity Entity = InitializedEntity::InitializeMember(FD); | |||
3592 | InitializationKind Kind = | |||
3593 | FD->getInClassInitStyle() == ICIS_ListInit | |||
3594 | ? InitializationKind::CreateDirectList(InitExpr->getLocStart(), | |||
3595 | InitExpr->getLocStart(), | |||
3596 | InitExpr->getLocEnd()) | |||
3597 | : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); | |||
3598 | InitializationSequence Seq(*this, Entity, Kind, InitExpr); | |||
3599 | Init = Seq.Perform(*this, Entity, Kind, InitExpr); | |||
3600 | if (Init.isInvalid()) { | |||
3601 | FD->setInvalidDecl(); | |||
3602 | return; | |||
3603 | } | |||
3604 | } | |||
3605 | ||||
3606 | // C++11 [class.base.init]p7: | |||
3607 | // The initialization of each base and member constitutes a | |||
3608 | // full-expression. | |||
3609 | Init = ActOnFinishFullExpr(Init.get(), InitLoc); | |||
3610 | if (Init.isInvalid()) { | |||
3611 | FD->setInvalidDecl(); | |||
3612 | return; | |||
3613 | } | |||
3614 | ||||
3615 | InitExpr = Init.get(); | |||
3616 | ||||
3617 | FD->setInClassInitializer(InitExpr); | |||
3618 | } | |||
3619 | ||||
3620 | /// \brief Find the direct and/or virtual base specifiers that | |||
3621 | /// correspond to the given base type, for use in base initialization | |||
3622 | /// within a constructor. | |||
3623 | static bool FindBaseInitializer(Sema &SemaRef, | |||
3624 | CXXRecordDecl *ClassDecl, | |||
3625 | QualType BaseType, | |||
3626 | const CXXBaseSpecifier *&DirectBaseSpec, | |||
3627 | const CXXBaseSpecifier *&VirtualBaseSpec) { | |||
3628 | // First, check for a direct base class. | |||
3629 | DirectBaseSpec = nullptr; | |||
3630 | for (const auto &Base : ClassDecl->bases()) { | |||
3631 | if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { | |||
3632 | // We found a direct base of this type. That's what we're | |||
3633 | // initializing. | |||
3634 | DirectBaseSpec = &Base; | |||
3635 | break; | |||
3636 | } | |||
3637 | } | |||
3638 | ||||
3639 | // Check for a virtual base class. | |||
3640 | // FIXME: We might be able to short-circuit this if we know in advance that | |||
3641 | // there are no virtual bases. | |||
3642 | VirtualBaseSpec = nullptr; | |||
3643 | if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { | |||
3644 | // We haven't found a base yet; search the class hierarchy for a | |||
3645 | // virtual base class. | |||
3646 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
3647 | /*DetectVirtual=*/false); | |||
3648 | if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), | |||
3649 | SemaRef.Context.getTypeDeclType(ClassDecl), | |||
3650 | BaseType, Paths)) { | |||
3651 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | |||
3652 | Path != Paths.end(); ++Path) { | |||
3653 | if (Path->back().Base->isVirtual()) { | |||
3654 | VirtualBaseSpec = Path->back().Base; | |||
3655 | break; | |||
3656 | } | |||
3657 | } | |||
3658 | } | |||
3659 | } | |||
3660 | ||||
3661 | return DirectBaseSpec || VirtualBaseSpec; | |||
3662 | } | |||
3663 | ||||
3664 | /// \brief Handle a C++ member initializer using braced-init-list syntax. | |||
3665 | MemInitResult | |||
3666 | Sema::ActOnMemInitializer(Decl *ConstructorD, | |||
3667 | Scope *S, | |||
3668 | CXXScopeSpec &SS, | |||
3669 | IdentifierInfo *MemberOrBase, | |||
3670 | ParsedType TemplateTypeTy, | |||
3671 | const DeclSpec &DS, | |||
3672 | SourceLocation IdLoc, | |||
3673 | Expr *InitList, | |||
3674 | SourceLocation EllipsisLoc) { | |||
3675 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | |||
3676 | DS, IdLoc, InitList, | |||
3677 | EllipsisLoc); | |||
3678 | } | |||
3679 | ||||
3680 | /// \brief Handle a C++ member initializer using parentheses syntax. | |||
3681 | MemInitResult | |||
3682 | Sema::ActOnMemInitializer(Decl *ConstructorD, | |||
3683 | Scope *S, | |||
3684 | CXXScopeSpec &SS, | |||
3685 | IdentifierInfo *MemberOrBase, | |||
3686 | ParsedType TemplateTypeTy, | |||
3687 | const DeclSpec &DS, | |||
3688 | SourceLocation IdLoc, | |||
3689 | SourceLocation LParenLoc, | |||
3690 | ArrayRef<Expr *> Args, | |||
3691 | SourceLocation RParenLoc, | |||
3692 | SourceLocation EllipsisLoc) { | |||
3693 | Expr *List = new (Context) ParenListExpr(Context, LParenLoc, | |||
3694 | Args, RParenLoc); | |||
3695 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | |||
| ||||
3696 | DS, IdLoc, List, EllipsisLoc); | |||
3697 | } | |||
3698 | ||||
3699 | namespace { | |||
3700 | ||||
3701 | // Callback to only accept typo corrections that can be a valid C++ member | |||
3702 | // intializer: either a non-static field member or a base class. | |||
3703 | class MemInitializerValidatorCCC : public CorrectionCandidateCallback { | |||
3704 | public: | |||
3705 | explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) | |||
3706 | : ClassDecl(ClassDecl) {} | |||
3707 | ||||
3708 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
3709 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | |||
3710 | if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) | |||
3711 | return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); | |||
3712 | return isa<TypeDecl>(ND); | |||
3713 | } | |||
3714 | return false; | |||
3715 | } | |||
3716 | ||||
3717 | private: | |||
3718 | CXXRecordDecl *ClassDecl; | |||
3719 | }; | |||
3720 | ||||
3721 | } | |||
3722 | ||||
3723 | /// \brief Handle a C++ member initializer. | |||
3724 | MemInitResult | |||
3725 | Sema::BuildMemInitializer(Decl *ConstructorD, | |||
3726 | Scope *S, | |||
3727 | CXXScopeSpec &SS, | |||
3728 | IdentifierInfo *MemberOrBase, | |||
3729 | ParsedType TemplateTypeTy, | |||
3730 | const DeclSpec &DS, | |||
3731 | SourceLocation IdLoc, | |||
3732 | Expr *Init, | |||
3733 | SourceLocation EllipsisLoc) { | |||
3734 | ExprResult Res = CorrectDelayedTyposInExpr(Init); | |||
3735 | if (!Res.isUsable()) | |||
3736 | return true; | |||
3737 | Init = Res.get(); | |||
3738 | ||||
3739 | if (!ConstructorD) | |||
3740 | return true; | |||
3741 | ||||
3742 | AdjustDeclIfTemplate(ConstructorD); | |||
3743 | ||||
3744 | CXXConstructorDecl *Constructor | |||
3745 | = dyn_cast<CXXConstructorDecl>(ConstructorD); | |||
3746 | if (!Constructor) { | |||
3747 | // The user wrote a constructor initializer on a function that is | |||
3748 | // not a C++ constructor. Ignore the error for now, because we may | |||
3749 | // have more member initializers coming; we'll diagnose it just | |||
3750 | // once in ActOnMemInitializers. | |||
3751 | return true; | |||
3752 | } | |||
3753 | ||||
3754 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
3755 | ||||
3756 | // C++ [class.base.init]p2: | |||
3757 | // Names in a mem-initializer-id are looked up in the scope of the | |||
3758 | // constructor's class and, if not found in that scope, are looked | |||
3759 | // up in the scope containing the constructor's definition. | |||
3760 | // [Note: if the constructor's class contains a member with the | |||
3761 | // same name as a direct or virtual base class of the class, a | |||
3762 | // mem-initializer-id naming the member or base class and composed | |||
3763 | // of a single identifier refers to the class member. A | |||
3764 | // mem-initializer-id for the hidden base class may be specified | |||
3765 | // using a qualified name. ] | |||
3766 | if (!SS.getScopeRep() && !TemplateTypeTy) { | |||
3767 | // Look for a member, first. | |||
3768 | DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); | |||
3769 | if (!Result.empty()) { | |||
3770 | ValueDecl *Member; | |||
3771 | if ((Member = dyn_cast<FieldDecl>(Result.front())) || | |||
3772 | (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { | |||
3773 | if (EllipsisLoc.isValid()) | |||
3774 | Diag(EllipsisLoc, diag::err_pack_expansion_member_init) | |||
3775 | << MemberOrBase | |||
3776 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); | |||
3777 | ||||
3778 | return BuildMemberInitializer(Member, Init, IdLoc); | |||
3779 | } | |||
3780 | } | |||
3781 | } | |||
3782 | // It didn't name a member, so see if it names a class. | |||
3783 | QualType BaseType; | |||
3784 | TypeSourceInfo *TInfo = nullptr; | |||
3785 | ||||
3786 | if (TemplateTypeTy) { | |||
3787 | BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); | |||
3788 | } else if (DS.getTypeSpecType() == TST_decltype) { | |||
3789 | BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); | |||
3790 | } else if (DS.getTypeSpecType() == TST_decltype_auto) { | |||
3791 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
3792 | return true; | |||
3793 | } else { | |||
3794 | LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); | |||
3795 | LookupParsedName(R, S, &SS); | |||
3796 | ||||
3797 | TypeDecl *TyD = R.getAsSingle<TypeDecl>(); | |||
3798 | if (!TyD) { | |||
3799 | if (R.isAmbiguous()) return true; | |||
3800 | ||||
3801 | // We don't want access-control diagnostics here. | |||
3802 | R.suppressDiagnostics(); | |||
3803 | ||||
3804 | if (SS.isSet() && isDependentScopeSpecifier(SS)) { | |||
3805 | bool NotUnknownSpecialization = false; | |||
3806 | DeclContext *DC = computeDeclContext(SS, false); | |||
3807 | if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) | |||
3808 | NotUnknownSpecialization = !Record->hasAnyDependentBases(); | |||
3809 | ||||
3810 | if (!NotUnknownSpecialization) { | |||
3811 | // When the scope specifier can refer to a member of an unknown | |||
3812 | // specialization, we take it as a type name. | |||
3813 | BaseType = CheckTypenameType(ETK_None, SourceLocation(), | |||
3814 | SS.getWithLocInContext(Context), | |||
3815 | *MemberOrBase, IdLoc); | |||
3816 | if (BaseType.isNull()) | |||
3817 | return true; | |||
3818 | ||||
3819 | TInfo = Context.CreateTypeSourceInfo(BaseType); | |||
3820 | DependentNameTypeLoc TL = | |||
3821 | TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
3822 | if (!TL.isNull()) { | |||
3823 | TL.setNameLoc(IdLoc); | |||
3824 | TL.setElaboratedKeywordLoc(SourceLocation()); | |||
3825 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
3826 | } | |||
3827 | ||||
3828 | R.clear(); | |||
3829 | R.setLookupName(MemberOrBase); | |||
3830 | } | |||
3831 | } | |||
3832 | ||||
3833 | // If no results were found, try to correct typos. | |||
3834 | TypoCorrection Corr; | |||
3835 | if (R.empty() && BaseType.isNull() && | |||
3836 | (Corr = CorrectTypo( | |||
3837 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, | |||
3838 | llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), | |||
3839 | CTK_ErrorRecovery, ClassDecl))) { | |||
3840 | if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { | |||
3841 | // We have found a non-static data member with a similar | |||
3842 | // name to what was typed; complain and initialize that | |||
3843 | // member. | |||
3844 | diagnoseTypo(Corr, | |||
3845 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | |||
3846 | << MemberOrBase << true); | |||
3847 | return BuildMemberInitializer(Member, Init, IdLoc); | |||
3848 | } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { | |||
3849 | const CXXBaseSpecifier *DirectBaseSpec; | |||
3850 | const CXXBaseSpecifier *VirtualBaseSpec; | |||
3851 | if (FindBaseInitializer(*this, ClassDecl, | |||
3852 | Context.getTypeDeclType(Type), | |||
3853 | DirectBaseSpec, VirtualBaseSpec)) { | |||
3854 | // We have found a direct or virtual base class with a | |||
3855 | // similar name to what was typed; complain and initialize | |||
3856 | // that base class. | |||
3857 | diagnoseTypo(Corr, | |||
3858 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | |||
3859 | << MemberOrBase << false, | |||
3860 | PDiag() /*Suppress note, we provide our own.*/); | |||
3861 | ||||
3862 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec | |||
3863 | : VirtualBaseSpec; | |||
3864 | Diag(BaseSpec->getLocStart(), | |||
3865 | diag::note_base_class_specified_here) | |||
3866 | << BaseSpec->getType() | |||
3867 | << BaseSpec->getSourceRange(); | |||
3868 | ||||
3869 | TyD = Type; | |||
3870 | } | |||
3871 | } | |||
3872 | } | |||
3873 | ||||
3874 | if (!TyD && BaseType.isNull()) { | |||
3875 | Diag(IdLoc, diag::err_mem_init_not_member_or_class) | |||
3876 | << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); | |||
3877 | return true; | |||
3878 | } | |||
3879 | } | |||
3880 | ||||
3881 | if (BaseType.isNull()) { | |||
3882 | BaseType = Context.getTypeDeclType(TyD); | |||
3883 | MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); | |||
3884 | if (SS.isSet()) { | |||
3885 | BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), | |||
3886 | BaseType); | |||
3887 | TInfo = Context.CreateTypeSourceInfo(BaseType); | |||
3888 | ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); | |||
3889 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); | |||
3890 | TL.setElaboratedKeywordLoc(SourceLocation()); | |||
3891 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
3892 | } | |||
3893 | } | |||
3894 | } | |||
3895 | ||||
3896 | if (!TInfo) | |||
3897 | TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); | |||
3898 | ||||
3899 | return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); | |||
3900 | } | |||
3901 | ||||
3902 | /// Checks a member initializer expression for cases where reference (or | |||
3903 | /// pointer) members are bound to by-value parameters (or their addresses). | |||
3904 | static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, | |||
3905 | Expr *Init, | |||
3906 | SourceLocation IdLoc) { | |||
3907 | QualType MemberTy = Member->getType(); | |||
3908 | ||||
3909 | // We only handle pointers and references currently. | |||
3910 | // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? | |||
3911 | if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) | |||
3912 | return; | |||
3913 | ||||
3914 | const bool IsPointer = MemberTy->isPointerType(); | |||
3915 | if (IsPointer) { | |||
3916 | if (const UnaryOperator *Op | |||
3917 | = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { | |||
3918 | // The only case we're worried about with pointers requires taking the | |||
3919 | // address. | |||
3920 | if (Op->getOpcode() != UO_AddrOf) | |||
3921 | return; | |||
3922 | ||||
3923 | Init = Op->getSubExpr(); | |||
3924 | } else { | |||
3925 | // We only handle address-of expression initializers for pointers. | |||
3926 | return; | |||
3927 | } | |||
3928 | } | |||
3929 | ||||
3930 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { | |||
3931 | // We only warn when referring to a non-reference parameter declaration. | |||
3932 | const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); | |||
3933 | if (!Parameter || Parameter->getType()->isReferenceType()) | |||
3934 | return; | |||
3935 | ||||
3936 | S.Diag(Init->getExprLoc(), | |||
3937 | IsPointer ? diag::warn_init_ptr_member_to_parameter_addr | |||
3938 | : diag::warn_bind_ref_member_to_parameter) | |||
3939 | << Member << Parameter << Init->getSourceRange(); | |||
3940 | } else { | |||
3941 | // Other initializers are fine. | |||
3942 | return; | |||
3943 | } | |||
3944 | ||||
3945 | S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) | |||
3946 | << (unsigned)IsPointer; | |||
3947 | } | |||
3948 | ||||
3949 | MemInitResult | |||
3950 | Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, | |||
3951 | SourceLocation IdLoc) { | |||
3952 | FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); | |||
3953 | IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); | |||
3954 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3955, __extension__ __PRETTY_FUNCTION__)) | |||
3955 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3955, __extension__ __PRETTY_FUNCTION__)); | |||
3956 | ||||
3957 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | |||
3958 | return true; | |||
3959 | ||||
3960 | if (Member->isInvalidDecl()) | |||
3961 | return true; | |||
3962 | ||||
3963 | MultiExprArg Args; | |||
3964 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
3965 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
3966 | } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { | |||
3967 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | |||
3968 | } else { | |||
3969 | // Template instantiation doesn't reconstruct ParenListExprs for us. | |||
3970 | Args = Init; | |||
3971 | } | |||
3972 | ||||
3973 | SourceRange InitRange = Init->getSourceRange(); | |||
3974 | ||||
3975 | if (Member->getType()->isDependentType() || Init->isTypeDependent()) { | |||
3976 | // Can't check initialization for a member of dependent type or when | |||
3977 | // any of the arguments are type-dependent expressions. | |||
3978 | DiscardCleanupsInEvaluationContext(); | |||
3979 | } else { | |||
3980 | bool InitList = false; | |||
3981 | if (isa<InitListExpr>(Init)) { | |||
3982 | InitList = true; | |||
3983 | Args = Init; | |||
3984 | } | |||
3985 | ||||
3986 | // Initialize the member. | |||
3987 | InitializedEntity MemberEntity = | |||
3988 | DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) | |||
3989 | : InitializedEntity::InitializeMember(IndirectMember, | |||
3990 | nullptr); | |||
3991 | InitializationKind Kind = | |||
3992 | InitList ? InitializationKind::CreateDirectList( | |||
3993 | IdLoc, Init->getLocStart(), Init->getLocEnd()) | |||
3994 | : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), | |||
3995 | InitRange.getEnd()); | |||
3996 | ||||
3997 | InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); | |||
3998 | ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, | |||
3999 | nullptr); | |||
4000 | if (MemberInit.isInvalid()) | |||
4001 | return true; | |||
4002 | ||||
4003 | CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); | |||
4004 | ||||
4005 | // C++11 [class.base.init]p7: | |||
4006 | // The initialization of each base and member constitutes a | |||
4007 | // full-expression. | |||
4008 | MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); | |||
4009 | if (MemberInit.isInvalid()) | |||
4010 | return true; | |||
4011 | ||||
4012 | Init = MemberInit.get(); | |||
4013 | } | |||
4014 | ||||
4015 | if (DirectMember) { | |||
4016 | return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, | |||
4017 | InitRange.getBegin(), Init, | |||
4018 | InitRange.getEnd()); | |||
4019 | } else { | |||
4020 | return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, | |||
4021 | InitRange.getBegin(), Init, | |||
4022 | InitRange.getEnd()); | |||
4023 | } | |||
4024 | } | |||
4025 | ||||
4026 | MemInitResult | |||
4027 | Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, | |||
4028 | CXXRecordDecl *ClassDecl) { | |||
4029 | SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
4030 | if (!LangOpts.CPlusPlus11) | |||
4031 | return Diag(NameLoc, diag::err_delegating_ctor) | |||
4032 | << TInfo->getTypeLoc().getLocalSourceRange(); | |||
4033 | Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); | |||
4034 | ||||
4035 | bool InitList = true; | |||
4036 | MultiExprArg Args = Init; | |||
4037 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4038 | InitList = false; | |||
4039 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4040 | } | |||
4041 | ||||
4042 | SourceRange InitRange = Init->getSourceRange(); | |||
4043 | // Initialize the object. | |||
4044 | InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( | |||
4045 | QualType(ClassDecl->getTypeForDecl(), 0)); | |||
4046 | InitializationKind Kind = | |||
4047 | InitList ? InitializationKind::CreateDirectList( | |||
4048 | NameLoc, Init->getLocStart(), Init->getLocEnd()) | |||
4049 | : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), | |||
4050 | InitRange.getEnd()); | |||
4051 | InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); | |||
4052 | ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, | |||
4053 | Args, nullptr); | |||
4054 | if (DelegationInit.isInvalid()) | |||
4055 | return true; | |||
4056 | ||||
4057 | assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&(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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4058, __extension__ __PRETTY_FUNCTION__)) | |||
4058 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4058, __extension__ __PRETTY_FUNCTION__)); | |||
4059 | ||||
4060 | // C++11 [class.base.init]p7: | |||
4061 | // The initialization of each base and member constitutes a | |||
4062 | // full-expression. | |||
4063 | DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), | |||
4064 | InitRange.getBegin()); | |||
4065 | if (DelegationInit.isInvalid()) | |||
4066 | return true; | |||
4067 | ||||
4068 | // If we are in a dependent context, template instantiation will | |||
4069 | // perform this type-checking again. Just save the arguments that we | |||
4070 | // received in a ParenListExpr. | |||
4071 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | |||
4072 | // of the information that we have about the base | |||
4073 | // initializer. However, deconstructing the ASTs is a dicey process, | |||
4074 | // and this approach is far more likely to get the corner cases right. | |||
4075 | if (CurContext->isDependentContext()) | |||
4076 | DelegationInit = Init; | |||
4077 | ||||
4078 | return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), | |||
4079 | DelegationInit.getAs<Expr>(), | |||
4080 | InitRange.getEnd()); | |||
4081 | } | |||
4082 | ||||
4083 | MemInitResult | |||
4084 | Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, | |||
4085 | Expr *Init, CXXRecordDecl *ClassDecl, | |||
4086 | SourceLocation EllipsisLoc) { | |||
4087 | SourceLocation BaseLoc | |||
4088 | = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
4089 | ||||
4090 | if (!BaseType->isDependentType() && !BaseType->isRecordType()) | |||
4091 | return Diag(BaseLoc, diag::err_base_init_does_not_name_class) | |||
4092 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4093 | ||||
4094 | // C++ [class.base.init]p2: | |||
4095 | // [...] Unless the mem-initializer-id names a nonstatic data | |||
4096 | // member of the constructor's class or a direct or virtual base | |||
4097 | // of that class, the mem-initializer is ill-formed. A | |||
4098 | // mem-initializer-list can initialize a base class using any | |||
4099 | // name that denotes that base class type. | |||
4100 | bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); | |||
4101 | ||||
4102 | SourceRange InitRange = Init->getSourceRange(); | |||
4103 | if (EllipsisLoc.isValid()) { | |||
4104 | // This is a pack expansion. | |||
4105 | if (!BaseType->containsUnexpandedParameterPack()) { | |||
4106 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
4107 | << SourceRange(BaseLoc, InitRange.getEnd()); | |||
4108 | ||||
4109 | EllipsisLoc = SourceLocation(); | |||
4110 | } | |||
4111 | } else { | |||
4112 | // Check for any unexpanded parameter packs. | |||
4113 | if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) | |||
4114 | return true; | |||
4115 | ||||
4116 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | |||
4117 | return true; | |||
4118 | } | |||
4119 | ||||
4120 | // Check for direct and virtual base classes. | |||
4121 | const CXXBaseSpecifier *DirectBaseSpec = nullptr; | |||
4122 | const CXXBaseSpecifier *VirtualBaseSpec = nullptr; | |||
4123 | if (!Dependent) { | |||
4124 | if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), | |||
4125 | BaseType)) | |||
4126 | return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); | |||
4127 | ||||
4128 | FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, | |||
4129 | VirtualBaseSpec); | |||
4130 | ||||
4131 | // C++ [base.class.init]p2: | |||
4132 | // Unless the mem-initializer-id names a nonstatic data member of the | |||
4133 | // constructor's class or a direct or virtual base of that class, the | |||
4134 | // mem-initializer is ill-formed. | |||
4135 | if (!DirectBaseSpec && !VirtualBaseSpec) { | |||
4136 | // If the class has any dependent bases, then it's possible that | |||
4137 | // one of those types will resolve to the same type as | |||
4138 | // BaseType. Therefore, just treat this as a dependent base | |||
4139 | // class initialization. FIXME: Should we try to check the | |||
4140 | // initialization anyway? It seems odd. | |||
4141 | if (ClassDecl->hasAnyDependentBases()) | |||
4142 | Dependent = true; | |||
4143 | else | |||
4144 | return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) | |||
4145 | << BaseType << Context.getTypeDeclType(ClassDecl) | |||
4146 | << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4147 | } | |||
4148 | } | |||
4149 | ||||
4150 | if (Dependent) { | |||
4151 | DiscardCleanupsInEvaluationContext(); | |||
4152 | ||||
4153 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | |||
4154 | /*IsVirtual=*/false, | |||
4155 | InitRange.getBegin(), Init, | |||
4156 | InitRange.getEnd(), EllipsisLoc); | |||
4157 | } | |||
4158 | ||||
4159 | // C++ [base.class.init]p2: | |||
4160 | // If a mem-initializer-id is ambiguous because it designates both | |||
4161 | // a direct non-virtual base class and an inherited virtual base | |||
4162 | // class, the mem-initializer is ill-formed. | |||
4163 | if (DirectBaseSpec && VirtualBaseSpec) | |||
4164 | return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) | |||
4165 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4166 | ||||
4167 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; | |||
4168 | if (!BaseSpec) | |||
4169 | BaseSpec = VirtualBaseSpec; | |||
4170 | ||||
4171 | // Initialize the base. | |||
4172 | bool InitList = true; | |||
4173 | MultiExprArg Args = Init; | |||
4174 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4175 | InitList = false; | |||
4176 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4177 | } | |||
4178 | ||||
4179 | InitializedEntity BaseEntity = | |||
4180 | InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); | |||
4181 | InitializationKind Kind = | |||
4182 | InitList ? InitializationKind::CreateDirectList(BaseLoc) | |||
4183 | : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), | |||
4184 | InitRange.getEnd()); | |||
4185 | InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); | |||
4186 | ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); | |||
4187 | if (BaseInit.isInvalid()) | |||
4188 | return true; | |||
4189 | ||||
4190 | // C++11 [class.base.init]p7: | |||
4191 | // The initialization of each base and member constitutes a | |||
4192 | // full-expression. | |||
4193 | BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); | |||
4194 | if (BaseInit.isInvalid()) | |||
4195 | return true; | |||
4196 | ||||
4197 | // If we are in a dependent context, template instantiation will | |||
4198 | // perform this type-checking again. Just save the arguments that we | |||
4199 | // received in a ParenListExpr. | |||
4200 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | |||
4201 | // of the information that we have about the base | |||
4202 | // initializer. However, deconstructing the ASTs is a dicey process, | |||
4203 | // and this approach is far more likely to get the corner cases right. | |||
4204 | if (CurContext->isDependentContext()) | |||
4205 | BaseInit = Init; | |||
4206 | ||||
4207 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | |||
4208 | BaseSpec->isVirtual(), | |||
| ||||
4209 | InitRange.getBegin(), | |||
4210 | BaseInit.getAs<Expr>(), | |||
4211 | InitRange.getEnd(), EllipsisLoc); | |||
4212 | } | |||
4213 | ||||
4214 | // Create a static_cast\<T&&>(expr). | |||
4215 | static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { | |||
4216 | if (T.isNull()) T = E->getType(); | |||
4217 | QualType TargetType = SemaRef.BuildReferenceType( | |||
4218 | T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); | |||
4219 | SourceLocation ExprLoc = E->getLocStart(); | |||
4220 | TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( | |||
4221 | TargetType, ExprLoc); | |||
4222 | ||||
4223 | return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, | |||
4224 | SourceRange(ExprLoc, ExprLoc), | |||
4225 | E->getSourceRange()).get(); | |||
4226 | } | |||
4227 | ||||
4228 | /// ImplicitInitializerKind - How an implicit base or member initializer should | |||
4229 | /// initialize its base or member. | |||
4230 | enum ImplicitInitializerKind { | |||
4231 | IIK_Default, | |||
4232 | IIK_Copy, | |||
4233 | IIK_Move, | |||
4234 | IIK_Inherit | |||
4235 | }; | |||
4236 | ||||
4237 | static bool | |||
4238 | BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | |||
4239 | ImplicitInitializerKind ImplicitInitKind, | |||
4240 | CXXBaseSpecifier *BaseSpec, | |||
4241 | bool IsInheritedVirtualBase, | |||
4242 | CXXCtorInitializer *&CXXBaseInit) { | |||
4243 | InitializedEntity InitEntity | |||
4244 | = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, | |||
4245 | IsInheritedVirtualBase); | |||
4246 | ||||
4247 | ExprResult BaseInit; | |||
4248 | ||||
4249 | switch (ImplicitInitKind) { | |||
4250 | case IIK_Inherit: | |||
4251 | case IIK_Default: { | |||
4252 | InitializationKind InitKind | |||
4253 | = InitializationKind::CreateDefault(Constructor->getLocation()); | |||
4254 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | |||
4255 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | |||
4256 | break; | |||
4257 | } | |||
4258 | ||||
4259 | case IIK_Move: | |||
4260 | case IIK_Copy: { | |||
4261 | bool Moving = ImplicitInitKind == IIK_Move; | |||
4262 | ParmVarDecl *Param = Constructor->getParamDecl(0); | |||
4263 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
4264 | ||||
4265 | Expr *CopyCtorArg = | |||
4266 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | |||
4267 | SourceLocation(), Param, false, | |||
4268 | Constructor->getLocation(), ParamType, | |||
4269 | VK_LValue, nullptr); | |||
4270 | ||||
4271 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); | |||
4272 | ||||
4273 | // Cast to the base class to avoid ambiguities. | |||
4274 | QualType ArgTy = | |||
4275 | SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), | |||
4276 | ParamType.getQualifiers()); | |||
4277 | ||||
4278 | if (Moving) { | |||
4279 | CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); | |||
4280 | } | |||
4281 | ||||
4282 | CXXCastPath BasePath; | |||
4283 | BasePath.push_back(BaseSpec); | |||
4284 | CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, | |||
4285 | CK_UncheckedDerivedToBase, | |||
4286 | Moving ? VK_XValue : VK_LValue, | |||
4287 | &BasePath).get(); | |||
4288 | ||||
4289 | InitializationKind InitKind | |||
4290 | = InitializationKind::CreateDirect(Constructor->getLocation(), | |||
4291 | SourceLocation(), SourceLocation()); | |||
4292 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); | |||
4293 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); | |||
4294 | break; | |||
4295 | } | |||
4296 | } | |||
4297 | ||||
4298 | BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); | |||
4299 | if (BaseInit.isInvalid()) | |||
4300 | return true; | |||
4301 | ||||
4302 | CXXBaseInit = | |||
4303 | new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4304 | SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), | |||
4305 | SourceLocation()), | |||
4306 | BaseSpec->isVirtual(), | |||
4307 | SourceLocation(), | |||
4308 | BaseInit.getAs<Expr>(), | |||
4309 | SourceLocation(), | |||
4310 | SourceLocation()); | |||
4311 | ||||
4312 | return false; | |||
4313 | } | |||
4314 | ||||
4315 | static bool RefersToRValueRef(Expr *MemRef) { | |||
4316 | ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); | |||
4317 | return Referenced->getType()->isRValueReferenceType(); | |||
4318 | } | |||
4319 | ||||
4320 | static bool | |||
4321 | BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | |||
4322 | ImplicitInitializerKind ImplicitInitKind, | |||
4323 | FieldDecl *Field, IndirectFieldDecl *Indirect, | |||
4324 | CXXCtorInitializer *&CXXMemberInit) { | |||
4325 | if (Field->isInvalidDecl()) | |||
4326 | return true; | |||
4327 | ||||
4328 | SourceLocation Loc = Constructor->getLocation(); | |||
4329 | ||||
4330 | if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { | |||
4331 | bool Moving = ImplicitInitKind == IIK_Move; | |||
4332 | ParmVarDecl *Param = Constructor->getParamDecl(0); | |||
4333 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
4334 | ||||
4335 | // Suppress copying zero-width bitfields. | |||
4336 | if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) | |||
4337 | return false; | |||
4338 | ||||
4339 | Expr *MemberExprBase = | |||
4340 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | |||
4341 | SourceLocation(), Param, false, | |||
4342 | Loc, ParamType, VK_LValue, nullptr); | |||
4343 | ||||
4344 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); | |||
4345 | ||||
4346 | if (Moving) { | |||
4347 | MemberExprBase = CastForMoving(SemaRef, MemberExprBase); | |||
4348 | } | |||
4349 | ||||
4350 | // Build a reference to this field within the parameter. | |||
4351 | CXXScopeSpec SS; | |||
4352 | LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, | |||
4353 | Sema::LookupMemberName); | |||
4354 | MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) | |||
4355 | : cast<ValueDecl>(Field), AS_public); | |||
4356 | MemberLookup.resolveKind(); | |||
4357 | ExprResult CtorArg | |||
4358 | = SemaRef.BuildMemberReferenceExpr(MemberExprBase, | |||
4359 | ParamType, Loc, | |||
4360 | /*IsArrow=*/false, | |||
4361 | SS, | |||
4362 | /*TemplateKWLoc=*/SourceLocation(), | |||
4363 | /*FirstQualifierInScope=*/nullptr, | |||
4364 | MemberLookup, | |||
4365 | /*TemplateArgs=*/nullptr, | |||
4366 | /*S*/nullptr); | |||
4367 | if (CtorArg.isInvalid()) | |||
4368 | return true; | |||
4369 | ||||
4370 | // C++11 [class.copy]p15: | |||
4371 | // - if a member m has rvalue reference type T&&, it is direct-initialized | |||
4372 | // with static_cast<T&&>(x.m); | |||
4373 | if (RefersToRValueRef(CtorArg.get())) { | |||
4374 | CtorArg = CastForMoving(SemaRef, CtorArg.get()); | |||
4375 | } | |||
4376 | ||||
4377 | InitializedEntity Entity = | |||
4378 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | |||
4379 | /*Implicit*/ true) | |||
4380 | : InitializedEntity::InitializeMember(Field, nullptr, | |||
4381 | /*Implicit*/ true); | |||
4382 | ||||
4383 | // Direct-initialize to use the copy constructor. | |||
4384 | InitializationKind InitKind = | |||
4385 | InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); | |||
4386 | ||||
4387 | Expr *CtorArgE = CtorArg.getAs<Expr>(); | |||
4388 | InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); | |||
4389 | ExprResult MemberInit = | |||
4390 | InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); | |||
4391 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | |||
4392 | if (MemberInit.isInvalid()) | |||
4393 | return true; | |||
4394 | ||||
4395 | if (Indirect) | |||
4396 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | |||
4397 | SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | |||
4398 | else | |||
4399 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | |||
4400 | SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | |||
4401 | return false; | |||
4402 | } | |||
4403 | ||||
4404 | assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4405, __extension__ __PRETTY_FUNCTION__)) | |||
4405 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4405, __extension__ __PRETTY_FUNCTION__)); | |||
4406 | ||||
4407 | QualType FieldBaseElementType = | |||
4408 | SemaRef.Context.getBaseElementType(Field->getType()); | |||
4409 | ||||
4410 | if (FieldBaseElementType->isRecordType()) { | |||
4411 | InitializedEntity InitEntity = | |||
4412 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | |||
4413 | /*Implicit*/ true) | |||
4414 | : InitializedEntity::InitializeMember(Field, nullptr, | |||
4415 | /*Implicit*/ true); | |||
4416 | InitializationKind InitKind = | |||
4417 | InitializationKind::CreateDefault(Loc); | |||
4418 | ||||
4419 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | |||
4420 | ExprResult MemberInit = | |||
4421 | InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | |||
4422 | ||||
4423 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | |||
4424 | if (MemberInit.isInvalid()) | |||
4425 | return true; | |||
4426 | ||||
4427 | if (Indirect) | |||
4428 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4429 | Indirect, Loc, | |||
4430 | Loc, | |||
4431 | MemberInit.get(), | |||
4432 | Loc); | |||
4433 | else | |||
4434 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4435 | Field, Loc, Loc, | |||
4436 | MemberInit.get(), | |||
4437 | Loc); | |||
4438 | return false; | |||
4439 | } | |||
4440 | ||||
4441 | if (!Field->getParent()->isUnion()) { | |||
4442 | if (FieldBaseElementType->isReferenceType()) { | |||
4443 | SemaRef.Diag(Constructor->getLocation(), | |||
4444 | diag::err_uninitialized_member_in_ctor) | |||
4445 | << (int)Constructor->isImplicit() | |||
4446 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | |||
4447 | << 0 << Field->getDeclName(); | |||
4448 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | |||
4449 | return true; | |||
4450 | } | |||
4451 | ||||
4452 | if (FieldBaseElementType.isConstQualified()) { | |||
4453 | SemaRef.Diag(Constructor->getLocation(), | |||
4454 | diag::err_uninitialized_member_in_ctor) | |||
4455 | << (int)Constructor->isImplicit() | |||
4456 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | |||
4457 | << 1 << Field->getDeclName(); | |||
4458 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | |||
4459 | return true; | |||
4460 | } | |||
4461 | } | |||
4462 | ||||
4463 | if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { | |||
4464 | // ARC and Weak: | |||
4465 | // Default-initialize Objective-C pointers to NULL. | |||
4466 | CXXMemberInit | |||
4467 | = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, | |||
4468 | Loc, Loc, | |||
4469 | new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), | |||
4470 | Loc); | |||
4471 | return false; | |||
4472 | } | |||
4473 | ||||
4474 | // Nothing to initialize. | |||
4475 | CXXMemberInit = nullptr; | |||
4476 | return false; | |||
4477 | } | |||
4478 | ||||
4479 | namespace { | |||
4480 | struct BaseAndFieldInfo { | |||
4481 | Sema &S; | |||
4482 | CXXConstructorDecl *Ctor; | |||
4483 | bool AnyErrorsInInits; | |||
4484 | ImplicitInitializerKind IIK; | |||
4485 | llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; | |||
4486 | SmallVector<CXXCtorInitializer*, 8> AllToInit; | |||
4487 | llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; | |||
4488 | ||||
4489 | BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) | |||
4490 | : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { | |||
4491 | bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); | |||
4492 | if (Ctor->getInheritedConstructor()) | |||
4493 | IIK = IIK_Inherit; | |||
4494 | else if (Generated && Ctor->isCopyConstructor()) | |||
4495 | IIK = IIK_Copy; | |||
4496 | else if (Generated && Ctor->isMoveConstructor()) | |||
4497 | IIK = IIK_Move; | |||
4498 | else | |||
4499 | IIK = IIK_Default; | |||
4500 | } | |||
4501 | ||||
4502 | bool isImplicitCopyOrMove() const { | |||
4503 | switch (IIK) { | |||
4504 | case IIK_Copy: | |||
4505 | case IIK_Move: | |||
4506 | return true; | |||
4507 | ||||
4508 | case IIK_Default: | |||
4509 | case IIK_Inherit: | |||
4510 | return false; | |||
4511 | } | |||
4512 | ||||
4513 | llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4513); | |||
4514 | } | |||
4515 | ||||
4516 | bool addFieldInitializer(CXXCtorInitializer *Init) { | |||
4517 | AllToInit.push_back(Init); | |||
4518 | ||||
4519 | // Check whether this initializer makes the field "used". | |||
4520 | if (Init->getInit()->HasSideEffects(S.Context)) | |||
4521 | S.UnusedPrivateFields.remove(Init->getAnyMember()); | |||
4522 | ||||
4523 | return false; | |||
4524 | } | |||
4525 | ||||
4526 | bool isInactiveUnionMember(FieldDecl *Field) { | |||
4527 | RecordDecl *Record = Field->getParent(); | |||
4528 | if (!Record->isUnion()) | |||
4529 | return false; | |||
4530 | ||||
4531 | if (FieldDecl *Active = | |||
4532 | ActiveUnionMember.lookup(Record->getCanonicalDecl())) | |||
4533 | return Active != Field->getCanonicalDecl(); | |||
4534 | ||||
4535 | // In an implicit copy or move constructor, ignore any in-class initializer. | |||
4536 | if (isImplicitCopyOrMove()) | |||
4537 | return true; | |||
4538 | ||||
4539 | // If there's no explicit initialization, the field is active only if it | |||
4540 | // has an in-class initializer... | |||
4541 | if (Field->hasInClassInitializer()) | |||
4542 | return false; | |||
4543 | // ... or it's an anonymous struct or union whose class has an in-class | |||
4544 | // initializer. | |||
4545 | if (!Field->isAnonymousStructOrUnion()) | |||
4546 | return true; | |||
4547 | CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); | |||
4548 | return !FieldRD->hasInClassInitializer(); | |||
4549 | } | |||
4550 | ||||
4551 | /// \brief Determine whether the given field is, or is within, a union member | |||
4552 | /// that is inactive (because there was an initializer given for a different | |||
4553 | /// member of the union, or because the union was not initialized at all). | |||
4554 | bool isWithinInactiveUnionMember(FieldDecl *Field, | |||
4555 | IndirectFieldDecl *Indirect) { | |||
4556 | if (!Indirect) | |||
4557 | return isInactiveUnionMember(Field); | |||
4558 | ||||
4559 | for (auto *C : Indirect->chain()) { | |||
4560 | FieldDecl *Field = dyn_cast<FieldDecl>(C); | |||
4561 | if (Field && isInactiveUnionMember(Field)) | |||
4562 | return true; | |||
4563 | } | |||
4564 | return false; | |||
4565 | } | |||
4566 | }; | |||
4567 | } | |||
4568 | ||||
4569 | /// \brief Determine whether the given type is an incomplete or zero-lenfgth | |||
4570 | /// array type. | |||
4571 | static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { | |||
4572 | if (T->isIncompleteArrayType()) | |||
4573 | return true; | |||
4574 | ||||
4575 | while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { | |||
4576 | if (!ArrayT->getSize()) | |||
4577 | return true; | |||
4578 | ||||
4579 | T = ArrayT->getElementType(); | |||
4580 | } | |||
4581 | ||||
4582 | return false; | |||
4583 | } | |||
4584 | ||||
4585 | static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, | |||
4586 | FieldDecl *Field, | |||
4587 | IndirectFieldDecl *Indirect = nullptr) { | |||
4588 | if (Field->isInvalidDecl()) | |||
4589 | return false; | |||
4590 | ||||
4591 | // Overwhelmingly common case: we have a direct initializer for this field. | |||
4592 | if (CXXCtorInitializer *Init = | |||
4593 | Info.AllBaseFields.lookup(Field->getCanonicalDecl())) | |||
4594 | return Info.addFieldInitializer(Init); | |||
4595 | ||||
4596 | // C++11 [class.base.init]p8: | |||
4597 | // if the entity is a non-static data member that has a | |||
4598 | // brace-or-equal-initializer and either | |||
4599 | // -- the constructor's class is a union and no other variant member of that | |||
4600 | // union is designated by a mem-initializer-id or | |||
4601 | // -- the constructor's class is not a union, and, if the entity is a member | |||
4602 | // of an anonymous union, no other member of that union is designated by | |||
4603 | // a mem-initializer-id, | |||
4604 | // the entity is initialized as specified in [dcl.init]. | |||
4605 | // | |||
4606 | // We also apply the same rules to handle anonymous structs within anonymous | |||
4607 | // unions. | |||
4608 | if (Info.isWithinInactiveUnionMember(Field, Indirect)) | |||
4609 | return false; | |||
4610 | ||||
4611 | if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { | |||
4612 | ExprResult DIE = | |||
4613 | SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); | |||
4614 | if (DIE.isInvalid()) | |||
4615 | return true; | |||
4616 | CXXCtorInitializer *Init; | |||
4617 | if (Indirect) | |||
4618 | Init = new (SemaRef.Context) | |||
4619 | CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), | |||
4620 | SourceLocation(), DIE.get(), SourceLocation()); | |||
4621 | else | |||
4622 | Init = new (SemaRef.Context) | |||
4623 | CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), | |||
4624 | SourceLocation(), DIE.get(), SourceLocation()); | |||
4625 | return Info.addFieldInitializer(Init); | |||
4626 | } | |||
4627 | ||||
4628 | // Don't initialize incomplete or zero-length arrays. | |||
4629 | if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) | |||
4630 | return false; | |||
4631 | ||||
4632 | // Don't try to build an implicit initializer if there were semantic | |||
4633 | // errors in any of the initializers (and therefore we might be | |||
4634 | // missing some that the user actually wrote). | |||
4635 | if (Info.AnyErrorsInInits) | |||
4636 | return false; | |||
4637 | ||||
4638 | CXXCtorInitializer *Init = nullptr; | |||
4639 | if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, | |||
4640 | Indirect, Init)) | |||
4641 | return true; | |||
4642 | ||||
4643 | if (!Init) | |||
4644 | return false; | |||
4645 | ||||
4646 | return Info.addFieldInitializer(Init); | |||
4647 | } | |||
4648 | ||||
4649 | bool | |||
4650 | Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, | |||
4651 | CXXCtorInitializer *Initializer) { | |||
4652 | assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer ()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4652, __extension__ __PRETTY_FUNCTION__)); | |||
4653 | Constructor->setNumCtorInitializers(1); | |||
4654 | CXXCtorInitializer **initializer = | |||
4655 | new (Context) CXXCtorInitializer*[1]; | |||
4656 | memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); | |||
4657 | Constructor->setCtorInitializers(initializer); | |||
4658 | ||||
4659 | if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { | |||
4660 | MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); | |||
4661 | DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); | |||
4662 | } | |||
4663 | ||||
4664 | DelegatingCtorDecls.push_back(Constructor); | |||
4665 | ||||
4666 | DiagnoseUninitializedFields(*this, Constructor); | |||
4667 | ||||
4668 | return false; | |||
4669 | } | |||
4670 | ||||
4671 | bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, | |||
4672 | ArrayRef<CXXCtorInitializer *> Initializers) { | |||
4673 | if (Constructor->isDependentContext()) { | |||
4674 | // Just store the initializers as written, they will be checked during | |||
4675 | // instantiation. | |||
4676 | if (!Initializers.empty()) { | |||
4677 | Constructor->setNumCtorInitializers(Initializers.size()); | |||
4678 | CXXCtorInitializer **baseOrMemberInitializers = | |||
4679 | new (Context) CXXCtorInitializer*[Initializers.size()]; | |||
4680 | memcpy(baseOrMemberInitializers, Initializers.data(), | |||
4681 | Initializers.size() * sizeof(CXXCtorInitializer*)); | |||
4682 | Constructor->setCtorInitializers(baseOrMemberInitializers); | |||
4683 | } | |||
4684 | ||||
4685 | // Let template instantiation know whether we had errors. | |||
4686 | if (AnyErrors) | |||
4687 | Constructor->setInvalidDecl(); | |||
4688 | ||||
4689 | return false; | |||
4690 | } | |||
4691 | ||||
4692 | BaseAndFieldInfo Info(*this, Constructor, AnyErrors); | |||
4693 | ||||
4694 | // We need to build the initializer AST according to order of construction | |||
4695 | // and not what user specified in the Initializers list. | |||
4696 | CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); | |||
4697 | if (!ClassDecl) | |||
4698 | return true; | |||
4699 | ||||
4700 | bool HadError = false; | |||
4701 | ||||
4702 | for (unsigned i = 0; i < Initializers.size(); i++) { | |||
4703 | CXXCtorInitializer *Member = Initializers[i]; | |||
4704 | ||||
4705 | if (Member->isBaseInitializer()) | |||
4706 | Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; | |||
4707 | else { | |||
4708 | Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; | |||
4709 | ||||
4710 | if (IndirectFieldDecl *F = Member->getIndirectMember()) { | |||
4711 | for (auto *C : F->chain()) { | |||
4712 | FieldDecl *FD = dyn_cast<FieldDecl>(C); | |||
4713 | if (FD && FD->getParent()->isUnion()) | |||
4714 | Info.ActiveUnionMember.insert(std::make_pair( | |||
4715 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | |||
4716 | } | |||
4717 | } else if (FieldDecl *FD = Member->getMember()) { | |||
4718 | if (FD->getParent()->isUnion()) | |||
4719 | Info.ActiveUnionMember.insert(std::make_pair( | |||
4720 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | |||
4721 | } | |||
4722 | } | |||
4723 | } | |||
4724 | ||||
4725 | // Keep track of the direct virtual bases. | |||
4726 | llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; | |||
4727 | for (auto &I : ClassDecl->bases()) { | |||
4728 | if (I.isVirtual()) | |||
4729 | DirectVBases.insert(&I); | |||
4730 | } | |||
4731 | ||||
4732 | // Push virtual bases before others. | |||
4733 | for (auto &VBase : ClassDecl->vbases()) { | |||
4734 | if (CXXCtorInitializer *Value | |||
4735 | = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { | |||
4736 | // [class.base.init]p7, per DR257: | |||
4737 | // A mem-initializer where the mem-initializer-id names a virtual base | |||
4738 | // class is ignored during execution of a constructor of any class that | |||
4739 | // is not the most derived class. | |||
4740 | if (ClassDecl->isAbstract()) { | |||
4741 | // FIXME: Provide a fixit to remove the base specifier. This requires | |||
4742 | // tracking the location of the associated comma for a base specifier. | |||
4743 | Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) | |||
4744 | << VBase.getType() << ClassDecl; | |||
4745 | DiagnoseAbstractType(ClassDecl); | |||
4746 | } | |||
4747 | ||||
4748 | Info.AllToInit.push_back(Value); | |||
4749 | } else if (!AnyErrors && !ClassDecl->isAbstract()) { | |||
4750 | // [class.base.init]p8, per DR257: | |||
4751 | // If a given [...] base class is not named by a mem-initializer-id | |||
4752 | // [...] and the entity is not a virtual base class of an abstract | |||
4753 | // class, then [...] the entity is default-initialized. | |||
4754 | bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); | |||
4755 | CXXCtorInitializer *CXXBaseInit; | |||
4756 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | |||
4757 | &VBase, IsInheritedVirtualBase, | |||
4758 | CXXBaseInit)) { | |||
4759 | HadError = true; | |||
4760 | continue; | |||
4761 | } | |||
4762 | ||||
4763 | Info.AllToInit.push_back(CXXBaseInit); | |||
4764 | } | |||
4765 | } | |||
4766 | ||||
4767 | // Non-virtual bases. | |||
4768 | for (auto &Base : ClassDecl->bases()) { | |||
4769 | // Virtuals are in the virtual base list and already constructed. | |||
4770 | if (Base.isVirtual()) | |||
4771 | continue; | |||
4772 | ||||
4773 | if (CXXCtorInitializer *Value | |||
4774 | = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { | |||
4775 | Info.AllToInit.push_back(Value); | |||
4776 | } else if (!AnyErrors) { | |||
4777 | CXXCtorInitializer *CXXBaseInit; | |||
4778 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | |||
4779 | &Base, /*IsInheritedVirtualBase=*/false, | |||
4780 | CXXBaseInit)) { | |||
4781 | HadError = true; | |||
4782 | continue; | |||
4783 | } | |||
4784 | ||||
4785 | Info.AllToInit.push_back(CXXBaseInit); | |||
4786 | } | |||
4787 | } | |||
4788 | ||||
4789 | // Fields. | |||
4790 | for (auto *Mem : ClassDecl->decls()) { | |||
4791 | if (auto *F = dyn_cast<FieldDecl>(Mem)) { | |||
4792 | // C++ [class.bit]p2: | |||
4793 | // A declaration for a bit-field that omits the identifier declares an | |||
4794 | // unnamed bit-field. Unnamed bit-fields are not members and cannot be | |||
4795 | // initialized. | |||
4796 | if (F->isUnnamedBitfield()) | |||
4797 | continue; | |||
4798 | ||||
4799 | // If we're not generating the implicit copy/move constructor, then we'll | |||
4800 | // handle anonymous struct/union fields based on their individual | |||
4801 | // indirect fields. | |||
4802 | if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) | |||
4803 | continue; | |||
4804 | ||||
4805 | if (CollectFieldInitializer(*this, Info, F)) | |||
4806 | HadError = true; | |||
4807 | continue; | |||
4808 | } | |||
4809 | ||||
4810 | // Beyond this point, we only consider default initialization. | |||
4811 | if (Info.isImplicitCopyOrMove()) | |||
4812 | continue; | |||
4813 | ||||
4814 | if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { | |||
4815 | if (F->getType()->isIncompleteArrayType()) { | |||
4816 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4817, __extension__ __PRETTY_FUNCTION__)) | |||
4817 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4817, __extension__ __PRETTY_FUNCTION__)); | |||
4818 | continue; | |||
4819 | } | |||
4820 | ||||
4821 | // Initialize each field of an anonymous struct individually. | |||
4822 | if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) | |||
4823 | HadError = true; | |||
4824 | ||||
4825 | continue; | |||
4826 | } | |||
4827 | } | |||
4828 | ||||
4829 | unsigned NumInitializers = Info.AllToInit.size(); | |||
4830 | if (NumInitializers > 0) { | |||
4831 | Constructor->setNumCtorInitializers(NumInitializers); | |||
4832 | CXXCtorInitializer **baseOrMemberInitializers = | |||
4833 | new (Context) CXXCtorInitializer*[NumInitializers]; | |||
4834 | memcpy(baseOrMemberInitializers, Info.AllToInit.data(), | |||
4835 | NumInitializers * sizeof(CXXCtorInitializer*)); | |||
4836 | Constructor->setCtorInitializers(baseOrMemberInitializers); | |||
4837 | ||||
4838 | // Constructors implicitly reference the base and member | |||
4839 | // destructors. | |||
4840 | MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), | |||
4841 | Constructor->getParent()); | |||
4842 | } | |||
4843 | ||||
4844 | return HadError; | |||
4845 | } | |||
4846 | ||||
4847 | static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { | |||
4848 | if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { | |||
4849 | const RecordDecl *RD = RT->getDecl(); | |||
4850 | if (RD->isAnonymousStructOrUnion()) { | |||
4851 | for (auto *Field : RD->fields()) | |||
4852 | PopulateKeysForFields(Field, IdealInits); | |||
4853 | return; | |||
4854 | } | |||
4855 | } | |||
4856 | IdealInits.push_back(Field->getCanonicalDecl()); | |||
4857 | } | |||
4858 | ||||
4859 | static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { | |||
4860 | return Context.getCanonicalType(BaseType).getTypePtr(); | |||
4861 | } | |||
4862 | ||||
4863 | static const void *GetKeyForMember(ASTContext &Context, | |||
4864 | CXXCtorInitializer *Member) { | |||
4865 | if (!Member->isAnyMemberInitializer()) | |||
4866 | return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); | |||
4867 | ||||
4868 | return Member->getAnyMember()->getCanonicalDecl(); | |||
4869 | } | |||
4870 | ||||
4871 | static void DiagnoseBaseOrMemInitializerOrder( | |||
4872 | Sema &SemaRef, const CXXConstructorDecl *Constructor, | |||
4873 | ArrayRef<CXXCtorInitializer *> Inits) { | |||
4874 | if (Constructor->getDeclContext()->isDependentContext()) | |||
4875 | return; | |||
4876 | ||||
4877 | // Don't check initializers order unless the warning is enabled at the | |||
4878 | // location of at least one initializer. | |||
4879 | bool ShouldCheckOrder = false; | |||
4880 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | |||
4881 | CXXCtorInitializer *Init = Inits[InitIndex]; | |||
4882 | if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, | |||
4883 | Init->getSourceLocation())) { | |||
4884 | ShouldCheckOrder = true; | |||
4885 | break; | |||
4886 | } | |||
4887 | } | |||
4888 | if (!ShouldCheckOrder) | |||
4889 | return; | |||
4890 | ||||
4891 | // Build the list of bases and members in the order that they'll | |||
4892 | // actually be initialized. The explicit initializers should be in | |||
4893 | // this same order but may be missing things. | |||
4894 | SmallVector<const void*, 32> IdealInitKeys; | |||
4895 | ||||
4896 | const CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
4897 | ||||
4898 | // 1. Virtual bases. | |||
4899 | for (const auto &VBase : ClassDecl->vbases()) | |||
4900 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); | |||
4901 | ||||
4902 | // 2. Non-virtual bases. | |||
4903 | for (const auto &Base : ClassDecl->bases()) { | |||
4904 | if (Base.isVirtual()) | |||
4905 | continue; | |||
4906 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); | |||
4907 | } | |||
4908 | ||||
4909 | // 3. Direct fields. | |||
4910 | for (auto *Field : ClassDecl->fields()) { | |||
4911 | if (Field->isUnnamedBitfield()) | |||
4912 | continue; | |||
4913 | ||||
4914 | PopulateKeysForFields(Field, IdealInitKeys); | |||
4915 | } | |||
4916 | ||||
4917 | unsigned NumIdealInits = IdealInitKeys.size(); | |||
4918 | unsigned IdealIndex = 0; | |||
4919 | ||||
4920 | CXXCtorInitializer *PrevInit = nullptr; | |||
4921 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | |||
4922 | CXXCtorInitializer *Init = Inits[InitIndex]; | |||
4923 | const void *InitKey = GetKeyForMember(SemaRef.Context, Init); | |||
4924 | ||||
4925 | // Scan forward to try to find this initializer in the idealized | |||
4926 | // initializers list. | |||
4927 | for (; IdealIndex != NumIdealInits; ++IdealIndex) | |||
4928 | if (InitKey == IdealInitKeys[IdealIndex]) | |||
4929 | break; | |||
4930 | ||||
4931 | // If we didn't find this initializer, it must be because we | |||
4932 | // scanned past it on a previous iteration. That can only | |||
4933 | // happen if we're out of order; emit a warning. | |||
4934 | if (IdealIndex == NumIdealInits && PrevInit) { | |||
4935 | Sema::SemaDiagnosticBuilder D = | |||
4936 | SemaRef.Diag(PrevInit->getSourceLocation(), | |||
4937 | diag::warn_initializer_out_of_order); | |||
4938 | ||||
4939 | if (PrevInit->isAnyMemberInitializer()) | |||
4940 | D << 0 << PrevInit->getAnyMember()->getDeclName(); | |||
4941 | else | |||
4942 | D << 1 << PrevInit->getTypeSourceInfo()->getType(); | |||
4943 | ||||
4944 | if (Init->isAnyMemberInitializer()) | |||
4945 | D << 0 << Init->getAnyMember()->getDeclName(); | |||
4946 | else | |||
4947 | D << 1 << Init->getTypeSourceInfo()->getType(); | |||
4948 | ||||
4949 | // Move back to the initializer's location in the ideal list. | |||
4950 | for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) | |||
4951 | if (InitKey == IdealInitKeys[IdealIndex]) | |||
4952 | break; | |||
4953 | ||||
4954 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4955, __extension__ __PRETTY_FUNCTION__)) | |||
4955 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4955, __extension__ __PRETTY_FUNCTION__)); | |||
4956 | } | |||
4957 | ||||
4958 | PrevInit = Init; | |||
4959 | } | |||
4960 | } | |||
4961 | ||||
4962 | namespace { | |||
4963 | bool CheckRedundantInit(Sema &S, | |||
4964 | CXXCtorInitializer *Init, | |||
4965 | CXXCtorInitializer *&PrevInit) { | |||
4966 | if (!PrevInit) { | |||
4967 | PrevInit = Init; | |||
4968 | return false; | |||
4969 | } | |||
4970 | ||||
4971 | if (FieldDecl *Field = Init->getAnyMember()) | |||
4972 | S.Diag(Init->getSourceLocation(), | |||
4973 | diag::err_multiple_mem_initialization) | |||
4974 | << Field->getDeclName() | |||
4975 | << Init->getSourceRange(); | |||
4976 | else { | |||
4977 | const Type *BaseClass = Init->getBaseClass(); | |||
4978 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4978, __extension__ __PRETTY_FUNCTION__)); | |||
4979 | S.Diag(Init->getSourceLocation(), | |||
4980 | diag::err_multiple_base_initialization) | |||
4981 | << QualType(BaseClass, 0) | |||
4982 | << Init->getSourceRange(); | |||
4983 | } | |||
4984 | S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) | |||
4985 | << 0 << PrevInit->getSourceRange(); | |||
4986 | ||||
4987 | return true; | |||
4988 | } | |||
4989 | ||||
4990 | typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; | |||
4991 | typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; | |||
4992 | ||||
4993 | bool CheckRedundantUnionInit(Sema &S, | |||
4994 | CXXCtorInitializer *Init, | |||
4995 | RedundantUnionMap &Unions) { | |||
4996 | FieldDecl *Field = Init->getAnyMember(); | |||
4997 | RecordDecl *Parent = Field->getParent(); | |||
4998 | NamedDecl *Child = Field; | |||
4999 | ||||
5000 | while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { | |||
5001 | if (Parent->isUnion()) { | |||
5002 | UnionEntry &En = Unions[Parent]; | |||
5003 | if (En.first && En.first != Child) { | |||
5004 | S.Diag(Init->getSourceLocation(), | |||
5005 | diag::err_multiple_mem_union_initialization) | |||
5006 | << Field->getDeclName() | |||
5007 | << Init->getSourceRange(); | |||
5008 | S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) | |||
5009 | << 0 << En.second->getSourceRange(); | |||
5010 | return true; | |||
5011 | } | |||
5012 | if (!En.first) { | |||
5013 | En.first = Child; | |||
5014 | En.second = Init; | |||
5015 | } | |||
5016 | if (!Parent->isAnonymousStructOrUnion()) | |||
5017 | return false; | |||
5018 | } | |||
5019 | ||||
5020 | Child = Parent; | |||
5021 | Parent = cast<RecordDecl>(Parent->getDeclContext()); | |||
5022 | } | |||
5023 | ||||
5024 | return false; | |||
5025 | } | |||
5026 | } | |||
5027 | ||||
5028 | /// ActOnMemInitializers - Handle the member initializers for a constructor. | |||
5029 | void Sema::ActOnMemInitializers(Decl *ConstructorDecl, | |||
5030 | SourceLocation ColonLoc, | |||
5031 | ArrayRef<CXXCtorInitializer*> MemInits, | |||
5032 | bool AnyErrors) { | |||
5033 | if (!ConstructorDecl) | |||
5034 | return; | |||
5035 | ||||
5036 | AdjustDeclIfTemplate(ConstructorDecl); | |||
5037 | ||||
5038 | CXXConstructorDecl *Constructor | |||
5039 | = dyn_cast<CXXConstructorDecl>(ConstructorDecl); | |||
5040 | ||||
5041 | if (!Constructor) { | |||
5042 | Diag(ColonLoc, diag::err_only_constructors_take_base_inits); | |||
5043 | return; | |||
5044 | } | |||
5045 | ||||
5046 | // Mapping for the duplicate initializers check. | |||
5047 | // For member initializers, this is keyed with a FieldDecl*. | |||
5048 | // For base initializers, this is keyed with a Type*. | |||
5049 | llvm::DenseMap<const void *, CXXCtorInitializer *> Members; | |||
5050 | ||||
5051 | // Mapping for the inconsistent anonymous-union initializers check. | |||
5052 | RedundantUnionMap MemberUnions; | |||
5053 | ||||
5054 | bool HadError = false; | |||
5055 | for (unsigned i = 0; i < MemInits.size(); i++) { | |||
5056 | CXXCtorInitializer *Init = MemInits[i]; | |||
5057 | ||||
5058 | // Set the source order index. | |||
5059 | Init->setSourceOrder(i); | |||
5060 | ||||
5061 | if (Init->isAnyMemberInitializer()) { | |||
5062 | const void *Key = GetKeyForMember(Context, Init); | |||
5063 | if (CheckRedundantInit(*this, Init, Members[Key]) || | |||
5064 | CheckRedundantUnionInit(*this, Init, MemberUnions)) | |||
5065 | HadError = true; | |||
5066 | } else if (Init->isBaseInitializer()) { | |||
5067 | const void *Key = GetKeyForMember(Context, Init); | |||
5068 | if (CheckRedundantInit(*this, Init, Members[Key])) | |||
5069 | HadError = true; | |||
5070 | } else { | |||
5071 | assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer() ) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5071, __extension__ __PRETTY_FUNCTION__)); | |||
5072 | // This must be the only initializer | |||
5073 | if (MemInits.size() != 1) { | |||
5074 | Diag(Init->getSourceLocation(), | |||
5075 | diag::err_delegating_initializer_alone) | |||
5076 | << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); | |||
5077 | // We will treat this as being the only initializer. | |||
5078 | } | |||
5079 | SetDelegatingInitializer(Constructor, MemInits[i]); | |||
5080 | // Return immediately as the initializer is set. | |||
5081 | return; | |||
5082 | } | |||
5083 | } | |||
5084 | ||||
5085 | if (HadError) | |||
5086 | return; | |||
5087 | ||||
5088 | DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); | |||
5089 | ||||
5090 | SetCtorInitializers(Constructor, AnyErrors, MemInits); | |||
5091 | ||||
5092 | DiagnoseUninitializedFields(*this, Constructor); | |||
5093 | } | |||
5094 | ||||
5095 | void | |||
5096 | Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, | |||
5097 | CXXRecordDecl *ClassDecl) { | |||
5098 | // Ignore dependent contexts. Also ignore unions, since their members never | |||
5099 | // have destructors implicitly called. | |||
5100 | if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) | |||
5101 | return; | |||
5102 | ||||
5103 | // FIXME: all the access-control diagnostics are positioned on the | |||
5104 | // field/base declaration. That's probably good; that said, the | |||
5105 | // user might reasonably want to know why the destructor is being | |||
5106 | // emitted, and we currently don't say. | |||
5107 | ||||
5108 | // Non-static data members. | |||
5109 | for (auto *Field : ClassDecl->fields()) { | |||
5110 | if (Field->isInvalidDecl()) | |||
5111 | continue; | |||
5112 | ||||
5113 | // Don't destroy incomplete or zero-length arrays. | |||
5114 | if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) | |||
5115 | continue; | |||
5116 | ||||
5117 | QualType FieldType = Context.getBaseElementType(Field->getType()); | |||
5118 | ||||
5119 | const RecordType* RT = FieldType->getAs<RecordType>(); | |||
5120 | if (!RT) | |||
5121 | continue; | |||
5122 | ||||
5123 | CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5124 | if (FieldClassDecl->isInvalidDecl()) | |||
5125 | continue; | |||
5126 | if (FieldClassDecl->hasIrrelevantDestructor()) | |||
5127 | continue; | |||
5128 | // The destructor for an implicit anonymous union member is never invoked. | |||
5129 | if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) | |||
5130 | continue; | |||
5131 | ||||
5132 | CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); | |||
5133 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5133, __extension__ __PRETTY_FUNCTION__)); | |||
5134 | CheckDestructorAccess(Field->getLocation(), Dtor, | |||
5135 | PDiag(diag::err_access_dtor_field) | |||
5136 | << Field->getDeclName() | |||
5137 | << FieldType); | |||
5138 | ||||
5139 | MarkFunctionReferenced(Location, Dtor); | |||
5140 | DiagnoseUseOfDecl(Dtor, Location); | |||
5141 | } | |||
5142 | ||||
5143 | // We only potentially invoke the destructors of potentially constructed | |||
5144 | // subobjects. | |||
5145 | bool VisitVirtualBases = !ClassDecl->isAbstract(); | |||
5146 | ||||
5147 | llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; | |||
5148 | ||||
5149 | // Bases. | |||
5150 | for (const auto &Base : ClassDecl->bases()) { | |||
5151 | // Bases are always records in a well-formed non-dependent class. | |||
5152 | const RecordType *RT = Base.getType()->getAs<RecordType>(); | |||
5153 | ||||
5154 | // Remember direct virtual bases. | |||
5155 | if (Base.isVirtual()) { | |||
5156 | if (!VisitVirtualBases) | |||
5157 | continue; | |||
5158 | DirectVirtualBases.insert(RT); | |||
5159 | } | |||
5160 | ||||
5161 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5162 | // If our base class is invalid, we probably can't get its dtor anyway. | |||
5163 | if (BaseClassDecl->isInvalidDecl()) | |||
5164 | continue; | |||
5165 | if (BaseClassDecl->hasIrrelevantDestructor()) | |||
5166 | continue; | |||
5167 | ||||
5168 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | |||
5169 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5169, __extension__ __PRETTY_FUNCTION__)); | |||
5170 | ||||
5171 | // FIXME: caret should be on the start of the class name | |||
5172 | CheckDestructorAccess(Base.getLocStart(), Dtor, | |||
5173 | PDiag(diag::err_access_dtor_base) | |||
5174 | << Base.getType() | |||
5175 | << Base.getSourceRange(), | |||
5176 | Context.getTypeDeclType(ClassDecl)); | |||
5177 | ||||
5178 | MarkFunctionReferenced(Location, Dtor); | |||
5179 | DiagnoseUseOfDecl(Dtor, Location); | |||
5180 | } | |||
5181 | ||||
5182 | if (!VisitVirtualBases) | |||
5183 | return; | |||
5184 | ||||
5185 | // Virtual bases. | |||
5186 | for (const auto &VBase : ClassDecl->vbases()) { | |||
5187 | // Bases are always records in a well-formed non-dependent class. | |||
5188 | const RecordType *RT = VBase.getType()->castAs<RecordType>(); | |||
5189 | ||||
5190 | // Ignore direct virtual bases. | |||
5191 | if (DirectVirtualBases.count(RT)) | |||
5192 | continue; | |||
5193 | ||||
5194 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5195 | // If our base class is invalid, we probably can't get its dtor anyway. | |||
5196 | if (BaseClassDecl->isInvalidDecl()) | |||
5197 | continue; | |||
5198 | if (BaseClassDecl->hasIrrelevantDestructor()) | |||
5199 | continue; | |||
5200 | ||||
5201 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | |||
5202 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5202, __extension__ __PRETTY_FUNCTION__)); | |||
5203 | if (CheckDestructorAccess( | |||
5204 | ClassDecl->getLocation(), Dtor, | |||
5205 | PDiag(diag::err_access_dtor_vbase) | |||
5206 | << Context.getTypeDeclType(ClassDecl) << VBase.getType(), | |||
5207 | Context.getTypeDeclType(ClassDecl)) == | |||
5208 | AR_accessible) { | |||
5209 | CheckDerivedToBaseConversion( | |||
5210 | Context.getTypeDeclType(ClassDecl), VBase.getType(), | |||
5211 | diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), | |||
5212 | SourceRange(), DeclarationName(), nullptr); | |||
5213 | } | |||
5214 | ||||
5215 | MarkFunctionReferenced(Location, Dtor); | |||
5216 | DiagnoseUseOfDecl(Dtor, Location); | |||
5217 | } | |||
5218 | } | |||
5219 | ||||
5220 | void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { | |||
5221 | if (!CDtorDecl) | |||
5222 | return; | |||
5223 | ||||
5224 | if (CXXConstructorDecl *Constructor | |||
5225 | = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { | |||
5226 | SetCtorInitializers(Constructor, /*AnyErrors=*/false); | |||
5227 | DiagnoseUninitializedFields(*this, Constructor); | |||
5228 | } | |||
5229 | } | |||
5230 | ||||
5231 | bool Sema::isAbstractType(SourceLocation Loc, QualType T) { | |||
5232 | if (!getLangOpts().CPlusPlus) | |||
5233 | return false; | |||
5234 | ||||
5235 | const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); | |||
5236 | if (!RD) | |||
5237 | return false; | |||
5238 | ||||
5239 | // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a | |||
5240 | // class template specialization here, but doing so breaks a lot of code. | |||
5241 | ||||
5242 | // We can't answer whether something is abstract until it has a | |||
5243 | // definition. If it's currently being defined, we'll walk back | |||
5244 | // over all the declarations when we have a full definition. | |||
5245 | const CXXRecordDecl *Def = RD->getDefinition(); | |||
5246 | if (!Def || Def->isBeingDefined()) | |||
5247 | return false; | |||
5248 | ||||
5249 | return RD->isAbstract(); | |||
5250 | } | |||
5251 | ||||
5252 | bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, | |||
5253 | TypeDiagnoser &Diagnoser) { | |||
5254 | if (!isAbstractType(Loc, T)) | |||
5255 | return false; | |||
5256 | ||||
5257 | T = Context.getBaseElementType(T); | |||
5258 | Diagnoser.diagnose(*this, Loc, T); | |||
5259 | DiagnoseAbstractType(T->getAsCXXRecordDecl()); | |||
5260 | return true; | |||
5261 | } | |||
5262 | ||||
5263 | void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { | |||
5264 | // Check if we've already emitted the list of pure virtual functions | |||
5265 | // for this class. | |||
5266 | if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) | |||
5267 | return; | |||
5268 | ||||
5269 | // If the diagnostic is suppressed, don't emit the notes. We're only | |||
5270 | // going to emit them once, so try to attach them to a diagnostic we're | |||
5271 | // actually going to show. | |||
5272 | if (Diags.isLastDiagnosticIgnored()) | |||
5273 | return; | |||
5274 | ||||
5275 | CXXFinalOverriderMap FinalOverriders; | |||
5276 | RD->getFinalOverriders(FinalOverriders); | |||
5277 | ||||
5278 | // Keep a set of seen pure methods so we won't diagnose the same method | |||
5279 | // more than once. | |||
5280 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; | |||
5281 | ||||
5282 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | |||
5283 | MEnd = FinalOverriders.end(); | |||
5284 | M != MEnd; | |||
5285 | ++M) { | |||
5286 | for (OverridingMethods::iterator SO = M->second.begin(), | |||
5287 | SOEnd = M->second.end(); | |||
5288 | SO != SOEnd; ++SO) { | |||
5289 | // C++ [class.abstract]p4: | |||
5290 | // A class is abstract if it contains or inherits at least one | |||
5291 | // pure virtual function for which the final overrider is pure | |||
5292 | // virtual. | |||
5293 | ||||
5294 | // | |||
5295 | if (SO->second.size() != 1) | |||
5296 | continue; | |||
5297 | ||||
5298 | if (!SO->second.front().Method->isPure()) | |||
5299 | continue; | |||
5300 | ||||
5301 | if (!SeenPureMethods.insert(SO->second.front().Method).second) | |||
5302 | continue; | |||
5303 | ||||
5304 | Diag(SO->second.front().Method->getLocation(), | |||
5305 | diag::note_pure_virtual_function) | |||
5306 | << SO->second.front().Method->getDeclName() << RD->getDeclName(); | |||
5307 | } | |||
5308 | } | |||
5309 | ||||
5310 | if (!PureVirtualClassDiagSet) | |||
5311 | PureVirtualClassDiagSet.reset(new RecordDeclSetTy); | |||
5312 | PureVirtualClassDiagSet->insert(RD); | |||
5313 | } | |||
5314 | ||||
5315 | namespace { | |||
5316 | struct AbstractUsageInfo { | |||
5317 | Sema &S; | |||
5318 | CXXRecordDecl *Record; | |||
5319 | CanQualType AbstractType; | |||
5320 | bool Invalid; | |||
5321 | ||||
5322 | AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) | |||
5323 | : S(S), Record(Record), | |||
5324 | AbstractType(S.Context.getCanonicalType( | |||
5325 | S.Context.getTypeDeclType(Record))), | |||
5326 | Invalid(false) {} | |||
5327 | ||||
5328 | void DiagnoseAbstractType() { | |||
5329 | if (Invalid) return; | |||
5330 | S.DiagnoseAbstractType(Record); | |||
5331 | Invalid = true; | |||
5332 | } | |||
5333 | ||||
5334 | void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); | |||
5335 | }; | |||
5336 | ||||
5337 | struct CheckAbstractUsage { | |||
5338 | AbstractUsageInfo &Info; | |||
5339 | const NamedDecl *Ctx; | |||
5340 | ||||
5341 | CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) | |||
5342 | : Info(Info), Ctx(Ctx) {} | |||
5343 | ||||
5344 | void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5345 | switch (TL.getTypeLocClass()) { | |||
5346 | #define ABSTRACT_TYPELOC(CLASS, PARENT) | |||
5347 | #define TYPELOC(CLASS, PARENT) \ | |||
5348 | case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; | |||
5349 | #include "clang/AST/TypeLocNodes.def" | |||
5350 | } | |||
5351 | } | |||
5352 | ||||
5353 | void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5354 | Visit(TL.getReturnLoc(), Sema::AbstractReturnType); | |||
5355 | for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { | |||
5356 | if (!TL.getParam(I)) | |||
5357 | continue; | |||
5358 | ||||
5359 | TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); | |||
5360 | if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); | |||
5361 | } | |||
5362 | } | |||
5363 | ||||
5364 | void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5365 | Visit(TL.getElementLoc(), Sema::AbstractArrayType); | |||
5366 | } | |||
5367 | ||||
5368 | void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5369 | // Visit the type parameters from a permissive context. | |||
5370 | for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { | |||
5371 | TemplateArgumentLoc TAL = TL.getArgLoc(I); | |||
5372 | if (TAL.getArgument().getKind() == TemplateArgument::Type) | |||
5373 | if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) | |||
5374 | Visit(TSI->getTypeLoc(), Sema::AbstractNone); | |||
5375 | // TODO: other template argument types? | |||
5376 | } | |||
5377 | } | |||
5378 | ||||
5379 | // Visit pointee types from a permissive context. | |||
5380 | #define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc (), Sema::AbstractNone); } \ | |||
5381 | void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ | |||
5382 | Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ | |||
5383 | } | |||
5384 | CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5385 | CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5386 | CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5387 | CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5388 | CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5389 | ||||
5390 | /// Handle all the types we haven't given a more specific | |||
5391 | /// implementation for above. | |||
5392 | void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5393 | // Every other kind of type that we haven't called out already | |||
5394 | // that has an inner type is either (1) sugar or (2) contains that | |||
5395 | // inner type in some way as a subobject. | |||
5396 | if (TypeLoc Next = TL.getNextTypeLoc()) | |||
5397 | return Visit(Next, Sel); | |||
5398 | ||||
5399 | // If there's no inner type and we're in a permissive context, | |||
5400 | // don't diagnose. | |||
5401 | if (Sel == Sema::AbstractNone) return; | |||
5402 | ||||
5403 | // Check whether the type matches the abstract type. | |||
5404 | QualType T = TL.getType(); | |||
5405 | if (T->isArrayType()) { | |||
5406 | Sel = Sema::AbstractArrayType; | |||
5407 | T = Info.S.Context.getBaseElementType(T); | |||
5408 | } | |||
5409 | CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); | |||
5410 | if (CT != Info.AbstractType) return; | |||
5411 | ||||
5412 | // It matched; do some magic. | |||
5413 | if (Sel == Sema::AbstractArrayType) { | |||
5414 | Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) | |||
5415 | << T << TL.getSourceRange(); | |||
5416 | } else { | |||
5417 | Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) | |||
5418 | << Sel << T << TL.getSourceRange(); | |||
5419 | } | |||
5420 | Info.DiagnoseAbstractType(); | |||
5421 | } | |||
5422 | }; | |||
5423 | ||||
5424 | void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, | |||
5425 | Sema::AbstractDiagSelID Sel) { | |||
5426 | CheckAbstractUsage(*this, D).Visit(TL, Sel); | |||
5427 | } | |||
5428 | ||||
5429 | } | |||
5430 | ||||
5431 | /// Check for invalid uses of an abstract type in a method declaration. | |||
5432 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | |||
5433 | CXXMethodDecl *MD) { | |||
5434 | // No need to do the check on definitions, which require that | |||
5435 | // the return/param types be complete. | |||
5436 | if (MD->doesThisDeclarationHaveABody()) | |||
5437 | return; | |||
5438 | ||||
5439 | // For safety's sake, just ignore it if we don't have type source | |||
5440 | // information. This should never happen for non-implicit methods, | |||
5441 | // but... | |||
5442 | if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) | |||
5443 | Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); | |||
5444 | } | |||
5445 | ||||
5446 | /// Check for invalid uses of an abstract type within a class definition. | |||
5447 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | |||
5448 | CXXRecordDecl *RD) { | |||
5449 | for (auto *D : RD->decls()) { | |||
5450 | if (D->isImplicit()) continue; | |||
5451 | ||||
5452 | // Methods and method templates. | |||
5453 | if (isa<CXXMethodDecl>(D)) { | |||
5454 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); | |||
5455 | } else if (isa<FunctionTemplateDecl>(D)) { | |||
5456 | FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); | |||
5457 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); | |||
5458 | ||||
5459 | // Fields and static variables. | |||
5460 | } else if (isa<FieldDecl>(D)) { | |||
5461 | FieldDecl *FD = cast<FieldDecl>(D); | |||
5462 | if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) | |||
5463 | Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); | |||
5464 | } else if (isa<VarDecl>(D)) { | |||
5465 | VarDecl *VD = cast<VarDecl>(D); | |||
5466 | if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) | |||
5467 | Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); | |||
5468 | ||||
5469 | // Nested classes and class templates. | |||
5470 | } else if (isa<CXXRecordDecl>(D)) { | |||
5471 | CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); | |||
5472 | } else if (isa<ClassTemplateDecl>(D)) { | |||
5473 | CheckAbstractClassUsage(Info, | |||
5474 | cast<ClassTemplateDecl>(D)->getTemplatedDecl()); | |||
5475 | } | |||
5476 | } | |||
5477 | } | |||
5478 | ||||
5479 | static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { | |||
5480 | Attr *ClassAttr = getDLLAttr(Class); | |||
5481 | if (!ClassAttr) | |||
5482 | return; | |||
5483 | ||||
5484 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5484, __extension__ __PRETTY_FUNCTION__)); | |||
5485 | ||||
5486 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | |||
5487 | ||||
5488 | if (TSK == TSK_ExplicitInstantiationDeclaration) | |||
5489 | // Don't go any further if this is just an explicit instantiation | |||
5490 | // declaration. | |||
5491 | return; | |||
5492 | ||||
5493 | for (Decl *Member : Class->decls()) { | |||
5494 | // Defined static variables that are members of an exported base | |||
5495 | // class must be marked export too. | |||
5496 | auto *VD = dyn_cast<VarDecl>(Member); | |||
5497 | if (VD && Member->getAttr<DLLExportAttr>() && | |||
5498 | VD->getStorageClass() == SC_Static && | |||
5499 | TSK == TSK_ImplicitInstantiation) | |||
5500 | S.MarkVariableReferenced(VD->getLocation(), VD); | |||
5501 | ||||
5502 | auto *MD = dyn_cast<CXXMethodDecl>(Member); | |||
5503 | if (!MD) | |||
5504 | continue; | |||
5505 | ||||
5506 | if (Member->getAttr<DLLExportAttr>()) { | |||
5507 | if (MD->isUserProvided()) { | |||
5508 | // Instantiate non-default class member functions ... | |||
5509 | ||||
5510 | // .. except for certain kinds of template specializations. | |||
5511 | if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) | |||
5512 | continue; | |||
5513 | ||||
5514 | S.MarkFunctionReferenced(Class->getLocation(), MD); | |||
5515 | ||||
5516 | // The function will be passed to the consumer when its definition is | |||
5517 | // encountered. | |||
5518 | } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || | |||
5519 | MD->isCopyAssignmentOperator() || | |||
5520 | MD->isMoveAssignmentOperator()) { | |||
5521 | // Synthesize and instantiate non-trivial implicit methods, explicitly | |||
5522 | // defaulted methods, and the copy and move assignment operators. The | |||
5523 | // latter are exported even if they are trivial, because the address of | |||
5524 | // an operator can be taken and should compare equal across libraries. | |||
5525 | DiagnosticErrorTrap Trap(S.Diags); | |||
5526 | S.MarkFunctionReferenced(Class->getLocation(), MD); | |||
5527 | if (Trap.hasErrorOccurred()) { | |||
5528 | S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) | |||
5529 | << Class->getName() << !S.getLangOpts().CPlusPlus11; | |||
5530 | break; | |||
5531 | } | |||
5532 | ||||
5533 | // There is no later point when we will see the definition of this | |||
5534 | // function, so pass it to the consumer now. | |||
5535 | S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); | |||
5536 | } | |||
5537 | } | |||
5538 | } | |||
5539 | } | |||
5540 | ||||
5541 | static void checkForMultipleExportedDefaultConstructors(Sema &S, | |||
5542 | CXXRecordDecl *Class) { | |||
5543 | // Only the MS ABI has default constructor closures, so we don't need to do | |||
5544 | // this semantic checking anywhere else. | |||
5545 | if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
5546 | return; | |||
5547 | ||||
5548 | CXXConstructorDecl *LastExportedDefaultCtor = nullptr; | |||
5549 | for (Decl *Member : Class->decls()) { | |||
5550 | // Look for exported default constructors. | |||
5551 | auto *CD = dyn_cast<CXXConstructorDecl>(Member); | |||
5552 | if (!CD || !CD->isDefaultConstructor()) | |||
5553 | continue; | |||
5554 | auto *Attr = CD->getAttr<DLLExportAttr>(); | |||
5555 | if (!Attr) | |||
5556 | continue; | |||
5557 | ||||
5558 | // If the class is non-dependent, mark the default arguments as ODR-used so | |||
5559 | // that we can properly codegen the constructor closure. | |||
5560 | if (!Class->isDependentContext()) { | |||
5561 | for (ParmVarDecl *PD : CD->parameters()) { | |||
5562 | (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); | |||
5563 | S.DiscardCleanupsInEvaluationContext(); | |||
5564 | } | |||
5565 | } | |||
5566 | ||||
5567 | if (LastExportedDefaultCtor) { | |||
5568 | S.Diag(LastExportedDefaultCtor->getLocation(), | |||
5569 | diag::err_attribute_dll_ambiguous_default_ctor) | |||
5570 | << Class; | |||
5571 | S.Diag(CD->getLocation(), diag::note_entity_declared_at) | |||
5572 | << CD->getDeclName(); | |||
5573 | return; | |||
5574 | } | |||
5575 | LastExportedDefaultCtor = CD; | |||
5576 | } | |||
5577 | } | |||
5578 | ||||
5579 | /// \brief Check class-level dllimport/dllexport attribute. | |||
5580 | void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { | |||
5581 | Attr *ClassAttr = getDLLAttr(Class); | |||
5582 | ||||
5583 | // MSVC inherits DLL attributes to partial class template specializations. | |||
5584 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { | |||
5585 | if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { | |||
5586 | if (Attr *TemplateAttr = | |||
5587 | getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { | |||
5588 | auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); | |||
5589 | A->setInherited(true); | |||
5590 | ClassAttr = A; | |||
5591 | } | |||
5592 | } | |||
5593 | } | |||
5594 | ||||
5595 | if (!ClassAttr) | |||
5596 | return; | |||
5597 | ||||
5598 | if (!Class->isExternallyVisible()) { | |||
5599 | Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) | |||
5600 | << Class << ClassAttr; | |||
5601 | return; | |||
5602 | } | |||
5603 | ||||
5604 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
5605 | !ClassAttr->isInherited()) { | |||
5606 | // Diagnose dll attributes on members of class with dll attribute. | |||
5607 | for (Decl *Member : Class->decls()) { | |||
5608 | if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) | |||
5609 | continue; | |||
5610 | InheritableAttr *MemberAttr = getDLLAttr(Member); | |||
5611 | if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) | |||
5612 | continue; | |||
5613 | ||||
5614 | Diag(MemberAttr->getLocation(), | |||
5615 | diag::err_attribute_dll_member_of_dll_class) | |||
5616 | << MemberAttr << ClassAttr; | |||
5617 | Diag(ClassAttr->getLocation(), diag::note_previous_attribute); | |||
5618 | Member->setInvalidDecl(); | |||
5619 | } | |||
5620 | } | |||
5621 | ||||
5622 | if (Class->getDescribedClassTemplate()) | |||
5623 | // Don't inherit dll attribute until the template is instantiated. | |||
5624 | return; | |||
5625 | ||||
5626 | // The class is either imported or exported. | |||
5627 | const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; | |||
5628 | ||||
5629 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | |||
5630 | ||||
5631 | // Ignore explicit dllexport on explicit class template instantiation declarations. | |||
5632 | if (ClassExported && !ClassAttr->isInherited() && | |||
5633 | TSK == TSK_ExplicitInstantiationDeclaration) { | |||
5634 | Class->dropAttr<DLLExportAttr>(); | |||
5635 | return; | |||
5636 | } | |||
5637 | ||||
5638 | // Force declaration of implicit members so they can inherit the attribute. | |||
5639 | ForceDeclarationOfImplicitMembers(Class); | |||
5640 | ||||
5641 | // FIXME: MSVC's docs say all bases must be exportable, but this doesn't | |||
5642 | // seem to be true in practice? | |||
5643 | ||||
5644 | for (Decl *Member : Class->decls()) { | |||
5645 | VarDecl *VD = dyn_cast<VarDecl>(Member); | |||
5646 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); | |||
5647 | ||||
5648 | // Only methods and static fields inherit the attributes. | |||
5649 | if (!VD && !MD) | |||
5650 | continue; | |||
5651 | ||||
5652 | if (MD) { | |||
5653 | // Don't process deleted methods. | |||
5654 | if (MD->isDeleted()) | |||
5655 | continue; | |||
5656 | ||||
5657 | if (MD->isInlined()) { | |||
5658 | // MinGW does not import or export inline methods. | |||
5659 | if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
5660 | !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) | |||
5661 | continue; | |||
5662 | ||||
5663 | // MSVC versions before 2015 don't export the move assignment operators | |||
5664 | // and move constructor, so don't attempt to import/export them if | |||
5665 | // we have a definition. | |||
5666 | auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); | |||
5667 | if ((MD->isMoveAssignmentOperator() || | |||
5668 | (Ctor && Ctor->isMoveConstructor())) && | |||
5669 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) | |||
5670 | continue; | |||
5671 | ||||
5672 | // MSVC2015 doesn't export trivial defaulted x-tor but copy assign | |||
5673 | // operator is exported anyway. | |||
5674 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
5675 | (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) | |||
5676 | continue; | |||
5677 | } | |||
5678 | } | |||
5679 | ||||
5680 | if (!cast<NamedDecl>(Member)->isExternallyVisible()) | |||
5681 | continue; | |||
5682 | ||||
5683 | if (!getDLLAttr(Member)) { | |||
5684 | auto *NewAttr = | |||
5685 | cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
5686 | NewAttr->setInherited(true); | |||
5687 | Member->addAttr(NewAttr); | |||
5688 | } | |||
5689 | } | |||
5690 | ||||
5691 | if (ClassExported) | |||
5692 | DelayedDllExportClasses.push_back(Class); | |||
5693 | } | |||
5694 | ||||
5695 | /// \brief Perform propagation of DLL attributes from a derived class to a | |||
5696 | /// templated base class for MS compatibility. | |||
5697 | void Sema::propagateDLLAttrToBaseClassTemplate( | |||
5698 | CXXRecordDecl *Class, Attr *ClassAttr, | |||
5699 | ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { | |||
5700 | if (getDLLAttr( | |||
5701 | BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { | |||
5702 | // If the base class template has a DLL attribute, don't try to change it. | |||
5703 | return; | |||
5704 | } | |||
5705 | ||||
5706 | auto TSK = BaseTemplateSpec->getSpecializationKind(); | |||
5707 | if (!getDLLAttr(BaseTemplateSpec) && | |||
5708 | (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || | |||
5709 | TSK == TSK_ImplicitInstantiation)) { | |||
5710 | // The template hasn't been instantiated yet (or it has, but only as an | |||
5711 | // explicit instantiation declaration or implicit instantiation, which means | |||
5712 | // we haven't codegenned any members yet), so propagate the attribute. | |||
5713 | auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
5714 | NewAttr->setInherited(true); | |||
5715 | BaseTemplateSpec->addAttr(NewAttr); | |||
5716 | ||||
5717 | // If the template is already instantiated, checkDLLAttributeRedeclaration() | |||
5718 | // needs to be run again to work see the new attribute. Otherwise this will | |||
5719 | // get run whenever the template is instantiated. | |||
5720 | if (TSK != TSK_Undeclared) | |||
5721 | checkClassLevelDLLAttribute(BaseTemplateSpec); | |||
5722 | ||||
5723 | return; | |||
5724 | } | |||
5725 | ||||
5726 | if (getDLLAttr(BaseTemplateSpec)) { | |||
5727 | // The template has already been specialized or instantiated with an | |||
5728 | // attribute, explicitly or through propagation. We should not try to change | |||
5729 | // it. | |||
5730 | return; | |||
5731 | } | |||
5732 | ||||
5733 | // The template was previously instantiated or explicitly specialized without | |||
5734 | // a dll attribute, It's too late for us to add an attribute, so warn that | |||
5735 | // this is unsupported. | |||
5736 | Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) | |||
5737 | << BaseTemplateSpec->isExplicitSpecialization(); | |||
5738 | Diag(ClassAttr->getLocation(), diag::note_attribute); | |||
5739 | if (BaseTemplateSpec->isExplicitSpecialization()) { | |||
5740 | Diag(BaseTemplateSpec->getLocation(), | |||
5741 | diag::note_template_class_explicit_specialization_was_here) | |||
5742 | << BaseTemplateSpec; | |||
5743 | } else { | |||
5744 | Diag(BaseTemplateSpec->getPointOfInstantiation(), | |||
5745 | diag::note_template_class_instantiation_was_here) | |||
5746 | << BaseTemplateSpec; | |||
5747 | } | |||
5748 | } | |||
5749 | ||||
5750 | static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, | |||
5751 | SourceLocation DefaultLoc) { | |||
5752 | switch (S.getSpecialMember(MD)) { | |||
5753 | case Sema::CXXDefaultConstructor: | |||
5754 | S.DefineImplicitDefaultConstructor(DefaultLoc, | |||
5755 | cast<CXXConstructorDecl>(MD)); | |||
5756 | break; | |||
5757 | case Sema::CXXCopyConstructor: | |||
5758 | S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | |||
5759 | break; | |||
5760 | case Sema::CXXCopyAssignment: | |||
5761 | S.DefineImplicitCopyAssignment(DefaultLoc, MD); | |||
5762 | break; | |||
5763 | case Sema::CXXDestructor: | |||
5764 | S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); | |||
5765 | break; | |||
5766 | case Sema::CXXMoveConstructor: | |||
5767 | S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | |||
5768 | break; | |||
5769 | case Sema::CXXMoveAssignment: | |||
5770 | S.DefineImplicitMoveAssignment(DefaultLoc, MD); | |||
5771 | break; | |||
5772 | case Sema::CXXInvalid: | |||
5773 | llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5773); | |||
5774 | } | |||
5775 | } | |||
5776 | ||||
5777 | /// Determine whether a type is permitted to be passed or returned in | |||
5778 | /// registers, per C++ [class.temporary]p3. | |||
5779 | static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { | |||
5780 | if (D->isDependentType() || D->isInvalidDecl()) | |||
5781 | return false; | |||
5782 | ||||
5783 | // Per C++ [class.temporary]p3, the relevant condition is: | |||
5784 | // each copy constructor, move constructor, and destructor of X is | |||
5785 | // either trivial or deleted, and X has at least one non-deleted copy | |||
5786 | // or move constructor | |||
5787 | bool HasNonDeletedCopyOrMove = false; | |||
5788 | ||||
5789 | if (D->needsImplicitCopyConstructor() && | |||
5790 | !D->defaultedCopyConstructorIsDeleted()) { | |||
5791 | if (!D->hasTrivialCopyConstructorForCall()) | |||
5792 | return false; | |||
5793 | HasNonDeletedCopyOrMove = true; | |||
5794 | } | |||
5795 | ||||
5796 | if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && | |||
5797 | !D->defaultedMoveConstructorIsDeleted()) { | |||
5798 | if (!D->hasTrivialMoveConstructorForCall()) | |||
5799 | return false; | |||
5800 | HasNonDeletedCopyOrMove = true; | |||
5801 | } | |||
5802 | ||||
5803 | if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && | |||
5804 | !D->hasTrivialDestructorForCall()) | |||
5805 | return false; | |||
5806 | ||||
5807 | for (const CXXMethodDecl *MD : D->methods()) { | |||
5808 | if (MD->isDeleted()) | |||
5809 | continue; | |||
5810 | ||||
5811 | auto *CD = dyn_cast<CXXConstructorDecl>(MD); | |||
5812 | if (CD && CD->isCopyOrMoveConstructor()) | |||
5813 | HasNonDeletedCopyOrMove = true; | |||
5814 | else if (!isa<CXXDestructorDecl>(MD)) | |||
5815 | continue; | |||
5816 | ||||
5817 | if (!MD->isTrivialForCall()) | |||
5818 | return false; | |||
5819 | } | |||
5820 | ||||
5821 | return HasNonDeletedCopyOrMove; | |||
5822 | } | |||
5823 | ||||
5824 | /// \brief Perform semantic checks on a class definition that has been | |||
5825 | /// completing, introducing implicitly-declared members, checking for | |||
5826 | /// abstract types, etc. | |||
5827 | void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { | |||
5828 | if (!Record) | |||
5829 | return; | |||
5830 | ||||
5831 | if (Record->isAbstract() && !Record->isInvalidDecl()) { | |||
5832 | AbstractUsageInfo Info(*this, Record); | |||
5833 | CheckAbstractClassUsage(Info, Record); | |||
5834 | } | |||
5835 | ||||
5836 | // If this is not an aggregate type and has no user-declared constructor, | |||
5837 | // complain about any non-static data members of reference or const scalar | |||
5838 | // type, since they will never get initializers. | |||
5839 | if (!Record->isInvalidDecl() && !Record->isDependentType() && | |||
5840 | !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && | |||
5841 | !Record->isLambda()) { | |||
5842 | bool Complained = false; | |||
5843 | for (const auto *F : Record->fields()) { | |||
5844 | if (F->hasInClassInitializer() || F->isUnnamedBitfield()) | |||
5845 | continue; | |||
5846 | ||||
5847 | if (F->getType()->isReferenceType() || | |||
5848 | (F->getType().isConstQualified() && F->getType()->isScalarType())) { | |||
5849 | if (!Complained) { | |||
5850 | Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) | |||
5851 | << Record->getTagKind() << Record; | |||
5852 | Complained = true; | |||
5853 | } | |||
5854 | ||||
5855 | Diag(F->getLocation(), diag::note_refconst_member_not_initialized) | |||
5856 | << F->getType()->isReferenceType() | |||
5857 | << F->getDeclName(); | |||
5858 | } | |||
5859 | } | |||
5860 | } | |||
5861 | ||||
5862 | if (Record->getIdentifier()) { | |||
5863 | // C++ [class.mem]p13: | |||
5864 | // If T is the name of a class, then each of the following shall have a | |||
5865 | // name different from T: | |||
5866 | // - every member of every anonymous union that is a member of class T. | |||
5867 | // | |||
5868 | // C++ [class.mem]p14: | |||
5869 | // In addition, if class T has a user-declared constructor (12.1), every | |||
5870 | // non-static data member of class T shall have a name different from T. | |||
5871 | DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); | |||
5872 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; | |||
5873 | ++I) { | |||
5874 | NamedDecl *D = *I; | |||
5875 | if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || | |||
5876 | isa<IndirectFieldDecl>(D)) { | |||
5877 | Diag(D->getLocation(), diag::err_member_name_of_class) | |||
5878 | << D->getDeclName(); | |||
5879 | break; | |||
5880 | } | |||
5881 | } | |||
5882 | } | |||
5883 | ||||
5884 | // Warn if the class has virtual methods but non-virtual public destructor. | |||
5885 | if (Record->isPolymorphic() && !Record->isDependentType()) { | |||
5886 | CXXDestructorDecl *dtor = Record->getDestructor(); | |||
5887 | if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && | |||
5888 | !Record->hasAttr<FinalAttr>()) | |||
5889 | Diag(dtor ? dtor->getLocation() : Record->getLocation(), | |||
5890 | diag::warn_non_virtual_dtor) << Context.getRecordType(Record); | |||
5891 | } | |||
5892 | ||||
5893 | if (Record->isAbstract()) { | |||
5894 | if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { | |||
5895 | Diag(Record->getLocation(), diag::warn_abstract_final_class) | |||
5896 | << FA->isSpelledAsSealed(); | |||
5897 | DiagnoseAbstractType(Record); | |||
5898 | } | |||
5899 | } | |||
5900 | ||||
5901 | // Set HasTrivialSpecialMemberForCall if the record has attribute | |||
5902 | // "trivial_abi". | |||
5903 | bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); | |||
5904 | ||||
5905 | if (HasTrivialABI) | |||
5906 | Record->setHasTrivialSpecialMemberForCall(); | |||
5907 | ||||
5908 | bool HasMethodWithOverrideControl = false, | |||
5909 | HasOverridingMethodWithoutOverrideControl = false; | |||
5910 | if (!Record->isDependentType()) { | |||
5911 | for (auto *M : Record->methods()) { | |||
5912 | // See if a method overloads virtual methods in a base | |||
5913 | // class without overriding any. | |||
5914 | if (!M->isStatic()) | |||
5915 | DiagnoseHiddenVirtualMethods(M); | |||
5916 | if (M->hasAttr<OverrideAttr>()) | |||
5917 | HasMethodWithOverrideControl = true; | |||
5918 | else if (M->size_overridden_methods() > 0) | |||
5919 | HasOverridingMethodWithoutOverrideControl = true; | |||
5920 | // Check whether the explicitly-defaulted special members are valid. | |||
5921 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) | |||
5922 | CheckExplicitlyDefaultedSpecialMember(M); | |||
5923 | ||||
5924 | // For an explicitly defaulted or deleted special member, we defer | |||
5925 | // determining triviality until the class is complete. That time is now! | |||
5926 | CXXSpecialMember CSM = getSpecialMember(M); | |||
5927 | if (!M->isImplicit() && !M->isUserProvided()) { | |||
5928 | if (CSM != CXXInvalid) { | |||
5929 | M->setTrivial(SpecialMemberIsTrivial(M, CSM)); | |||
5930 | // Inform the class that we've finished declaring this member. | |||
5931 | Record->finishedDefaultedOrDeletedMember(M); | |||
5932 | M->setTrivialForCall( | |||
5933 | HasTrivialABI || | |||
5934 | SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); | |||
5935 | Record->setTrivialForCallFlags(M); | |||
5936 | } | |||
5937 | } | |||
5938 | ||||
5939 | // Set triviality for the purpose of calls if this is a user-provided | |||
5940 | // copy/move constructor or destructor. | |||
5941 | if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || | |||
5942 | CSM == CXXDestructor) && M->isUserProvided()) { | |||
5943 | M->setTrivialForCall(HasTrivialABI); | |||
5944 | Record->setTrivialForCallFlags(M); | |||
5945 | } | |||
5946 | ||||
5947 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && | |||
5948 | M->hasAttr<DLLExportAttr>()) { | |||
5949 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
5950 | M->isTrivial() && | |||
5951 | (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || | |||
5952 | CSM == CXXDestructor)) | |||
5953 | M->dropAttr<DLLExportAttr>(); | |||
5954 | ||||
5955 | if (M->hasAttr<DLLExportAttr>()) { | |||
5956 | DefineImplicitSpecialMember(*this, M, M->getLocation()); | |||
5957 | ActOnFinishInlineFunctionDef(M); | |||
5958 | } | |||
5959 | } | |||
5960 | } | |||
5961 | } | |||
5962 | ||||
5963 | if (HasMethodWithOverrideControl && | |||
5964 | HasOverridingMethodWithoutOverrideControl) { | |||
5965 | // At least one method has the 'override' control declared. | |||
5966 | // Diagnose all other overridden methods which do not have 'override' specified on them. | |||
5967 | for (auto *M : Record->methods()) | |||
5968 | DiagnoseAbsenceOfOverrideControl(M); | |||
5969 | } | |||
5970 | ||||
5971 | // ms_struct is a request to use the same ABI rules as MSVC. Check | |||
5972 | // whether this class uses any C++ features that are implemented | |||
5973 | // completely differently in MSVC, and if so, emit a diagnostic. | |||
5974 | // That diagnostic defaults to an error, but we allow projects to | |||
5975 | // map it down to a warning (or ignore it). It's a fairly common | |||
5976 | // practice among users of the ms_struct pragma to mass-annotate | |||
5977 | // headers, sweeping up a bunch of types that the project doesn't | |||
5978 | // really rely on MSVC-compatible layout for. We must therefore | |||
5979 | // support "ms_struct except for C++ stuff" as a secondary ABI. | |||
5980 | if (Record->isMsStruct(Context) && | |||
5981 | (Record->isPolymorphic() || Record->getNumBases())) { | |||
5982 | Diag(Record->getLocation(), diag::warn_cxx_ms_struct); | |||
5983 | } | |||
5984 | ||||
5985 | checkClassLevelDLLAttribute(Record); | |||
5986 | ||||
5987 | Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); | |||
5988 | } | |||
5989 | ||||
5990 | /// Look up the special member function that would be called by a special | |||
5991 | /// member function for a subobject of class type. | |||
5992 | /// | |||
5993 | /// \param Class The class type of the subobject. | |||
5994 | /// \param CSM The kind of special member function. | |||
5995 | /// \param FieldQuals If the subobject is a field, its cv-qualifiers. | |||
5996 | /// \param ConstRHS True if this is a copy operation with a const object | |||
5997 | /// on its RHS, that is, if the argument to the outer special member | |||
5998 | /// function is 'const' and this is not a field marked 'mutable'. | |||
5999 | static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( | |||
6000 | Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, | |||
6001 | unsigned FieldQuals, bool ConstRHS) { | |||
6002 | unsigned LHSQuals = 0; | |||
6003 | if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) | |||
6004 | LHSQuals = FieldQuals; | |||
6005 | ||||
6006 | unsigned RHSQuals = FieldQuals; | |||
6007 | if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) | |||
6008 | RHSQuals = 0; | |||
6009 | else if (ConstRHS) | |||
6010 | RHSQuals |= Qualifiers::Const; | |||
6011 | ||||
6012 | return S.LookupSpecialMember(Class, CSM, | |||
6013 | RHSQuals & Qualifiers::Const, | |||
6014 | RHSQuals & Qualifiers::Volatile, | |||
6015 | false, | |||
6016 | LHSQuals & Qualifiers::Const, | |||
6017 | LHSQuals & Qualifiers::Volatile); | |||
6018 | } | |||
6019 | ||||
6020 | class Sema::InheritedConstructorInfo { | |||
6021 | Sema &S; | |||
6022 | SourceLocation UseLoc; | |||
6023 | ||||
6024 | /// A mapping from the base classes through which the constructor was | |||
6025 | /// inherited to the using shadow declaration in that base class (or a null | |||
6026 | /// pointer if the constructor was declared in that base class). | |||
6027 | llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> | |||
6028 | InheritedFromBases; | |||
6029 | ||||
6030 | public: | |||
6031 | InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, | |||
6032 | ConstructorUsingShadowDecl *Shadow) | |||
6033 | : S(S), UseLoc(UseLoc) { | |||
6034 | bool DiagnosedMultipleConstructedBases = false; | |||
6035 | CXXRecordDecl *ConstructedBase = nullptr; | |||
6036 | UsingDecl *ConstructedBaseUsing = nullptr; | |||
6037 | ||||
6038 | // Find the set of such base class subobjects and check that there's a | |||
6039 | // unique constructed subobject. | |||
6040 | for (auto *D : Shadow->redecls()) { | |||
6041 | auto *DShadow = cast<ConstructorUsingShadowDecl>(D); | |||
6042 | auto *DNominatedBase = DShadow->getNominatedBaseClass(); | |||
6043 | auto *DConstructedBase = DShadow->getConstructedBaseClass(); | |||
6044 | ||||
6045 | InheritedFromBases.insert( | |||
6046 | std::make_pair(DNominatedBase->getCanonicalDecl(), | |||
6047 | DShadow->getNominatedBaseClassShadowDecl())); | |||
6048 | if (DShadow->constructsVirtualBase()) | |||
6049 | InheritedFromBases.insert( | |||
6050 | std::make_pair(DConstructedBase->getCanonicalDecl(), | |||
6051 | DShadow->getConstructedBaseClassShadowDecl())); | |||
6052 | else | |||
6053 | assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase ) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6053, __extension__ __PRETTY_FUNCTION__)); | |||
6054 | ||||
6055 | // [class.inhctor.init]p2: | |||
6056 | // If the constructor was inherited from multiple base class subobjects | |||
6057 | // of type B, the program is ill-formed. | |||
6058 | if (!ConstructedBase) { | |||
6059 | ConstructedBase = DConstructedBase; | |||
6060 | ConstructedBaseUsing = D->getUsingDecl(); | |||
6061 | } else if (ConstructedBase != DConstructedBase && | |||
6062 | !Shadow->isInvalidDecl()) { | |||
6063 | if (!DiagnosedMultipleConstructedBases) { | |||
6064 | S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) | |||
6065 | << Shadow->getTargetDecl(); | |||
6066 | S.Diag(ConstructedBaseUsing->getLocation(), | |||
6067 | diag::note_ambiguous_inherited_constructor_using) | |||
6068 | << ConstructedBase; | |||
6069 | DiagnosedMultipleConstructedBases = true; | |||
6070 | } | |||
6071 | S.Diag(D->getUsingDecl()->getLocation(), | |||
6072 | diag::note_ambiguous_inherited_constructor_using) | |||
6073 | << DConstructedBase; | |||
6074 | } | |||
6075 | } | |||
6076 | ||||
6077 | if (DiagnosedMultipleConstructedBases) | |||
6078 | Shadow->setInvalidDecl(); | |||
6079 | } | |||
6080 | ||||
6081 | /// Find the constructor to use for inherited construction of a base class, | |||
6082 | /// and whether that base class constructor inherits the constructor from a | |||
6083 | /// virtual base class (in which case it won't actually invoke it). | |||
6084 | std::pair<CXXConstructorDecl *, bool> | |||
6085 | findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { | |||
6086 | auto It = InheritedFromBases.find(Base->getCanonicalDecl()); | |||
6087 | if (It == InheritedFromBases.end()) | |||
6088 | return std::make_pair(nullptr, false); | |||
6089 | ||||
6090 | // This is an intermediary class. | |||
6091 | if (It->second) | |||
6092 | return std::make_pair( | |||
6093 | S.findInheritingConstructor(UseLoc, Ctor, It->second), | |||
6094 | It->second->constructsVirtualBase()); | |||
6095 | ||||
6096 | // This is the base class from which the constructor was inherited. | |||
6097 | return std::make_pair(Ctor, false); | |||
6098 | } | |||
6099 | }; | |||
6100 | ||||
6101 | /// Is the special member function which would be selected to perform the | |||
6102 | /// specified operation on the specified class type a constexpr constructor? | |||
6103 | static bool | |||
6104 | specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, | |||
6105 | Sema::CXXSpecialMember CSM, unsigned Quals, | |||
6106 | bool ConstRHS, | |||
6107 | CXXConstructorDecl *InheritedCtor = nullptr, | |||
6108 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | |||
6109 | // If we're inheriting a constructor, see if we need to call it for this base | |||
6110 | // class. | |||
6111 | if (InheritedCtor) { | |||
6112 | assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor ) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6112, __extension__ __PRETTY_FUNCTION__)); | |||
6113 | auto BaseCtor = | |||
6114 | Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; | |||
6115 | if (BaseCtor) | |||
6116 | return BaseCtor->isConstexpr(); | |||
6117 | } | |||
6118 | ||||
6119 | if (CSM == Sema::CXXDefaultConstructor) | |||
6120 | return ClassDecl->hasConstexprDefaultConstructor(); | |||
6121 | ||||
6122 | Sema::SpecialMemberOverloadResult SMOR = | |||
6123 | lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); | |||
6124 | if (!SMOR.getMethod()) | |||
6125 | // A constructor we wouldn't select can't be "involved in initializing" | |||
6126 | // anything. | |||
6127 | return true; | |||
6128 | return SMOR.getMethod()->isConstexpr(); | |||
6129 | } | |||
6130 | ||||
6131 | /// Determine whether the specified special member function would be constexpr | |||
6132 | /// if it were implicitly defined. | |||
6133 | static bool defaultedSpecialMemberIsConstexpr( | |||
6134 | Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, | |||
6135 | bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, | |||
6136 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | |||
6137 | if (!S.getLangOpts().CPlusPlus11) | |||
6138 | return false; | |||
6139 | ||||
6140 | // C++11 [dcl.constexpr]p4: | |||
6141 | // In the definition of a constexpr constructor [...] | |||
6142 | bool Ctor = true; | |||
6143 | switch (CSM) { | |||
6144 | case Sema::CXXDefaultConstructor: | |||
6145 | if (Inherited) | |||
6146 | break; | |||
6147 | // Since default constructor lookup is essentially trivial (and cannot | |||
6148 | // involve, for instance, template instantiation), we compute whether a | |||
6149 | // defaulted default constructor is constexpr directly within CXXRecordDecl. | |||
6150 | // | |||
6151 | // This is important for performance; we need to know whether the default | |||
6152 | // constructor is constexpr to determine whether the type is a literal type. | |||
6153 | return ClassDecl->defaultedDefaultConstructorIsConstexpr(); | |||
6154 | ||||
6155 | case Sema::CXXCopyConstructor: | |||
6156 | case Sema::CXXMoveConstructor: | |||
6157 | // For copy or move constructors, we need to perform overload resolution. | |||
6158 | break; | |||
6159 | ||||
6160 | case Sema::CXXCopyAssignment: | |||
6161 | case Sema::CXXMoveAssignment: | |||
6162 | if (!S.getLangOpts().CPlusPlus14) | |||
6163 | return false; | |||
6164 | // In C++1y, we need to perform overload resolution. | |||
6165 | Ctor = false; | |||
6166 | break; | |||
6167 | ||||
6168 | case Sema::CXXDestructor: | |||
6169 | case Sema::CXXInvalid: | |||
6170 | return false; | |||
6171 | } | |||
6172 | ||||
6173 | // -- if the class is a non-empty union, or for each non-empty anonymous | |||
6174 | // union member of a non-union class, exactly one non-static data member | |||
6175 | // shall be initialized; [DR1359] | |||
6176 | // | |||
6177 | // If we squint, this is guaranteed, since exactly one non-static data member | |||
6178 | // will be initialized (if the constructor isn't deleted), we just don't know | |||
6179 | // which one. | |||
6180 | if (Ctor && ClassDecl->isUnion()) | |||
6181 | return CSM == Sema::CXXDefaultConstructor | |||
6182 | ? ClassDecl->hasInClassInitializer() || | |||
6183 | !ClassDecl->hasVariantMembers() | |||
6184 | : true; | |||
6185 | ||||
6186 | // -- the class shall not have any virtual base classes; | |||
6187 | if (Ctor && ClassDecl->getNumVBases()) | |||
6188 | return false; | |||
6189 | ||||
6190 | // C++1y [class.copy]p26: | |||
6191 | // -- [the class] is a literal type, and | |||
6192 | if (!Ctor && !ClassDecl->isLiteral()) | |||
6193 | return false; | |||
6194 | ||||
6195 | // -- every constructor involved in initializing [...] base class | |||
6196 | // sub-objects shall be a constexpr constructor; | |||
6197 | // -- the assignment operator selected to copy/move each direct base | |||
6198 | // class is a constexpr function, and | |||
6199 | for (const auto &B : ClassDecl->bases()) { | |||
6200 | const RecordType *BaseType = B.getType()->getAs<RecordType>(); | |||
6201 | if (!BaseType) continue; | |||
6202 | ||||
6203 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); | |||
6204 | if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, | |||
6205 | InheritedCtor, Inherited)) | |||
6206 | return false; | |||
6207 | } | |||
6208 | ||||
6209 | // -- every constructor involved in initializing non-static data members | |||
6210 | // [...] shall be a constexpr constructor; | |||
6211 | // -- every non-static data member and base class sub-object shall be | |||
6212 | // initialized | |||
6213 | // -- for each non-static data member of X that is of class type (or array | |||
6214 | // thereof), the assignment operator selected to copy/move that member is | |||
6215 | // a constexpr function | |||
6216 | for (const auto *F : ClassDecl->fields()) { | |||
6217 | if (F->isInvalidDecl()) | |||
6218 | continue; | |||
6219 | if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) | |||
6220 | continue; | |||
6221 | QualType BaseType = S.Context.getBaseElementType(F->getType()); | |||
6222 | if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { | |||
6223 | CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
6224 | if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, | |||
6225 | BaseType.getCVRQualifiers(), | |||
6226 | ConstArg && !F->isMutable())) | |||
6227 | return false; | |||
6228 | } else if (CSM == Sema::CXXDefaultConstructor) { | |||
6229 | return false; | |||
6230 | } | |||
6231 | } | |||
6232 | ||||
6233 | // All OK, it's constexpr! | |||
6234 | return true; | |||
6235 | } | |||
6236 | ||||
6237 | static Sema::ImplicitExceptionSpecification | |||
6238 | ComputeDefaultedSpecialMemberExceptionSpec( | |||
6239 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
6240 | Sema::InheritedConstructorInfo *ICI); | |||
6241 | ||||
6242 | static Sema::ImplicitExceptionSpecification | |||
6243 | computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { | |||
6244 | auto CSM = S.getSpecialMember(MD); | |||
6245 | if (CSM != Sema::CXXInvalid) | |||
6246 | return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); | |||
6247 | ||||
6248 | auto *CD = cast<CXXConstructorDecl>(MD); | |||
6249 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6250, __extension__ __PRETTY_FUNCTION__)) | |||
6250 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6250, __extension__ __PRETTY_FUNCTION__)); | |||
6251 | Sema::InheritedConstructorInfo ICI( | |||
6252 | S, Loc, CD->getInheritedConstructor().getShadowDecl()); | |||
6253 | return ComputeDefaultedSpecialMemberExceptionSpec( | |||
6254 | S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); | |||
6255 | } | |||
6256 | ||||
6257 | static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, | |||
6258 | CXXMethodDecl *MD) { | |||
6259 | FunctionProtoType::ExtProtoInfo EPI; | |||
6260 | ||||
6261 | // Build an exception specification pointing back at this member. | |||
6262 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
6263 | EPI.ExceptionSpec.SourceDecl = MD; | |||
6264 | ||||
6265 | // Set the calling convention to the default for C++ instance methods. | |||
6266 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv( | |||
6267 | S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, | |||
6268 | /*IsCXXMethod=*/true)); | |||
6269 | return EPI; | |||
6270 | } | |||
6271 | ||||
6272 | void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { | |||
6273 | const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); | |||
6274 | if (FPT->getExceptionSpecType() != EST_Unevaluated) | |||
6275 | return; | |||
6276 | ||||
6277 | // Evaluate the exception specification. | |||
6278 | auto IES = computeImplicitExceptionSpec(*this, Loc, MD); | |||
6279 | auto ESI = IES.getExceptionSpec(); | |||
6280 | ||||
6281 | // Update the type of the special member to use it. | |||
6282 | UpdateExceptionSpec(MD, ESI); | |||
6283 | ||||
6284 | // A user-provided destructor can be defined outside the class. When that | |||
6285 | // happens, be sure to update the exception specification on both | |||
6286 | // declarations. | |||
6287 | const FunctionProtoType *CanonicalFPT = | |||
6288 | MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); | |||
6289 | if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) | |||
6290 | UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); | |||
6291 | } | |||
6292 | ||||
6293 | void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { | |||
6294 | CXXRecordDecl *RD = MD->getParent(); | |||
6295 | CXXSpecialMember CSM = getSpecialMember(MD); | |||
6296 | ||||
6297 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6298, __extension__ __PRETTY_FUNCTION__)) | |||
6298 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6298, __extension__ __PRETTY_FUNCTION__)); | |||
6299 | ||||
6300 | // Whether this was the first-declared instance of the constructor. | |||
6301 | // This affects whether we implicitly add an exception spec and constexpr. | |||
6302 | bool First = MD == MD->getCanonicalDecl(); | |||
6303 | ||||
6304 | bool HadError = false; | |||
6305 | ||||
6306 | // C++11 [dcl.fct.def.default]p1: | |||
6307 | // A function that is explicitly defaulted shall | |||
6308 | // -- be a special member function (checked elsewhere), | |||
6309 | // -- have the same type (except for ref-qualifiers, and except that a | |||
6310 | // copy operation can take a non-const reference) as an implicit | |||
6311 | // declaration, and | |||
6312 | // -- not have default arguments. | |||
6313 | unsigned ExpectedParams = 1; | |||
6314 | if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) | |||
6315 | ExpectedParams = 0; | |||
6316 | if (MD->getNumParams() != ExpectedParams) { | |||
6317 | // This also checks for default arguments: a copy or move constructor with a | |||
6318 | // default argument is classified as a default constructor, and assignment | |||
6319 | // operations and destructors can't have default arguments. | |||
6320 | Diag(MD->getLocation(), diag::err_defaulted_special_member_params) | |||
6321 | << CSM << MD->getSourceRange(); | |||
6322 | HadError = true; | |||
6323 | } else if (MD->isVariadic()) { | |||
6324 | Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) | |||
6325 | << CSM << MD->getSourceRange(); | |||
6326 | HadError = true; | |||
6327 | } | |||
6328 | ||||
6329 | const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); | |||
6330 | ||||
6331 | bool CanHaveConstParam = false; | |||
6332 | if (CSM == CXXCopyConstructor) | |||
6333 | CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); | |||
6334 | else if (CSM == CXXCopyAssignment) | |||
6335 | CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); | |||
6336 | ||||
6337 | QualType ReturnType = Context.VoidTy; | |||
6338 | if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { | |||
6339 | // Check for return type matching. | |||
6340 | ReturnType = Type->getReturnType(); | |||
6341 | QualType ExpectedReturnType = | |||
6342 | Context.getLValueReferenceType(Context.getTypeDeclType(RD)); | |||
6343 | if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { | |||
6344 | Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) | |||
6345 | << (CSM == CXXMoveAssignment) << ExpectedReturnType; | |||
6346 | HadError = true; | |||
6347 | } | |||
6348 | ||||
6349 | // A defaulted special member cannot have cv-qualifiers. | |||
6350 | if (Type->getTypeQuals()) { | |||
6351 | Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) | |||
6352 | << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; | |||
6353 | HadError = true; | |||
6354 | } | |||
6355 | } | |||
6356 | ||||
6357 | // Check for parameter type matching. | |||
6358 | QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); | |||
6359 | bool HasConstParam = false; | |||
6360 | if (ExpectedParams && ArgType->isReferenceType()) { | |||
6361 | // Argument must be reference to possibly-const T. | |||
6362 | QualType ReferentType = ArgType->getPointeeType(); | |||
6363 | HasConstParam = ReferentType.isConstQualified(); | |||
6364 | ||||
6365 | if (ReferentType.isVolatileQualified()) { | |||
6366 | Diag(MD->getLocation(), | |||
6367 | diag::err_defaulted_special_member_volatile_param) << CSM; | |||
6368 | HadError = true; | |||
6369 | } | |||
6370 | ||||
6371 | if (HasConstParam && !CanHaveConstParam) { | |||
6372 | if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { | |||
6373 | Diag(MD->getLocation(), | |||
6374 | diag::err_defaulted_special_member_copy_const_param) | |||
6375 | << (CSM == CXXCopyAssignment); | |||
6376 | // FIXME: Explain why this special member can't be const. | |||
6377 | } else { | |||
6378 | Diag(MD->getLocation(), | |||
6379 | diag::err_defaulted_special_member_move_const_param) | |||
6380 | << (CSM == CXXMoveAssignment); | |||
6381 | } | |||
6382 | HadError = true; | |||
6383 | } | |||
6384 | } else if (ExpectedParams) { | |||
6385 | // A copy assignment operator can take its argument by value, but a | |||
6386 | // defaulted one cannot. | |||
6387 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6387, __extension__ __PRETTY_FUNCTION__)); | |||
6388 | Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); | |||
6389 | HadError = true; | |||
6390 | } | |||
6391 | ||||
6392 | // C++11 [dcl.fct.def.default]p2: | |||
6393 | // An explicitly-defaulted function may be declared constexpr only if it | |||
6394 | // would have been implicitly declared as constexpr, | |||
6395 | // Do not apply this rule to members of class templates, since core issue 1358 | |||
6396 | // makes such functions always instantiate to constexpr functions. For | |||
6397 | // functions which cannot be constexpr (for non-constructors in C++11 and for | |||
6398 | // destructors in C++1y), this is checked elsewhere. | |||
6399 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, | |||
6400 | HasConstParam); | |||
6401 | if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) | |||
6402 | : isa<CXXConstructorDecl>(MD)) && | |||
6403 | MD->isConstexpr() && !Constexpr && | |||
6404 | MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { | |||
6405 | Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; | |||
6406 | // FIXME: Explain why the special member can't be constexpr. | |||
6407 | HadError = true; | |||
6408 | } | |||
6409 | ||||
6410 | // and may have an explicit exception-specification only if it is compatible | |||
6411 | // with the exception-specification on the implicit declaration. | |||
6412 | if (Type->hasExceptionSpec()) { | |||
6413 | // Delay the check if this is the first declaration of the special member, | |||
6414 | // since we may not have parsed some necessary in-class initializers yet. | |||
6415 | if (First) { | |||
6416 | // If the exception specification needs to be instantiated, do so now, | |||
6417 | // before we clobber it with an EST_Unevaluated specification below. | |||
6418 | if (Type->getExceptionSpecType() == EST_Uninstantiated) { | |||
6419 | InstantiateExceptionSpec(MD->getLocStart(), MD); | |||
6420 | Type = MD->getType()->getAs<FunctionProtoType>(); | |||
6421 | } | |||
6422 | DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); | |||
6423 | } else | |||
6424 | CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); | |||
6425 | } | |||
6426 | ||||
6427 | // If a function is explicitly defaulted on its first declaration, | |||
6428 | if (First) { | |||
6429 | // -- it is implicitly considered to be constexpr if the implicit | |||
6430 | // definition would be, | |||
6431 | MD->setConstexpr(Constexpr); | |||
6432 | ||||
6433 | // -- it is implicitly considered to have the same exception-specification | |||
6434 | // as if it had been implicitly declared, | |||
6435 | FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); | |||
6436 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
6437 | EPI.ExceptionSpec.SourceDecl = MD; | |||
6438 | MD->setType(Context.getFunctionType(ReturnType, | |||
6439 | llvm::makeArrayRef(&ArgType, | |||
6440 | ExpectedParams), | |||
6441 | EPI)); | |||
6442 | } | |||
6443 | ||||
6444 | if (ShouldDeleteSpecialMember(MD, CSM)) { | |||
6445 | if (First) { | |||
6446 | SetDeclDeleted(MD, MD->getLocation()); | |||
6447 | } else { | |||
6448 | // C++11 [dcl.fct.def.default]p4: | |||
6449 | // [For a] user-provided explicitly-defaulted function [...] if such a | |||
6450 | // function is implicitly defined as deleted, the program is ill-formed. | |||
6451 | Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; | |||
6452 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | |||
6453 | HadError = true; | |||
6454 | } | |||
6455 | } | |||
6456 | ||||
6457 | if (HadError) | |||
6458 | MD->setInvalidDecl(); | |||
6459 | } | |||
6460 | ||||
6461 | /// Check whether the exception specification provided for an | |||
6462 | /// explicitly-defaulted special member matches the exception specification | |||
6463 | /// that would have been generated for an implicit special member, per | |||
6464 | /// C++11 [dcl.fct.def.default]p2. | |||
6465 | void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( | |||
6466 | CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { | |||
6467 | // If the exception specification was explicitly specified but hadn't been | |||
6468 | // parsed when the method was defaulted, grab it now. | |||
6469 | if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) | |||
6470 | SpecifiedType = | |||
6471 | MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); | |||
6472 | ||||
6473 | // Compute the implicit exception specification. | |||
6474 | CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, | |||
6475 | /*IsCXXMethod=*/true); | |||
6476 | FunctionProtoType::ExtProtoInfo EPI(CC); | |||
6477 | auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); | |||
6478 | EPI.ExceptionSpec = IES.getExceptionSpec(); | |||
6479 | const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( | |||
6480 | Context.getFunctionType(Context.VoidTy, None, EPI)); | |||
6481 | ||||
6482 | // Ensure that it matches. | |||
6483 | CheckEquivalentExceptionSpec( | |||
6484 | PDiag(diag::err_incorrect_defaulted_exception_spec) | |||
6485 | << getSpecialMember(MD), PDiag(), | |||
6486 | ImplicitType, SourceLocation(), | |||
6487 | SpecifiedType, MD->getLocation()); | |||
6488 | } | |||
6489 | ||||
6490 | void Sema::CheckDelayedMemberExceptionSpecs() { | |||
6491 | decltype(DelayedExceptionSpecChecks) Checks; | |||
6492 | decltype(DelayedDefaultedMemberExceptionSpecs) Specs; | |||
6493 | ||||
6494 | std::swap(Checks, DelayedExceptionSpecChecks); | |||
6495 | std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); | |||
6496 | ||||
6497 | // Perform any deferred checking of exception specifications for virtual | |||
6498 | // destructors. | |||
6499 | for (auto &Check : Checks) | |||
6500 | CheckOverridingFunctionExceptionSpec(Check.first, Check.second); | |||
6501 | ||||
6502 | // Check that any explicitly-defaulted methods have exception specifications | |||
6503 | // compatible with their implicit exception specifications. | |||
6504 | for (auto &Spec : Specs) | |||
6505 | CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); | |||
6506 | } | |||
6507 | ||||
6508 | namespace { | |||
6509 | /// CRTP base class for visiting operations performed by a special member | |||
6510 | /// function (or inherited constructor). | |||
6511 | template<typename Derived> | |||
6512 | struct SpecialMemberVisitor { | |||
6513 | Sema &S; | |||
6514 | CXXMethodDecl *MD; | |||
6515 | Sema::CXXSpecialMember CSM; | |||
6516 | Sema::InheritedConstructorInfo *ICI; | |||
6517 | ||||
6518 | // Properties of the special member, computed for convenience. | |||
6519 | bool IsConstructor = false, IsAssignment = false, ConstArg = false; | |||
6520 | ||||
6521 | SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
6522 | Sema::InheritedConstructorInfo *ICI) | |||
6523 | : S(S), MD(MD), CSM(CSM), ICI(ICI) { | |||
6524 | switch (CSM) { | |||
6525 | case Sema::CXXDefaultConstructor: | |||
6526 | case Sema::CXXCopyConstructor: | |||
6527 | case Sema::CXXMoveConstructor: | |||
6528 | IsConstructor = true; | |||
6529 | break; | |||
6530 | case Sema::CXXCopyAssignment: | |||
6531 | case Sema::CXXMoveAssignment: | |||
6532 | IsAssignment = true; | |||
6533 | break; | |||
6534 | case Sema::CXXDestructor: | |||
6535 | break; | |||
6536 | case Sema::CXXInvalid: | |||
6537 | llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6537); | |||
6538 | } | |||
6539 | ||||
6540 | if (MD->getNumParams()) { | |||
6541 | if (const ReferenceType *RT = | |||
6542 | MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) | |||
6543 | ConstArg = RT->getPointeeType().isConstQualified(); | |||
6544 | } | |||
6545 | } | |||
6546 | ||||
6547 | Derived &getDerived() { return static_cast<Derived&>(*this); } | |||
6548 | ||||
6549 | /// Is this a "move" special member? | |||
6550 | bool isMove() const { | |||
6551 | return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; | |||
6552 | } | |||
6553 | ||||
6554 | /// Look up the corresponding special member in the given class. | |||
6555 | Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, | |||
6556 | unsigned Quals, bool IsMutable) { | |||
6557 | return lookupCallFromSpecialMember(S, Class, CSM, Quals, | |||
6558 | ConstArg && !IsMutable); | |||
6559 | } | |||
6560 | ||||
6561 | /// Look up the constructor for the specified base class to see if it's | |||
6562 | /// overridden due to this being an inherited constructor. | |||
6563 | Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { | |||
6564 | if (!ICI) | |||
6565 | return {}; | |||
6566 | assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor ) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6566, __extension__ __PRETTY_FUNCTION__)); | |||
6567 | auto *BaseCtor = | |||
6568 | cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); | |||
6569 | if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) | |||
6570 | return MD; | |||
6571 | return {}; | |||
6572 | } | |||
6573 | ||||
6574 | /// A base or member subobject. | |||
6575 | typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; | |||
6576 | ||||
6577 | /// Get the location to use for a subobject in diagnostics. | |||
6578 | static SourceLocation getSubobjectLoc(Subobject Subobj) { | |||
6579 | // FIXME: For an indirect virtual base, the direct base leading to | |||
6580 | // the indirect virtual base would be a more useful choice. | |||
6581 | if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) | |||
6582 | return B->getBaseTypeLoc(); | |||
6583 | else | |||
6584 | return Subobj.get<FieldDecl*>()->getLocation(); | |||
6585 | } | |||
6586 | ||||
6587 | enum BasesToVisit { | |||
6588 | /// Visit all non-virtual (direct) bases. | |||
6589 | VisitNonVirtualBases, | |||
6590 | /// Visit all direct bases, virtual or not. | |||
6591 | VisitDirectBases, | |||
6592 | /// Visit all non-virtual bases, and all virtual bases if the class | |||
6593 | /// is not abstract. | |||
6594 | VisitPotentiallyConstructedBases, | |||
6595 | /// Visit all direct or virtual bases. | |||
6596 | VisitAllBases | |||
6597 | }; | |||
6598 | ||||
6599 | // Visit the bases and members of the class. | |||
6600 | bool visit(BasesToVisit Bases) { | |||
6601 | CXXRecordDecl *RD = MD->getParent(); | |||
6602 | ||||
6603 | if (Bases == VisitPotentiallyConstructedBases) | |||
6604 | Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; | |||
6605 | ||||
6606 | for (auto &B : RD->bases()) | |||
6607 | if ((Bases == VisitDirectBases || !B.isVirtual()) && | |||
6608 | getDerived().visitBase(&B)) | |||
6609 | return true; | |||
6610 | ||||
6611 | if (Bases == VisitAllBases) | |||
6612 | for (auto &B : RD->vbases()) | |||
6613 | if (getDerived().visitBase(&B)) | |||
6614 | return true; | |||
6615 | ||||
6616 | for (auto *F : RD->fields()) | |||
6617 | if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && | |||
6618 | getDerived().visitField(F)) | |||
6619 | return true; | |||
6620 | ||||
6621 | return false; | |||
6622 | } | |||
6623 | }; | |||
6624 | } | |||
6625 | ||||
6626 | namespace { | |||
6627 | struct SpecialMemberDeletionInfo | |||
6628 | : SpecialMemberVisitor<SpecialMemberDeletionInfo> { | |||
6629 | bool Diagnose; | |||
6630 | ||||
6631 | SourceLocation Loc; | |||
6632 | ||||
6633 | bool AllFieldsAreConst; | |||
6634 | ||||
6635 | SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, | |||
6636 | Sema::CXXSpecialMember CSM, | |||
6637 | Sema::InheritedConstructorInfo *ICI, bool Diagnose) | |||
6638 | : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), | |||
6639 | Loc(MD->getLocation()), AllFieldsAreConst(true) {} | |||
6640 | ||||
6641 | bool inUnion() const { return MD->getParent()->isUnion(); } | |||
6642 | ||||
6643 | Sema::CXXSpecialMember getEffectiveCSM() { | |||
6644 | return ICI ? Sema::CXXInvalid : CSM; | |||
6645 | } | |||
6646 | ||||
6647 | bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } | |||
6648 | bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } | |||
6649 | ||||
6650 | bool shouldDeleteForBase(CXXBaseSpecifier *Base); | |||
6651 | bool shouldDeleteForField(FieldDecl *FD); | |||
6652 | bool shouldDeleteForAllConstMembers(); | |||
6653 | ||||
6654 | bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | |||
6655 | unsigned Quals); | |||
6656 | bool shouldDeleteForSubobjectCall(Subobject Subobj, | |||
6657 | Sema::SpecialMemberOverloadResult SMOR, | |||
6658 | bool IsDtorCallInCtor); | |||
6659 | ||||
6660 | bool isAccessible(Subobject Subobj, CXXMethodDecl *D); | |||
6661 | }; | |||
6662 | } | |||
6663 | ||||
6664 | /// Is the given special member inaccessible when used on the given | |||
6665 | /// sub-object. | |||
6666 | bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, | |||
6667 | CXXMethodDecl *target) { | |||
6668 | /// If we're operating on a base class, the object type is the | |||
6669 | /// type of this special member. | |||
6670 | QualType objectTy; | |||
6671 | AccessSpecifier access = target->getAccess(); | |||
6672 | if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { | |||
6673 | objectTy = S.Context.getTypeDeclType(MD->getParent()); | |||
6674 | access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); | |||
6675 | ||||
6676 | // If we're operating on a field, the object type is the type of the field. | |||
6677 | } else { | |||
6678 | objectTy = S.Context.getTypeDeclType(target->getParent()); | |||
6679 | } | |||
6680 | ||||
6681 | return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); | |||
6682 | } | |||
6683 | ||||
6684 | /// Check whether we should delete a special member due to the implicit | |||
6685 | /// definition containing a call to a special member of a subobject. | |||
6686 | bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( | |||
6687 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, | |||
6688 | bool IsDtorCallInCtor) { | |||
6689 | CXXMethodDecl *Decl = SMOR.getMethod(); | |||
6690 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
6691 | ||||
6692 | int DiagKind = -1; | |||
6693 | ||||
6694 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) | |||
6695 | DiagKind = !Decl ? 0 : 1; | |||
6696 | else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | |||
6697 | DiagKind = 2; | |||
6698 | else if (!isAccessible(Subobj, Decl)) | |||
6699 | DiagKind = 3; | |||
6700 | else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && | |||
6701 | !Decl->isTrivial()) { | |||
6702 | // A member of a union must have a trivial corresponding special member. | |||
6703 | // As a weird special case, a destructor call from a union's constructor | |||
6704 | // must be accessible and non-deleted, but need not be trivial. Such a | |||
6705 | // destructor is never actually called, but is semantically checked as | |||
6706 | // if it were. | |||
6707 | DiagKind = 4; | |||
6708 | } | |||
6709 | ||||
6710 | if (DiagKind == -1) | |||
6711 | return false; | |||
6712 | ||||
6713 | if (Diagnose) { | |||
6714 | if (Field) { | |||
6715 | S.Diag(Field->getLocation(), | |||
6716 | diag::note_deleted_special_member_class_subobject) | |||
6717 | << getEffectiveCSM() << MD->getParent() << /*IsField*/true | |||
6718 | << Field << DiagKind << IsDtorCallInCtor; | |||
6719 | } else { | |||
6720 | CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); | |||
6721 | S.Diag(Base->getLocStart(), | |||
6722 | diag::note_deleted_special_member_class_subobject) | |||
6723 | << getEffectiveCSM() << MD->getParent() << /*IsField*/false | |||
6724 | << Base->getType() << DiagKind << IsDtorCallInCtor; | |||
6725 | } | |||
6726 | ||||
6727 | if (DiagKind == 1) | |||
6728 | S.NoteDeletedFunction(Decl); | |||
6729 | // FIXME: Explain inaccessibility if DiagKind == 3. | |||
6730 | } | |||
6731 | ||||
6732 | return true; | |||
6733 | } | |||
6734 | ||||
6735 | /// Check whether we should delete a special member function due to having a | |||
6736 | /// direct or virtual base class or non-static data member of class type M. | |||
6737 | bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( | |||
6738 | CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { | |||
6739 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
6740 | bool IsMutable = Field && Field->isMutable(); | |||
6741 | ||||
6742 | // C++11 [class.ctor]p5: | |||
6743 | // -- any direct or virtual base class, or non-static data member with no | |||
6744 | // brace-or-equal-initializer, has class type M (or array thereof) and | |||
6745 | // either M has no default constructor or overload resolution as applied | |||
6746 | // to M's default constructor results in an ambiguity or in a function | |||
6747 | // that is deleted or inaccessible | |||
6748 | // C++11 [class.copy]p11, C++11 [class.copy]p23: | |||
6749 | // -- a direct or virtual base class B that cannot be copied/moved because | |||
6750 | // overload resolution, as applied to B's corresponding special member, | |||
6751 | // results in an ambiguity or a function that is deleted or inaccessible | |||
6752 | // from the defaulted special member | |||
6753 | // C++11 [class.dtor]p5: | |||
6754 | // -- any direct or virtual base class [...] has a type with a destructor | |||
6755 | // that is deleted or inaccessible | |||
6756 | if (!(CSM == Sema::CXXDefaultConstructor && | |||
6757 | Field && Field->hasInClassInitializer()) && | |||
6758 | shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), | |||
6759 | false)) | |||
6760 | return true; | |||
6761 | ||||
6762 | // C++11 [class.ctor]p5, C++11 [class.copy]p11: | |||
6763 | // -- any direct or virtual base class or non-static data member has a | |||
6764 | // type with a destructor that is deleted or inaccessible | |||
6765 | if (IsConstructor) { | |||
6766 | Sema::SpecialMemberOverloadResult SMOR = | |||
6767 | S.LookupSpecialMember(Class, Sema::CXXDestructor, | |||
6768 | false, false, false, false, false); | |||
6769 | if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) | |||
6770 | return true; | |||
6771 | } | |||
6772 | ||||
6773 | return false; | |||
6774 | } | |||
6775 | ||||
6776 | /// Check whether we should delete a special member function due to the class | |||
6777 | /// having a particular direct or virtual base class. | |||
6778 | bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { | |||
6779 | CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); | |||
6780 | // If program is correct, BaseClass cannot be null, but if it is, the error | |||
6781 | // must be reported elsewhere. | |||
6782 | if (!BaseClass) | |||
6783 | return false; | |||
6784 | // If we have an inheriting constructor, check whether we're calling an | |||
6785 | // inherited constructor instead of a default constructor. | |||
6786 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | |||
6787 | if (auto *BaseCtor = SMOR.getMethod()) { | |||
6788 | // Note that we do not check access along this path; other than that, | |||
6789 | // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); | |||
6790 | // FIXME: Check that the base has a usable destructor! Sink this into | |||
6791 | // shouldDeleteForClassSubobject. | |||
6792 | if (BaseCtor->isDeleted() && Diagnose) { | |||
6793 | S.Diag(Base->getLocStart(), | |||
6794 | diag::note_deleted_special_member_class_subobject) | |||
6795 | << getEffectiveCSM() << MD->getParent() << /*IsField*/false | |||
6796 | << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; | |||
6797 | S.NoteDeletedFunction(BaseCtor); | |||
6798 | } | |||
6799 | return BaseCtor->isDeleted(); | |||
6800 | } | |||
6801 | return shouldDeleteForClassSubobject(BaseClass, Base, 0); | |||
6802 | } | |||
6803 | ||||
6804 | /// Check whether we should delete a special member function due to the class | |||
6805 | /// having a particular non-static data member. | |||
6806 | bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { | |||
6807 | QualType FieldType = S.Context.getBaseElementType(FD->getType()); | |||
6808 | CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); | |||
6809 | ||||
6810 | if (CSM == Sema::CXXDefaultConstructor) { | |||
6811 | // For a default constructor, all references must be initialized in-class | |||
6812 | // and, if a union, it must have a non-const member. | |||
6813 | if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { | |||
6814 | if (Diagnose) | |||
6815 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | |||
6816 | << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; | |||
6817 | return true; | |||
6818 | } | |||
6819 | // C++11 [class.ctor]p5: any non-variant non-static data member of | |||
6820 | // const-qualified type (or array thereof) with no | |||
6821 | // brace-or-equal-initializer does not have a user-provided default | |||
6822 | // constructor. | |||
6823 | if (!inUnion() && FieldType.isConstQualified() && | |||
6824 | !FD->hasInClassInitializer() && | |||
6825 | (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { | |||
6826 | if (Diagnose) | |||
6827 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | |||
6828 | << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; | |||
6829 | return true; | |||
6830 | } | |||
6831 | ||||
6832 | if (inUnion() && !FieldType.isConstQualified()) | |||
6833 | AllFieldsAreConst = false; | |||
6834 | } else if (CSM == Sema::CXXCopyConstructor) { | |||
6835 | // For a copy constructor, data members must not be of rvalue reference | |||
6836 | // type. | |||
6837 | if (FieldType->isRValueReferenceType()) { | |||
6838 | if (Diagnose) | |||
6839 | S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) | |||
6840 | << MD->getParent() << FD << FieldType; | |||
6841 | return true; | |||
6842 | } | |||
6843 | } else if (IsAssignment) { | |||
6844 | // For an assignment operator, data members must not be of reference type. | |||
6845 | if (FieldType->isReferenceType()) { | |||
6846 | if (Diagnose) | |||
6847 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | |||
6848 | << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; | |||
6849 | return true; | |||
6850 | } | |||
6851 | if (!FieldRecord && FieldType.isConstQualified()) { | |||
6852 | // C++11 [class.copy]p23: | |||
6853 | // -- a non-static data member of const non-class type (or array thereof) | |||
6854 | if (Diagnose) | |||
6855 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | |||
6856 | << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; | |||
6857 | return true; | |||
6858 | } | |||
6859 | } | |||
6860 | ||||
6861 | if (FieldRecord) { | |||
6862 | // Some additional restrictions exist on the variant members. | |||
6863 | if (!inUnion() && FieldRecord->isUnion() && | |||
6864 | FieldRecord->isAnonymousStructOrUnion()) { | |||
6865 | bool AllVariantFieldsAreConst = true; | |||
6866 | ||||
6867 | // FIXME: Handle anonymous unions declared within anonymous unions. | |||
6868 | for (auto *UI : FieldRecord->fields()) { | |||
6869 | QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); | |||
6870 | ||||
6871 | if (!UnionFieldType.isConstQualified()) | |||
6872 | AllVariantFieldsAreConst = false; | |||
6873 | ||||
6874 | CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); | |||
6875 | if (UnionFieldRecord && | |||
6876 | shouldDeleteForClassSubobject(UnionFieldRecord, UI, | |||
6877 | UnionFieldType.getCVRQualifiers())) | |||
6878 | return true; | |||
6879 | } | |||
6880 | ||||
6881 | // At least one member in each anonymous union must be non-const | |||
6882 | if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && | |||
6883 | !FieldRecord->field_empty()) { | |||
6884 | if (Diagnose) | |||
6885 | S.Diag(FieldRecord->getLocation(), | |||
6886 | diag::note_deleted_default_ctor_all_const) | |||
6887 | << !!ICI << MD->getParent() << /*anonymous union*/1; | |||
6888 | return true; | |||
6889 | } | |||
6890 | ||||
6891 | // Don't check the implicit member of the anonymous union type. | |||
6892 | // This is technically non-conformant, but sanity demands it. | |||
6893 | return false; | |||
6894 | } | |||
6895 | ||||
6896 | if (shouldDeleteForClassSubobject(FieldRecord, FD, | |||
6897 | FieldType.getCVRQualifiers())) | |||
6898 | return true; | |||
6899 | } | |||
6900 | ||||
6901 | return false; | |||
6902 | } | |||
6903 | ||||
6904 | /// C++11 [class.ctor] p5: | |||
6905 | /// A defaulted default constructor for a class X is defined as deleted if | |||
6906 | /// X is a union and all of its variant members are of const-qualified type. | |||
6907 | bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { | |||
6908 | // This is a silly definition, because it gives an empty union a deleted | |||
6909 | // default constructor. Don't do that. | |||
6910 | if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { | |||
6911 | bool AnyFields = false; | |||
6912 | for (auto *F : MD->getParent()->fields()) | |||
6913 | if ((AnyFields = !F->isUnnamedBitfield())) | |||
6914 | break; | |||
6915 | if (!AnyFields) | |||
6916 | return false; | |||
6917 | if (Diagnose) | |||
6918 | S.Diag(MD->getParent()->getLocation(), | |||
6919 | diag::note_deleted_default_ctor_all_const) | |||
6920 | << !!ICI << MD->getParent() << /*not anonymous union*/0; | |||
6921 | return true; | |||
6922 | } | |||
6923 | return false; | |||
6924 | } | |||
6925 | ||||
6926 | /// Determine whether a defaulted special member function should be defined as | |||
6927 | /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, | |||
6928 | /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. | |||
6929 | bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
6930 | InheritedConstructorInfo *ICI, | |||
6931 | bool Diagnose) { | |||
6932 | if (MD->isInvalidDecl()) | |||
6933 | return false; | |||
6934 | CXXRecordDecl *RD = MD->getParent(); | |||
6935 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6935, __extension__ __PRETTY_FUNCTION__)); | |||
6936 | if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) | |||
6937 | return false; | |||
6938 | ||||
6939 | // C++11 [expr.lambda.prim]p19: | |||
6940 | // The closure type associated with a lambda-expression has a | |||
6941 | // deleted (8.4.3) default constructor and a deleted copy | |||
6942 | // assignment operator. | |||
6943 | if (RD->isLambda() && | |||
6944 | (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { | |||
6945 | if (Diagnose) | |||
6946 | Diag(RD->getLocation(), diag::note_lambda_decl); | |||
6947 | return true; | |||
6948 | } | |||
6949 | ||||
6950 | // For an anonymous struct or union, the copy and assignment special members | |||
6951 | // will never be used, so skip the check. For an anonymous union declared at | |||
6952 | // namespace scope, the constructor and destructor are used. | |||
6953 | if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && | |||
6954 | RD->isAnonymousStructOrUnion()) | |||
6955 | return false; | |||
6956 | ||||
6957 | // C++11 [class.copy]p7, p18: | |||
6958 | // If the class definition declares a move constructor or move assignment | |||
6959 | // operator, an implicitly declared copy constructor or copy assignment | |||
6960 | // operator is defined as deleted. | |||
6961 | if (MD->isImplicit() && | |||
6962 | (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { | |||
6963 | CXXMethodDecl *UserDeclaredMove = nullptr; | |||
6964 | ||||
6965 | // In Microsoft mode up to MSVC 2013, a user-declared move only causes the | |||
6966 | // deletion of the corresponding copy operation, not both copy operations. | |||
6967 | // MSVC 2015 has adopted the standards conforming behavior. | |||
6968 | bool DeletesOnlyMatchingCopy = | |||
6969 | getLangOpts().MSVCCompat && | |||
6970 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); | |||
6971 | ||||
6972 | if (RD->hasUserDeclaredMoveConstructor() && | |||
6973 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { | |||
6974 | if (!Diagnose) return true; | |||
6975 | ||||
6976 | // Find any user-declared move constructor. | |||
6977 | for (auto *I : RD->ctors()) { | |||
6978 | if (I->isMoveConstructor()) { | |||
6979 | UserDeclaredMove = I; | |||
6980 | break; | |||
6981 | } | |||
6982 | } | |||
6983 | assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6983, __extension__ __PRETTY_FUNCTION__)); | |||
6984 | } else if (RD->hasUserDeclaredMoveAssignment() && | |||
6985 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { | |||
6986 | if (!Diagnose) return true; | |||
6987 | ||||
6988 | // Find any user-declared move assignment operator. | |||
6989 | for (auto *I : RD->methods()) { | |||
6990 | if (I->isMoveAssignmentOperator()) { | |||
6991 | UserDeclaredMove = I; | |||
6992 | break; | |||
6993 | } | |||
6994 | } | |||
6995 | assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6995, __extension__ __PRETTY_FUNCTION__)); | |||
6996 | } | |||
6997 | ||||
6998 | if (UserDeclaredMove) { | |||
6999 | Diag(UserDeclaredMove->getLocation(), | |||
7000 | diag::note_deleted_copy_user_declared_move) | |||
7001 | << (CSM == CXXCopyAssignment) << RD | |||
7002 | << UserDeclaredMove->isMoveAssignmentOperator(); | |||
7003 | return true; | |||
7004 | } | |||
7005 | } | |||
7006 | ||||
7007 | // Do access control from the special member function | |||
7008 | ContextRAII MethodContext(*this, MD); | |||
7009 | ||||
7010 | // C++11 [class.dtor]p5: | |||
7011 | // -- for a virtual destructor, lookup of the non-array deallocation function | |||
7012 | // results in an ambiguity or in a function that is deleted or inaccessible | |||
7013 | if (CSM == CXXDestructor && MD->isVirtual()) { | |||
7014 | FunctionDecl *OperatorDelete = nullptr; | |||
7015 | DeclarationName Name = | |||
7016 | Context.DeclarationNames.getCXXOperatorName(OO_Delete); | |||
7017 | if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, | |||
7018 | OperatorDelete, /*Diagnose*/false)) { | |||
7019 | if (Diagnose) | |||
7020 | Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); | |||
7021 | return true; | |||
7022 | } | |||
7023 | } | |||
7024 | ||||
7025 | SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); | |||
7026 | ||||
7027 | // Per DR1611, do not consider virtual bases of constructors of abstract | |||
7028 | // classes, since we are not going to construct them. | |||
7029 | // Per DR1658, do not consider virtual bases of destructors of abstract | |||
7030 | // classes either. | |||
7031 | // Per DR2180, for assignment operators we only assign (and thus only | |||
7032 | // consider) direct bases. | |||
7033 | if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases | |||
7034 | : SMI.VisitPotentiallyConstructedBases)) | |||
7035 | return true; | |||
7036 | ||||
7037 | if (SMI.shouldDeleteForAllConstMembers()) | |||
7038 | return true; | |||
7039 | ||||
7040 | if (getLangOpts().CUDA) { | |||
7041 | // We should delete the special member in CUDA mode if target inference | |||
7042 | // failed. | |||
7043 | return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, | |||
7044 | Diagnose); | |||
7045 | } | |||
7046 | ||||
7047 | return false; | |||
7048 | } | |||
7049 | ||||
7050 | /// Perform lookup for a special member of the specified kind, and determine | |||
7051 | /// whether it is trivial. If the triviality can be determined without the | |||
7052 | /// lookup, skip it. This is intended for use when determining whether a | |||
7053 | /// special member of a containing object is trivial, and thus does not ever | |||
7054 | /// perform overload resolution for default constructors. | |||
7055 | /// | |||
7056 | /// If \p Selected is not \c NULL, \c *Selected will be filled in with the | |||
7057 | /// member that was most likely to be intended to be trivial, if any. | |||
7058 | /// | |||
7059 | /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to | |||
7060 | /// determine whether the special member is trivial. | |||
7061 | static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, | |||
7062 | Sema::CXXSpecialMember CSM, unsigned Quals, | |||
7063 | bool ConstRHS, | |||
7064 | Sema::TrivialABIHandling TAH, | |||
7065 | CXXMethodDecl **Selected) { | |||
7066 | if (Selected) | |||
7067 | *Selected = nullptr; | |||
7068 | ||||
7069 | switch (CSM) { | |||
7070 | case Sema::CXXInvalid: | |||
7071 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7071); | |||
7072 | ||||
7073 | case Sema::CXXDefaultConstructor: | |||
7074 | // C++11 [class.ctor]p5: | |||
7075 | // A default constructor is trivial if: | |||
7076 | // - all the [direct subobjects] have trivial default constructors | |||
7077 | // | |||
7078 | // Note, no overload resolution is performed in this case. | |||
7079 | if (RD->hasTrivialDefaultConstructor()) | |||
7080 | return true; | |||
7081 | ||||
7082 | if (Selected) { | |||
7083 | // If there's a default constructor which could have been trivial, dig it | |||
7084 | // out. Otherwise, if there's any user-provided default constructor, point | |||
7085 | // to that as an example of why there's not a trivial one. | |||
7086 | CXXConstructorDecl *DefCtor = nullptr; | |||
7087 | if (RD->needsImplicitDefaultConstructor()) | |||
7088 | S.DeclareImplicitDefaultConstructor(RD); | |||
7089 | for (auto *CI : RD->ctors()) { | |||
7090 | if (!CI->isDefaultConstructor()) | |||
7091 | continue; | |||
7092 | DefCtor = CI; | |||
7093 | if (!DefCtor->isUserProvided()) | |||
7094 | break; | |||
7095 | } | |||
7096 | ||||
7097 | *Selected = DefCtor; | |||
7098 | } | |||
7099 | ||||
7100 | return false; | |||
7101 | ||||
7102 | case Sema::CXXDestructor: | |||
7103 | // C++11 [class.dtor]p5: | |||
7104 | // A destructor is trivial if: | |||
7105 | // - all the direct [subobjects] have trivial destructors | |||
7106 | if (RD->hasTrivialDestructor() || | |||
7107 | (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7108 | RD->hasTrivialDestructorForCall())) | |||
7109 | return true; | |||
7110 | ||||
7111 | if (Selected) { | |||
7112 | if (RD->needsImplicitDestructor()) | |||
7113 | S.DeclareImplicitDestructor(RD); | |||
7114 | *Selected = RD->getDestructor(); | |||
7115 | } | |||
7116 | ||||
7117 | return false; | |||
7118 | ||||
7119 | case Sema::CXXCopyConstructor: | |||
7120 | // C++11 [class.copy]p12: | |||
7121 | // A copy constructor is trivial if: | |||
7122 | // - the constructor selected to copy each direct [subobject] is trivial | |||
7123 | if (RD->hasTrivialCopyConstructor() || | |||
7124 | (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7125 | RD->hasTrivialCopyConstructorForCall())) { | |||
7126 | if (Quals == Qualifiers::Const) | |||
7127 | // We must either select the trivial copy constructor or reach an | |||
7128 | // ambiguity; no need to actually perform overload resolution. | |||
7129 | return true; | |||
7130 | } else if (!Selected) { | |||
7131 | return false; | |||
7132 | } | |||
7133 | // In C++98, we are not supposed to perform overload resolution here, but we | |||
7134 | // treat that as a language defect, as suggested on cxx-abi-dev, to treat | |||
7135 | // cases like B as having a non-trivial copy constructor: | |||
7136 | // struct A { template<typename T> A(T&); }; | |||
7137 | // struct B { mutable A a; }; | |||
7138 | goto NeedOverloadResolution; | |||
7139 | ||||
7140 | case Sema::CXXCopyAssignment: | |||
7141 | // C++11 [class.copy]p25: | |||
7142 | // A copy assignment operator is trivial if: | |||
7143 | // - the assignment operator selected to copy each direct [subobject] is | |||
7144 | // trivial | |||
7145 | if (RD->hasTrivialCopyAssignment()) { | |||
7146 | if (Quals == Qualifiers::Const) | |||
7147 | return true; | |||
7148 | } else if (!Selected) { | |||
7149 | return false; | |||
7150 | } | |||
7151 | // In C++98, we are not supposed to perform overload resolution here, but we | |||
7152 | // treat that as a language defect. | |||
7153 | goto NeedOverloadResolution; | |||
7154 | ||||
7155 | case Sema::CXXMoveConstructor: | |||
7156 | case Sema::CXXMoveAssignment: | |||
7157 | NeedOverloadResolution: | |||
7158 | Sema::SpecialMemberOverloadResult SMOR = | |||
7159 | lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); | |||
7160 | ||||
7161 | // The standard doesn't describe how to behave if the lookup is ambiguous. | |||
7162 | // We treat it as not making the member non-trivial, just like the standard | |||
7163 | // mandates for the default constructor. This should rarely matter, because | |||
7164 | // the member will also be deleted. | |||
7165 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | |||
7166 | return true; | |||
7167 | ||||
7168 | if (!SMOR.getMethod()) { | |||
7169 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7170, __extension__ __PRETTY_FUNCTION__)) | |||
7170 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7170, __extension__ __PRETTY_FUNCTION__)); | |||
7171 | return false; | |||
7172 | } | |||
7173 | ||||
7174 | // We deliberately don't check if we found a deleted special member. We're | |||
7175 | // not supposed to! | |||
7176 | if (Selected) | |||
7177 | *Selected = SMOR.getMethod(); | |||
7178 | ||||
7179 | if (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7180 | (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) | |||
7181 | return SMOR.getMethod()->isTrivialForCall(); | |||
7182 | return SMOR.getMethod()->isTrivial(); | |||
7183 | } | |||
7184 | ||||
7185 | llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7185); | |||
7186 | } | |||
7187 | ||||
7188 | static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { | |||
7189 | for (auto *CI : RD->ctors()) | |||
7190 | if (!CI->isImplicit()) | |||
7191 | return CI; | |||
7192 | ||||
7193 | // Look for constructor templates. | |||
7194 | typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; | |||
7195 | for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { | |||
7196 | if (CXXConstructorDecl *CD = | |||
7197 | dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) | |||
7198 | return CD; | |||
7199 | } | |||
7200 | ||||
7201 | return nullptr; | |||
7202 | } | |||
7203 | ||||
7204 | /// The kind of subobject we are checking for triviality. The values of this | |||
7205 | /// enumeration are used in diagnostics. | |||
7206 | enum TrivialSubobjectKind { | |||
7207 | /// The subobject is a base class. | |||
7208 | TSK_BaseClass, | |||
7209 | /// The subobject is a non-static data member. | |||
7210 | TSK_Field, | |||
7211 | /// The object is actually the complete object. | |||
7212 | TSK_CompleteObject | |||
7213 | }; | |||
7214 | ||||
7215 | /// Check whether the special member selected for a given type would be trivial. | |||
7216 | static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, | |||
7217 | QualType SubType, bool ConstRHS, | |||
7218 | Sema::CXXSpecialMember CSM, | |||
7219 | TrivialSubobjectKind Kind, | |||
7220 | Sema::TrivialABIHandling TAH, bool Diagnose) { | |||
7221 | CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); | |||
7222 | if (!SubRD) | |||
7223 | return true; | |||
7224 | ||||
7225 | CXXMethodDecl *Selected; | |||
7226 | if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), | |||
7227 | ConstRHS, TAH, Diagnose ? &Selected : nullptr)) | |||
7228 | return true; | |||
7229 | ||||
7230 | if (Diagnose) { | |||
7231 | if (ConstRHS) | |||
7232 | SubType.addConst(); | |||
7233 | ||||
7234 | if (!Selected && CSM == Sema::CXXDefaultConstructor) { | |||
7235 | S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) | |||
7236 | << Kind << SubType.getUnqualifiedType(); | |||
7237 | if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) | |||
7238 | S.Diag(CD->getLocation(), diag::note_user_declared_ctor); | |||
7239 | } else if (!Selected) | |||
7240 | S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) | |||
7241 | << Kind << SubType.getUnqualifiedType() << CSM << SubType; | |||
7242 | else if (Selected->isUserProvided()) { | |||
7243 | if (Kind == TSK_CompleteObject) | |||
7244 | S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) | |||
7245 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7246 | else { | |||
7247 | S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) | |||
7248 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7249 | S.Diag(Selected->getLocation(), diag::note_declared_at); | |||
7250 | } | |||
7251 | } else { | |||
7252 | if (Kind != TSK_CompleteObject) | |||
7253 | S.Diag(SubobjLoc, diag::note_nontrivial_subobject) | |||
7254 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7255 | ||||
7256 | // Explain why the defaulted or deleted special member isn't trivial. | |||
7257 | S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, | |||
7258 | Diagnose); | |||
7259 | } | |||
7260 | } | |||
7261 | ||||
7262 | return false; | |||
7263 | } | |||
7264 | ||||
7265 | /// Check whether the members of a class type allow a special member to be | |||
7266 | /// trivial. | |||
7267 | static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, | |||
7268 | Sema::CXXSpecialMember CSM, | |||
7269 | bool ConstArg, | |||
7270 | Sema::TrivialABIHandling TAH, | |||
7271 | bool Diagnose) { | |||
7272 | for (const auto *FI : RD->fields()) { | |||
7273 | if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) | |||
7274 | continue; | |||
7275 | ||||
7276 | QualType FieldType = S.Context.getBaseElementType(FI->getType()); | |||
7277 | ||||
7278 | // Pretend anonymous struct or union members are members of this class. | |||
7279 | if (FI->isAnonymousStructOrUnion()) { | |||
7280 | if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), | |||
7281 | CSM, ConstArg, TAH, Diagnose)) | |||
7282 | return false; | |||
7283 | continue; | |||
7284 | } | |||
7285 | ||||
7286 | // C++11 [class.ctor]p5: | |||
7287 | // A default constructor is trivial if [...] | |||
7288 | // -- no non-static data member of its class has a | |||
7289 | // brace-or-equal-initializer | |||
7290 | if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { | |||
7291 | if (Diagnose) | |||
7292 | S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; | |||
7293 | return false; | |||
7294 | } | |||
7295 | ||||
7296 | // Objective C ARC 4.3.5: | |||
7297 | // [...] nontrivally ownership-qualified types are [...] not trivially | |||
7298 | // default constructible, copy constructible, move constructible, copy | |||
7299 | // assignable, move assignable, or destructible [...] | |||
7300 | if (FieldType.hasNonTrivialObjCLifetime()) { | |||
7301 | if (Diagnose) | |||
7302 | S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) | |||
7303 | << RD << FieldType.getObjCLifetime(); | |||
7304 | return false; | |||
7305 | } | |||
7306 | ||||
7307 | bool ConstRHS = ConstArg && !FI->isMutable(); | |||
7308 | if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, | |||
7309 | CSM, TSK_Field, TAH, Diagnose)) | |||
7310 | return false; | |||
7311 | } | |||
7312 | ||||
7313 | return true; | |||
7314 | } | |||
7315 | ||||
7316 | /// Diagnose why the specified class does not have a trivial special member of | |||
7317 | /// the given kind. | |||
7318 | void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { | |||
7319 | QualType Ty = Context.getRecordType(RD); | |||
7320 | ||||
7321 | bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); | |||
7322 | checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, | |||
7323 | TSK_CompleteObject, TAH_IgnoreTrivialABI, | |||
7324 | /*Diagnose*/true); | |||
7325 | } | |||
7326 | ||||
7327 | /// Determine whether a defaulted or deleted special member function is trivial, | |||
7328 | /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, | |||
7329 | /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. | |||
7330 | bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
7331 | TrivialABIHandling TAH, bool Diagnose) { | |||
7332 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7332, __extension__ __PRETTY_FUNCTION__)); | |||
7333 | ||||
7334 | CXXRecordDecl *RD = MD->getParent(); | |||
7335 | ||||
7336 | bool ConstArg = false; | |||
7337 | ||||
7338 | // C++11 [class.copy]p12, p25: [DR1593] | |||
7339 | // A [special member] is trivial if [...] its parameter-type-list is | |||
7340 | // equivalent to the parameter-type-list of an implicit declaration [...] | |||
7341 | switch (CSM) { | |||
7342 | case CXXDefaultConstructor: | |||
7343 | case CXXDestructor: | |||
7344 | // Trivial default constructors and destructors cannot have parameters. | |||
7345 | break; | |||
7346 | ||||
7347 | case CXXCopyConstructor: | |||
7348 | case CXXCopyAssignment: { | |||
7349 | // Trivial copy operations always have const, non-volatile parameter types. | |||
7350 | ConstArg = true; | |||
7351 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | |||
7352 | const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); | |||
7353 | if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { | |||
7354 | if (Diagnose) | |||
7355 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | |||
7356 | << Param0->getSourceRange() << Param0->getType() | |||
7357 | << Context.getLValueReferenceType( | |||
7358 | Context.getRecordType(RD).withConst()); | |||
7359 | return false; | |||
7360 | } | |||
7361 | break; | |||
7362 | } | |||
7363 | ||||
7364 | case CXXMoveConstructor: | |||
7365 | case CXXMoveAssignment: { | |||
7366 | // Trivial move operations always have non-cv-qualified parameters. | |||
7367 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | |||
7368 | const RValueReferenceType *RT = | |||
7369 | Param0->getType()->getAs<RValueReferenceType>(); | |||
7370 | if (!RT || RT->getPointeeType().getCVRQualifiers()) { | |||
7371 | if (Diagnose) | |||
7372 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | |||
7373 | << Param0->getSourceRange() << Param0->getType() | |||
7374 | << Context.getRValueReferenceType(Context.getRecordType(RD)); | |||
7375 | return false; | |||
7376 | } | |||
7377 | break; | |||
7378 | } | |||
7379 | ||||
7380 | case CXXInvalid: | |||
7381 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7381); | |||
7382 | } | |||
7383 | ||||
7384 | if (MD->getMinRequiredArguments() < MD->getNumParams()) { | |||
7385 | if (Diagnose) | |||
7386 | Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), | |||
7387 | diag::note_nontrivial_default_arg) | |||
7388 | << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); | |||
7389 | return false; | |||
7390 | } | |||
7391 | if (MD->isVariadic()) { | |||
7392 | if (Diagnose) | |||
7393 | Diag(MD->getLocation(), diag::note_nontrivial_variadic); | |||
7394 | return false; | |||
7395 | } | |||
7396 | ||||
7397 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | |||
7398 | // A copy/move [constructor or assignment operator] is trivial if | |||
7399 | // -- the [member] selected to copy/move each direct base class subobject | |||
7400 | // is trivial | |||
7401 | // | |||
7402 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7403 | // A [default constructor or destructor] is trivial if | |||
7404 | // -- all the direct base classes have trivial [default constructors or | |||
7405 | // destructors] | |||
7406 | for (const auto &BI : RD->bases()) | |||
7407 | if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), | |||
7408 | ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) | |||
7409 | return false; | |||
7410 | ||||
7411 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | |||
7412 | // A copy/move [constructor or assignment operator] for a class X is | |||
7413 | // trivial if | |||
7414 | // -- for each non-static data member of X that is of class type (or array | |||
7415 | // thereof), the constructor selected to copy/move that member is | |||
7416 | // trivial | |||
7417 | // | |||
7418 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7419 | // A [default constructor or destructor] is trivial if | |||
7420 | // -- for all of the non-static data members of its class that are of class | |||
7421 | // type (or array thereof), each such class has a trivial [default | |||
7422 | // constructor or destructor] | |||
7423 | if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) | |||
7424 | return false; | |||
7425 | ||||
7426 | // C++11 [class.dtor]p5: | |||
7427 | // A destructor is trivial if [...] | |||
7428 | // -- the destructor is not virtual | |||
7429 | if (CSM == CXXDestructor && MD->isVirtual()) { | |||
7430 | if (Diagnose) | |||
7431 | Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; | |||
7432 | return false; | |||
7433 | } | |||
7434 | ||||
7435 | // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7436 | // A [special member] for class X is trivial if [...] | |||
7437 | // -- class X has no virtual functions and no virtual base classes | |||
7438 | if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { | |||
7439 | if (!Diagnose) | |||
7440 | return false; | |||
7441 | ||||
7442 | if (RD->getNumVBases()) { | |||
7443 | // Check for virtual bases. We already know that the corresponding | |||
7444 | // member in all bases is trivial, so vbases must all be direct. | |||
7445 | CXXBaseSpecifier &BS = *RD->vbases_begin(); | |||
7446 | assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail ("BS.isVirtual()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7446, __extension__ __PRETTY_FUNCTION__)); | |||
7447 | Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; | |||
7448 | return false; | |||
7449 | } | |||
7450 | ||||
7451 | // Must have a virtual method. | |||
7452 | for (const auto *MI : RD->methods()) { | |||
7453 | if (MI->isVirtual()) { | |||
7454 | SourceLocation MLoc = MI->getLocStart(); | |||
7455 | Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; | |||
7456 | return false; | |||
7457 | } | |||
7458 | } | |||
7459 | ||||
7460 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7460); | |||
7461 | } | |||
7462 | ||||
7463 | // Looks like it's trivial! | |||
7464 | return true; | |||
7465 | } | |||
7466 | ||||
7467 | namespace { | |||
7468 | struct FindHiddenVirtualMethod { | |||
7469 | Sema *S; | |||
7470 | CXXMethodDecl *Method; | |||
7471 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; | |||
7472 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
7473 | ||||
7474 | private: | |||
7475 | /// Check whether any most overriden method from MD in Methods | |||
7476 | static bool CheckMostOverridenMethods( | |||
7477 | const CXXMethodDecl *MD, | |||
7478 | const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { | |||
7479 | if (MD->size_overridden_methods() == 0) | |||
7480 | return Methods.count(MD->getCanonicalDecl()); | |||
7481 | for (const CXXMethodDecl *O : MD->overridden_methods()) | |||
7482 | if (CheckMostOverridenMethods(O, Methods)) | |||
7483 | return true; | |||
7484 | return false; | |||
7485 | } | |||
7486 | ||||
7487 | public: | |||
7488 | /// Member lookup function that determines whether a given C++ | |||
7489 | /// method overloads virtual methods in a base class without overriding any, | |||
7490 | /// to be used with CXXRecordDecl::lookupInBases(). | |||
7491 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | |||
7492 | RecordDecl *BaseRecord = | |||
7493 | Specifier->getType()->getAs<RecordType>()->getDecl(); | |||
7494 | ||||
7495 | DeclarationName Name = Method->getDeclName(); | |||
7496 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7496, __extension__ __PRETTY_FUNCTION__)); | |||
7497 | ||||
7498 | bool foundSameNameMethod = false; | |||
7499 | SmallVector<CXXMethodDecl *, 8> overloadedMethods; | |||
7500 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | |||
7501 | Path.Decls = Path.Decls.slice(1)) { | |||
7502 | NamedDecl *D = Path.Decls.front(); | |||
7503 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
7504 | MD = MD->getCanonicalDecl(); | |||
7505 | foundSameNameMethod = true; | |||
7506 | // Interested only in hidden virtual methods. | |||
7507 | if (!MD->isVirtual()) | |||
7508 | continue; | |||
7509 | // If the method we are checking overrides a method from its base | |||
7510 | // don't warn about the other overloaded methods. Clang deviates from | |||
7511 | // GCC by only diagnosing overloads of inherited virtual functions that | |||
7512 | // do not override any other virtual functions in the base. GCC's | |||
7513 | // -Woverloaded-virtual diagnoses any derived function hiding a virtual | |||
7514 | // function from a base class. These cases may be better served by a | |||
7515 | // warning (not specific to virtual functions) on call sites when the | |||
7516 | // call would select a different function from the base class, were it | |||
7517 | // visible. | |||
7518 | // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. | |||
7519 | if (!S->IsOverload(Method, MD, false)) | |||
7520 | return true; | |||
7521 | // Collect the overload only if its hidden. | |||
7522 | if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) | |||
7523 | overloadedMethods.push_back(MD); | |||
7524 | } | |||
7525 | } | |||
7526 | ||||
7527 | if (foundSameNameMethod) | |||
7528 | OverloadedMethods.append(overloadedMethods.begin(), | |||
7529 | overloadedMethods.end()); | |||
7530 | return foundSameNameMethod; | |||
7531 | } | |||
7532 | }; | |||
7533 | } // end anonymous namespace | |||
7534 | ||||
7535 | /// \brief Add the most overriden methods from MD to Methods | |||
7536 | static void AddMostOverridenMethods(const CXXMethodDecl *MD, | |||
7537 | llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { | |||
7538 | if (MD->size_overridden_methods() == 0) | |||
7539 | Methods.insert(MD->getCanonicalDecl()); | |||
7540 | else | |||
7541 | for (const CXXMethodDecl *O : MD->overridden_methods()) | |||
7542 | AddMostOverridenMethods(O, Methods); | |||
7543 | } | |||
7544 | ||||
7545 | /// \brief Check if a method overloads virtual methods in a base class without | |||
7546 | /// overriding any. | |||
7547 | void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, | |||
7548 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | |||
7549 | if (!MD->getDeclName().isIdentifier()) | |||
7550 | return; | |||
7551 | ||||
7552 | CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. | |||
7553 | /*bool RecordPaths=*/false, | |||
7554 | /*bool DetectVirtual=*/false); | |||
7555 | FindHiddenVirtualMethod FHVM; | |||
7556 | FHVM.Method = MD; | |||
7557 | FHVM.S = this; | |||
7558 | ||||
7559 | // Keep the base methods that were overriden or introduced in the subclass | |||
7560 | // by 'using' in a set. A base method not in this set is hidden. | |||
7561 | CXXRecordDecl *DC = MD->getParent(); | |||
7562 | DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); | |||
7563 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
7564 | NamedDecl *ND = *I; | |||
7565 | if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) | |||
7566 | ND = shad->getTargetDecl(); | |||
7567 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) | |||
7568 | AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); | |||
7569 | } | |||
7570 | ||||
7571 | if (DC->lookupInBases(FHVM, Paths)) | |||
7572 | OverloadedMethods = FHVM.OverloadedMethods; | |||
7573 | } | |||
7574 | ||||
7575 | void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, | |||
7576 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | |||
7577 | for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { | |||
7578 | CXXMethodDecl *overloadedMD = OverloadedMethods[i]; | |||
7579 | PartialDiagnostic PD = PDiag( | |||
7580 | diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; | |||
7581 | HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); | |||
7582 | Diag(overloadedMD->getLocation(), PD); | |||
7583 | } | |||
7584 | } | |||
7585 | ||||
7586 | /// \brief Diagnose methods which overload virtual methods in a base class | |||
7587 | /// without overriding any. | |||
7588 | void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { | |||
7589 | if (MD->isInvalidDecl()) | |||
7590 | return; | |||
7591 | ||||
7592 | if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) | |||
7593 | return; | |||
7594 | ||||
7595 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
7596 | FindHiddenVirtualMethods(MD, OverloadedMethods); | |||
7597 | if (!OverloadedMethods.empty()) { | |||
7598 | Diag(MD->getLocation(), diag::warn_overloaded_virtual) | |||
7599 | << MD << (OverloadedMethods.size() > 1); | |||
7600 | ||||
7601 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | |||
7602 | } | |||
7603 | } | |||
7604 | ||||
7605 | void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { | |||
7606 | auto PrintDiagAndRemoveAttr = [&]() { | |||
7607 | // No diagnostics if this is a template instantiation. | |||
7608 | if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) | |||
7609 | Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), | |||
7610 | diag::ext_cannot_use_trivial_abi) << &RD; | |||
7611 | RD.dropAttr<TrivialABIAttr>(); | |||
7612 | }; | |||
7613 | ||||
7614 | // Ill-formed if the struct has virtual functions. | |||
7615 | if (RD.isPolymorphic()) { | |||
7616 | PrintDiagAndRemoveAttr(); | |||
7617 | return; | |||
7618 | } | |||
7619 | ||||
7620 | for (const auto &B : RD.bases()) { | |||
7621 | // Ill-formed if the base class is non-trivial for the purpose of calls or a | |||
7622 | // virtual base. | |||
7623 | if ((!B.getType()->isDependentType() && | |||
7624 | !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || | |||
7625 | B.isVirtual()) { | |||
7626 | PrintDiagAndRemoveAttr(); | |||
7627 | return; | |||
7628 | } | |||
7629 | } | |||
7630 | ||||
7631 | for (const auto *FD : RD.fields()) { | |||
7632 | // Ill-formed if the field is an ObjectiveC pointer or of a type that is | |||
7633 | // non-trivial for the purpose of calls. | |||
7634 | QualType FT = FD->getType(); | |||
7635 | if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
7636 | PrintDiagAndRemoveAttr(); | |||
7637 | return; | |||
7638 | } | |||
7639 | ||||
7640 | if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) | |||
7641 | if (!RT->isDependentType() && | |||
7642 | !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { | |||
7643 | PrintDiagAndRemoveAttr(); | |||
7644 | return; | |||
7645 | } | |||
7646 | } | |||
7647 | } | |||
7648 | ||||
7649 | void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, | |||
7650 | Decl *TagDecl, | |||
7651 | SourceLocation LBrac, | |||
7652 | SourceLocation RBrac, | |||
7653 | AttributeList *AttrList) { | |||
7654 | if (!TagDecl) | |||
7655 | return; | |||
7656 | ||||
7657 | AdjustDeclIfTemplate(TagDecl); | |||
7658 | ||||
7659 | for (const AttributeList* l = AttrList; l; l = l->getNext()) { | |||
7660 | if (l->getKind() != AttributeList::AT_Visibility) | |||
7661 | continue; | |||
7662 | l->setInvalid(); | |||
7663 | Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << | |||
7664 | l->getName(); | |||
7665 | } | |||
7666 | ||||
7667 | // See if trivial_abi has to be dropped. | |||
7668 | auto *RD = dyn_cast<CXXRecordDecl>(TagDecl); | |||
7669 | if (RD && RD->hasAttr<TrivialABIAttr>()) | |||
7670 | checkIllFormedTrivialABIStruct(*RD); | |||
7671 | ||||
7672 | ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( | |||
7673 | // strict aliasing violation! | |||
7674 | reinterpret_cast<Decl**>(FieldCollector->getCurFields()), | |||
7675 | FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); | |||
7676 | ||||
7677 | CheckCompletedCXXClass(RD); | |||
7678 | } | |||
7679 | ||||
7680 | /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared | |||
7681 | /// special functions, such as the default constructor, copy | |||
7682 | /// constructor, or destructor, to the given C++ class (C++ | |||
7683 | /// [special]p1). This routine can only be executed just before the | |||
7684 | /// definition of the class is complete. | |||
7685 | void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { | |||
7686 | if (ClassDecl->needsImplicitDefaultConstructor()) { | |||
7687 | ++ASTContext::NumImplicitDefaultConstructors; | |||
7688 | ||||
7689 | if (ClassDecl->hasInheritedConstructor()) | |||
7690 | DeclareImplicitDefaultConstructor(ClassDecl); | |||
7691 | } | |||
7692 | ||||
7693 | if (ClassDecl->needsImplicitCopyConstructor()) { | |||
7694 | ++ASTContext::NumImplicitCopyConstructors; | |||
7695 | ||||
7696 | // If the properties or semantics of the copy constructor couldn't be | |||
7697 | // determined while the class was being declared, force a declaration | |||
7698 | // of it now. | |||
7699 | if (ClassDecl->needsOverloadResolutionForCopyConstructor() || | |||
7700 | ClassDecl->hasInheritedConstructor()) | |||
7701 | DeclareImplicitCopyConstructor(ClassDecl); | |||
7702 | // For the MS ABI we need to know whether the copy ctor is deleted. A | |||
7703 | // prerequisite for deleting the implicit copy ctor is that the class has a | |||
7704 | // move ctor or move assignment that is either user-declared or whose | |||
7705 | // semantics are inherited from a subobject. FIXME: We should provide a more | |||
7706 | // direct way for CodeGen to ask whether the constructor was deleted. | |||
7707 | else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
7708 | (ClassDecl->hasUserDeclaredMoveConstructor() || | |||
7709 | ClassDecl->needsOverloadResolutionForMoveConstructor() || | |||
7710 | ClassDecl->hasUserDeclaredMoveAssignment() || | |||
7711 | ClassDecl->needsOverloadResolutionForMoveAssignment())) | |||
7712 | DeclareImplicitCopyConstructor(ClassDecl); | |||
7713 | } | |||
7714 | ||||
7715 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { | |||
7716 | ++ASTContext::NumImplicitMoveConstructors; | |||
7717 | ||||
7718 | if (ClassDecl->needsOverloadResolutionForMoveConstructor() || | |||
7719 | ClassDecl->hasInheritedConstructor()) | |||
7720 | DeclareImplicitMoveConstructor(ClassDecl); | |||
7721 | } | |||
7722 | ||||
7723 | if (ClassDecl->needsImplicitCopyAssignment()) { | |||
7724 | ++ASTContext::NumImplicitCopyAssignmentOperators; | |||
7725 | ||||
7726 | // If we have a dynamic class, then the copy assignment operator may be | |||
7727 | // virtual, so we have to declare it immediately. This ensures that, e.g., | |||
7728 | // it shows up in the right place in the vtable and that we diagnose | |||
7729 | // problems with the implicit exception specification. | |||
7730 | if (ClassDecl->isDynamicClass() || | |||
7731 | ClassDecl->needsOverloadResolutionForCopyAssignment() || | |||
7732 | ClassDecl->hasInheritedAssignment()) | |||
7733 | DeclareImplicitCopyAssignment(ClassDecl); | |||
7734 | } | |||
7735 | ||||
7736 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { | |||
7737 | ++ASTContext::NumImplicitMoveAssignmentOperators; | |||
7738 | ||||
7739 | // Likewise for the move assignment operator. | |||
7740 | if (ClassDecl->isDynamicClass() || | |||
7741 | ClassDecl->needsOverloadResolutionForMoveAssignment() || | |||
7742 | ClassDecl->hasInheritedAssignment()) | |||
7743 | DeclareImplicitMoveAssignment(ClassDecl); | |||
7744 | } | |||
7745 | ||||
7746 | if (ClassDecl->needsImplicitDestructor()) { | |||
7747 | ++ASTContext::NumImplicitDestructors; | |||
7748 | ||||
7749 | // If we have a dynamic class, then the destructor may be virtual, so we | |||
7750 | // have to declare the destructor immediately. This ensures that, e.g., it | |||
7751 | // shows up in the right place in the vtable and that we diagnose problems | |||
7752 | // with the implicit exception specification. | |||
7753 | if (ClassDecl->isDynamicClass() || | |||
7754 | ClassDecl->needsOverloadResolutionForDestructor()) | |||
7755 | DeclareImplicitDestructor(ClassDecl); | |||
7756 | } | |||
7757 | } | |||
7758 | ||||
7759 | unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { | |||
7760 | if (!D) | |||
7761 | return 0; | |||
7762 | ||||
7763 | // The order of template parameters is not important here. All names | |||
7764 | // get added to the same scope. | |||
7765 | SmallVector<TemplateParameterList *, 4> ParameterLists; | |||
7766 | ||||
7767 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | |||
7768 | D = TD->getTemplatedDecl(); | |||
7769 | ||||
7770 | if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) | |||
7771 | ParameterLists.push_back(PSD->getTemplateParameters()); | |||
7772 | ||||
7773 | if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { | |||
7774 | for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) | |||
7775 | ParameterLists.push_back(DD->getTemplateParameterList(i)); | |||
7776 | ||||
7777 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
7778 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) | |||
7779 | ParameterLists.push_back(FTD->getTemplateParameters()); | |||
7780 | } | |||
7781 | } | |||
7782 | ||||
7783 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) { | |||
7784 | for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) | |||
7785 | ParameterLists.push_back(TD->getTemplateParameterList(i)); | |||
7786 | ||||
7787 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { | |||
7788 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) | |||
7789 | ParameterLists.push_back(CTD->getTemplateParameters()); | |||
7790 | } | |||
7791 | } | |||
7792 | ||||
7793 | unsigned Count = 0; | |||
7794 | for (TemplateParameterList *Params : ParameterLists) { | |||
7795 | if (Params->size() > 0) | |||
7796 | // Ignore explicit specializations; they don't contribute to the template | |||
7797 | // depth. | |||
7798 | ++Count; | |||
7799 | for (NamedDecl *Param : *Params) { | |||
7800 | if (Param->getDeclName()) { | |||
7801 | S->AddDecl(Param); | |||
7802 | IdResolver.AddDecl(Param); | |||
7803 | } | |||
7804 | } | |||
7805 | } | |||
7806 | ||||
7807 | return Count; | |||
7808 | } | |||
7809 | ||||
7810 | void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | |||
7811 | if (!RecordD) return; | |||
7812 | AdjustDeclIfTemplate(RecordD); | |||
7813 | CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); | |||
7814 | PushDeclContext(S, Record); | |||
7815 | } | |||
7816 | ||||
7817 | void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | |||
7818 | if (!RecordD) return; | |||
7819 | PopDeclContext(); | |||
7820 | } | |||
7821 | ||||
7822 | /// This is used to implement the constant expression evaluation part of the | |||
7823 | /// attribute enable_if extension. There is nothing in standard C++ which would | |||
7824 | /// require reentering parameters. | |||
7825 | void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { | |||
7826 | if (!Param) | |||
7827 | return; | |||
7828 | ||||
7829 | S->AddDecl(Param); | |||
7830 | if (Param->getDeclName()) | |||
7831 | IdResolver.AddDecl(Param); | |||
7832 | } | |||
7833 | ||||
7834 | /// ActOnStartDelayedCXXMethodDeclaration - We have completed | |||
7835 | /// parsing a top-level (non-nested) C++ class, and we are now | |||
7836 | /// parsing those parts of the given Method declaration that could | |||
7837 | /// not be parsed earlier (C++ [class.mem]p2), such as default | |||
7838 | /// arguments. This action should enter the scope of the given | |||
7839 | /// Method declaration as if we had just parsed the qualified method | |||
7840 | /// name. However, it should not bring the parameters into scope; | |||
7841 | /// that will be performed by ActOnDelayedCXXMethodParameter. | |||
7842 | void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | |||
7843 | } | |||
7844 | ||||
7845 | /// ActOnDelayedCXXMethodParameter - We've already started a delayed | |||
7846 | /// C++ method declaration. We're (re-)introducing the given | |||
7847 | /// function parameter into scope for use in parsing later parts of | |||
7848 | /// the method declaration. For example, we could see an | |||
7849 | /// ActOnParamDefaultArgument event for this parameter. | |||
7850 | void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { | |||
7851 | if (!ParamD) | |||
7852 | return; | |||
7853 | ||||
7854 | ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); | |||
7855 | ||||
7856 | // If this parameter has an unparsed default argument, clear it out | |||
7857 | // to make way for the parsed default argument. | |||
7858 | if (Param->hasUnparsedDefaultArg()) | |||
7859 | Param->setDefaultArg(nullptr); | |||
7860 | ||||
7861 | S->AddDecl(Param); | |||
7862 | if (Param->getDeclName()) | |||
7863 | IdResolver.AddDecl(Param); | |||
7864 | } | |||
7865 | ||||
7866 | /// ActOnFinishDelayedCXXMethodDeclaration - We have finished | |||
7867 | /// processing the delayed method declaration for Method. The method | |||
7868 | /// declaration is now considered finished. There may be a separate | |||
7869 | /// ActOnStartOfFunctionDef action later (not necessarily | |||
7870 | /// immediately!) for this method, if it was also defined inside the | |||
7871 | /// class body. | |||
7872 | void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | |||
7873 | if (!MethodD) | |||
7874 | return; | |||
7875 | ||||
7876 | AdjustDeclIfTemplate(MethodD); | |||
7877 | ||||
7878 | FunctionDecl *Method = cast<FunctionDecl>(MethodD); | |||
7879 | ||||
7880 | // Now that we have our default arguments, check the constructor | |||
7881 | // again. It could produce additional diagnostics or affect whether | |||
7882 | // the class has implicitly-declared destructors, among other | |||
7883 | // things. | |||
7884 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) | |||
7885 | CheckConstructor(Constructor); | |||
7886 | ||||
7887 | // Check the default arguments, which we may have added. | |||
7888 | if (!Method->isInvalidDecl()) | |||
7889 | CheckCXXDefaultArguments(Method); | |||
7890 | } | |||
7891 | ||||
7892 | /// CheckConstructorDeclarator - Called by ActOnDeclarator to check | |||
7893 | /// the well-formedness of the constructor declarator @p D with type @p | |||
7894 | /// R. If there are any errors in the declarator, this routine will | |||
7895 | /// emit diagnostics and set the invalid bit to true. In any case, the type | |||
7896 | /// will be updated to reflect a well-formed type for the constructor and | |||
7897 | /// returned. | |||
7898 | QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, | |||
7899 | StorageClass &SC) { | |||
7900 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | |||
7901 | ||||
7902 | // C++ [class.ctor]p3: | |||
7903 | // A constructor shall not be virtual (10.3) or static (9.4). A | |||
7904 | // constructor can be invoked for a const, volatile or const | |||
7905 | // volatile object. A constructor shall not be declared const, | |||
7906 | // volatile, or const volatile (9.3.2). | |||
7907 | if (isVirtual) { | |||
7908 | if (!D.isInvalidType()) | |||
7909 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | |||
7910 | << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) | |||
7911 | << SourceRange(D.getIdentifierLoc()); | |||
7912 | D.setInvalidType(); | |||
7913 | } | |||
7914 | if (SC == SC_Static) { | |||
7915 | if (!D.isInvalidType()) | |||
7916 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | |||
7917 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
7918 | << SourceRange(D.getIdentifierLoc()); | |||
7919 | D.setInvalidType(); | |||
7920 | SC = SC_None; | |||
7921 | } | |||
7922 | ||||
7923 | if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | |||
7924 | diagnoseIgnoredQualifiers( | |||
7925 | diag::err_constructor_return_type, TypeQuals, SourceLocation(), | |||
7926 | D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), | |||
7927 | D.getDeclSpec().getRestrictSpecLoc(), | |||
7928 | D.getDeclSpec().getAtomicSpecLoc()); | |||
7929 | D.setInvalidType(); | |||
7930 | } | |||
7931 | ||||
7932 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
7933 | if (FTI.TypeQuals != 0) { | |||
7934 | if (FTI.TypeQuals & Qualifiers::Const) | |||
7935 | Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) | |||
7936 | << "const" << SourceRange(D.getIdentifierLoc()); | |||
7937 | if (FTI.TypeQuals & Qualifiers::Volatile) | |||
7938 | Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) | |||
7939 | << "volatile" << SourceRange(D.getIdentifierLoc()); | |||
7940 | if (FTI.TypeQuals & Qualifiers::Restrict) | |||
7941 | Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) | |||
7942 | << "restrict" << SourceRange(D.getIdentifierLoc()); | |||
7943 | D.setInvalidType(); | |||
7944 | } | |||
7945 | ||||
7946 | // C++0x [class.ctor]p4: | |||
7947 | // A constructor shall not be declared with a ref-qualifier. | |||
7948 | if (FTI.hasRefQualifier()) { | |||
7949 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) | |||
7950 | << FTI.RefQualifierIsLValueRef | |||
7951 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | |||
7952 | D.setInvalidType(); | |||
7953 | } | |||
7954 | ||||
7955 | // Rebuild the function type "R" without any type qualifiers (in | |||
7956 | // case any of the errors above fired) and with "void" as the | |||
7957 | // return type, since constructors don't have return types. | |||
7958 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
7959 | if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) | |||
7960 | return R; | |||
7961 | ||||
7962 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | |||
7963 | EPI.TypeQuals = 0; | |||
7964 | EPI.RefQualifier = RQ_None; | |||
7965 | ||||
7966 | return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); | |||
7967 | } | |||
7968 | ||||
7969 | /// CheckConstructor - Checks a fully-formed constructor for | |||
7970 | /// well-formedness, issuing any diagnostics required. Returns true if | |||
7971 | /// the constructor declarator is invalid. | |||
7972 | void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { | |||
7973 | CXXRecordDecl *ClassDecl | |||
7974 | = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); | |||
7975 | if (!ClassDecl) | |||
7976 | return Constructor->setInvalidDecl(); | |||
7977 | ||||
7978 | // C++ [class.copy]p3: | |||
7979 | // A declaration of a constructor for a class X is ill-formed if | |||
7980 | // its first parameter is of type (optionally cv-qualified) X and | |||
7981 | // either there are no other parameters or else all other | |||
7982 | // parameters have default arguments. | |||
7983 | if (!Constructor->isInvalidDecl() && | |||
7984 | ((Constructor->getNumParams() == 1) || | |||
7985 | (Constructor->getNumParams() > 1 && | |||
7986 | Constructor->getParamDecl(1)->hasDefaultArg())) && | |||
7987 | Constructor->getTemplateSpecializationKind() | |||
7988 | != TSK_ImplicitInstantiation) { | |||
7989 | QualType ParamType = Constructor->getParamDecl(0)->getType(); | |||
7990 | QualType ClassTy = Context.getTagDeclType(ClassDecl); | |||
7991 | if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { | |||
7992 | SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); | |||
7993 | const char *ConstRef | |||
7994 | = Constructor->getParamDecl(0)->getIdentifier() ? "const &" | |||
7995 | : " const &"; | |||
7996 | Diag(ParamLoc, diag::err_constructor_byvalue_arg) | |||
7997 | << FixItHint::CreateInsertion(ParamLoc, ConstRef); | |||
7998 | ||||
7999 | // FIXME: Rather that making the constructor invalid, we should endeavor | |||
8000 | // to fix the type. | |||
8001 | Constructor->setInvalidDecl(); | |||
8002 | } | |||
8003 | } | |||
8004 | } | |||
8005 | ||||
8006 | /// CheckDestructor - Checks a fully-formed destructor definition for | |||
8007 | /// well-formedness, issuing any diagnostics required. Returns true | |||
8008 | /// on error. | |||
8009 | bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { | |||
8010 | CXXRecordDecl *RD = Destructor->getParent(); | |||
8011 | ||||
8012 | if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { | |||
8013 | SourceLocation Loc; | |||
8014 | ||||
8015 | if (!Destructor->isImplicit()) | |||
8016 | Loc = Destructor->getLocation(); | |||
8017 | else | |||
8018 | Loc = RD->getLocation(); | |||
8019 | ||||
8020 | // If we have a virtual destructor, look up the deallocation function | |||
8021 | if (FunctionDecl *OperatorDelete = | |||
8022 | FindDeallocationFunctionForDestructor(Loc, RD)) { | |||
8023 | Expr *ThisArg = nullptr; | |||
8024 | ||||
8025 | // If the notional 'delete this' expression requires a non-trivial | |||
8026 | // conversion from 'this' to the type of a destroying operator delete's | |||
8027 | // first parameter, perform that conversion now. | |||
8028 | if (OperatorDelete->isDestroyingOperatorDelete()) { | |||
8029 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | |||
8030 | if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { | |||
8031 | // C++ [class.dtor]p13: | |||
8032 | // ... as if for the expression 'delete this' appearing in a | |||
8033 | // non-virtual destructor of the destructor's class. | |||
8034 | ContextRAII SwitchContext(*this, Destructor); | |||
8035 | ExprResult This = | |||
8036 | ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); | |||
8037 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8037, __extension__ __PRETTY_FUNCTION__)); | |||
8038 | This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); | |||
8039 | if (This.isInvalid()) { | |||
8040 | // FIXME: Register this as a context note so that it comes out | |||
8041 | // in the right order. | |||
8042 | Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); | |||
8043 | return true; | |||
8044 | } | |||
8045 | ThisArg = This.get(); | |||
8046 | } | |||
8047 | } | |||
8048 | ||||
8049 | MarkFunctionReferenced(Loc, OperatorDelete); | |||
8050 | Destructor->setOperatorDelete(OperatorDelete, ThisArg); | |||
8051 | } | |||
8052 | } | |||
8053 | ||||
8054 | return false; | |||
8055 | } | |||
8056 | ||||
8057 | /// CheckDestructorDeclarator - Called by ActOnDeclarator to check | |||
8058 | /// the well-formednes of the destructor declarator @p D with type @p | |||
8059 | /// R. If there are any errors in the declarator, this routine will | |||
8060 | /// emit diagnostics and set the declarator to invalid. Even if this happens, | |||
8061 | /// will be updated to reflect a well-formed type for the destructor and | |||
8062 | /// returned. | |||
8063 | QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, | |||
8064 | StorageClass& SC) { | |||
8065 | // C++ [class.dtor]p1: | |||
8066 | // [...] A typedef-name that names a class is a class-name | |||
8067 | // (7.1.3); however, a typedef-name that names a class shall not | |||
8068 | // be used as the identifier in the declarator for a destructor | |||
8069 | // declaration. | |||
8070 | QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); | |||
8071 | if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) | |||
8072 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | |||
8073 | << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); | |||
8074 | else if (const TemplateSpecializationType *TST = | |||
8075 | DeclaratorType->getAs<TemplateSpecializationType>()) | |||
8076 | if (TST->isTypeAlias()) | |||
8077 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | |||
8078 | << DeclaratorType << 1; | |||
8079 | ||||
8080 | // C++ [class.dtor]p2: | |||
8081 | // A destructor is used to destroy objects of its class type. A | |||
8082 | // destructor takes no parameters, and no return type can be | |||
8083 | // specified for it (not even void). The address of a destructor | |||
8084 | // shall not be taken. A destructor shall not be static. A | |||
8085 | // destructor can be invoked for a const, volatile or const | |||
8086 | // volatile object. A destructor shall not be declared const, | |||
8087 | // volatile or const volatile (9.3.2). | |||
8088 | if (SC == SC_Static) { | |||
8089 | if (!D.isInvalidType()) | |||
8090 | Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) | |||
8091 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8092 | << SourceRange(D.getIdentifierLoc()) | |||
8093 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
8094 | ||||
8095 | SC = SC_None; | |||
8096 | } | |||
8097 | if (!D.isInvalidType()) { | |||
8098 | // Destructors don't have return types, but the parser will | |||
8099 | // happily parse something like: | |||
8100 | // | |||
8101 | // class X { | |||
8102 | // float ~X(); | |||
8103 | // }; | |||
8104 | // | |||
8105 | // The return type will be eliminated later. | |||
8106 | if (D.getDeclSpec().hasTypeSpecifier()) | |||
8107 | Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) | |||
8108 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8109 | << SourceRange(D.getIdentifierLoc()); | |||
8110 | else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | |||
8111 | diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, | |||
8112 | SourceLocation(), | |||
8113 | D.getDeclSpec().getConstSpecLoc(), | |||
8114 | D.getDeclSpec().getVolatileSpecLoc(), | |||
8115 | D.getDeclSpec().getRestrictSpecLoc(), | |||
8116 | D.getDeclSpec().getAtomicSpecLoc()); | |||
8117 | D.setInvalidType(); | |||
8118 | } | |||
8119 | } | |||
8120 | ||||
8121 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
8122 | if (FTI.TypeQuals != 0 && !D.isInvalidType()) { | |||
8123 | if (FTI.TypeQuals & Qualifiers::Const) | |||
8124 | Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) | |||
8125 | << "const" << SourceRange(D.getIdentifierLoc()); | |||
8126 | if (FTI.TypeQuals & Qualifiers::Volatile) | |||
8127 | Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) | |||
8128 | << "volatile" << SourceRange(D.getIdentifierLoc()); | |||
8129 | if (FTI.TypeQuals & Qualifiers::Restrict) | |||
8130 | Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) | |||
8131 | << "restrict" << SourceRange(D.getIdentifierLoc()); | |||
8132 | D.setInvalidType(); | |||
8133 | } | |||
8134 | ||||
8135 | // C++0x [class.dtor]p2: | |||
8136 | // A destructor shall not be declared with a ref-qualifier. | |||
8137 | if (FTI.hasRefQualifier()) { | |||
8138 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) | |||
8139 | << FTI.RefQualifierIsLValueRef | |||
8140 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | |||
8141 | D.setInvalidType(); | |||
8142 | } | |||
8143 | ||||
8144 | // Make sure we don't have any parameters. | |||
8145 | if (FTIHasNonVoidParameters(FTI)) { | |||
8146 | Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); | |||
8147 | ||||
8148 | // Delete the parameters. | |||
8149 | FTI.freeParams(); | |||
8150 | D.setInvalidType(); | |||
8151 | } | |||
8152 | ||||
8153 | // Make sure the destructor isn't variadic. | |||
8154 | if (FTI.isVariadic) { | |||
8155 | Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); | |||
8156 | D.setInvalidType(); | |||
8157 | } | |||
8158 | ||||
8159 | // Rebuild the function type "R" without any type qualifiers or | |||
8160 | // parameters (in case any of the errors above fired) and with | |||
8161 | // "void" as the return type, since destructors don't have return | |||
8162 | // types. | |||
8163 | if (!D.isInvalidType()) | |||
8164 | return R; | |||
8165 | ||||
8166 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8167 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | |||
8168 | EPI.Variadic = false; | |||
8169 | EPI.TypeQuals = 0; | |||
8170 | EPI.RefQualifier = RQ_None; | |||
8171 | return Context.getFunctionType(Context.VoidTy, None, EPI); | |||
8172 | } | |||
8173 | ||||
8174 | static void extendLeft(SourceRange &R, SourceRange Before) { | |||
8175 | if (Before.isInvalid()) | |||
8176 | return; | |||
8177 | R.setBegin(Before.getBegin()); | |||
8178 | if (R.getEnd().isInvalid()) | |||
8179 | R.setEnd(Before.getEnd()); | |||
8180 | } | |||
8181 | ||||
8182 | static void extendRight(SourceRange &R, SourceRange After) { | |||
8183 | if (After.isInvalid()) | |||
8184 | return; | |||
8185 | if (R.getBegin().isInvalid()) | |||
8186 | R.setBegin(After.getBegin()); | |||
8187 | R.setEnd(After.getEnd()); | |||
8188 | } | |||
8189 | ||||
8190 | /// CheckConversionDeclarator - Called by ActOnDeclarator to check the | |||
8191 | /// well-formednes of the conversion function declarator @p D with | |||
8192 | /// type @p R. If there are any errors in the declarator, this routine | |||
8193 | /// will emit diagnostics and return true. Otherwise, it will return | |||
8194 | /// false. Either way, the type @p R will be updated to reflect a | |||
8195 | /// well-formed type for the conversion operator. | |||
8196 | void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, | |||
8197 | StorageClass& SC) { | |||
8198 | // C++ [class.conv.fct]p1: | |||
8199 | // Neither parameter types nor return type can be specified. The | |||
8200 | // type of a conversion function (8.3.5) is "function taking no | |||
8201 | // parameter returning conversion-type-id." | |||
8202 | if (SC == SC_Static) { | |||
8203 | if (!D.isInvalidType()) | |||
8204 | Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) | |||
8205 | << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8206 | << D.getName().getSourceRange(); | |||
8207 | D.setInvalidType(); | |||
8208 | SC = SC_None; | |||
8209 | } | |||
8210 | ||||
8211 | TypeSourceInfo *ConvTSI = nullptr; | |||
8212 | QualType ConvType = | |||
8213 | GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); | |||
8214 | ||||
8215 | if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { | |||
8216 | // Conversion functions don't have return types, but the parser will | |||
8217 | // happily parse something like: | |||
8218 | // | |||
8219 | // class X { | |||
8220 | // float operator bool(); | |||
8221 | // }; | |||
8222 | // | |||
8223 | // The return type will be changed later anyway. | |||
8224 | Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) | |||
8225 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8226 | << SourceRange(D.getIdentifierLoc()); | |||
8227 | D.setInvalidType(); | |||
8228 | } | |||
8229 | ||||
8230 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8231 | ||||
8232 | // Make sure we don't have any parameters. | |||
8233 | if (Proto->getNumParams() > 0) { | |||
8234 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); | |||
8235 | ||||
8236 | // Delete the parameters. | |||
8237 | D.getFunctionTypeInfo().freeParams(); | |||
8238 | D.setInvalidType(); | |||
8239 | } else if (Proto->isVariadic()) { | |||
8240 | Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); | |||
8241 | D.setInvalidType(); | |||
8242 | } | |||
8243 | ||||
8244 | // Diagnose "&operator bool()" and other such nonsense. This | |||
8245 | // is actually a gcc extension which we don't support. | |||
8246 | if (Proto->getReturnType() != ConvType) { | |||
8247 | bool NeedsTypedef = false; | |||
8248 | SourceRange Before, After; | |||
8249 | ||||
8250 | // Walk the chunks and extract information on them for our diagnostic. | |||
8251 | bool PastFunctionChunk = false; | |||
8252 | for (auto &Chunk : D.type_objects()) { | |||
8253 | switch (Chunk.Kind) { | |||
8254 | case DeclaratorChunk::Function: | |||
8255 | if (!PastFunctionChunk) { | |||
8256 | if (Chunk.Fun.HasTrailingReturnType) { | |||
8257 | TypeSourceInfo *TRT = nullptr; | |||
8258 | GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); | |||
8259 | if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); | |||
8260 | } | |||
8261 | PastFunctionChunk = true; | |||
8262 | break; | |||
8263 | } | |||
8264 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
8265 | case DeclaratorChunk::Array: | |||
8266 | NeedsTypedef = true; | |||
8267 | extendRight(After, Chunk.getSourceRange()); | |||
8268 | break; | |||
8269 | ||||
8270 | case DeclaratorChunk::Pointer: | |||
8271 | case DeclaratorChunk::BlockPointer: | |||
8272 | case DeclaratorChunk::Reference: | |||
8273 | case DeclaratorChunk::MemberPointer: | |||
8274 | case DeclaratorChunk::Pipe: | |||
8275 | extendLeft(Before, Chunk.getSourceRange()); | |||
8276 | break; | |||
8277 | ||||
8278 | case DeclaratorChunk::Paren: | |||
8279 | extendLeft(Before, Chunk.Loc); | |||
8280 | extendRight(After, Chunk.EndLoc); | |||
8281 | break; | |||
8282 | } | |||
8283 | } | |||
8284 | ||||
8285 | SourceLocation Loc = Before.isValid() ? Before.getBegin() : | |||
8286 | After.isValid() ? After.getBegin() : | |||
8287 | D.getIdentifierLoc(); | |||
8288 | auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); | |||
8289 | DB << Before << After; | |||
8290 | ||||
8291 | if (!NeedsTypedef) { | |||
8292 | DB << /*don't need a typedef*/0; | |||
8293 | ||||
8294 | // If we can provide a correct fix-it hint, do so. | |||
8295 | if (After.isInvalid() && ConvTSI) { | |||
8296 | SourceLocation InsertLoc = | |||
8297 | getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); | |||
8298 | DB << FixItHint::CreateInsertion(InsertLoc, " ") | |||
8299 | << FixItHint::CreateInsertionFromRange( | |||
8300 | InsertLoc, CharSourceRange::getTokenRange(Before)) | |||
8301 | << FixItHint::CreateRemoval(Before); | |||
8302 | } | |||
8303 | } else if (!Proto->getReturnType()->isDependentType()) { | |||
8304 | DB << /*typedef*/1 << Proto->getReturnType(); | |||
8305 | } else if (getLangOpts().CPlusPlus11) { | |||
8306 | DB << /*alias template*/2 << Proto->getReturnType(); | |||
8307 | } else { | |||
8308 | DB << /*might not be fixable*/3; | |||
8309 | } | |||
8310 | ||||
8311 | // Recover by incorporating the other type chunks into the result type. | |||
8312 | // Note, this does *not* change the name of the function. This is compatible | |||
8313 | // with the GCC extension: | |||
8314 | // struct S { &operator int(); } s; | |||
8315 | // int &r = s.operator int(); // ok in GCC | |||
8316 | // S::operator int&() {} // error in GCC, function name is 'operator int'. | |||
8317 | ConvType = Proto->getReturnType(); | |||
8318 | } | |||
8319 | ||||
8320 | // C++ [class.conv.fct]p4: | |||
8321 | // The conversion-type-id shall not represent a function type nor | |||
8322 | // an array type. | |||
8323 | if (ConvType->isArrayType()) { | |||
8324 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); | |||
8325 | ConvType = Context.getPointerType(ConvType); | |||
8326 | D.setInvalidType(); | |||
8327 | } else if (ConvType->isFunctionType()) { | |||
8328 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); | |||
8329 | ConvType = Context.getPointerType(ConvType); | |||
8330 | D.setInvalidType(); | |||
8331 | } | |||
8332 | ||||
8333 | // Rebuild the function type "R" without any parameters (in case any | |||
8334 | // of the errors above fired) and with the conversion type as the | |||
8335 | // return type. | |||
8336 | if (D.isInvalidType()) | |||
8337 | R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); | |||
8338 | ||||
8339 | // C++0x explicit conversion operators. | |||
8340 | if (D.getDeclSpec().isExplicitSpecified()) | |||
8341 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
8342 | getLangOpts().CPlusPlus11 ? | |||
8343 | diag::warn_cxx98_compat_explicit_conversion_functions : | |||
8344 | diag::ext_explicit_conversion_functions) | |||
8345 | << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); | |||
8346 | } | |||
8347 | ||||
8348 | /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete | |||
8349 | /// the declaration of the given C++ conversion function. This routine | |||
8350 | /// is responsible for recording the conversion function in the C++ | |||
8351 | /// class, if possible. | |||
8352 | Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { | |||
8353 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8353, __extension__ __PRETTY_FUNCTION__)); | |||
8354 | ||||
8355 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); | |||
8356 | ||||
8357 | // Make sure we aren't redeclaring the conversion function. | |||
8358 | QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); | |||
8359 | ||||
8360 | // C++ [class.conv.fct]p1: | |||
8361 | // [...] A conversion function is never used to convert a | |||
8362 | // (possibly cv-qualified) object to the (possibly cv-qualified) | |||
8363 | // same object type (or a reference to it), to a (possibly | |||
8364 | // cv-qualified) base class of that type (or a reference to it), | |||
8365 | // or to (possibly cv-qualified) void. | |||
8366 | // FIXME: Suppress this warning if the conversion function ends up being a | |||
8367 | // virtual function that overrides a virtual function in a base class. | |||
8368 | QualType ClassType | |||
8369 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
8370 | if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) | |||
8371 | ConvType = ConvTypeRef->getPointeeType(); | |||
8372 | if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && | |||
8373 | Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) | |||
8374 | /* Suppress diagnostics for instantiations. */; | |||
8375 | else if (ConvType->isRecordType()) { | |||
8376 | ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); | |||
8377 | if (ConvType == ClassType) | |||
8378 | Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) | |||
8379 | << ClassType; | |||
8380 | else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) | |||
8381 | Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) | |||
8382 | << ClassType << ConvType; | |||
8383 | } else if (ConvType->isVoidType()) { | |||
8384 | Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) | |||
8385 | << ClassType << ConvType; | |||
8386 | } | |||
8387 | ||||
8388 | if (FunctionTemplateDecl *ConversionTemplate | |||
8389 | = Conversion->getDescribedFunctionTemplate()) | |||
8390 | return ConversionTemplate; | |||
8391 | ||||
8392 | return Conversion; | |||
8393 | } | |||
8394 | ||||
8395 | namespace { | |||
8396 | /// Utility class to accumulate and print a diagnostic listing the invalid | |||
8397 | /// specifier(s) on a declaration. | |||
8398 | struct BadSpecifierDiagnoser { | |||
8399 | BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) | |||
8400 | : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} | |||
8401 | ~BadSpecifierDiagnoser() { | |||
8402 | Diagnostic << Specifiers; | |||
8403 | } | |||
8404 | ||||
8405 | template<typename T> void check(SourceLocation SpecLoc, T Spec) { | |||
8406 | return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); | |||
8407 | } | |||
8408 | void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { | |||
8409 | return check(SpecLoc, | |||
8410 | DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); | |||
8411 | } | |||
8412 | void check(SourceLocation SpecLoc, const char *Spec) { | |||
8413 | if (SpecLoc.isInvalid()) return; | |||
8414 | Diagnostic << SourceRange(SpecLoc, SpecLoc); | |||
8415 | if (!Specifiers.empty()) Specifiers += " "; | |||
8416 | Specifiers += Spec; | |||
8417 | } | |||
8418 | ||||
8419 | Sema &S; | |||
8420 | Sema::SemaDiagnosticBuilder Diagnostic; | |||
8421 | std::string Specifiers; | |||
8422 | }; | |||
8423 | } | |||
8424 | ||||
8425 | /// Check the validity of a declarator that we parsed for a deduction-guide. | |||
8426 | /// These aren't actually declarators in the grammar, so we need to check that | |||
8427 | /// the user didn't specify any pieces that are not part of the deduction-guide | |||
8428 | /// grammar. | |||
8429 | void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, | |||
8430 | StorageClass &SC) { | |||
8431 | TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); | |||
8432 | TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); | |||
8433 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8433, __extension__ __PRETTY_FUNCTION__)); | |||
8434 | ||||
8435 | // C++ [temp.deduct.guide]p3: | |||
8436 | // A deduction-gide shall be declared in the same scope as the | |||
8437 | // corresponding class template. | |||
8438 | if (!CurContext->getRedeclContext()->Equals( | |||
8439 | GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { | |||
8440 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) | |||
8441 | << GuidedTemplateDecl; | |||
8442 | Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); | |||
8443 | } | |||
8444 | ||||
8445 | auto &DS = D.getMutableDeclSpec(); | |||
8446 | // We leave 'friend' and 'virtual' to be rejected in the normal way. | |||
8447 | if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || | |||
8448 | DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || | |||
8449 | DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { | |||
8450 | BadSpecifierDiagnoser Diagnoser( | |||
8451 | *this, D.getIdentifierLoc(), | |||
8452 | diag::err_deduction_guide_invalid_specifier); | |||
8453 | ||||
8454 | Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); | |||
8455 | DS.ClearStorageClassSpecs(); | |||
8456 | SC = SC_None; | |||
8457 | ||||
8458 | // 'explicit' is permitted. | |||
8459 | Diagnoser.check(DS.getInlineSpecLoc(), "inline"); | |||
8460 | Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); | |||
8461 | Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); | |||
8462 | DS.ClearConstexprSpec(); | |||
8463 | ||||
8464 | Diagnoser.check(DS.getConstSpecLoc(), "const"); | |||
8465 | Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); | |||
8466 | Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); | |||
8467 | Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); | |||
8468 | Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); | |||
8469 | DS.ClearTypeQualifiers(); | |||
8470 | ||||
8471 | Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); | |||
8472 | Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); | |||
8473 | Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); | |||
8474 | Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); | |||
8475 | DS.ClearTypeSpecType(); | |||
8476 | } | |||
8477 | ||||
8478 | if (D.isInvalidType()) | |||
8479 | return; | |||
8480 | ||||
8481 | // Check the declarator is simple enough. | |||
8482 | bool FoundFunction = false; | |||
8483 | for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { | |||
8484 | if (Chunk.Kind == DeclaratorChunk::Paren) | |||
8485 | continue; | |||
8486 | if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { | |||
8487 | Diag(D.getDeclSpec().getLocStart(), | |||
8488 | diag::err_deduction_guide_with_complex_decl) | |||
8489 | << D.getSourceRange(); | |||
8490 | break; | |||
8491 | } | |||
8492 | if (!Chunk.Fun.hasTrailingReturnType()) { | |||
8493 | Diag(D.getName().getLocStart(), | |||
8494 | diag::err_deduction_guide_no_trailing_return_type); | |||
8495 | break; | |||
8496 | } | |||
8497 | ||||
8498 | // Check that the return type is written as a specialization of | |||
8499 | // the template specified as the deduction-guide's name. | |||
8500 | ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); | |||
8501 | TypeSourceInfo *TSI = nullptr; | |||
8502 | QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); | |||
8503 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8503, __extension__ __PRETTY_FUNCTION__)); | |||
8504 | bool AcceptableReturnType = false; | |||
8505 | bool MightInstantiateToSpecialization = false; | |||
8506 | if (auto RetTST = | |||
8507 | TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { | |||
8508 | TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); | |||
8509 | bool TemplateMatches = | |||
8510 | Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); | |||
8511 | if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) | |||
8512 | AcceptableReturnType = true; | |||
8513 | else { | |||
8514 | // This could still instantiate to the right type, unless we know it | |||
8515 | // names the wrong class template. | |||
8516 | auto *TD = SpecifiedName.getAsTemplateDecl(); | |||
8517 | MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && | |||
8518 | !TemplateMatches); | |||
8519 | } | |||
8520 | } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { | |||
8521 | MightInstantiateToSpecialization = true; | |||
8522 | } | |||
8523 | ||||
8524 | if (!AcceptableReturnType) { | |||
8525 | Diag(TSI->getTypeLoc().getLocStart(), | |||
8526 | diag::err_deduction_guide_bad_trailing_return_type) | |||
8527 | << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization | |||
8528 | << TSI->getTypeLoc().getSourceRange(); | |||
8529 | } | |||
8530 | ||||
8531 | // Keep going to check that we don't have any inner declarator pieces (we | |||
8532 | // could still have a function returning a pointer to a function). | |||
8533 | FoundFunction = true; | |||
8534 | } | |||
8535 | ||||
8536 | if (D.isFunctionDefinition()) | |||
8537 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); | |||
8538 | } | |||
8539 | ||||
8540 | //===----------------------------------------------------------------------===// | |||
8541 | // Namespace Handling | |||
8542 | //===----------------------------------------------------------------------===// | |||
8543 | ||||
8544 | /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is | |||
8545 | /// reopened. | |||
8546 | static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, | |||
8547 | SourceLocation Loc, | |||
8548 | IdentifierInfo *II, bool *IsInline, | |||
8549 | NamespaceDecl *PrevNS) { | |||
8550 | assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline() ) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8550, __extension__ __PRETTY_FUNCTION__)); | |||
8551 | ||||
8552 | // HACK: Work around a bug in libstdc++4.6's <atomic>, where | |||
8553 | // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as | |||
8554 | // inline namespaces, with the intention of bringing names into namespace std. | |||
8555 | // | |||
8556 | // We support this just well enough to get that case working; this is not | |||
8557 | // sufficient to support reopening namespaces as inline in general. | |||
8558 | if (*IsInline && II && II->getName().startswith("__atomic") && | |||
8559 | S.getSourceManager().isInSystemHeader(Loc)) { | |||
8560 | // Mark all prior declarations of the namespace as inline. | |||
8561 | for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; | |||
8562 | NS = NS->getPreviousDecl()) | |||
8563 | NS->setInline(*IsInline); | |||
8564 | // Patch up the lookup table for the containing namespace. This isn't really | |||
8565 | // correct, but it's good enough for this particular case. | |||
8566 | for (auto *I : PrevNS->decls()) | |||
8567 | if (auto *ND = dyn_cast<NamedDecl>(I)) | |||
8568 | PrevNS->getParent()->makeDeclVisibleInContext(ND); | |||
8569 | return; | |||
8570 | } | |||
8571 | ||||
8572 | if (PrevNS->isInline()) | |||
8573 | // The user probably just forgot the 'inline', so suggest that it | |||
8574 | // be added back. | |||
8575 | S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) | |||
8576 | << FixItHint::CreateInsertion(KeywordLoc, "inline "); | |||
8577 | else | |||
8578 | S.Diag(Loc, diag::err_inline_namespace_mismatch); | |||
8579 | ||||
8580 | S.Diag(PrevNS->getLocation(), diag::note_previous_definition); | |||
8581 | *IsInline = PrevNS->isInline(); | |||
8582 | } | |||
8583 | ||||
8584 | /// ActOnStartNamespaceDef - This is called at the start of a namespace | |||
8585 | /// definition. | |||
8586 | Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, | |||
8587 | SourceLocation InlineLoc, | |||
8588 | SourceLocation NamespaceLoc, | |||
8589 | SourceLocation IdentLoc, | |||
8590 | IdentifierInfo *II, | |||
8591 | SourceLocation LBrace, | |||
8592 | AttributeList *AttrList, | |||
8593 | UsingDirectiveDecl *&UD) { | |||
8594 | SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; | |||
8595 | // For anonymous namespace, take the location of the left brace. | |||
8596 | SourceLocation Loc = II ? IdentLoc : LBrace; | |||
8597 | bool IsInline = InlineLoc.isValid(); | |||
8598 | bool IsInvalid = false; | |||
8599 | bool IsStd = false; | |||
8600 | bool AddToKnown = false; | |||
8601 | Scope *DeclRegionScope = NamespcScope->getParent(); | |||
8602 | ||||
8603 | NamespaceDecl *PrevNS = nullptr; | |||
8604 | if (II) { | |||
8605 | // C++ [namespace.def]p2: | |||
8606 | // The identifier in an original-namespace-definition shall not | |||
8607 | // have been previously defined in the declarative region in | |||
8608 | // which the original-namespace-definition appears. The | |||
8609 | // identifier in an original-namespace-definition is the name of | |||
8610 | // the namespace. Subsequently in that declarative region, it is | |||
8611 | // treated as an original-namespace-name. | |||
8612 | // | |||
8613 | // Since namespace names are unique in their scope, and we don't | |||
8614 | // look through using directives, just look for any ordinary names | |||
8615 | // as if by qualified name lookup. | |||
8616 | LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, | |||
8617 | ForExternalRedeclaration); | |||
8618 | LookupQualifiedName(R, CurContext->getRedeclContext()); | |||
8619 | NamedDecl *PrevDecl = | |||
8620 | R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; | |||
8621 | PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); | |||
8622 | ||||
8623 | if (PrevNS) { | |||
8624 | // This is an extended namespace definition. | |||
8625 | if (IsInline != PrevNS->isInline()) | |||
8626 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, | |||
8627 | &IsInline, PrevNS); | |||
8628 | } else if (PrevDecl) { | |||
8629 | // This is an invalid name redefinition. | |||
8630 | Diag(Loc, diag::err_redefinition_different_kind) | |||
8631 | << II; | |||
8632 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
8633 | IsInvalid = true; | |||
8634 | // Continue on to push Namespc as current DeclContext and return it. | |||
8635 | } else if (II->isStr("std") && | |||
8636 | CurContext->getRedeclContext()->isTranslationUnit()) { | |||
8637 | // This is the first "real" definition of the namespace "std", so update | |||
8638 | // our cache of the "std" namespace to point at this definition. | |||
8639 | PrevNS = getStdNamespace(); | |||
8640 | IsStd = true; | |||
8641 | AddToKnown = !IsInline; | |||
8642 | } else { | |||
8643 | // We've seen this namespace for the first time. | |||
8644 | AddToKnown = !IsInline; | |||
8645 | } | |||
8646 | } else { | |||
8647 | // Anonymous namespaces. | |||
8648 | ||||
8649 | // Determine whether the parent already has an anonymous namespace. | |||
8650 | DeclContext *Parent = CurContext->getRedeclContext(); | |||
8651 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | |||
8652 | PrevNS = TU->getAnonymousNamespace(); | |||
8653 | } else { | |||
8654 | NamespaceDecl *ND = cast<NamespaceDecl>(Parent); | |||
8655 | PrevNS = ND->getAnonymousNamespace(); | |||
8656 | } | |||
8657 | ||||
8658 | if (PrevNS && IsInline != PrevNS->isInline()) | |||
8659 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, | |||
8660 | &IsInline, PrevNS); | |||
8661 | } | |||
8662 | ||||
8663 | NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, | |||
8664 | StartLoc, Loc, II, PrevNS); | |||
8665 | if (IsInvalid) | |||
8666 | Namespc->setInvalidDecl(); | |||
8667 | ||||
8668 | ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); | |||
8669 | AddPragmaAttributes(DeclRegionScope, Namespc); | |||
8670 | ||||
8671 | // FIXME: Should we be merging attributes? | |||
8672 | if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) | |||
8673 | PushNamespaceVisibilityAttr(Attr, Loc); | |||
8674 | ||||
8675 | if (IsStd) | |||
8676 | StdNamespace = Namespc; | |||
8677 | if (AddToKnown) | |||
8678 | KnownNamespaces[Namespc] = false; | |||
8679 | ||||
8680 | if (II) { | |||
8681 | PushOnScopeChains(Namespc, DeclRegionScope); | |||
8682 | } else { | |||
8683 | // Link the anonymous namespace into its parent. | |||
8684 | DeclContext *Parent = CurContext->getRedeclContext(); | |||
8685 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | |||
8686 | TU->setAnonymousNamespace(Namespc); | |||
8687 | } else { | |||
8688 | cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); | |||
8689 | } | |||
8690 | ||||
8691 | CurContext->addDecl(Namespc); | |||
8692 | ||||
8693 | // C++ [namespace.unnamed]p1. An unnamed-namespace-definition | |||
8694 | // behaves as if it were replaced by | |||
8695 | // namespace unique { /* empty body */ } | |||
8696 | // using namespace unique; | |||
8697 | // namespace unique { namespace-body } | |||
8698 | // where all occurrences of 'unique' in a translation unit are | |||
8699 | // replaced by the same identifier and this identifier differs | |||
8700 | // from all other identifiers in the entire program. | |||
8701 | ||||
8702 | // We just create the namespace with an empty name and then add an | |||
8703 | // implicit using declaration, just like the standard suggests. | |||
8704 | // | |||
8705 | // CodeGen enforces the "universally unique" aspect by giving all | |||
8706 | // declarations semantically contained within an anonymous | |||
8707 | // namespace internal linkage. | |||
8708 | ||||
8709 | if (!PrevNS) { | |||
8710 | UD = UsingDirectiveDecl::Create(Context, Parent, | |||
8711 | /* 'using' */ LBrace, | |||
8712 | /* 'namespace' */ SourceLocation(), | |||
8713 | /* qualifier */ NestedNameSpecifierLoc(), | |||
8714 | /* identifier */ SourceLocation(), | |||
8715 | Namespc, | |||
8716 | /* Ancestor */ Parent); | |||
8717 | UD->setImplicit(); | |||
8718 | Parent->addDecl(UD); | |||
8719 | } | |||
8720 | } | |||
8721 | ||||
8722 | ActOnDocumentableDecl(Namespc); | |||
8723 | ||||
8724 | // Although we could have an invalid decl (i.e. the namespace name is a | |||
8725 | // redefinition), push it as current DeclContext and try to continue parsing. | |||
8726 | // FIXME: We should be able to push Namespc here, so that the each DeclContext | |||
8727 | // for the namespace has the declarations that showed up in that particular | |||
8728 | // namespace definition. | |||
8729 | PushDeclContext(NamespcScope, Namespc); | |||
8730 | return Namespc; | |||
8731 | } | |||
8732 | ||||
8733 | /// getNamespaceDecl - Returns the namespace a decl represents. If the decl | |||
8734 | /// is a namespace alias, returns the namespace it points to. | |||
8735 | static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { | |||
8736 | if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) | |||
8737 | return AD->getNamespace(); | |||
8738 | return dyn_cast_or_null<NamespaceDecl>(D); | |||
8739 | } | |||
8740 | ||||
8741 | /// ActOnFinishNamespaceDef - This callback is called after a namespace is | |||
8742 | /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. | |||
8743 | void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { | |||
8744 | NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); | |||
8745 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8745, __extension__ __PRETTY_FUNCTION__)); | |||
8746 | Namespc->setRBraceLoc(RBrace); | |||
8747 | PopDeclContext(); | |||
8748 | if (Namespc->hasAttr<VisibilityAttr>()) | |||
8749 | PopPragmaVisibility(true, RBrace); | |||
8750 | } | |||
8751 | ||||
8752 | CXXRecordDecl *Sema::getStdBadAlloc() const { | |||
8753 | return cast_or_null<CXXRecordDecl>( | |||
8754 | StdBadAlloc.get(Context.getExternalSource())); | |||
8755 | } | |||
8756 | ||||
8757 | EnumDecl *Sema::getStdAlignValT() const { | |||
8758 | return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); | |||
8759 | } | |||
8760 | ||||
8761 | NamespaceDecl *Sema::getStdNamespace() const { | |||
8762 | return cast_or_null<NamespaceDecl>( | |||
8763 | StdNamespace.get(Context.getExternalSource())); | |||
8764 | } | |||
8765 | ||||
8766 | NamespaceDecl *Sema::lookupStdExperimentalNamespace() { | |||
8767 | if (!StdExperimentalNamespaceCache) { | |||
8768 | if (auto Std = getStdNamespace()) { | |||
8769 | LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), | |||
8770 | SourceLocation(), LookupNamespaceName); | |||
8771 | if (!LookupQualifiedName(Result, Std) || | |||
8772 | !(StdExperimentalNamespaceCache = | |||
8773 | Result.getAsSingle<NamespaceDecl>())) | |||
8774 | Result.suppressDiagnostics(); | |||
8775 | } | |||
8776 | } | |||
8777 | return StdExperimentalNamespaceCache; | |||
8778 | } | |||
8779 | ||||
8780 | /// \brief Retrieve the special "std" namespace, which may require us to | |||
8781 | /// implicitly define the namespace. | |||
8782 | NamespaceDecl *Sema::getOrCreateStdNamespace() { | |||
8783 | if (!StdNamespace) { | |||
8784 | // The "std" namespace has not yet been defined, so build one implicitly. | |||
8785 | StdNamespace = NamespaceDecl::Create(Context, | |||
8786 | Context.getTranslationUnitDecl(), | |||
8787 | /*Inline=*/false, | |||
8788 | SourceLocation(), SourceLocation(), | |||
8789 | &PP.getIdentifierTable().get("std"), | |||
8790 | /*PrevDecl=*/nullptr); | |||
8791 | getStdNamespace()->setImplicit(true); | |||
8792 | } | |||
8793 | ||||
8794 | return getStdNamespace(); | |||
8795 | } | |||
8796 | ||||
8797 | bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { | |||
8798 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8799, __extension__ __PRETTY_FUNCTION__)) | |||
8799 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8799, __extension__ __PRETTY_FUNCTION__)); | |||
8800 | ||||
8801 | // We're looking for implicit instantiations of | |||
8802 | // template <typename E> class std::initializer_list. | |||
8803 | ||||
8804 | if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. | |||
8805 | return false; | |||
8806 | ||||
8807 | ClassTemplateDecl *Template = nullptr; | |||
8808 | const TemplateArgument *Arguments = nullptr; | |||
8809 | ||||
8810 | if (const RecordType *RT = Ty->getAs<RecordType>()) { | |||
8811 | ||||
8812 | ClassTemplateSpecializationDecl *Specialization = | |||
8813 | dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); | |||
8814 | if (!Specialization) | |||
8815 | return false; | |||
8816 | ||||
8817 | Template = Specialization->getSpecializedTemplate(); | |||
8818 | Arguments = Specialization->getTemplateArgs().data(); | |||
8819 | } else if (const TemplateSpecializationType *TST = | |||
8820 | Ty->getAs<TemplateSpecializationType>()) { | |||
8821 | Template = dyn_cast_or_null<ClassTemplateDecl>( | |||
8822 | TST->getTemplateName().getAsTemplateDecl()); | |||
8823 | Arguments = TST->getArgs(); | |||
8824 | } | |||
8825 | if (!Template) | |||
8826 | return false; | |||
8827 | ||||
8828 | if (!StdInitializerList) { | |||
8829 | // Haven't recognized std::initializer_list yet, maybe this is it. | |||
8830 | CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); | |||
8831 | if (TemplateClass->getIdentifier() != | |||
8832 | &PP.getIdentifierTable().get("initializer_list") || | |||
8833 | !getStdNamespace()->InEnclosingNamespaceSetOf( | |||
8834 | TemplateClass->getDeclContext())) | |||
8835 | return false; | |||
8836 | // This is a template called std::initializer_list, but is it the right | |||
8837 | // template? | |||
8838 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
8839 | if (Params->getMinRequiredArguments() != 1) | |||
8840 | return false; | |||
8841 | if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) | |||
8842 | return false; | |||
8843 | ||||
8844 | // It's the right template. | |||
8845 | StdInitializerList = Template; | |||
8846 | } | |||
8847 | ||||
8848 | if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) | |||
8849 | return false; | |||
8850 | ||||
8851 | // This is an instance of std::initializer_list. Find the argument type. | |||
8852 | if (Element) | |||
8853 | *Element = Arguments[0].getAsType(); | |||
8854 | return true; | |||
8855 | } | |||
8856 | ||||
8857 | static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ | |||
8858 | NamespaceDecl *Std = S.getStdNamespace(); | |||
8859 | if (!Std) { | |||
8860 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | |||
8861 | return nullptr; | |||
8862 | } | |||
8863 | ||||
8864 | LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), | |||
8865 | Loc, Sema::LookupOrdinaryName); | |||
8866 | if (!S.LookupQualifiedName(Result, Std)) { | |||
8867 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | |||
8868 | return nullptr; | |||
8869 | } | |||
8870 | ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); | |||
8871 | if (!Template) { | |||
8872 | Result.suppressDiagnostics(); | |||
8873 | // We found something weird. Complain about the first thing we found. | |||
8874 | NamedDecl *Found = *Result.begin(); | |||
8875 | S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); | |||
8876 | return nullptr; | |||
8877 | } | |||
8878 | ||||
8879 | // We found some template called std::initializer_list. Now verify that it's | |||
8880 | // correct. | |||
8881 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
8882 | if (Params->getMinRequiredArguments() != 1 || | |||
8883 | !isa<TemplateTypeParmDecl>(Params->getParam(0))) { | |||
8884 | S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); | |||
8885 | return nullptr; | |||
8886 | } | |||
8887 | ||||
8888 | return Template; | |||
8889 | } | |||
8890 | ||||
8891 | QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { | |||
8892 | if (!StdInitializerList) { | |||
8893 | StdInitializerList = LookupStdInitializerList(*this, Loc); | |||
8894 | if (!StdInitializerList) | |||
8895 | return QualType(); | |||
8896 | } | |||
8897 | ||||
8898 | TemplateArgumentListInfo Args(Loc, Loc); | |||
8899 | Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), | |||
8900 | Context.getTrivialTypeSourceInfo(Element, | |||
8901 | Loc))); | |||
8902 | return Context.getCanonicalType( | |||
8903 | CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); | |||
8904 | } | |||
8905 | ||||
8906 | bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { | |||
8907 | // C++ [dcl.init.list]p2: | |||
8908 | // A constructor is an initializer-list constructor if its first parameter | |||
8909 | // is of type std::initializer_list<E> or reference to possibly cv-qualified | |||
8910 | // std::initializer_list<E> for some type E, and either there are no other | |||
8911 | // parameters or else all other parameters have default arguments. | |||
8912 | if (Ctor->getNumParams() < 1 || | |||
8913 | (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) | |||
8914 | return false; | |||
8915 | ||||
8916 | QualType ArgType = Ctor->getParamDecl(0)->getType(); | |||
8917 | if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) | |||
8918 | ArgType = RT->getPointeeType().getUnqualifiedType(); | |||
8919 | ||||
8920 | return isStdInitializerList(ArgType, nullptr); | |||
8921 | } | |||
8922 | ||||
8923 | /// \brief Determine whether a using statement is in a context where it will be | |||
8924 | /// apply in all contexts. | |||
8925 | static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { | |||
8926 | switch (CurContext->getDeclKind()) { | |||
8927 | case Decl::TranslationUnit: | |||
8928 | return true; | |||
8929 | case Decl::LinkageSpec: | |||
8930 | return IsUsingDirectiveInToplevelContext(CurContext->getParent()); | |||
8931 | default: | |||
8932 | return false; | |||
8933 | } | |||
8934 | } | |||
8935 | ||||
8936 | namespace { | |||
8937 | ||||
8938 | // Callback to only accept typo corrections that are namespaces. | |||
8939 | class NamespaceValidatorCCC : public CorrectionCandidateCallback { | |||
8940 | public: | |||
8941 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
8942 | if (NamedDecl *ND = candidate.getCorrectionDecl()) | |||
8943 | return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); | |||
8944 | return false; | |||
8945 | } | |||
8946 | }; | |||
8947 | ||||
8948 | } | |||
8949 | ||||
8950 | static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, | |||
8951 | CXXScopeSpec &SS, | |||
8952 | SourceLocation IdentLoc, | |||
8953 | IdentifierInfo *Ident) { | |||
8954 | R.clear(); | |||
8955 | if (TypoCorrection Corrected = | |||
8956 | S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, | |||
8957 | llvm::make_unique<NamespaceValidatorCCC>(), | |||
8958 | Sema::CTK_ErrorRecovery)) { | |||
8959 | if (DeclContext *DC = S.computeDeclContext(SS, false)) { | |||
8960 | std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); | |||
8961 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
8962 | Ident->getName().equals(CorrectedStr); | |||
8963 | S.diagnoseTypo(Corrected, | |||
8964 | S.PDiag(diag::err_using_directive_member_suggest) | |||
8965 | << Ident << DC << DroppedSpecifier << SS.getRange(), | |||
8966 | S.PDiag(diag::note_namespace_defined_here)); | |||
8967 | } else { | |||
8968 | S.diagnoseTypo(Corrected, | |||
8969 | S.PDiag(diag::err_using_directive_suggest) << Ident, | |||
8970 | S.PDiag(diag::note_namespace_defined_here)); | |||
8971 | } | |||
8972 | R.addDecl(Corrected.getFoundDecl()); | |||
8973 | return true; | |||
8974 | } | |||
8975 | return false; | |||
8976 | } | |||
8977 | ||||
8978 | Decl *Sema::ActOnUsingDirective(Scope *S, | |||
8979 | SourceLocation UsingLoc, | |||
8980 | SourceLocation NamespcLoc, | |||
8981 | CXXScopeSpec &SS, | |||
8982 | SourceLocation IdentLoc, | |||
8983 | IdentifierInfo *NamespcName, | |||
8984 | AttributeList *AttrList) { | |||
8985 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8985, __extension__ __PRETTY_FUNCTION__)); | |||
8986 | assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName." ) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8986, __extension__ __PRETTY_FUNCTION__)); | |||
8987 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8987, __extension__ __PRETTY_FUNCTION__)); | |||
8988 | ||||
8989 | // This can only happen along a recovery path. | |||
8990 | while (S->isTemplateParamScope()) | |||
8991 | S = S->getParent(); | |||
8992 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8992, __extension__ __PRETTY_FUNCTION__)); | |||
8993 | ||||
8994 | UsingDirectiveDecl *UDir = nullptr; | |||
8995 | NestedNameSpecifier *Qualifier = nullptr; | |||
8996 | if (SS.isSet()) | |||
8997 | Qualifier = SS.getScopeRep(); | |||
8998 | ||||
8999 | // Lookup namespace name. | |||
9000 | LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); | |||
9001 | LookupParsedName(R, S, &SS); | |||
9002 | if (R.isAmbiguous()) | |||
9003 | return nullptr; | |||
9004 | ||||
9005 | if (R.empty()) { | |||
9006 | R.clear(); | |||
9007 | // Allow "using namespace std;" or "using namespace ::std;" even if | |||
9008 | // "std" hasn't been defined yet, for GCC compatibility. | |||
9009 | if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && | |||
9010 | NamespcName->isStr("std")) { | |||
9011 | Diag(IdentLoc, diag::ext_using_undefined_std); | |||
9012 | R.addDecl(getOrCreateStdNamespace()); | |||
9013 | R.resolveKind(); | |||
9014 | } | |||
9015 | // Otherwise, attempt typo correction. | |||
9016 | else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); | |||
9017 | } | |||
9018 | ||||
9019 | if (!R.empty()) { | |||
9020 | NamedDecl *Named = R.getRepresentativeDecl(); | |||
9021 | NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); | |||
9022 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9022, __extension__ __PRETTY_FUNCTION__)); | |||
9023 | ||||
9024 | // The use of a nested name specifier may trigger deprecation warnings. | |||
9025 | DiagnoseUseOfDecl(Named, IdentLoc); | |||
9026 | ||||
9027 | // C++ [namespace.udir]p1: | |||
9028 | // A using-directive specifies that the names in the nominated | |||
9029 | // namespace can be used in the scope in which the | |||
9030 | // using-directive appears after the using-directive. During | |||
9031 | // unqualified name lookup (3.4.1), the names appear as if they | |||
9032 | // were declared in the nearest enclosing namespace which | |||
9033 | // contains both the using-directive and the nominated | |||
9034 | // namespace. [Note: in this context, "contains" means "contains | |||
9035 | // directly or indirectly". ] | |||
9036 | ||||
9037 | // Find enclosing context containing both using-directive and | |||
9038 | // nominated namespace. | |||
9039 | DeclContext *CommonAncestor = cast<DeclContext>(NS); | |||
9040 | while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) | |||
9041 | CommonAncestor = CommonAncestor->getParent(); | |||
9042 | ||||
9043 | UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, | |||
9044 | SS.getWithLocInContext(Context), | |||
9045 | IdentLoc, Named, CommonAncestor); | |||
9046 | ||||
9047 | if (IsUsingDirectiveInToplevelContext(CurContext) && | |||
9048 | !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { | |||
9049 | Diag(IdentLoc, diag::warn_using_directive_in_header); | |||
9050 | } | |||
9051 | ||||
9052 | PushUsingDirective(S, UDir); | |||
9053 | } else { | |||
9054 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | |||
9055 | } | |||
9056 | ||||
9057 | if (UDir) | |||
9058 | ProcessDeclAttributeList(S, UDir, AttrList); | |||
9059 | ||||
9060 | return UDir; | |||
9061 | } | |||
9062 | ||||
9063 | void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { | |||
9064 | // If the scope has an associated entity and the using directive is at | |||
9065 | // namespace or translation unit scope, add the UsingDirectiveDecl into | |||
9066 | // its lookup structure so qualified name lookup can find it. | |||
9067 | DeclContext *Ctx = S->getEntity(); | |||
9068 | if (Ctx && !Ctx->isFunctionOrMethod()) | |||
9069 | Ctx->addDecl(UDir); | |||
9070 | else | |||
9071 | // Otherwise, it is at block scope. The using-directives will affect lookup | |||
9072 | // only to the end of the scope. | |||
9073 | S->PushUsingDirective(UDir); | |||
9074 | } | |||
9075 | ||||
9076 | ||||
9077 | Decl *Sema::ActOnUsingDeclaration(Scope *S, | |||
9078 | AccessSpecifier AS, | |||
9079 | SourceLocation UsingLoc, | |||
9080 | SourceLocation TypenameLoc, | |||
9081 | CXXScopeSpec &SS, | |||
9082 | UnqualifiedId &Name, | |||
9083 | SourceLocation EllipsisLoc, | |||
9084 | AttributeList *AttrList) { | |||
9085 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9085, __extension__ __PRETTY_FUNCTION__)); | |||
9086 | ||||
9087 | if (SS.isEmpty()) { | |||
9088 | Diag(Name.getLocStart(), diag::err_using_requires_qualname); | |||
9089 | return nullptr; | |||
9090 | } | |||
9091 | ||||
9092 | switch (Name.getKind()) { | |||
9093 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
9094 | case UnqualifiedIdKind::IK_Identifier: | |||
9095 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
9096 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
9097 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
9098 | break; | |||
9099 | ||||
9100 | case UnqualifiedIdKind::IK_ConstructorName: | |||
9101 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
9102 | // C++11 inheriting constructors. | |||
9103 | Diag(Name.getLocStart(), | |||
9104 | getLangOpts().CPlusPlus11 ? | |||
9105 | diag::warn_cxx98_compat_using_decl_constructor : | |||
9106 | diag::err_using_decl_constructor) | |||
9107 | << SS.getRange(); | |||
9108 | ||||
9109 | if (getLangOpts().CPlusPlus11) break; | |||
9110 | ||||
9111 | return nullptr; | |||
9112 | ||||
9113 | case UnqualifiedIdKind::IK_DestructorName: | |||
9114 | Diag(Name.getLocStart(), diag::err_using_decl_destructor) | |||
9115 | << SS.getRange(); | |||
9116 | return nullptr; | |||
9117 | ||||
9118 | case UnqualifiedIdKind::IK_TemplateId: | |||
9119 | Diag(Name.getLocStart(), diag::err_using_decl_template_id) | |||
9120 | << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); | |||
9121 | return nullptr; | |||
9122 | ||||
9123 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
9124 | llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9124); | |||
9125 | } | |||
9126 | ||||
9127 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | |||
9128 | DeclarationName TargetName = TargetNameInfo.getName(); | |||
9129 | if (!TargetName) | |||
9130 | return nullptr; | |||
9131 | ||||
9132 | // Warn about access declarations. | |||
9133 | if (UsingLoc.isInvalid()) { | |||
9134 | Diag(Name.getLocStart(), | |||
9135 | getLangOpts().CPlusPlus11 ? diag::err_access_decl | |||
9136 | : diag::warn_access_decl_deprecated) | |||
9137 | << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); | |||
9138 | } | |||
9139 | ||||
9140 | if (EllipsisLoc.isInvalid()) { | |||
9141 | if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || | |||
9142 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) | |||
9143 | return nullptr; | |||
9144 | } else { | |||
9145 | if (!SS.getScopeRep()->containsUnexpandedParameterPack() && | |||
9146 | !TargetNameInfo.containsUnexpandedParameterPack()) { | |||
9147 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
9148 | << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); | |||
9149 | EllipsisLoc = SourceLocation(); | |||
9150 | } | |||
9151 | } | |||
9152 | ||||
9153 | NamedDecl *UD = | |||
9154 | BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, | |||
9155 | SS, TargetNameInfo, EllipsisLoc, AttrList, | |||
9156 | /*IsInstantiation*/false); | |||
9157 | if (UD) | |||
9158 | PushOnScopeChains(UD, S, /*AddToContext*/ false); | |||
9159 | ||||
9160 | return UD; | |||
9161 | } | |||
9162 | ||||
9163 | /// \brief Determine whether a using declaration considers the given | |||
9164 | /// declarations as "equivalent", e.g., if they are redeclarations of | |||
9165 | /// the same entity or are both typedefs of the same type. | |||
9166 | static bool | |||
9167 | IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { | |||
9168 | if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) | |||
9169 | return true; | |||
9170 | ||||
9171 | if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) | |||
9172 | if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) | |||
9173 | return Context.hasSameType(TD1->getUnderlyingType(), | |||
9174 | TD2->getUnderlyingType()); | |||
9175 | ||||
9176 | return false; | |||
9177 | } | |||
9178 | ||||
9179 | ||||
9180 | /// Determines whether to create a using shadow decl for a particular | |||
9181 | /// decl, given the set of decls existing prior to this using lookup. | |||
9182 | bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, | |||
9183 | const LookupResult &Previous, | |||
9184 | UsingShadowDecl *&PrevShadow) { | |||
9185 | // Diagnose finding a decl which is not from a base class of the | |||
9186 | // current class. We do this now because there are cases where this | |||
9187 | // function will silently decide not to build a shadow decl, which | |||
9188 | // will pre-empt further diagnostics. | |||
9189 | // | |||
9190 | // We don't need to do this in C++11 because we do the check once on | |||
9191 | // the qualifier. | |||
9192 | // | |||
9193 | // FIXME: diagnose the following if we care enough: | |||
9194 | // struct A { int foo; }; | |||
9195 | // struct B : A { using A::foo; }; | |||
9196 | // template <class T> struct C : A {}; | |||
9197 | // template <class T> struct D : C<T> { using B::foo; } // <--- | |||
9198 | // This is invalid (during instantiation) in C++03 because B::foo | |||
9199 | // resolves to the using decl in B, which is not a base class of D<T>. | |||
9200 | // We can't diagnose it immediately because C<T> is an unknown | |||
9201 | // specialization. The UsingShadowDecl in D<T> then points directly | |||
9202 | // to A::foo, which will look well-formed when we instantiate. | |||
9203 | // The right solution is to not collapse the shadow-decl chain. | |||
9204 | if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { | |||
9205 | DeclContext *OrigDC = Orig->getDeclContext(); | |||
9206 | ||||
9207 | // Handle enums and anonymous structs. | |||
9208 | if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); | |||
9209 | CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); | |||
9210 | while (OrigRec->isAnonymousStructOrUnion()) | |||
9211 | OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); | |||
9212 | ||||
9213 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { | |||
9214 | if (OrigDC == CurContext) { | |||
9215 | Diag(Using->getLocation(), | |||
9216 | diag::err_using_decl_nested_name_specifier_is_current_class) | |||
9217 | << Using->getQualifierLoc().getSourceRange(); | |||
9218 | Diag(Orig->getLocation(), diag::note_using_decl_target); | |||
9219 | Using->setInvalidDecl(); | |||
9220 | return true; | |||
9221 | } | |||
9222 | ||||
9223 | Diag(Using->getQualifierLoc().getBeginLoc(), | |||
9224 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
9225 | << Using->getQualifier() | |||
9226 | << cast<CXXRecordDecl>(CurContext) | |||
9227 | << Using->getQualifierLoc().getSourceRange(); | |||
9228 | Diag(Orig->getLocation(), diag::note_using_decl_target); | |||
9229 | Using->setInvalidDecl(); | |||
9230 | return true; | |||
9231 | } | |||
9232 | } | |||
9233 | ||||
9234 | if (Previous.empty()) return false; | |||
9235 | ||||
9236 | NamedDecl *Target = Orig; | |||
9237 | if (isa<UsingShadowDecl>(Target)) | |||
9238 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | |||
9239 | ||||
9240 | // If the target happens to be one of the previous declarations, we | |||
9241 | // don't have a conflict. | |||
9242 | // | |||
9243 | // FIXME: but we might be increasing its access, in which case we | |||
9244 | // should redeclare it. | |||
9245 | NamedDecl *NonTag = nullptr, *Tag = nullptr; | |||
9246 | bool FoundEquivalentDecl = false; | |||
9247 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
9248 | I != E; ++I) { | |||
9249 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
9250 | // We can have UsingDecls in our Previous results because we use the same | |||
9251 | // LookupResult for checking whether the UsingDecl itself is a valid | |||
9252 | // redeclaration. | |||
9253 | if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) | |||
9254 | continue; | |||
9255 | ||||
9256 | if (IsEquivalentForUsingDecl(Context, D, Target)) { | |||
9257 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) | |||
9258 | PrevShadow = Shadow; | |||
9259 | FoundEquivalentDecl = true; | |||
9260 | } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { | |||
9261 | // We don't conflict with an existing using shadow decl of an equivalent | |||
9262 | // declaration, but we're not a redeclaration of it. | |||
9263 | FoundEquivalentDecl = true; | |||
9264 | } | |||
9265 | ||||
9266 | if (isVisible(D)) | |||
9267 | (isa<TagDecl>(D) ? Tag : NonTag) = D; | |||
9268 | } | |||
9269 | ||||
9270 | if (FoundEquivalentDecl) | |||
9271 | return false; | |||
9272 | ||||
9273 | if (FunctionDecl *FD = Target->getAsFunction()) { | |||
9274 | NamedDecl *OldDecl = nullptr; | |||
9275 | switch (CheckOverload(nullptr, FD, Previous, OldDecl, | |||
9276 | /*IsForUsingDecl*/ true)) { | |||
9277 | case Ovl_Overload: | |||
9278 | return false; | |||
9279 | ||||
9280 | case Ovl_NonFunction: | |||
9281 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9282 | break; | |||
9283 | ||||
9284 | // We found a decl with the exact signature. | |||
9285 | case Ovl_Match: | |||
9286 | // If we're in a record, we want to hide the target, so we | |||
9287 | // return true (without a diagnostic) to tell the caller not to | |||
9288 | // build a shadow decl. | |||
9289 | if (CurContext->isRecord()) | |||
9290 | return true; | |||
9291 | ||||
9292 | // If we're not in a record, this is an error. | |||
9293 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9294 | break; | |||
9295 | } | |||
9296 | ||||
9297 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9298 | Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); | |||
9299 | Using->setInvalidDecl(); | |||
9300 | return true; | |||
9301 | } | |||
9302 | ||||
9303 | // Target is not a function. | |||
9304 | ||||
9305 | if (isa<TagDecl>(Target)) { | |||
9306 | // No conflict between a tag and a non-tag. | |||
9307 | if (!Tag) return false; | |||
9308 | ||||
9309 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9310 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9311 | Diag(Tag->getLocation(), diag::note_using_decl_conflict); | |||
9312 | Using->setInvalidDecl(); | |||
9313 | return true; | |||
9314 | } | |||
9315 | ||||
9316 | // No conflict between a tag and a non-tag. | |||
9317 | if (!NonTag) return false; | |||
9318 | ||||
9319 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9320 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9321 | Diag(NonTag->getLocation(), diag::note_using_decl_conflict); | |||
9322 | Using->setInvalidDecl(); | |||
9323 | return true; | |||
9324 | } | |||
9325 | ||||
9326 | /// Determine whether a direct base class is a virtual base class. | |||
9327 | static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { | |||
9328 | if (!Derived->getNumVBases()) | |||
9329 | return false; | |||
9330 | for (auto &B : Derived->bases()) | |||
9331 | if (B.getType()->getAsCXXRecordDecl() == Base) | |||
9332 | return B.isVirtual(); | |||
9333 | llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9333); | |||
9334 | } | |||
9335 | ||||
9336 | /// Builds a shadow declaration corresponding to a 'using' declaration. | |||
9337 | UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, | |||
9338 | UsingDecl *UD, | |||
9339 | NamedDecl *Orig, | |||
9340 | UsingShadowDecl *PrevDecl) { | |||
9341 | // If we resolved to another shadow declaration, just coalesce them. | |||
9342 | NamedDecl *Target = Orig; | |||
9343 | if (isa<UsingShadowDecl>(Target)) { | |||
9344 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | |||
9345 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9345, __extension__ __PRETTY_FUNCTION__)); | |||
9346 | } | |||
9347 | ||||
9348 | NamedDecl *NonTemplateTarget = Target; | |||
9349 | if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) | |||
9350 | NonTemplateTarget = TargetTD->getTemplatedDecl(); | |||
9351 | ||||
9352 | UsingShadowDecl *Shadow; | |||
9353 | if (isa<CXXConstructorDecl>(NonTemplateTarget)) { | |||
9354 | bool IsVirtualBase = | |||
9355 | isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), | |||
9356 | UD->getQualifier()->getAsRecordDecl()); | |||
9357 | Shadow = ConstructorUsingShadowDecl::Create( | |||
9358 | Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); | |||
9359 | } else { | |||
9360 | Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, | |||
9361 | Target); | |||
9362 | } | |||
9363 | UD->addShadowDecl(Shadow); | |||
9364 | ||||
9365 | Shadow->setAccess(UD->getAccess()); | |||
9366 | if (Orig->isInvalidDecl() || UD->isInvalidDecl()) | |||
9367 | Shadow->setInvalidDecl(); | |||
9368 | ||||
9369 | Shadow->setPreviousDecl(PrevDecl); | |||
9370 | ||||
9371 | if (S) | |||
9372 | PushOnScopeChains(Shadow, S); | |||
9373 | else | |||
9374 | CurContext->addDecl(Shadow); | |||
9375 | ||||
9376 | ||||
9377 | return Shadow; | |||
9378 | } | |||
9379 | ||||
9380 | /// Hides a using shadow declaration. This is required by the current | |||
9381 | /// using-decl implementation when a resolvable using declaration in a | |||
9382 | /// class is followed by a declaration which would hide or override | |||
9383 | /// one or more of the using decl's targets; for example: | |||
9384 | /// | |||
9385 | /// struct Base { void foo(int); }; | |||
9386 | /// struct Derived : Base { | |||
9387 | /// using Base::foo; | |||
9388 | /// void foo(int); | |||
9389 | /// }; | |||
9390 | /// | |||
9391 | /// The governing language is C++03 [namespace.udecl]p12: | |||
9392 | /// | |||
9393 | /// When a using-declaration brings names from a base class into a | |||
9394 | /// derived class scope, member functions in the derived class | |||
9395 | /// override and/or hide member functions with the same name and | |||
9396 | /// parameter types in a base class (rather than conflicting). | |||
9397 | /// | |||
9398 | /// There are two ways to implement this: | |||
9399 | /// (1) optimistically create shadow decls when they're not hidden | |||
9400 | /// by existing declarations, or | |||
9401 | /// (2) don't create any shadow decls (or at least don't make them | |||
9402 | /// visible) until we've fully parsed/instantiated the class. | |||
9403 | /// The problem with (1) is that we might have to retroactively remove | |||
9404 | /// a shadow decl, which requires several O(n) operations because the | |||
9405 | /// decl structures are (very reasonably) not designed for removal. | |||
9406 | /// (2) avoids this but is very fiddly and phase-dependent. | |||
9407 | void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { | |||
9408 | if (Shadow->getDeclName().getNameKind() == | |||
9409 | DeclarationName::CXXConversionFunctionName) | |||
9410 | cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); | |||
9411 | ||||
9412 | // Remove it from the DeclContext... | |||
9413 | Shadow->getDeclContext()->removeDecl(Shadow); | |||
9414 | ||||
9415 | // ...and the scope, if applicable... | |||
9416 | if (S) { | |||
9417 | S->RemoveDecl(Shadow); | |||
9418 | IdResolver.RemoveDecl(Shadow); | |||
9419 | } | |||
9420 | ||||
9421 | // ...and the using decl. | |||
9422 | Shadow->getUsingDecl()->removeShadowDecl(Shadow); | |||
9423 | ||||
9424 | // TODO: complain somehow if Shadow was used. It shouldn't | |||
9425 | // be possible for this to happen, because...? | |||
9426 | } | |||
9427 | ||||
9428 | /// Find the base specifier for a base class with the given type. | |||
9429 | static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, | |||
9430 | QualType DesiredBase, | |||
9431 | bool &AnyDependentBases) { | |||
9432 | // Check whether the named type is a direct base class. | |||
9433 | CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); | |||
9434 | for (auto &Base : Derived->bases()) { | |||
9435 | CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); | |||
9436 | if (CanonicalDesiredBase == BaseType) | |||
9437 | return &Base; | |||
9438 | if (BaseType->isDependentType()) | |||
9439 | AnyDependentBases = true; | |||
9440 | } | |||
9441 | return nullptr; | |||
9442 | } | |||
9443 | ||||
9444 | namespace { | |||
9445 | class UsingValidatorCCC : public CorrectionCandidateCallback { | |||
9446 | public: | |||
9447 | UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, | |||
9448 | NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) | |||
9449 | : HasTypenameKeyword(HasTypenameKeyword), | |||
9450 | IsInstantiation(IsInstantiation), OldNNS(NNS), | |||
9451 | RequireMemberOf(RequireMemberOf) {} | |||
9452 | ||||
9453 | bool ValidateCandidate(const TypoCorrection &Candidate) override { | |||
9454 | NamedDecl *ND = Candidate.getCorrectionDecl(); | |||
9455 | ||||
9456 | // Keywords are not valid here. | |||
9457 | if (!ND || isa<NamespaceDecl>(ND)) | |||
9458 | return false; | |||
9459 | ||||
9460 | // Completely unqualified names are invalid for a 'using' declaration. | |||
9461 | if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) | |||
9462 | return false; | |||
9463 | ||||
9464 | // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would | |||
9465 | // reject. | |||
9466 | ||||
9467 | if (RequireMemberOf) { | |||
9468 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | |||
9469 | if (FoundRecord && FoundRecord->isInjectedClassName()) { | |||
9470 | // No-one ever wants a using-declaration to name an injected-class-name | |||
9471 | // of a base class, unless they're declaring an inheriting constructor. | |||
9472 | ASTContext &Ctx = ND->getASTContext(); | |||
9473 | if (!Ctx.getLangOpts().CPlusPlus11) | |||
9474 | return false; | |||
9475 | QualType FoundType = Ctx.getRecordType(FoundRecord); | |||
9476 | ||||
9477 | // Check that the injected-class-name is named as a member of its own | |||
9478 | // type; we don't want to suggest 'using Derived::Base;', since that | |||
9479 | // means something else. | |||
9480 | NestedNameSpecifier *Specifier = | |||
9481 | Candidate.WillReplaceSpecifier() | |||
9482 | ? Candidate.getCorrectionSpecifier() | |||
9483 | : OldNNS; | |||
9484 | if (!Specifier->getAsType() || | |||
9485 | !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) | |||
9486 | return false; | |||
9487 | ||||
9488 | // Check that this inheriting constructor declaration actually names a | |||
9489 | // direct base class of the current class. | |||
9490 | bool AnyDependentBases = false; | |||
9491 | if (!findDirectBaseWithType(RequireMemberOf, | |||
9492 | Ctx.getRecordType(FoundRecord), | |||
9493 | AnyDependentBases) && | |||
9494 | !AnyDependentBases) | |||
9495 | return false; | |||
9496 | } else { | |||
9497 | auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); | |||
9498 | if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) | |||
9499 | return false; | |||
9500 | ||||
9501 | // FIXME: Check that the base class member is accessible? | |||
9502 | } | |||
9503 | } else { | |||
9504 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | |||
9505 | if (FoundRecord && FoundRecord->isInjectedClassName()) | |||
9506 | return false; | |||
9507 | } | |||
9508 | ||||
9509 | if (isa<TypeDecl>(ND)) | |||
9510 | return HasTypenameKeyword || !IsInstantiation; | |||
9511 | ||||
9512 | return !HasTypenameKeyword; | |||
9513 | } | |||
9514 | ||||
9515 | private: | |||
9516 | bool HasTypenameKeyword; | |||
9517 | bool IsInstantiation; | |||
9518 | NestedNameSpecifier *OldNNS; | |||
9519 | CXXRecordDecl *RequireMemberOf; | |||
9520 | }; | |||
9521 | } // end anonymous namespace | |||
9522 | ||||
9523 | /// Builds a using declaration. | |||
9524 | /// | |||
9525 | /// \param IsInstantiation - Whether this call arises from an | |||
9526 | /// instantiation of an unresolved using declaration. We treat | |||
9527 | /// the lookup differently for these declarations. | |||
9528 | NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, | |||
9529 | SourceLocation UsingLoc, | |||
9530 | bool HasTypenameKeyword, | |||
9531 | SourceLocation TypenameLoc, | |||
9532 | CXXScopeSpec &SS, | |||
9533 | DeclarationNameInfo NameInfo, | |||
9534 | SourceLocation EllipsisLoc, | |||
9535 | AttributeList *AttrList, | |||
9536 | bool IsInstantiation) { | |||
9537 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9537, __extension__ __PRETTY_FUNCTION__)); | |||
9538 | SourceLocation IdentLoc = NameInfo.getLoc(); | |||
9539 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9539, __extension__ __PRETTY_FUNCTION__)); | |||
9540 | ||||
9541 | // FIXME: We ignore attributes for now. | |||
9542 | ||||
9543 | // For an inheriting constructor declaration, the name of the using | |||
9544 | // declaration is the name of a constructor in this class, not in the | |||
9545 | // base class. | |||
9546 | DeclarationNameInfo UsingName = NameInfo; | |||
9547 | if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) | |||
9548 | if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) | |||
9549 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | |||
9550 | Context.getCanonicalType(Context.getRecordType(RD)))); | |||
9551 | ||||
9552 | // Do the redeclaration lookup in the current scope. | |||
9553 | LookupResult Previous(*this, UsingName, LookupUsingDeclName, | |||
9554 | ForVisibleRedeclaration); | |||
9555 | Previous.setHideTags(false); | |||
9556 | if (S) { | |||
9557 | LookupName(Previous, S); | |||
9558 | ||||
9559 | // It is really dumb that we have to do this. | |||
9560 | LookupResult::Filter F = Previous.makeFilter(); | |||
9561 | while (F.hasNext()) { | |||
9562 | NamedDecl *D = F.next(); | |||
9563 | if (!isDeclInScope(D, CurContext, S)) | |||
9564 | F.erase(); | |||
9565 | // If we found a local extern declaration that's not ordinarily visible, | |||
9566 | // and this declaration is being added to a non-block scope, ignore it. | |||
9567 | // We're only checking for scope conflicts here, not also for violations | |||
9568 | // of the linkage rules. | |||
9569 | else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && | |||
9570 | !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) | |||
9571 | F.erase(); | |||
9572 | } | |||
9573 | F.done(); | |||
9574 | } else { | |||
9575 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9575, __extension__ __PRETTY_FUNCTION__)); | |||
9576 | if (CurContext->isRecord()) | |||
9577 | LookupQualifiedName(Previous, CurContext); | |||
9578 | else { | |||
9579 | // No redeclaration check is needed here; in non-member contexts we | |||
9580 | // diagnosed all possible conflicts with other using-declarations when | |||
9581 | // building the template: | |||
9582 | // | |||
9583 | // For a dependent non-type using declaration, the only valid case is | |||
9584 | // if we instantiate to a single enumerator. We check for conflicts | |||
9585 | // between shadow declarations we introduce, and we check in the template | |||
9586 | // definition for conflicts between a non-type using declaration and any | |||
9587 | // other declaration, which together covers all cases. | |||
9588 | // | |||
9589 | // A dependent typename using declaration will never successfully | |||
9590 | // instantiate, since it will always name a class member, so we reject | |||
9591 | // that in the template definition. | |||
9592 | } | |||
9593 | } | |||
9594 | ||||
9595 | // Check for invalid redeclarations. | |||
9596 | if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, | |||
9597 | SS, IdentLoc, Previous)) | |||
9598 | return nullptr; | |||
9599 | ||||
9600 | // Check for bad qualifiers. | |||
9601 | if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, | |||
9602 | IdentLoc)) | |||
9603 | return nullptr; | |||
9604 | ||||
9605 | DeclContext *LookupContext = computeDeclContext(SS); | |||
9606 | NamedDecl *D; | |||
9607 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | |||
9608 | if (!LookupContext || EllipsisLoc.isValid()) { | |||
9609 | if (HasTypenameKeyword) { | |||
9610 | // FIXME: not all declaration name kinds are legal here | |||
9611 | D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, | |||
9612 | UsingLoc, TypenameLoc, | |||
9613 | QualifierLoc, | |||
9614 | IdentLoc, NameInfo.getName(), | |||
9615 | EllipsisLoc); | |||
9616 | } else { | |||
9617 | D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, | |||
9618 | QualifierLoc, NameInfo, EllipsisLoc); | |||
9619 | } | |||
9620 | D->setAccess(AS); | |||
9621 | CurContext->addDecl(D); | |||
9622 | return D; | |||
9623 | } | |||
9624 | ||||
9625 | auto Build = [&](bool Invalid) { | |||
9626 | UsingDecl *UD = | |||
9627 | UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, | |||
9628 | UsingName, HasTypenameKeyword); | |||
9629 | UD->setAccess(AS); | |||
9630 | CurContext->addDecl(UD); | |||
9631 | UD->setInvalidDecl(Invalid); | |||
9632 | return UD; | |||
9633 | }; | |||
9634 | auto BuildInvalid = [&]{ return Build(true); }; | |||
9635 | auto BuildValid = [&]{ return Build(false); }; | |||
9636 | ||||
9637 | if (RequireCompleteDeclContext(SS, LookupContext)) | |||
9638 | return BuildInvalid(); | |||
9639 | ||||
9640 | // Look up the target name. | |||
9641 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
9642 | ||||
9643 | // Unlike most lookups, we don't always want to hide tag | |||
9644 | // declarations: tag names are visible through the using declaration | |||
9645 | // even if hidden by ordinary names, *except* in a dependent context | |||
9646 | // where it's important for the sanity of two-phase lookup. | |||
9647 | if (!IsInstantiation) | |||
9648 | R.setHideTags(false); | |||
9649 | ||||
9650 | // For the purposes of this lookup, we have a base object type | |||
9651 | // equal to that of the current context. | |||
9652 | if (CurContext->isRecord()) { | |||
9653 | R.setBaseObjectType( | |||
9654 | Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); | |||
9655 | } | |||
9656 | ||||
9657 | LookupQualifiedName(R, LookupContext); | |||
9658 | ||||
9659 | // Try to correct typos if possible. If constructor name lookup finds no | |||
9660 | // results, that means the named class has no explicit constructors, and we | |||
9661 | // suppressed declaring implicit ones (probably because it's dependent or | |||
9662 | // invalid). | |||
9663 | if (R.empty() && | |||
9664 | NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { | |||
9665 | // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes | |||
9666 | // it will believe that glibc provides a ::gets in cases where it does not, | |||
9667 | // and will try to pull it into namespace std with a using-declaration. | |||
9668 | // Just ignore the using-declaration in that case. | |||
9669 | auto *II = NameInfo.getName().getAsIdentifierInfo(); | |||
9670 | if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && | |||
9671 | CurContext->isStdNamespace() && | |||
9672 | isa<TranslationUnitDecl>(LookupContext) && | |||
9673 | getSourceManager().isInSystemHeader(UsingLoc)) | |||
9674 | return nullptr; | |||
9675 | if (TypoCorrection Corrected = CorrectTypo( | |||
9676 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, | |||
9677 | llvm::make_unique<UsingValidatorCCC>( | |||
9678 | HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), | |||
9679 | dyn_cast<CXXRecordDecl>(CurContext)), | |||
9680 | CTK_ErrorRecovery)) { | |||
9681 | // We reject candidates where DroppedSpecifier == true, hence the | |||
9682 | // literal '0' below. | |||
9683 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
9684 | << NameInfo.getName() << LookupContext << 0 | |||
9685 | << SS.getRange()); | |||
9686 | ||||
9687 | // If we picked a correction with no attached Decl we can't do anything | |||
9688 | // useful with it, bail out. | |||
9689 | NamedDecl *ND = Corrected.getCorrectionDecl(); | |||
9690 | if (!ND) | |||
9691 | return BuildInvalid(); | |||
9692 | ||||
9693 | // If we corrected to an inheriting constructor, handle it as one. | |||
9694 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
9695 | if (RD && RD->isInjectedClassName()) { | |||
9696 | // The parent of the injected class name is the class itself. | |||
9697 | RD = cast<CXXRecordDecl>(RD->getParent()); | |||
9698 | ||||
9699 | // Fix up the information we'll use to build the using declaration. | |||
9700 | if (Corrected.WillReplaceSpecifier()) { | |||
9701 | NestedNameSpecifierLocBuilder Builder; | |||
9702 | Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | |||
9703 | QualifierLoc.getSourceRange()); | |||
9704 | QualifierLoc = Builder.getWithLocInContext(Context); | |||
9705 | } | |||
9706 | ||||
9707 | // In this case, the name we introduce is the name of a derived class | |||
9708 | // constructor. | |||
9709 | auto *CurClass = cast<CXXRecordDecl>(CurContext); | |||
9710 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | |||
9711 | Context.getCanonicalType(Context.getRecordType(CurClass)))); | |||
9712 | UsingName.setNamedTypeInfo(nullptr); | |||
9713 | for (auto *Ctor : LookupConstructors(RD)) | |||
9714 | R.addDecl(Ctor); | |||
9715 | R.resolveKind(); | |||
9716 | } else { | |||
9717 | // FIXME: Pick up all the declarations if we found an overloaded | |||
9718 | // function. | |||
9719 | UsingName.setName(ND->getDeclName()); | |||
9720 | R.addDecl(ND); | |||
9721 | } | |||
9722 | } else { | |||
9723 | Diag(IdentLoc, diag::err_no_member) | |||
9724 | << NameInfo.getName() << LookupContext << SS.getRange(); | |||
9725 | return BuildInvalid(); | |||
9726 | } | |||
9727 | } | |||
9728 | ||||
9729 | if (R.isAmbiguous()) | |||
9730 | return BuildInvalid(); | |||
9731 | ||||
9732 | if (HasTypenameKeyword) { | |||
9733 | // If we asked for a typename and got a non-type decl, error out. | |||
9734 | if (!R.getAsSingle<TypeDecl>()) { | |||
9735 | Diag(IdentLoc, diag::err_using_typename_non_type); | |||
9736 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) | |||
9737 | Diag((*I)->getUnderlyingDecl()->getLocation(), | |||
9738 | diag::note_using_decl_target); | |||
9739 | return BuildInvalid(); | |||
9740 | } | |||
9741 | } else { | |||
9742 | // If we asked for a non-typename and we got a type, error out, | |||
9743 | // but only if this is an instantiation of an unresolved using | |||
9744 | // decl. Otherwise just silently find the type name. | |||
9745 | if (IsInstantiation && R.getAsSingle<TypeDecl>()) { | |||
9746 | Diag(IdentLoc, diag::err_using_dependent_value_is_type); | |||
9747 | Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); | |||
9748 | return BuildInvalid(); | |||
9749 | } | |||
9750 | } | |||
9751 | ||||
9752 | // C++14 [namespace.udecl]p6: | |||
9753 | // A using-declaration shall not name a namespace. | |||
9754 | if (R.getAsSingle<NamespaceDecl>()) { | |||
9755 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) | |||
9756 | << SS.getRange(); | |||
9757 | return BuildInvalid(); | |||
9758 | } | |||
9759 | ||||
9760 | // C++14 [namespace.udecl]p7: | |||
9761 | // A using-declaration shall not name a scoped enumerator. | |||
9762 | if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { | |||
9763 | if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { | |||
9764 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) | |||
9765 | << SS.getRange(); | |||
9766 | return BuildInvalid(); | |||
9767 | } | |||
9768 | } | |||
9769 | ||||
9770 | UsingDecl *UD = BuildValid(); | |||
9771 | ||||
9772 | // Some additional rules apply to inheriting constructors. | |||
9773 | if (UsingName.getName().getNameKind() == | |||
9774 | DeclarationName::CXXConstructorName) { | |||
9775 | // Suppress access diagnostics; the access check is instead performed at the | |||
9776 | // point of use for an inheriting constructor. | |||
9777 | R.suppressDiagnostics(); | |||
9778 | if (CheckInheritingConstructorUsingDecl(UD)) | |||
9779 | return UD; | |||
9780 | } | |||
9781 | ||||
9782 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
9783 | UsingShadowDecl *PrevDecl = nullptr; | |||
9784 | if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) | |||
9785 | BuildUsingShadowDecl(S, UD, *I, PrevDecl); | |||
9786 | } | |||
9787 | ||||
9788 | return UD; | |||
9789 | } | |||
9790 | ||||
9791 | NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, | |||
9792 | ArrayRef<NamedDecl *> Expansions) { | |||
9793 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9795, __extension__ __PRETTY_FUNCTION__)) | |||
9794 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9795, __extension__ __PRETTY_FUNCTION__)) | |||
9795 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9795, __extension__ __PRETTY_FUNCTION__)); | |||
9796 | ||||
9797 | auto *UPD = | |||
9798 | UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); | |||
9799 | UPD->setAccess(InstantiatedFrom->getAccess()); | |||
9800 | CurContext->addDecl(UPD); | |||
9801 | return UPD; | |||
9802 | } | |||
9803 | ||||
9804 | /// Additional checks for a using declaration referring to a constructor name. | |||
9805 | bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { | |||
9806 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9806, __extension__ __PRETTY_FUNCTION__)); | |||
9807 | ||||
9808 | const Type *SourceType = UD->getQualifier()->getAsType(); | |||
9809 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9810, __extension__ __PRETTY_FUNCTION__)) | |||
9810 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9810, __extension__ __PRETTY_FUNCTION__)); | |||
9811 | CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); | |||
9812 | ||||
9813 | // Check whether the named type is a direct base class. | |||
9814 | bool AnyDependentBases = false; | |||
9815 | auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), | |||
9816 | AnyDependentBases); | |||
9817 | if (!Base && !AnyDependentBases) { | |||
9818 | Diag(UD->getUsingLoc(), | |||
9819 | diag::err_using_decl_constructor_not_in_direct_base) | |||
9820 | << UD->getNameInfo().getSourceRange() | |||
9821 | << QualType(SourceType, 0) << TargetClass; | |||
9822 | UD->setInvalidDecl(); | |||
9823 | return true; | |||
9824 | } | |||
9825 | ||||
9826 | if (Base) | |||
9827 | Base->setInheritConstructors(); | |||
9828 | ||||
9829 | return false; | |||
9830 | } | |||
9831 | ||||
9832 | /// Checks that the given using declaration is not an invalid | |||
9833 | /// redeclaration. Note that this is checking only for the using decl | |||
9834 | /// itself, not for any ill-formedness among the UsingShadowDecls. | |||
9835 | bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, | |||
9836 | bool HasTypenameKeyword, | |||
9837 | const CXXScopeSpec &SS, | |||
9838 | SourceLocation NameLoc, | |||
9839 | const LookupResult &Prev) { | |||
9840 | NestedNameSpecifier *Qual = SS.getScopeRep(); | |||
9841 | ||||
9842 | // C++03 [namespace.udecl]p8: | |||
9843 | // C++0x [namespace.udecl]p10: | |||
9844 | // A using-declaration is a declaration and can therefore be used | |||
9845 | // repeatedly where (and only where) multiple declarations are | |||
9846 | // allowed. | |||
9847 | // | |||
9848 | // That's in non-member contexts. | |||
9849 | if (!CurContext->getRedeclContext()->isRecord()) { | |||
9850 | // A dependent qualifier outside a class can only ever resolve to an | |||
9851 | // enumeration type. Therefore it conflicts with any other non-type | |||
9852 | // declaration in the same scope. | |||
9853 | // FIXME: How should we check for dependent type-type conflicts at block | |||
9854 | // scope? | |||
9855 | if (Qual->isDependent() && !HasTypenameKeyword) { | |||
9856 | for (auto *D : Prev) { | |||
9857 | if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { | |||
9858 | bool OldCouldBeEnumerator = | |||
9859 | isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); | |||
9860 | Diag(NameLoc, | |||
9861 | OldCouldBeEnumerator ? diag::err_redefinition | |||
9862 | : diag::err_redefinition_different_kind) | |||
9863 | << Prev.getLookupName(); | |||
9864 | Diag(D->getLocation(), diag::note_previous_definition); | |||
9865 | return true; | |||
9866 | } | |||
9867 | } | |||
9868 | } | |||
9869 | return false; | |||
9870 | } | |||
9871 | ||||
9872 | for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { | |||
9873 | NamedDecl *D = *I; | |||
9874 | ||||
9875 | bool DTypename; | |||
9876 | NestedNameSpecifier *DQual; | |||
9877 | if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { | |||
9878 | DTypename = UD->hasTypename(); | |||
9879 | DQual = UD->getQualifier(); | |||
9880 | } else if (UnresolvedUsingValueDecl *UD | |||
9881 | = dyn_cast<UnresolvedUsingValueDecl>(D)) { | |||
9882 | DTypename = false; | |||
9883 | DQual = UD->getQualifier(); | |||
9884 | } else if (UnresolvedUsingTypenameDecl *UD | |||
9885 | = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { | |||
9886 | DTypename = true; | |||
9887 | DQual = UD->getQualifier(); | |||
9888 | } else continue; | |||
9889 | ||||
9890 | // using decls differ if one says 'typename' and the other doesn't. | |||
9891 | // FIXME: non-dependent using decls? | |||
9892 | if (HasTypenameKeyword != DTypename) continue; | |||
9893 | ||||
9894 | // using decls differ if they name different scopes (but note that | |||
9895 | // template instantiation can cause this check to trigger when it | |||
9896 | // didn't before instantiation). | |||
9897 | if (Context.getCanonicalNestedNameSpecifier(Qual) != | |||
9898 | Context.getCanonicalNestedNameSpecifier(DQual)) | |||
9899 | continue; | |||
9900 | ||||
9901 | Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); | |||
9902 | Diag(D->getLocation(), diag::note_using_decl) << 1; | |||
9903 | return true; | |||
9904 | } | |||
9905 | ||||
9906 | return false; | |||
9907 | } | |||
9908 | ||||
9909 | ||||
9910 | /// Checks that the given nested-name qualifier used in a using decl | |||
9911 | /// in the current context is appropriately related to the current | |||
9912 | /// scope. If an error is found, diagnoses it and returns true. | |||
9913 | bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, | |||
9914 | bool HasTypename, | |||
9915 | const CXXScopeSpec &SS, | |||
9916 | const DeclarationNameInfo &NameInfo, | |||
9917 | SourceLocation NameLoc) { | |||
9918 | DeclContext *NamedContext = computeDeclContext(SS); | |||
9919 | ||||
9920 | if (!CurContext->isRecord()) { | |||
9921 | // C++03 [namespace.udecl]p3: | |||
9922 | // C++0x [namespace.udecl]p8: | |||
9923 | // A using-declaration for a class member shall be a member-declaration. | |||
9924 | ||||
9925 | // If we weren't able to compute a valid scope, it might validly be a | |||
9926 | // dependent class scope or a dependent enumeration unscoped scope. If | |||
9927 | // we have a 'typename' keyword, the scope must resolve to a class type. | |||
9928 | if ((HasTypename && !NamedContext) || | |||
9929 | (NamedContext && NamedContext->getRedeclContext()->isRecord())) { | |||
9930 | auto *RD = NamedContext | |||
9931 | ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) | |||
9932 | : nullptr; | |||
9933 | if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) | |||
9934 | RD = nullptr; | |||
9935 | ||||
9936 | Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) | |||
9937 | << SS.getRange(); | |||
9938 | ||||
9939 | // If we have a complete, non-dependent source type, try to suggest a | |||
9940 | // way to get the same effect. | |||
9941 | if (!RD) | |||
9942 | return true; | |||
9943 | ||||
9944 | // Find what this using-declaration was referring to. | |||
9945 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
9946 | R.setHideTags(false); | |||
9947 | R.suppressDiagnostics(); | |||
9948 | LookupQualifiedName(R, RD); | |||
9949 | ||||
9950 | if (R.getAsSingle<TypeDecl>()) { | |||
9951 | if (getLangOpts().CPlusPlus11) { | |||
9952 | // Convert 'using X::Y;' to 'using Y = X::Y;'. | |||
9953 | Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) | |||
9954 | << 0 // alias declaration | |||
9955 | << FixItHint::CreateInsertion(SS.getBeginLoc(), | |||
9956 | NameInfo.getName().getAsString() + | |||
9957 | " = "); | |||
9958 | } else { | |||
9959 | // Convert 'using X::Y;' to 'typedef X::Y Y;'. | |||
9960 | SourceLocation InsertLoc = | |||
9961 | getLocForEndOfToken(NameInfo.getLocEnd()); | |||
9962 | Diag(InsertLoc, diag::note_using_decl_class_member_workaround) | |||
9963 | << 1 // typedef declaration | |||
9964 | << FixItHint::CreateReplacement(UsingLoc, "typedef") | |||
9965 | << FixItHint::CreateInsertion( | |||
9966 | InsertLoc, " " + NameInfo.getName().getAsString()); | |||
9967 | } | |||
9968 | } else if (R.getAsSingle<VarDecl>()) { | |||
9969 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | |||
9970 | // repeating the type of the static data member here. | |||
9971 | FixItHint FixIt; | |||
9972 | if (getLangOpts().CPlusPlus11) { | |||
9973 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | |||
9974 | FixIt = FixItHint::CreateReplacement( | |||
9975 | UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); | |||
9976 | } | |||
9977 | ||||
9978 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | |||
9979 | << 2 // reference declaration | |||
9980 | << FixIt; | |||
9981 | } else if (R.getAsSingle<EnumConstantDecl>()) { | |||
9982 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | |||
9983 | // repeating the type of the enumeration here, and we can't do so if | |||
9984 | // the type is anonymous. | |||
9985 | FixItHint FixIt; | |||
9986 | if (getLangOpts().CPlusPlus11) { | |||
9987 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | |||
9988 | FixIt = FixItHint::CreateReplacement( | |||
9989 | UsingLoc, | |||
9990 | "constexpr auto " + NameInfo.getName().getAsString() + " = "); | |||
9991 | } | |||
9992 | ||||
9993 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | |||
9994 | << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable | |||
9995 | << FixIt; | |||
9996 | } | |||
9997 | return true; | |||
9998 | } | |||
9999 | ||||
10000 | // Otherwise, this might be valid. | |||
10001 | return false; | |||
10002 | } | |||
10003 | ||||
10004 | // The current scope is a record. | |||
10005 | ||||
10006 | // If the named context is dependent, we can't decide much. | |||
10007 | if (!NamedContext) { | |||
10008 | // FIXME: in C++0x, we can diagnose if we can prove that the | |||
10009 | // nested-name-specifier does not refer to a base class, which is | |||
10010 | // still possible in some cases. | |||
10011 | ||||
10012 | // Otherwise we have to conservatively report that things might be | |||
10013 | // okay. | |||
10014 | return false; | |||
10015 | } | |||
10016 | ||||
10017 | if (!NamedContext->isRecord()) { | |||
10018 | // Ideally this would point at the last name in the specifier, | |||
10019 | // but we don't have that level of source info. | |||
10020 | Diag(SS.getRange().getBegin(), | |||
10021 | diag::err_using_decl_nested_name_specifier_is_not_class) | |||
10022 | << SS.getScopeRep() << SS.getRange(); | |||
10023 | return true; | |||
10024 | } | |||
10025 | ||||
10026 | if (!NamedContext->isDependentContext() && | |||
10027 | RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) | |||
10028 | return true; | |||
10029 | ||||
10030 | if (getLangOpts().CPlusPlus11) { | |||
10031 | // C++11 [namespace.udecl]p3: | |||
10032 | // In a using-declaration used as a member-declaration, the | |||
10033 | // nested-name-specifier shall name a base class of the class | |||
10034 | // being defined. | |||
10035 | ||||
10036 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( | |||
10037 | cast<CXXRecordDecl>(NamedContext))) { | |||
10038 | if (CurContext == NamedContext) { | |||
10039 | Diag(NameLoc, | |||
10040 | diag::err_using_decl_nested_name_specifier_is_current_class) | |||
10041 | << SS.getRange(); | |||
10042 | return true; | |||
10043 | } | |||
10044 | ||||
10045 | if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { | |||
10046 | Diag(SS.getRange().getBegin(), | |||
10047 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
10048 | << SS.getScopeRep() | |||
10049 | << cast<CXXRecordDecl>(CurContext) | |||
10050 | << SS.getRange(); | |||
10051 | } | |||
10052 | return true; | |||
10053 | } | |||
10054 | ||||
10055 | return false; | |||
10056 | } | |||
10057 | ||||
10058 | // C++03 [namespace.udecl]p4: | |||
10059 | // A using-declaration used as a member-declaration shall refer | |||
10060 | // to a member of a base class of the class being defined [etc.]. | |||
10061 | ||||
10062 | // Salient point: SS doesn't have to name a base class as long as | |||
10063 | // lookup only finds members from base classes. Therefore we can | |||
10064 | // diagnose here only if we can prove that that can't happen, | |||
10065 | // i.e. if the class hierarchies provably don't intersect. | |||
10066 | ||||
10067 | // TODO: it would be nice if "definitely valid" results were cached | |||
10068 | // in the UsingDecl and UsingShadowDecl so that these checks didn't | |||
10069 | // need to be repeated. | |||
10070 | ||||
10071 | llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; | |||
10072 | auto Collect = [&Bases](const CXXRecordDecl *Base) { | |||
10073 | Bases.insert(Base); | |||
10074 | return true; | |||
10075 | }; | |||
10076 | ||||
10077 | // Collect all bases. Return false if we find a dependent base. | |||
10078 | if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) | |||
10079 | return false; | |||
10080 | ||||
10081 | // Returns true if the base is dependent or is one of the accumulated base | |||
10082 | // classes. | |||
10083 | auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { | |||
10084 | return !Bases.count(Base); | |||
10085 | }; | |||
10086 | ||||
10087 | // Return false if the class has a dependent base or if it or one | |||
10088 | // of its bases is present in the base set of the current context. | |||
10089 | if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || | |||
10090 | !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) | |||
10091 | return false; | |||
10092 | ||||
10093 | Diag(SS.getRange().getBegin(), | |||
10094 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
10095 | << SS.getScopeRep() | |||
10096 | << cast<CXXRecordDecl>(CurContext) | |||
10097 | << SS.getRange(); | |||
10098 | ||||
10099 | return true; | |||
10100 | } | |||
10101 | ||||
10102 | Decl *Sema::ActOnAliasDeclaration(Scope *S, | |||
10103 | AccessSpecifier AS, | |||
10104 | MultiTemplateParamsArg TemplateParamLists, | |||
10105 | SourceLocation UsingLoc, | |||
10106 | UnqualifiedId &Name, | |||
10107 | AttributeList *AttrList, | |||
10108 | TypeResult Type, | |||
10109 | Decl *DeclFromDeclSpec) { | |||
10110 | // Skip up to the relevant declaration scope. | |||
10111 | while (S->isTemplateParamScope()) | |||
10112 | S = S->getParent(); | |||
10113 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10114, __extension__ __PRETTY_FUNCTION__)) | |||
10114 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10114, __extension__ __PRETTY_FUNCTION__)); | |||
10115 | ||||
10116 | if (Type.isInvalid()) | |||
10117 | return nullptr; | |||
10118 | ||||
10119 | bool Invalid = false; | |||
10120 | DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); | |||
10121 | TypeSourceInfo *TInfo = nullptr; | |||
10122 | GetTypeFromParser(Type.get(), &TInfo); | |||
10123 | ||||
10124 | if (DiagnoseClassNameShadow(CurContext, NameInfo)) | |||
10125 | return nullptr; | |||
10126 | ||||
10127 | if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, | |||
10128 | UPPC_DeclarationType)) { | |||
10129 | Invalid = true; | |||
10130 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | |||
10131 | TInfo->getTypeLoc().getBeginLoc()); | |||
10132 | } | |||
10133 | ||||
10134 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
10135 | TemplateParamLists.size() | |||
10136 | ? forRedeclarationInCurContext() | |||
10137 | : ForVisibleRedeclaration); | |||
10138 | LookupName(Previous, S); | |||
10139 | ||||
10140 | // Warn about shadowing the name of a template parameter. | |||
10141 | if (Previous.isSingleResult() && | |||
10142 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
10143 | DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); | |||
10144 | Previous.clear(); | |||
10145 | } | |||
10146 | ||||
10147 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10148, __extension__ __PRETTY_FUNCTION__)) | |||
10148 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10148, __extension__ __PRETTY_FUNCTION__)); | |||
10149 | TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, | |||
10150 | Name.StartLocation, | |||
10151 | Name.Identifier, TInfo); | |||
10152 | ||||
10153 | NewTD->setAccess(AS); | |||
10154 | ||||
10155 | if (Invalid) | |||
10156 | NewTD->setInvalidDecl(); | |||
10157 | ||||
10158 | ProcessDeclAttributeList(S, NewTD, AttrList); | |||
10159 | AddPragmaAttributes(S, NewTD); | |||
10160 | ||||
10161 | CheckTypedefForVariablyModifiedType(S, NewTD); | |||
10162 | Invalid |= NewTD->isInvalidDecl(); | |||
10163 | ||||
10164 | bool Redeclaration = false; | |||
10165 | ||||
10166 | NamedDecl *NewND; | |||
10167 | if (TemplateParamLists.size()) { | |||
10168 | TypeAliasTemplateDecl *OldDecl = nullptr; | |||
10169 | TemplateParameterList *OldTemplateParams = nullptr; | |||
10170 | ||||
10171 | if (TemplateParamLists.size() != 1) { | |||
10172 | Diag(UsingLoc, diag::err_alias_template_extra_headers) | |||
10173 | << SourceRange(TemplateParamLists[1]->getTemplateLoc(), | |||
10174 | TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); | |||
10175 | } | |||
10176 | TemplateParameterList *TemplateParams = TemplateParamLists[0]; | |||
10177 | ||||
10178 | // Check that we can declare a template here. | |||
10179 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
10180 | return nullptr; | |||
10181 | ||||
10182 | // Only consider previous declarations in the same scope. | |||
10183 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, | |||
10184 | /*ExplicitInstantiationOrSpecialization*/false); | |||
10185 | if (!Previous.empty()) { | |||
10186 | Redeclaration = true; | |||
10187 | ||||
10188 | OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); | |||
10189 | if (!OldDecl && !Invalid) { | |||
10190 | Diag(UsingLoc, diag::err_redefinition_different_kind) | |||
10191 | << Name.Identifier; | |||
10192 | ||||
10193 | NamedDecl *OldD = Previous.getRepresentativeDecl(); | |||
10194 | if (OldD->getLocation().isValid()) | |||
10195 | Diag(OldD->getLocation(), diag::note_previous_definition); | |||
10196 | ||||
10197 | Invalid = true; | |||
10198 | } | |||
10199 | ||||
10200 | if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { | |||
10201 | if (TemplateParameterListsAreEqual(TemplateParams, | |||
10202 | OldDecl->getTemplateParameters(), | |||
10203 | /*Complain=*/true, | |||
10204 | TPL_TemplateMatch)) | |||
10205 | OldTemplateParams = OldDecl->getTemplateParameters(); | |||
10206 | else | |||
10207 | Invalid = true; | |||
10208 | ||||
10209 | TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); | |||
10210 | if (!Invalid && | |||
10211 | !Context.hasSameType(OldTD->getUnderlyingType(), | |||
10212 | NewTD->getUnderlyingType())) { | |||
10213 | // FIXME: The C++0x standard does not clearly say this is ill-formed, | |||
10214 | // but we can't reasonably accept it. | |||
10215 | Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) | |||
10216 | << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); | |||
10217 | if (OldTD->getLocation().isValid()) | |||
10218 | Diag(OldTD->getLocation(), diag::note_previous_definition); | |||
10219 | Invalid = true; | |||
10220 | } | |||
10221 | } | |||
10222 | } | |||
10223 | ||||
10224 | // Merge any previous default template arguments into our parameters, | |||
10225 | // and check the parameter list. | |||
10226 | if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, | |||
10227 | TPC_TypeAliasTemplate)) | |||
10228 | return nullptr; | |||
10229 | ||||
10230 | TypeAliasTemplateDecl *NewDecl = | |||
10231 | TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, | |||
10232 | Name.Identifier, TemplateParams, | |||
10233 | NewTD); | |||
10234 | NewTD->setDescribedAliasTemplate(NewDecl); | |||
10235 | ||||
10236 | NewDecl->setAccess(AS); | |||
10237 | ||||
10238 | if (Invalid) | |||
10239 | NewDecl->setInvalidDecl(); | |||
10240 | else if (OldDecl) { | |||
10241 | NewDecl->setPreviousDecl(OldDecl); | |||
10242 | CheckRedeclarationModuleOwnership(NewDecl, OldDecl); | |||
10243 | } | |||
10244 | ||||
10245 | NewND = NewDecl; | |||
10246 | } else { | |||
10247 | if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { | |||
10248 | setTagNameForLinkagePurposes(TD, NewTD); | |||
10249 | handleTagNumbering(TD, S); | |||
10250 | } | |||
10251 | ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); | |||
10252 | NewND = NewTD; | |||
10253 | } | |||
10254 | ||||
10255 | PushOnScopeChains(NewND, S); | |||
10256 | ActOnDocumentableDecl(NewND); | |||
10257 | return NewND; | |||
10258 | } | |||
10259 | ||||
10260 | Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, | |||
10261 | SourceLocation AliasLoc, | |||
10262 | IdentifierInfo *Alias, CXXScopeSpec &SS, | |||
10263 | SourceLocation IdentLoc, | |||
10264 | IdentifierInfo *Ident) { | |||
10265 | ||||
10266 | // Lookup the namespace name. | |||
10267 | LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); | |||
10268 | LookupParsedName(R, S, &SS); | |||
10269 | ||||
10270 | if (R.isAmbiguous()) | |||
10271 | return nullptr; | |||
10272 | ||||
10273 | if (R.empty()) { | |||
10274 | if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { | |||
10275 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | |||
10276 | return nullptr; | |||
10277 | } | |||
10278 | } | |||
10279 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10279, __extension__ __PRETTY_FUNCTION__)); | |||
10280 | NamedDecl *ND = R.getRepresentativeDecl(); | |||
10281 | ||||
10282 | // Check if we have a previous declaration with the same name. | |||
10283 | LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, | |||
10284 | ForVisibleRedeclaration); | |||
10285 | LookupName(PrevR, S); | |||
10286 | ||||
10287 | // Check we're not shadowing a template parameter. | |||
10288 | if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { | |||
10289 | DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); | |||
10290 | PrevR.clear(); | |||
10291 | } | |||
10292 | ||||
10293 | // Filter out any other lookup result from an enclosing scope. | |||
10294 | FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, | |||
10295 | /*AllowInlineNamespace*/false); | |||
10296 | ||||
10297 | // Find the previous declaration and check that we can redeclare it. | |||
10298 | NamespaceAliasDecl *Prev = nullptr; | |||
10299 | if (PrevR.isSingleResult()) { | |||
10300 | NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); | |||
10301 | if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { | |||
10302 | // We already have an alias with the same name that points to the same | |||
10303 | // namespace; check that it matches. | |||
10304 | if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { | |||
10305 | Prev = AD; | |||
10306 | } else if (isVisible(PrevDecl)) { | |||
10307 | Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) | |||
10308 | << Alias; | |||
10309 | Diag(AD->getLocation(), diag::note_previous_namespace_alias) | |||
10310 | << AD->getNamespace(); | |||
10311 | return nullptr; | |||
10312 | } | |||
10313 | } else if (isVisible(PrevDecl)) { | |||
10314 | unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) | |||
10315 | ? diag::err_redefinition | |||
10316 | : diag::err_redefinition_different_kind; | |||
10317 | Diag(AliasLoc, DiagID) << Alias; | |||
10318 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
10319 | return nullptr; | |||
10320 | } | |||
10321 | } | |||
10322 | ||||
10323 | // The use of a nested name specifier may trigger deprecation warnings. | |||
10324 | DiagnoseUseOfDecl(ND, IdentLoc); | |||
10325 | ||||
10326 | NamespaceAliasDecl *AliasDecl = | |||
10327 | NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, | |||
10328 | Alias, SS.getWithLocInContext(Context), | |||
10329 | IdentLoc, ND); | |||
10330 | if (Prev) | |||
10331 | AliasDecl->setPreviousDecl(Prev); | |||
10332 | ||||
10333 | PushOnScopeChains(AliasDecl, S); | |||
10334 | return AliasDecl; | |||
10335 | } | |||
10336 | ||||
10337 | namespace { | |||
10338 | struct SpecialMemberExceptionSpecInfo | |||
10339 | : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { | |||
10340 | SourceLocation Loc; | |||
10341 | Sema::ImplicitExceptionSpecification ExceptSpec; | |||
10342 | ||||
10343 | SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, | |||
10344 | Sema::CXXSpecialMember CSM, | |||
10345 | Sema::InheritedConstructorInfo *ICI, | |||
10346 | SourceLocation Loc) | |||
10347 | : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} | |||
10348 | ||||
10349 | bool visitBase(CXXBaseSpecifier *Base); | |||
10350 | bool visitField(FieldDecl *FD); | |||
10351 | ||||
10352 | void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | |||
10353 | unsigned Quals); | |||
10354 | ||||
10355 | void visitSubobjectCall(Subobject Subobj, | |||
10356 | Sema::SpecialMemberOverloadResult SMOR); | |||
10357 | }; | |||
10358 | } | |||
10359 | ||||
10360 | bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { | |||
10361 | auto *RT = Base->getType()->getAs<RecordType>(); | |||
10362 | if (!RT) | |||
10363 | return false; | |||
10364 | ||||
10365 | auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); | |||
10366 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | |||
10367 | if (auto *BaseCtor = SMOR.getMethod()) { | |||
10368 | visitSubobjectCall(Base, BaseCtor); | |||
10369 | return false; | |||
10370 | } | |||
10371 | ||||
10372 | visitClassSubobject(BaseClass, Base, 0); | |||
10373 | return false; | |||
10374 | } | |||
10375 | ||||
10376 | bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { | |||
10377 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { | |||
10378 | Expr *E = FD->getInClassInitializer(); | |||
10379 | if (!E) | |||
10380 | // FIXME: It's a little wasteful to build and throw away a | |||
10381 | // CXXDefaultInitExpr here. | |||
10382 | // FIXME: We should have a single context note pointing at Loc, and | |||
10383 | // this location should be MD->getLocation() instead, since that's | |||
10384 | // the location where we actually use the default init expression. | |||
10385 | E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); | |||
10386 | if (E) | |||
10387 | ExceptSpec.CalledExpr(E); | |||
10388 | } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) | |||
10389 | ->getAs<RecordType>()) { | |||
10390 | visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, | |||
10391 | FD->getType().getCVRQualifiers()); | |||
10392 | } | |||
10393 | return false; | |||
10394 | } | |||
10395 | ||||
10396 | void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, | |||
10397 | Subobject Subobj, | |||
10398 | unsigned Quals) { | |||
10399 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
10400 | bool IsMutable = Field && Field->isMutable(); | |||
10401 | visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); | |||
10402 | } | |||
10403 | ||||
10404 | void SpecialMemberExceptionSpecInfo::visitSubobjectCall( | |||
10405 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { | |||
10406 | // Note, if lookup fails, it doesn't matter what exception specification we | |||
10407 | // choose because the special member will be deleted. | |||
10408 | if (CXXMethodDecl *MD = SMOR.getMethod()) | |||
10409 | ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); | |||
10410 | } | |||
10411 | ||||
10412 | static Sema::ImplicitExceptionSpecification | |||
10413 | ComputeDefaultedSpecialMemberExceptionSpec( | |||
10414 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
10415 | Sema::InheritedConstructorInfo *ICI) { | |||
10416 | CXXRecordDecl *ClassDecl = MD->getParent(); | |||
10417 | ||||
10418 | // C++ [except.spec]p14: | |||
10419 | // An implicitly declared special member function (Clause 12) shall have an | |||
10420 | // exception-specification. [...] | |||
10421 | SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); | |||
10422 | if (ClassDecl->isInvalidDecl()) | |||
10423 | return Info.ExceptSpec; | |||
10424 | ||||
10425 | // C++1z [except.spec]p7: | |||
10426 | // [Look for exceptions thrown by] a constructor selected [...] to | |||
10427 | // initialize a potentially constructed subobject, | |||
10428 | // C++1z [except.spec]p8: | |||
10429 | // The exception specification for an implicitly-declared destructor, or a | |||
10430 | // destructor without a noexcept-specifier, is potentially-throwing if and | |||
10431 | // only if any of the destructors for any of its potentially constructed | |||
10432 | // subojects is potentially throwing. | |||
10433 | // FIXME: We respect the first rule but ignore the "potentially constructed" | |||
10434 | // in the second rule to resolve a core issue (no number yet) that would have | |||
10435 | // us reject: | |||
10436 | // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; | |||
10437 | // struct B : A {}; | |||
10438 | // struct C : B { void f(); }; | |||
10439 | // ... due to giving B::~B() a non-throwing exception specification. | |||
10440 | Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases | |||
10441 | : Info.VisitAllBases); | |||
10442 | ||||
10443 | return Info.ExceptSpec; | |||
10444 | } | |||
10445 | ||||
10446 | namespace { | |||
10447 | /// RAII object to register a special member as being currently declared. | |||
10448 | struct DeclaringSpecialMember { | |||
10449 | Sema &S; | |||
10450 | Sema::SpecialMemberDecl D; | |||
10451 | Sema::ContextRAII SavedContext; | |||
10452 | bool WasAlreadyBeingDeclared; | |||
10453 | ||||
10454 | DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) | |||
10455 | : S(S), D(RD, CSM), SavedContext(S, RD) { | |||
10456 | WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; | |||
10457 | if (WasAlreadyBeingDeclared) | |||
10458 | // This almost never happens, but if it does, ensure that our cache | |||
10459 | // doesn't contain a stale result. | |||
10460 | S.SpecialMemberCache.clear(); | |||
10461 | else { | |||
10462 | // Register a note to be produced if we encounter an error while | |||
10463 | // declaring the special member. | |||
10464 | Sema::CodeSynthesisContext Ctx; | |||
10465 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; | |||
10466 | // FIXME: We don't have a location to use here. Using the class's | |||
10467 | // location maintains the fiction that we declare all special members | |||
10468 | // with the class, but (1) it's not clear that lying about that helps our | |||
10469 | // users understand what's going on, and (2) there may be outer contexts | |||
10470 | // on the stack (some of which are relevant) and printing them exposes | |||
10471 | // our lies. | |||
10472 | Ctx.PointOfInstantiation = RD->getLocation(); | |||
10473 | Ctx.Entity = RD; | |||
10474 | Ctx.SpecialMember = CSM; | |||
10475 | S.pushCodeSynthesisContext(Ctx); | |||
10476 | } | |||
10477 | } | |||
10478 | ~DeclaringSpecialMember() { | |||
10479 | if (!WasAlreadyBeingDeclared) { | |||
10480 | S.SpecialMembersBeingDeclared.erase(D); | |||
10481 | S.popCodeSynthesisContext(); | |||
10482 | } | |||
10483 | } | |||
10484 | ||||
10485 | /// \brief Are we already trying to declare this special member? | |||
10486 | bool isAlreadyBeingDeclared() const { | |||
10487 | return WasAlreadyBeingDeclared; | |||
10488 | } | |||
10489 | }; | |||
10490 | } | |||
10491 | ||||
10492 | void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { | |||
10493 | // Look up any existing declarations, but don't trigger declaration of all | |||
10494 | // implicit special members with this name. | |||
10495 | DeclarationName Name = FD->getDeclName(); | |||
10496 | LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, | |||
10497 | ForExternalRedeclaration); | |||
10498 | for (auto *D : FD->getParent()->lookup(Name)) | |||
10499 | if (auto *Acceptable = R.getAcceptableDecl(D)) | |||
10500 | R.addDecl(Acceptable); | |||
10501 | R.resolveKind(); | |||
10502 | R.suppressDiagnostics(); | |||
10503 | ||||
10504 | CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); | |||
10505 | } | |||
10506 | ||||
10507 | CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( | |||
10508 | CXXRecordDecl *ClassDecl) { | |||
10509 | // C++ [class.ctor]p5: | |||
10510 | // A default constructor for a class X is a constructor of class X | |||
10511 | // that can be called without an argument. If there is no | |||
10512 | // user-declared constructor for class X, a default constructor is | |||
10513 | // implicitly declared. An implicitly-declared default constructor | |||
10514 | // is an inline public member of its class. | |||
10515 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10516, __extension__ __PRETTY_FUNCTION__)) | |||
10516 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10516, __extension__ __PRETTY_FUNCTION__)); | |||
10517 | ||||
10518 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); | |||
10519 | if (DSM.isAlreadyBeingDeclared()) | |||
10520 | return nullptr; | |||
10521 | ||||
10522 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
10523 | CXXDefaultConstructor, | |||
10524 | false); | |||
10525 | ||||
10526 | // Create the actual constructor declaration. | |||
10527 | CanQualType ClassType | |||
10528 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
10529 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
10530 | DeclarationName Name | |||
10531 | = Context.DeclarationNames.getCXXConstructorName(ClassType); | |||
10532 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
10533 | CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( | |||
10534 | Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), | |||
10535 | /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, | |||
10536 | /*isImplicitlyDeclared=*/true, Constexpr); | |||
10537 | DefaultCon->setAccess(AS_public); | |||
10538 | DefaultCon->setDefaulted(); | |||
10539 | ||||
10540 | if (getLangOpts().CUDA) { | |||
10541 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, | |||
10542 | DefaultCon, | |||
10543 | /* ConstRHS */ false, | |||
10544 | /* Diagnose */ false); | |||
10545 | } | |||
10546 | ||||
10547 | // Build an exception specification pointing back at this constructor. | |||
10548 | FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); | |||
10549 | DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); | |||
10550 | ||||
10551 | // We don't need to use SpecialMemberIsTrivial here; triviality for default | |||
10552 | // constructors is easy to compute. | |||
10553 | DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); | |||
10554 | ||||
10555 | // Note that we have declared this constructor. | |||
10556 | ++ASTContext::NumImplicitDefaultConstructorsDeclared; | |||
10557 | ||||
10558 | Scope *S = getScopeForContext(ClassDecl); | |||
10559 | CheckImplicitSpecialMemberDeclaration(S, DefaultCon); | |||
10560 | ||||
10561 | if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) | |||
10562 | SetDeclDeleted(DefaultCon, ClassLoc); | |||
10563 | ||||
10564 | if (S) | |||
10565 | PushOnScopeChains(DefaultCon, S, false); | |||
10566 | ClassDecl->addDecl(DefaultCon); | |||
10567 | ||||
10568 | return DefaultCon; | |||
10569 | } | |||
10570 | ||||
10571 | void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, | |||
10572 | CXXConstructorDecl *Constructor) { | |||
10573 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10576, __extension__ __PRETTY_FUNCTION__)) | |||
10574 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10576, __extension__ __PRETTY_FUNCTION__)) | |||
10575 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10576, __extension__ __PRETTY_FUNCTION__)) | |||
10576 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10576, __extension__ __PRETTY_FUNCTION__)); | |||
10577 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | |||
10578 | return; | |||
10579 | ||||
10580 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
10581 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10581, __extension__ __PRETTY_FUNCTION__)); | |||
10582 | ||||
10583 | SynthesizedFunctionScope Scope(*this, Constructor); | |||
10584 | ||||
10585 | // The exception specification is needed because we are defining the | |||
10586 | // function. | |||
10587 | ResolveExceptionSpec(CurrentLocation, | |||
10588 | Constructor->getType()->castAs<FunctionProtoType>()); | |||
10589 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
10590 | ||||
10591 | // Add a context note for diagnostics produced after this point. | |||
10592 | Scope.addContextNote(CurrentLocation); | |||
10593 | ||||
10594 | if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { | |||
10595 | Constructor->setInvalidDecl(); | |||
10596 | return; | |||
10597 | } | |||
10598 | ||||
10599 | SourceLocation Loc = Constructor->getLocEnd().isValid() | |||
10600 | ? Constructor->getLocEnd() | |||
10601 | : Constructor->getLocation(); | |||
10602 | Constructor->setBody(new (Context) CompoundStmt(Loc)); | |||
10603 | Constructor->markUsed(Context); | |||
10604 | ||||
10605 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
10606 | L->CompletedImplicitDefinition(Constructor); | |||
10607 | } | |||
10608 | ||||
10609 | DiagnoseUninitializedFields(*this, Constructor); | |||
10610 | } | |||
10611 | ||||
10612 | void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { | |||
10613 | // Perform any delayed checks on exception specifications. | |||
10614 | CheckDelayedMemberExceptionSpecs(); | |||
10615 | } | |||
10616 | ||||
10617 | /// Find or create the fake constructor we synthesize to model constructing an | |||
10618 | /// object of a derived class via a constructor of a base class. | |||
10619 | CXXConstructorDecl * | |||
10620 | Sema::findInheritingConstructor(SourceLocation Loc, | |||
10621 | CXXConstructorDecl *BaseCtor, | |||
10622 | ConstructorUsingShadowDecl *Shadow) { | |||
10623 | CXXRecordDecl *Derived = Shadow->getParent(); | |||
10624 | SourceLocation UsingLoc = Shadow->getLocation(); | |||
10625 | ||||
10626 | // FIXME: Add a new kind of DeclarationName for an inherited constructor. | |||
10627 | // For now we use the name of the base class constructor as a member of the | |||
10628 | // derived class to indicate a (fake) inherited constructor name. | |||
10629 | DeclarationName Name = BaseCtor->getDeclName(); | |||
10630 | ||||
10631 | // Check to see if we already have a fake constructor for this inherited | |||
10632 | // constructor call. | |||
10633 | for (NamedDecl *Ctor : Derived->lookup(Name)) | |||
10634 | if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) | |||
10635 | ->getInheritedConstructor() | |||
10636 | .getConstructor(), | |||
10637 | BaseCtor)) | |||
10638 | return cast<CXXConstructorDecl>(Ctor); | |||
10639 | ||||
10640 | DeclarationNameInfo NameInfo(Name, UsingLoc); | |||
10641 | TypeSourceInfo *TInfo = | |||
10642 | Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); | |||
10643 | FunctionProtoTypeLoc ProtoLoc = | |||
10644 | TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); | |||
10645 | ||||
10646 | // Check the inherited constructor is valid and find the list of base classes | |||
10647 | // from which it was inherited. | |||
10648 | InheritedConstructorInfo ICI(*this, Loc, Shadow); | |||
10649 | ||||
10650 | bool Constexpr = | |||
10651 | BaseCtor->isConstexpr() && | |||
10652 | defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, | |||
10653 | false, BaseCtor, &ICI); | |||
10654 | ||||
10655 | CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( | |||
10656 | Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, | |||
10657 | BaseCtor->isExplicit(), /*Inline=*/true, | |||
10658 | /*ImplicitlyDeclared=*/true, Constexpr, | |||
10659 | InheritedConstructor(Shadow, BaseCtor)); | |||
10660 | if (Shadow->isInvalidDecl()) | |||
10661 | DerivedCtor->setInvalidDecl(); | |||
10662 | ||||
10663 | // Build an unevaluated exception specification for this fake constructor. | |||
10664 | const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); | |||
10665 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
10666 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
10667 | EPI.ExceptionSpec.SourceDecl = DerivedCtor; | |||
10668 | DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), | |||
10669 | FPT->getParamTypes(), EPI)); | |||
10670 | ||||
10671 | // Build the parameter declarations. | |||
10672 | SmallVector<ParmVarDecl *, 16> ParamDecls; | |||
10673 | for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { | |||
10674 | TypeSourceInfo *TInfo = | |||
10675 | Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); | |||
10676 | ParmVarDecl *PD = ParmVarDecl::Create( | |||
10677 | Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, | |||
10678 | FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); | |||
10679 | PD->setScopeInfo(0, I); | |||
10680 | PD->setImplicit(); | |||
10681 | // Ensure attributes are propagated onto parameters (this matters for | |||
10682 | // format, pass_object_size, ...). | |||
10683 | mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); | |||
10684 | ParamDecls.push_back(PD); | |||
10685 | ProtoLoc.setParam(I, PD); | |||
10686 | } | |||
10687 | ||||
10688 | // Set up the new constructor. | |||
10689 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10689, __extension__ __PRETTY_FUNCTION__)); | |||
10690 | DerivedCtor->setAccess(BaseCtor->getAccess()); | |||
10691 | DerivedCtor->setParams(ParamDecls); | |||
10692 | Derived->addDecl(DerivedCtor); | |||
10693 | ||||
10694 | if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) | |||
10695 | SetDeclDeleted(DerivedCtor, UsingLoc); | |||
10696 | ||||
10697 | return DerivedCtor; | |||
10698 | } | |||
10699 | ||||
10700 | void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { | |||
10701 | InheritedConstructorInfo ICI(*this, Ctor->getLocation(), | |||
10702 | Ctor->getInheritedConstructor().getShadowDecl()); | |||
10703 | ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, | |||
10704 | /*Diagnose*/true); | |||
10705 | } | |||
10706 | ||||
10707 | void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, | |||
10708 | CXXConstructorDecl *Constructor) { | |||
10709 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
10710 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10712, __extension__ __PRETTY_FUNCTION__)) | |||
10711 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10712, __extension__ __PRETTY_FUNCTION__)) | |||
10712 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10712, __extension__ __PRETTY_FUNCTION__)); | |||
10713 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | |||
10714 | return; | |||
10715 | ||||
10716 | // Initializations are performed "as if by a defaulted default constructor", | |||
10717 | // so enter the appropriate scope. | |||
10718 | SynthesizedFunctionScope Scope(*this, Constructor); | |||
10719 | ||||
10720 | // The exception specification is needed because we are defining the | |||
10721 | // function. | |||
10722 | ResolveExceptionSpec(CurrentLocation, | |||
10723 | Constructor->getType()->castAs<FunctionProtoType>()); | |||
10724 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
10725 | ||||
10726 | // Add a context note for diagnostics produced after this point. | |||
10727 | Scope.addContextNote(CurrentLocation); | |||
10728 | ||||
10729 | ConstructorUsingShadowDecl *Shadow = | |||
10730 | Constructor->getInheritedConstructor().getShadowDecl(); | |||
10731 | CXXConstructorDecl *InheritedCtor = | |||
10732 | Constructor->getInheritedConstructor().getConstructor(); | |||
10733 | ||||
10734 | // [class.inhctor.init]p1: | |||
10735 | // initialization proceeds as if a defaulted default constructor is used to | |||
10736 | // initialize the D object and each base class subobject from which the | |||
10737 | // constructor was inherited | |||
10738 | ||||
10739 | InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); | |||
10740 | CXXRecordDecl *RD = Shadow->getParent(); | |||
10741 | SourceLocation InitLoc = Shadow->getLocation(); | |||
10742 | ||||
10743 | // Build explicit initializers for all base classes from which the | |||
10744 | // constructor was inherited. | |||
10745 | SmallVector<CXXCtorInitializer*, 8> Inits; | |||
10746 | for (bool VBase : {false, true}) { | |||
10747 | for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { | |||
10748 | if (B.isVirtual() != VBase) | |||
10749 | continue; | |||
10750 | ||||
10751 | auto *BaseRD = B.getType()->getAsCXXRecordDecl(); | |||
10752 | if (!BaseRD) | |||
10753 | continue; | |||
10754 | ||||
10755 | auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); | |||
10756 | if (!BaseCtor.first) | |||
10757 | continue; | |||
10758 | ||||
10759 | MarkFunctionReferenced(CurrentLocation, BaseCtor.first); | |||
10760 | ExprResult Init = new (Context) CXXInheritedCtorInitExpr( | |||
10761 | InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); | |||
10762 | ||||
10763 | auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); | |||
10764 | Inits.push_back(new (Context) CXXCtorInitializer( | |||
10765 | Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, | |||
10766 | SourceLocation())); | |||
10767 | } | |||
10768 | } | |||
10769 | ||||
10770 | // We now proceed as if for a defaulted default constructor, with the relevant | |||
10771 | // initializers replaced. | |||
10772 | ||||
10773 | if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { | |||
10774 | Constructor->setInvalidDecl(); | |||
10775 | return; | |||
10776 | } | |||
10777 | ||||
10778 | Constructor->setBody(new (Context) CompoundStmt(InitLoc)); | |||
10779 | Constructor->markUsed(Context); | |||
10780 | ||||
10781 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
10782 | L->CompletedImplicitDefinition(Constructor); | |||
10783 | } | |||
10784 | ||||
10785 | DiagnoseUninitializedFields(*this, Constructor); | |||
10786 | } | |||
10787 | ||||
10788 | CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { | |||
10789 | // C++ [class.dtor]p2: | |||
10790 | // If a class has no user-declared destructor, a destructor is | |||
10791 | // declared implicitly. An implicitly-declared destructor is an | |||
10792 | // inline public member of its class. | |||
10793 | assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor ()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10793, __extension__ __PRETTY_FUNCTION__)); | |||
10794 | ||||
10795 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); | |||
10796 | if (DSM.isAlreadyBeingDeclared()) | |||
10797 | return nullptr; | |||
10798 | ||||
10799 | // Create the actual destructor declaration. | |||
10800 | CanQualType ClassType | |||
10801 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
10802 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
10803 | DeclarationName Name | |||
10804 | = Context.DeclarationNames.getCXXDestructorName(ClassType); | |||
10805 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
10806 | CXXDestructorDecl *Destructor | |||
10807 | = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, | |||
10808 | QualType(), nullptr, /*isInline=*/true, | |||
10809 | /*isImplicitlyDeclared=*/true); | |||
10810 | Destructor->setAccess(AS_public); | |||
10811 | Destructor->setDefaulted(); | |||
10812 | ||||
10813 | if (getLangOpts().CUDA) { | |||
10814 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, | |||
10815 | Destructor, | |||
10816 | /* ConstRHS */ false, | |||
10817 | /* Diagnose */ false); | |||
10818 | } | |||
10819 | ||||
10820 | // Build an exception specification pointing back at this destructor. | |||
10821 | FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); | |||
10822 | Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); | |||
10823 | ||||
10824 | // We don't need to use SpecialMemberIsTrivial here; triviality for | |||
10825 | // destructors is easy to compute. | |||
10826 | Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); | |||
10827 | Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || | |||
10828 | ClassDecl->hasTrivialDestructorForCall()); | |||
10829 | ||||
10830 | // Note that we have declared this destructor. | |||
10831 | ++ASTContext::NumImplicitDestructorsDeclared; | |||
10832 | ||||
10833 | Scope *S = getScopeForContext(ClassDecl); | |||
10834 | CheckImplicitSpecialMemberDeclaration(S, Destructor); | |||
10835 | ||||
10836 | // We can't check whether an implicit destructor is deleted before we complete | |||
10837 | // the definition of the class, because its validity depends on the alignment | |||
10838 | // of the class. We'll check this from ActOnFields once the class is complete. | |||
10839 | if (ClassDecl->isCompleteDefinition() && | |||
10840 | ShouldDeleteSpecialMember(Destructor, CXXDestructor)) | |||
10841 | SetDeclDeleted(Destructor, ClassLoc); | |||
10842 | ||||
10843 | // Introduce this destructor into its scope. | |||
10844 | if (S) | |||
10845 | PushOnScopeChains(Destructor, S, false); | |||
10846 | ClassDecl->addDecl(Destructor); | |||
10847 | ||||
10848 | return Destructor; | |||
10849 | } | |||
10850 | ||||
10851 | void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, | |||
10852 | CXXDestructorDecl *Destructor) { | |||
10853 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10856, __extension__ __PRETTY_FUNCTION__)) | |||
10854 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10856, __extension__ __PRETTY_FUNCTION__)) | |||
10855 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10856, __extension__ __PRETTY_FUNCTION__)) | |||
10856 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10856, __extension__ __PRETTY_FUNCTION__)); | |||
10857 | if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) | |||
10858 | return; | |||
10859 | ||||
10860 | CXXRecordDecl *ClassDecl = Destructor->getParent(); | |||
10861 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10861, __extension__ __PRETTY_FUNCTION__)); | |||
10862 | ||||
10863 | SynthesizedFunctionScope Scope(*this, Destructor); | |||
10864 | ||||
10865 | // The exception specification is needed because we are defining the | |||
10866 | // function. | |||
10867 | ResolveExceptionSpec(CurrentLocation, | |||
10868 | Destructor->getType()->castAs<FunctionProtoType>()); | |||
10869 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
10870 | ||||
10871 | // Add a context note for diagnostics produced after this point. | |||
10872 | Scope.addContextNote(CurrentLocation); | |||
10873 | ||||
10874 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | |||
10875 | Destructor->getParent()); | |||
10876 | ||||
10877 | if (CheckDestructor(Destructor)) { | |||
10878 | Destructor->setInvalidDecl(); | |||
10879 | return; | |||
10880 | } | |||
10881 | ||||
10882 | SourceLocation Loc = Destructor->getLocEnd().isValid() | |||
10883 | ? Destructor->getLocEnd() | |||
10884 | : Destructor->getLocation(); | |||
10885 | Destructor->setBody(new (Context) CompoundStmt(Loc)); | |||
10886 | Destructor->markUsed(Context); | |||
10887 | ||||
10888 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
10889 | L->CompletedImplicitDefinition(Destructor); | |||
10890 | } | |||
10891 | } | |||
10892 | ||||
10893 | /// \brief Perform any semantic analysis which needs to be delayed until all | |||
10894 | /// pending class member declarations have been parsed. | |||
10895 | void Sema::ActOnFinishCXXMemberDecls() { | |||
10896 | // If the context is an invalid C++ class, just suppress these checks. | |||
10897 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { | |||
10898 | if (Record->isInvalidDecl()) { | |||
10899 | DelayedDefaultedMemberExceptionSpecs.clear(); | |||
10900 | DelayedExceptionSpecChecks.clear(); | |||
10901 | return; | |||
10902 | } | |||
10903 | checkForMultipleExportedDefaultConstructors(*this, Record); | |||
10904 | } | |||
10905 | } | |||
10906 | ||||
10907 | void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { | |||
10908 | referenceDLLExportedClassMethods(); | |||
10909 | } | |||
10910 | ||||
10911 | void Sema::referenceDLLExportedClassMethods() { | |||
10912 | if (!DelayedDllExportClasses.empty()) { | |||
10913 | // Calling ReferenceDllExportedMembers might cause the current function to | |||
10914 | // be called again, so use a local copy of DelayedDllExportClasses. | |||
10915 | SmallVector<CXXRecordDecl *, 4> WorkList; | |||
10916 | std::swap(DelayedDllExportClasses, WorkList); | |||
10917 | for (CXXRecordDecl *Class : WorkList) | |||
10918 | ReferenceDllExportedMembers(*this, Class); | |||
10919 | } | |||
10920 | } | |||
10921 | ||||
10922 | void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, | |||
10923 | CXXDestructorDecl *Destructor) { | |||
10924 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10925, __extension__ __PRETTY_FUNCTION__)) | |||
10925 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10925, __extension__ __PRETTY_FUNCTION__)); | |||
10926 | ||||
10927 | // C++11 [class.dtor]p3: | |||
10928 | // A declaration of a destructor that does not have an exception- | |||
10929 | // specification is implicitly considered to have the same exception- | |||
10930 | // specification as an implicit declaration. | |||
10931 | const FunctionProtoType *DtorType = Destructor->getType()-> | |||
10932 | getAs<FunctionProtoType>(); | |||
10933 | if (DtorType->hasExceptionSpec()) | |||
10934 | return; | |||
10935 | ||||
10936 | // Replace the destructor's type, building off the existing one. Fortunately, | |||
10937 | // the only thing of interest in the destructor type is its extended info. | |||
10938 | // The return and arguments are fixed. | |||
10939 | FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); | |||
10940 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
10941 | EPI.ExceptionSpec.SourceDecl = Destructor; | |||
10942 | Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); | |||
10943 | ||||
10944 | // FIXME: If the destructor has a body that could throw, and the newly created | |||
10945 | // spec doesn't allow exceptions, we should emit a warning, because this | |||
10946 | // change in behavior can break conforming C++03 programs at runtime. | |||
10947 | // However, we don't have a body or an exception specification yet, so it | |||
10948 | // needs to be done somewhere else. | |||
10949 | } | |||
10950 | ||||
10951 | namespace { | |||
10952 | /// \brief An abstract base class for all helper classes used in building the | |||
10953 | // copy/move operators. These classes serve as factory functions and help us | |||
10954 | // avoid using the same Expr* in the AST twice. | |||
10955 | class ExprBuilder { | |||
10956 | ExprBuilder(const ExprBuilder&) = delete; | |||
10957 | ExprBuilder &operator=(const ExprBuilder&) = delete; | |||
10958 | ||||
10959 | protected: | |||
10960 | static Expr *assertNotNull(Expr *E) { | |||
10961 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10961, __extension__ __PRETTY_FUNCTION__)); | |||
10962 | return E; | |||
10963 | } | |||
10964 | ||||
10965 | public: | |||
10966 | ExprBuilder() {} | |||
10967 | virtual ~ExprBuilder() {} | |||
10968 | ||||
10969 | virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; | |||
10970 | }; | |||
10971 | ||||
10972 | class RefBuilder: public ExprBuilder { | |||
10973 | VarDecl *Var; | |||
10974 | QualType VarType; | |||
10975 | ||||
10976 | public: | |||
10977 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
10978 | return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); | |||
10979 | } | |||
10980 | ||||
10981 | RefBuilder(VarDecl *Var, QualType VarType) | |||
10982 | : Var(Var), VarType(VarType) {} | |||
10983 | }; | |||
10984 | ||||
10985 | class ThisBuilder: public ExprBuilder { | |||
10986 | public: | |||
10987 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
10988 | return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); | |||
10989 | } | |||
10990 | }; | |||
10991 | ||||
10992 | class CastBuilder: public ExprBuilder { | |||
10993 | const ExprBuilder &Builder; | |||
10994 | QualType Type; | |||
10995 | ExprValueKind Kind; | |||
10996 | const CXXCastPath &Path; | |||
10997 | ||||
10998 | public: | |||
10999 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11000 | return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, | |||
11001 | CK_UncheckedDerivedToBase, Kind, | |||
11002 | &Path).get()); | |||
11003 | } | |||
11004 | ||||
11005 | CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, | |||
11006 | const CXXCastPath &Path) | |||
11007 | : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} | |||
11008 | }; | |||
11009 | ||||
11010 | class DerefBuilder: public ExprBuilder { | |||
11011 | const ExprBuilder &Builder; | |||
11012 | ||||
11013 | public: | |||
11014 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11015 | return assertNotNull( | |||
11016 | S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); | |||
11017 | } | |||
11018 | ||||
11019 | DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11020 | }; | |||
11021 | ||||
11022 | class MemberBuilder: public ExprBuilder { | |||
11023 | const ExprBuilder &Builder; | |||
11024 | QualType Type; | |||
11025 | CXXScopeSpec SS; | |||
11026 | bool IsArrow; | |||
11027 | LookupResult &MemberLookup; | |||
11028 | ||||
11029 | public: | |||
11030 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11031 | return assertNotNull(S.BuildMemberReferenceExpr( | |||
11032 | Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), | |||
11033 | nullptr, MemberLookup, nullptr, nullptr).get()); | |||
11034 | } | |||
11035 | ||||
11036 | MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, | |||
11037 | LookupResult &MemberLookup) | |||
11038 | : Builder(Builder), Type(Type), IsArrow(IsArrow), | |||
11039 | MemberLookup(MemberLookup) {} | |||
11040 | }; | |||
11041 | ||||
11042 | class MoveCastBuilder: public ExprBuilder { | |||
11043 | const ExprBuilder &Builder; | |||
11044 | ||||
11045 | public: | |||
11046 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11047 | return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); | |||
11048 | } | |||
11049 | ||||
11050 | MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11051 | }; | |||
11052 | ||||
11053 | class LvalueConvBuilder: public ExprBuilder { | |||
11054 | const ExprBuilder &Builder; | |||
11055 | ||||
11056 | public: | |||
11057 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11058 | return assertNotNull( | |||
11059 | S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); | |||
11060 | } | |||
11061 | ||||
11062 | LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11063 | }; | |||
11064 | ||||
11065 | class SubscriptBuilder: public ExprBuilder { | |||
11066 | const ExprBuilder &Base; | |||
11067 | const ExprBuilder &Index; | |||
11068 | ||||
11069 | public: | |||
11070 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11071 | return assertNotNull(S.CreateBuiltinArraySubscriptExpr( | |||
11072 | Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); | |||
11073 | } | |||
11074 | ||||
11075 | SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) | |||
11076 | : Base(Base), Index(Index) {} | |||
11077 | }; | |||
11078 | ||||
11079 | } // end anonymous namespace | |||
11080 | ||||
11081 | /// When generating a defaulted copy or move assignment operator, if a field | |||
11082 | /// should be copied with __builtin_memcpy rather than via explicit assignments, | |||
11083 | /// do so. This optimization only applies for arrays of scalars, and for arrays | |||
11084 | /// of class type where the selected copy/move-assignment operator is trivial. | |||
11085 | static StmtResult | |||
11086 | buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, | |||
11087 | const ExprBuilder &ToB, const ExprBuilder &FromB) { | |||
11088 | // Compute the size of the memory buffer to be copied. | |||
11089 | QualType SizeType = S.Context.getSizeType(); | |||
11090 | llvm::APInt Size(S.Context.getTypeSize(SizeType), | |||
11091 | S.Context.getTypeSizeInChars(T).getQuantity()); | |||
11092 | ||||
11093 | // Take the address of the field references for "from" and "to". We | |||
11094 | // directly construct UnaryOperators here because semantic analysis | |||
11095 | // does not permit us to take the address of an xvalue. | |||
11096 | Expr *From = FromB.build(S, Loc); | |||
11097 | From = new (S.Context) UnaryOperator(From, UO_AddrOf, | |||
11098 | S.Context.getPointerType(From->getType()), | |||
11099 | VK_RValue, OK_Ordinary, Loc, false); | |||
11100 | Expr *To = ToB.build(S, Loc); | |||
11101 | To = new (S.Context) UnaryOperator(To, UO_AddrOf, | |||
11102 | S.Context.getPointerType(To->getType()), | |||
11103 | VK_RValue, OK_Ordinary, Loc, false); | |||
11104 | ||||
11105 | const Type *E = T->getBaseElementTypeUnsafe(); | |||
11106 | bool NeedsCollectableMemCpy = | |||
11107 | E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); | |||
11108 | ||||
11109 | // Create a reference to the __builtin_objc_memmove_collectable function | |||
11110 | StringRef MemCpyName = NeedsCollectableMemCpy ? | |||
11111 | "__builtin_objc_memmove_collectable" : | |||
11112 | "__builtin_memcpy"; | |||
11113 | LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, | |||
11114 | Sema::LookupOrdinaryName); | |||
11115 | S.LookupName(R, S.TUScope, true); | |||
11116 | ||||
11117 | FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); | |||
11118 | if (!MemCpy) | |||
11119 | // Something went horribly wrong earlier, and we will have complained | |||
11120 | // about it. | |||
11121 | return StmtError(); | |||
11122 | ||||
11123 | ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, | |||
11124 | VK_RValue, Loc, nullptr); | |||
11125 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11125, __extension__ __PRETTY_FUNCTION__)); | |||
11126 | ||||
11127 | Expr *CallArgs[] = { | |||
11128 | To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) | |||
11129 | }; | |||
11130 | ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), | |||
11131 | Loc, CallArgs, Loc); | |||
11132 | ||||
11133 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11133, __extension__ __PRETTY_FUNCTION__)); | |||
11134 | return Call.getAs<Stmt>(); | |||
11135 | } | |||
11136 | ||||
11137 | /// \brief Builds a statement that copies/moves the given entity from \p From to | |||
11138 | /// \c To. | |||
11139 | /// | |||
11140 | /// This routine is used to copy/move the members of a class with an | |||
11141 | /// implicitly-declared copy/move assignment operator. When the entities being | |||
11142 | /// copied are arrays, this routine builds for loops to copy them. | |||
11143 | /// | |||
11144 | /// \param S The Sema object used for type-checking. | |||
11145 | /// | |||
11146 | /// \param Loc The location where the implicit copy/move is being generated. | |||
11147 | /// | |||
11148 | /// \param T The type of the expressions being copied/moved. Both expressions | |||
11149 | /// must have this type. | |||
11150 | /// | |||
11151 | /// \param To The expression we are copying/moving to. | |||
11152 | /// | |||
11153 | /// \param From The expression we are copying/moving from. | |||
11154 | /// | |||
11155 | /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. | |||
11156 | /// Otherwise, it's a non-static member subobject. | |||
11157 | /// | |||
11158 | /// \param Copying Whether we're copying or moving. | |||
11159 | /// | |||
11160 | /// \param Depth Internal parameter recording the depth of the recursion. | |||
11161 | /// | |||
11162 | /// \returns A statement or a loop that copies the expressions, or StmtResult(0) | |||
11163 | /// if a memcpy should be used instead. | |||
11164 | static StmtResult | |||
11165 | buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, | |||
11166 | const ExprBuilder &To, const ExprBuilder &From, | |||
11167 | bool CopyingBaseSubobject, bool Copying, | |||
11168 | unsigned Depth = 0) { | |||
11169 | // C++11 [class.copy]p28: | |||
11170 | // Each subobject is assigned in the manner appropriate to its type: | |||
11171 | // | |||
11172 | // - if the subobject is of class type, as if by a call to operator= with | |||
11173 | // the subobject as the object expression and the corresponding | |||
11174 | // subobject of x as a single function argument (as if by explicit | |||
11175 | // qualification; that is, ignoring any possible virtual overriding | |||
11176 | // functions in more derived classes); | |||
11177 | // | |||
11178 | // C++03 [class.copy]p13: | |||
11179 | // - if the subobject is of class type, the copy assignment operator for | |||
11180 | // the class is used (as if by explicit qualification; that is, | |||
11181 | // ignoring any possible virtual overriding functions in more derived | |||
11182 | // classes); | |||
11183 | if (const RecordType *RecordTy = T->getAs<RecordType>()) { | |||
11184 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
11185 | ||||
11186 | // Look for operator=. | |||
11187 | DeclarationName Name | |||
11188 | = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
11189 | LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); | |||
11190 | S.LookupQualifiedName(OpLookup, ClassDecl, false); | |||
11191 | ||||
11192 | // Prior to C++11, filter out any result that isn't a copy/move-assignment | |||
11193 | // operator. | |||
11194 | if (!S.getLangOpts().CPlusPlus11) { | |||
11195 | LookupResult::Filter F = OpLookup.makeFilter(); | |||
11196 | while (F.hasNext()) { | |||
11197 | NamedDecl *D = F.next(); | |||
11198 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) | |||
11199 | if (Method->isCopyAssignmentOperator() || | |||
11200 | (!Copying && Method->isMoveAssignmentOperator())) | |||
11201 | continue; | |||
11202 | ||||
11203 | F.erase(); | |||
11204 | } | |||
11205 | F.done(); | |||
11206 | } | |||
11207 | ||||
11208 | // Suppress the protected check (C++ [class.protected]) for each of the | |||
11209 | // assignment operators we found. This strange dance is required when | |||
11210 | // we're assigning via a base classes's copy-assignment operator. To | |||
11211 | // ensure that we're getting the right base class subobject (without | |||
11212 | // ambiguities), we need to cast "this" to that subobject type; to | |||
11213 | // ensure that we don't go through the virtual call mechanism, we need | |||
11214 | // to qualify the operator= name with the base class (see below). However, | |||
11215 | // this means that if the base class has a protected copy assignment | |||
11216 | // operator, the protected member access check will fail. So, we | |||
11217 | // rewrite "protected" access to "public" access in this case, since we | |||
11218 | // know by construction that we're calling from a derived class. | |||
11219 | if (CopyingBaseSubobject) { | |||
11220 | for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); | |||
11221 | L != LEnd; ++L) { | |||
11222 | if (L.getAccess() == AS_protected) | |||
11223 | L.setAccess(AS_public); | |||
11224 | } | |||
11225 | } | |||
11226 | ||||
11227 | // Create the nested-name-specifier that will be used to qualify the | |||
11228 | // reference to operator=; this is required to suppress the virtual | |||
11229 | // call mechanism. | |||
11230 | CXXScopeSpec SS; | |||
11231 | const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); | |||
11232 | SS.MakeTrivial(S.Context, | |||
11233 | NestedNameSpecifier::Create(S.Context, nullptr, false, | |||
11234 | CanonicalT), | |||
11235 | Loc); | |||
11236 | ||||
11237 | // Create the reference to operator=. | |||
11238 | ExprResult OpEqualRef | |||
11239 | = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, | |||
11240 | SS, /*TemplateKWLoc=*/SourceLocation(), | |||
11241 | /*FirstQualifierInScope=*/nullptr, | |||
11242 | OpLookup, | |||
11243 | /*TemplateArgs=*/nullptr, /*S*/nullptr, | |||
11244 | /*SuppressQualifierCheck=*/true); | |||
11245 | if (OpEqualRef.isInvalid()) | |||
11246 | return StmtError(); | |||
11247 | ||||
11248 | // Build the call to the assignment operator. | |||
11249 | ||||
11250 | Expr *FromInst = From.build(S, Loc); | |||
11251 | ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, | |||
11252 | OpEqualRef.getAs<Expr>(), | |||
11253 | Loc, FromInst, Loc); | |||
11254 | if (Call.isInvalid()) | |||
11255 | return StmtError(); | |||
11256 | ||||
11257 | // If we built a call to a trivial 'operator=' while copying an array, | |||
11258 | // bail out. We'll replace the whole shebang with a memcpy. | |||
11259 | CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); | |||
11260 | if (CE && CE->getMethodDecl()->isTrivial() && Depth) | |||
11261 | return StmtResult((Stmt*)nullptr); | |||
11262 | ||||
11263 | // Convert to an expression-statement, and clean up any produced | |||
11264 | // temporaries. | |||
11265 | return S.ActOnExprStmt(Call); | |||
11266 | } | |||
11267 | ||||
11268 | // - if the subobject is of scalar type, the built-in assignment | |||
11269 | // operator is used. | |||
11270 | const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); | |||
11271 | if (!ArrayTy) { | |||
11272 | ExprResult Assignment = S.CreateBuiltinBinOp( | |||
11273 | Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); | |||
11274 | if (Assignment.isInvalid()) | |||
11275 | return StmtError(); | |||
11276 | return S.ActOnExprStmt(Assignment); | |||
11277 | } | |||
11278 | ||||
11279 | // - if the subobject is an array, each element is assigned, in the | |||
11280 | // manner appropriate to the element type; | |||
11281 | ||||
11282 | // Construct a loop over the array bounds, e.g., | |||
11283 | // | |||
11284 | // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) | |||
11285 | // | |||
11286 | // that will copy each of the array elements. | |||
11287 | QualType SizeType = S.Context.getSizeType(); | |||
11288 | ||||
11289 | // Create the iteration variable. | |||
11290 | IdentifierInfo *IterationVarName = nullptr; | |||
11291 | { | |||
11292 | SmallString<8> Str; | |||
11293 | llvm::raw_svector_ostream OS(Str); | |||
11294 | OS << "__i" << Depth; | |||
11295 | IterationVarName = &S.Context.Idents.get(OS.str()); | |||
11296 | } | |||
11297 | VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, | |||
11298 | IterationVarName, SizeType, | |||
11299 | S.Context.getTrivialTypeSourceInfo(SizeType, Loc), | |||
11300 | SC_None); | |||
11301 | ||||
11302 | // Initialize the iteration variable to zero. | |||
11303 | llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); | |||
11304 | IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); | |||
11305 | ||||
11306 | // Creates a reference to the iteration variable. | |||
11307 | RefBuilder IterationVarRef(IterationVar, SizeType); | |||
11308 | LvalueConvBuilder IterationVarRefRVal(IterationVarRef); | |||
11309 | ||||
11310 | // Create the DeclStmt that holds the iteration variable. | |||
11311 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); | |||
11312 | ||||
11313 | // Subscript the "from" and "to" expressions with the iteration variable. | |||
11314 | SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); | |||
11315 | MoveCastBuilder FromIndexMove(FromIndexCopy); | |||
11316 | const ExprBuilder *FromIndex; | |||
11317 | if (Copying) | |||
11318 | FromIndex = &FromIndexCopy; | |||
11319 | else | |||
11320 | FromIndex = &FromIndexMove; | |||
11321 | ||||
11322 | SubscriptBuilder ToIndex(To, IterationVarRefRVal); | |||
11323 | ||||
11324 | // Build the copy/move for an individual element of the array. | |||
11325 | StmtResult Copy = | |||
11326 | buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), | |||
11327 | ToIndex, *FromIndex, CopyingBaseSubobject, | |||
11328 | Copying, Depth + 1); | |||
11329 | // Bail out if copying fails or if we determined that we should use memcpy. | |||
11330 | if (Copy.isInvalid() || !Copy.get()) | |||
11331 | return Copy; | |||
11332 | ||||
11333 | // Create the comparison against the array bound. | |||
11334 | llvm::APInt Upper | |||
11335 | = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); | |||
11336 | Expr *Comparison | |||
11337 | = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), | |||
11338 | IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), | |||
11339 | BO_NE, S.Context.BoolTy, | |||
11340 | VK_RValue, OK_Ordinary, Loc, FPOptions()); | |||
11341 | ||||
11342 | // Create the pre-increment of the iteration variable. We can determine | |||
11343 | // whether the increment will overflow based on the value of the array | |||
11344 | // bound. | |||
11345 | Expr *Increment = new (S.Context) | |||
11346 | UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, | |||
11347 | VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); | |||
11348 | ||||
11349 | // Construct the loop that copies all elements of this array. | |||
11350 | return S.ActOnForStmt( | |||
11351 | Loc, Loc, InitStmt, | |||
11352 | S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), | |||
11353 | S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); | |||
11354 | } | |||
11355 | ||||
11356 | static StmtResult | |||
11357 | buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, | |||
11358 | const ExprBuilder &To, const ExprBuilder &From, | |||
11359 | bool CopyingBaseSubobject, bool Copying) { | |||
11360 | // Maybe we should use a memcpy? | |||
11361 | if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && | |||
11362 | T.isTriviallyCopyableType(S.Context)) | |||
11363 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | |||
11364 | ||||
11365 | StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, | |||
11366 | CopyingBaseSubobject, | |||
11367 | Copying, 0)); | |||
11368 | ||||
11369 | // If we ended up picking a trivial assignment operator for an array of a | |||
11370 | // non-trivially-copyable class type, just emit a memcpy. | |||
11371 | if (!Result.isInvalid() && !Result.get()) | |||
11372 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | |||
11373 | ||||
11374 | return Result; | |||
11375 | } | |||
11376 | ||||
11377 | CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { | |||
11378 | // Note: The following rules are largely analoguous to the copy | |||
11379 | // constructor rules. Note that virtual bases are not taken into account | |||
11380 | // for determining the argument type of the operator. Note also that | |||
11381 | // operators taking an object instead of a reference are allowed. | |||
11382 | assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment ()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11382, __extension__ __PRETTY_FUNCTION__)); | |||
11383 | ||||
11384 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); | |||
11385 | if (DSM.isAlreadyBeingDeclared()) | |||
11386 | return nullptr; | |||
11387 | ||||
11388 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | |||
11389 | QualType RetType = Context.getLValueReferenceType(ArgType); | |||
11390 | bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); | |||
11391 | if (Const) | |||
11392 | ArgType = ArgType.withConst(); | |||
11393 | ArgType = Context.getLValueReferenceType(ArgType); | |||
11394 | ||||
11395 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
11396 | CXXCopyAssignment, | |||
11397 | Const); | |||
11398 | ||||
11399 | // An implicitly-declared copy assignment operator is an inline public | |||
11400 | // member of its class. | |||
11401 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
11402 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
11403 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
11404 | CXXMethodDecl *CopyAssignment = | |||
11405 | CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), | |||
11406 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | |||
11407 | /*isInline=*/true, Constexpr, SourceLocation()); | |||
11408 | CopyAssignment->setAccess(AS_public); | |||
11409 | CopyAssignment->setDefaulted(); | |||
11410 | CopyAssignment->setImplicit(); | |||
11411 | ||||
11412 | if (getLangOpts().CUDA) { | |||
11413 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, | |||
11414 | CopyAssignment, | |||
11415 | /* ConstRHS */ Const, | |||
11416 | /* Diagnose */ false); | |||
11417 | } | |||
11418 | ||||
11419 | // Build an exception specification pointing back at this member. | |||
11420 | FunctionProtoType::ExtProtoInfo EPI = | |||
11421 | getImplicitMethodEPI(*this, CopyAssignment); | |||
11422 | CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); | |||
11423 | ||||
11424 | // Add the parameter to the operator. | |||
11425 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, | |||
11426 | ClassLoc, ClassLoc, | |||
11427 | /*Id=*/nullptr, ArgType, | |||
11428 | /*TInfo=*/nullptr, SC_None, | |||
11429 | nullptr); | |||
11430 | CopyAssignment->setParams(FromParam); | |||
11431 | ||||
11432 | CopyAssignment->setTrivial( | |||
11433 | ClassDecl->needsOverloadResolutionForCopyAssignment() | |||
11434 | ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) | |||
11435 | : ClassDecl->hasTrivialCopyAssignment()); | |||
11436 | ||||
11437 | // Note that we have added this copy-assignment operator. | |||
11438 | ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; | |||
11439 | ||||
11440 | Scope *S = getScopeForContext(ClassDecl); | |||
11441 | CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); | |||
11442 | ||||
11443 | if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) | |||
11444 | SetDeclDeleted(CopyAssignment, ClassLoc); | |||
11445 | ||||
11446 | if (S) | |||
11447 | PushOnScopeChains(CopyAssignment, S, false); | |||
11448 | ClassDecl->addDecl(CopyAssignment); | |||
11449 | ||||
11450 | return CopyAssignment; | |||
11451 | } | |||
11452 | ||||
11453 | /// Diagnose an implicit copy operation for a class which is odr-used, but | |||
11454 | /// which is deprecated because the class has a user-declared copy constructor, | |||
11455 | /// copy assignment operator, or destructor. | |||
11456 | static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { | |||
11457 | assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0 ) : __assert_fail ("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11457, __extension__ __PRETTY_FUNCTION__)); | |||
11458 | ||||
11459 | CXXRecordDecl *RD = CopyOp->getParent(); | |||
11460 | CXXMethodDecl *UserDeclaredOperation = nullptr; | |||
11461 | ||||
11462 | // In Microsoft mode, assignment operations don't affect constructors and | |||
11463 | // vice versa. | |||
11464 | if (RD->hasUserDeclaredDestructor()) { | |||
11465 | UserDeclaredOperation = RD->getDestructor(); | |||
11466 | } else if (!isa<CXXConstructorDecl>(CopyOp) && | |||
11467 | RD->hasUserDeclaredCopyConstructor() && | |||
11468 | !S.getLangOpts().MSVCCompat) { | |||
11469 | // Find any user-declared copy constructor. | |||
11470 | for (auto *I : RD->ctors()) { | |||
11471 | if (I->isCopyConstructor()) { | |||
11472 | UserDeclaredOperation = I; | |||
11473 | break; | |||
11474 | } | |||
11475 | } | |||
11476 | assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11476, __extension__ __PRETTY_FUNCTION__)); | |||
11477 | } else if (isa<CXXConstructorDecl>(CopyOp) && | |||
11478 | RD->hasUserDeclaredCopyAssignment() && | |||
11479 | !S.getLangOpts().MSVCCompat) { | |||
11480 | // Find any user-declared move assignment operator. | |||
11481 | for (auto *I : RD->methods()) { | |||
11482 | if (I->isCopyAssignmentOperator()) { | |||
11483 | UserDeclaredOperation = I; | |||
11484 | break; | |||
11485 | } | |||
11486 | } | |||
11487 | assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11487, __extension__ __PRETTY_FUNCTION__)); | |||
11488 | } | |||
11489 | ||||
11490 | if (UserDeclaredOperation) { | |||
11491 | S.Diag(UserDeclaredOperation->getLocation(), | |||
11492 | diag::warn_deprecated_copy_operation) | |||
11493 | << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) | |||
11494 | << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); | |||
11495 | } | |||
11496 | } | |||
11497 | ||||
11498 | void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, | |||
11499 | CXXMethodDecl *CopyAssignOperator) { | |||
11500 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11505, __extension__ __PRETTY_FUNCTION__)) | |||
11501 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11505, __extension__ __PRETTY_FUNCTION__)) | |||
11502 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11505, __extension__ __PRETTY_FUNCTION__)) | |||
11503 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11505, __extension__ __PRETTY_FUNCTION__)) | |||
11504 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11505, __extension__ __PRETTY_FUNCTION__)) | |||
11505 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11505, __extension__ __PRETTY_FUNCTION__)); | |||
11506 | if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) | |||
11507 | return; | |||
11508 | ||||
11509 | CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); | |||
11510 | if (ClassDecl->isInvalidDecl()) { | |||
11511 | CopyAssignOperator->setInvalidDecl(); | |||
11512 | return; | |||
11513 | } | |||
11514 | ||||
11515 | SynthesizedFunctionScope Scope(*this, CopyAssignOperator); | |||
11516 | ||||
11517 | // The exception specification is needed because we are defining the | |||
11518 | // function. | |||
11519 | ResolveExceptionSpec(CurrentLocation, | |||
11520 | CopyAssignOperator->getType()->castAs<FunctionProtoType>()); | |||
11521 | ||||
11522 | // Add a context note for diagnostics produced after this point. | |||
11523 | Scope.addContextNote(CurrentLocation); | |||
11524 | ||||
11525 | // C++11 [class.copy]p18: | |||
11526 | // The [definition of an implicitly declared copy assignment operator] is | |||
11527 | // deprecated if the class has a user-declared copy constructor or a | |||
11528 | // user-declared destructor. | |||
11529 | if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) | |||
11530 | diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); | |||
11531 | ||||
11532 | // C++0x [class.copy]p30: | |||
11533 | // The implicitly-defined or explicitly-defaulted copy assignment operator | |||
11534 | // for a non-union class X performs memberwise copy assignment of its | |||
11535 | // subobjects. The direct base classes of X are assigned first, in the | |||
11536 | // order of their declaration in the base-specifier-list, and then the | |||
11537 | // immediate non-static data members of X are assigned, in the order in | |||
11538 | // which they were declared in the class definition. | |||
11539 | ||||
11540 | // The statements that form the synthesized function body. | |||
11541 | SmallVector<Stmt*, 8> Statements; | |||
11542 | ||||
11543 | // The parameter for the "other" object, which we are copying from. | |||
11544 | ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); | |||
11545 | Qualifiers OtherQuals = Other->getType().getQualifiers(); | |||
11546 | QualType OtherRefType = Other->getType(); | |||
11547 | if (const LValueReferenceType *OtherRef | |||
11548 | = OtherRefType->getAs<LValueReferenceType>()) { | |||
11549 | OtherRefType = OtherRef->getPointeeType(); | |||
11550 | OtherQuals = OtherRefType.getQualifiers(); | |||
11551 | } | |||
11552 | ||||
11553 | // Our location for everything implicitly-generated. | |||
11554 | SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() | |||
11555 | ? CopyAssignOperator->getLocEnd() | |||
11556 | : CopyAssignOperator->getLocation(); | |||
11557 | ||||
11558 | // Builds a DeclRefExpr for the "other" object. | |||
11559 | RefBuilder OtherRef(Other, OtherRefType); | |||
11560 | ||||
11561 | // Builds the "this" pointer. | |||
11562 | ThisBuilder This; | |||
11563 | ||||
11564 | // Assign base classes. | |||
11565 | bool Invalid = false; | |||
11566 | for (auto &Base : ClassDecl->bases()) { | |||
11567 | // Form the assignment: | |||
11568 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); | |||
11569 | QualType BaseType = Base.getType().getUnqualifiedType(); | |||
11570 | if (!BaseType->isRecordType()) { | |||
11571 | Invalid = true; | |||
11572 | continue; | |||
11573 | } | |||
11574 | ||||
11575 | CXXCastPath BasePath; | |||
11576 | BasePath.push_back(&Base); | |||
11577 | ||||
11578 | // Construct the "from" expression, which is an implicit cast to the | |||
11579 | // appropriately-qualified base type. | |||
11580 | CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), | |||
11581 | VK_LValue, BasePath); | |||
11582 | ||||
11583 | // Dereference "this". | |||
11584 | DerefBuilder DerefThis(This); | |||
11585 | CastBuilder To(DerefThis, | |||
11586 | Context.getCVRQualifiedType( | |||
11587 | BaseType, CopyAssignOperator->getTypeQualifiers()), | |||
11588 | VK_LValue, BasePath); | |||
11589 | ||||
11590 | // Build the copy. | |||
11591 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, | |||
11592 | To, From, | |||
11593 | /*CopyingBaseSubobject=*/true, | |||
11594 | /*Copying=*/true); | |||
11595 | if (Copy.isInvalid()) { | |||
11596 | CopyAssignOperator->setInvalidDecl(); | |||
11597 | return; | |||
11598 | } | |||
11599 | ||||
11600 | // Success! Record the copy. | |||
11601 | Statements.push_back(Copy.getAs<Expr>()); | |||
11602 | } | |||
11603 | ||||
11604 | // Assign non-static members. | |||
11605 | for (auto *Field : ClassDecl->fields()) { | |||
11606 | // FIXME: We should form some kind of AST representation for the implied | |||
11607 | // memcpy in a union copy operation. | |||
11608 | if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) | |||
11609 | continue; | |||
11610 | ||||
11611 | if (Field->isInvalidDecl()) { | |||
11612 | Invalid = true; | |||
11613 | continue; | |||
11614 | } | |||
11615 | ||||
11616 | // Check for members of reference type; we can't copy those. | |||
11617 | if (Field->getType()->isReferenceType()) { | |||
11618 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
11619 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); | |||
11620 | Diag(Field->getLocation(), diag::note_declared_at); | |||
11621 | Invalid = true; | |||
11622 | continue; | |||
11623 | } | |||
11624 | ||||
11625 | // Check for members of const-qualified, non-class type. | |||
11626 | QualType BaseType = Context.getBaseElementType(Field->getType()); | |||
11627 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { | |||
11628 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
11629 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); | |||
11630 | Diag(Field->getLocation(), diag::note_declared_at); | |||
11631 | Invalid = true; | |||
11632 | continue; | |||
11633 | } | |||
11634 | ||||
11635 | // Suppress assigning zero-width bitfields. | |||
11636 | if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) | |||
11637 | continue; | |||
11638 | ||||
11639 | QualType FieldType = Field->getType().getNonReferenceType(); | |||
11640 | if (FieldType->isIncompleteArrayType()) { | |||
11641 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11642, __extension__ __PRETTY_FUNCTION__)) | |||
11642 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11642, __extension__ __PRETTY_FUNCTION__)); | |||
11643 | continue; | |||
11644 | } | |||
11645 | ||||
11646 | // Build references to the field in the object we're copying from and to. | |||
11647 | CXXScopeSpec SS; // Intentionally empty | |||
11648 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, | |||
11649 | LookupMemberName); | |||
11650 | MemberLookup.addDecl(Field); | |||
11651 | MemberLookup.resolveKind(); | |||
11652 | ||||
11653 | MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); | |||
11654 | ||||
11655 | MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); | |||
11656 | ||||
11657 | // Build the copy of this field. | |||
11658 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, | |||
11659 | To, From, | |||
11660 | /*CopyingBaseSubobject=*/false, | |||
11661 | /*Copying=*/true); | |||
11662 | if (Copy.isInvalid()) { | |||
11663 | CopyAssignOperator->setInvalidDecl(); | |||
11664 | return; | |||
11665 | } | |||
11666 | ||||
11667 | // Success! Record the copy. | |||
11668 | Statements.push_back(Copy.getAs<Stmt>()); | |||
11669 | } | |||
11670 | ||||
11671 | if (!Invalid) { | |||
11672 | // Add a "return *this;" | |||
11673 | ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); | |||
11674 | ||||
11675 | StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); | |||
11676 | if (Return.isInvalid()) | |||
11677 | Invalid = true; | |||
11678 | else | |||
11679 | Statements.push_back(Return.getAs<Stmt>()); | |||
11680 | } | |||
11681 | ||||
11682 | if (Invalid) { | |||
11683 | CopyAssignOperator->setInvalidDecl(); | |||
11684 | return; | |||
11685 | } | |||
11686 | ||||
11687 | StmtResult Body; | |||
11688 | { | |||
11689 | CompoundScopeRAII CompoundScope(*this); | |||
11690 | Body = ActOnCompoundStmt(Loc, Loc, Statements, | |||
11691 | /*isStmtExpr=*/false); | |||
11692 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11692, __extension__ __PRETTY_FUNCTION__)); | |||
11693 | } | |||
11694 | CopyAssignOperator->setBody(Body.getAs<Stmt>()); | |||
11695 | CopyAssignOperator->markUsed(Context); | |||
11696 | ||||
11697 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11698 | L->CompletedImplicitDefinition(CopyAssignOperator); | |||
11699 | } | |||
11700 | } | |||
11701 | ||||
11702 | CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { | |||
11703 | assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment ()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11703, __extension__ __PRETTY_FUNCTION__)); | |||
11704 | ||||
11705 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); | |||
11706 | if (DSM.isAlreadyBeingDeclared()) | |||
11707 | return nullptr; | |||
11708 | ||||
11709 | // Note: The following rules are largely analoguous to the move | |||
11710 | // constructor rules. | |||
11711 | ||||
11712 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | |||
11713 | QualType RetType = Context.getLValueReferenceType(ArgType); | |||
11714 | ArgType = Context.getRValueReferenceType(ArgType); | |||
11715 | ||||
11716 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
11717 | CXXMoveAssignment, | |||
11718 | false); | |||
11719 | ||||
11720 | // An implicitly-declared move assignment operator is an inline public | |||
11721 | // member of its class. | |||
11722 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
11723 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
11724 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
11725 | CXXMethodDecl *MoveAssignment = | |||
11726 | CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), | |||
11727 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | |||
11728 | /*isInline=*/true, Constexpr, SourceLocation()); | |||
11729 | MoveAssignment->setAccess(AS_public); | |||
11730 | MoveAssignment->setDefaulted(); | |||
11731 | MoveAssignment->setImplicit(); | |||
11732 | ||||
11733 | if (getLangOpts().CUDA) { | |||
11734 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, | |||
11735 | MoveAssignment, | |||
11736 | /* ConstRHS */ false, | |||
11737 | /* Diagnose */ false); | |||
11738 | } | |||
11739 | ||||
11740 | // Build an exception specification pointing back at this member. | |||
11741 | FunctionProtoType::ExtProtoInfo EPI = | |||
11742 | getImplicitMethodEPI(*this, MoveAssignment); | |||
11743 | MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); | |||
11744 | ||||
11745 | // Add the parameter to the operator. | |||
11746 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, | |||
11747 | ClassLoc, ClassLoc, | |||
11748 | /*Id=*/nullptr, ArgType, | |||
11749 | /*TInfo=*/nullptr, SC_None, | |||
11750 | nullptr); | |||
11751 | MoveAssignment->setParams(FromParam); | |||
11752 | ||||
11753 | MoveAssignment->setTrivial( | |||
11754 | ClassDecl->needsOverloadResolutionForMoveAssignment() | |||
11755 | ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) | |||
11756 | : ClassDecl->hasTrivialMoveAssignment()); | |||
11757 | ||||
11758 | // Note that we have added this copy-assignment operator. | |||
11759 | ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; | |||
11760 | ||||
11761 | Scope *S = getScopeForContext(ClassDecl); | |||
11762 | CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); | |||
11763 | ||||
11764 | if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { | |||
11765 | ClassDecl->setImplicitMoveAssignmentIsDeleted(); | |||
11766 | SetDeclDeleted(MoveAssignment, ClassLoc); | |||
11767 | } | |||
11768 | ||||
11769 | if (S) | |||
11770 | PushOnScopeChains(MoveAssignment, S, false); | |||
11771 | ClassDecl->addDecl(MoveAssignment); | |||
11772 | ||||
11773 | return MoveAssignment; | |||
11774 | } | |||
11775 | ||||
11776 | /// Check if we're implicitly defining a move assignment operator for a class | |||
11777 | /// with virtual bases. Such a move assignment might move-assign the virtual | |||
11778 | /// base multiple times. | |||
11779 | static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, | |||
11780 | SourceLocation CurrentLocation) { | |||
11781 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11781, __extension__ __PRETTY_FUNCTION__)); | |||
11782 | ||||
11783 | // Only a virtual base could get implicitly move-assigned multiple times. | |||
11784 | // Only a non-trivial move assignment can observe this. We only want to | |||
11785 | // diagnose if we implicitly define an assignment operator that assigns | |||
11786 | // two base classes, both of which move-assign the same virtual base. | |||
11787 | if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || | |||
11788 | Class->getNumBases() < 2) | |||
11789 | return; | |||
11790 | ||||
11791 | llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; | |||
11792 | typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; | |||
11793 | VBaseMap VBases; | |||
11794 | ||||
11795 | for (auto &BI : Class->bases()) { | |||
11796 | Worklist.push_back(&BI); | |||
11797 | while (!Worklist.empty()) { | |||
11798 | CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); | |||
11799 | CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); | |||
11800 | ||||
11801 | // If the base has no non-trivial move assignment operators, | |||
11802 | // we don't care about moves from it. | |||
11803 | if (!Base->hasNonTrivialMoveAssignment()) | |||
11804 | continue; | |||
11805 | ||||
11806 | // If there's nothing virtual here, skip it. | |||
11807 | if (!BaseSpec->isVirtual() && !Base->getNumVBases()) | |||
11808 | continue; | |||
11809 | ||||
11810 | // If we're not actually going to call a move assignment for this base, | |||
11811 | // or the selected move assignment is trivial, skip it. | |||
11812 | Sema::SpecialMemberOverloadResult SMOR = | |||
11813 | S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, | |||
11814 | /*ConstArg*/false, /*VolatileArg*/false, | |||
11815 | /*RValueThis*/true, /*ConstThis*/false, | |||
11816 | /*VolatileThis*/false); | |||
11817 | if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || | |||
11818 | !SMOR.getMethod()->isMoveAssignmentOperator()) | |||
11819 | continue; | |||
11820 | ||||
11821 | if (BaseSpec->isVirtual()) { | |||
11822 | // We're going to move-assign this virtual base, and its move | |||
11823 | // assignment operator is not trivial. If this can happen for | |||
11824 | // multiple distinct direct bases of Class, diagnose it. (If it | |||
11825 | // only happens in one base, we'll diagnose it when synthesizing | |||
11826 | // that base class's move assignment operator.) | |||
11827 | CXXBaseSpecifier *&Existing = | |||
11828 | VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) | |||
11829 | .first->second; | |||
11830 | if (Existing && Existing != &BI) { | |||
11831 | S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) | |||
11832 | << Class << Base; | |||
11833 | S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) | |||
11834 | << (Base->getCanonicalDecl() == | |||
11835 | Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) | |||
11836 | << Base << Existing->getType() << Existing->getSourceRange(); | |||
11837 | S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) | |||
11838 | << (Base->getCanonicalDecl() == | |||
11839 | BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) | |||
11840 | << Base << BI.getType() << BaseSpec->getSourceRange(); | |||
11841 | ||||
11842 | // Only diagnose each vbase once. | |||
11843 | Existing = nullptr; | |||
11844 | } | |||
11845 | } else { | |||
11846 | // Only walk over bases that have defaulted move assignment operators. | |||
11847 | // We assume that any user-provided move assignment operator handles | |||
11848 | // the multiple-moves-of-vbase case itself somehow. | |||
11849 | if (!SMOR.getMethod()->isDefaulted()) | |||
11850 | continue; | |||
11851 | ||||
11852 | // We're going to move the base classes of Base. Add them to the list. | |||
11853 | for (auto &BI : Base->bases()) | |||
11854 | Worklist.push_back(&BI); | |||
11855 | } | |||
11856 | } | |||
11857 | } | |||
11858 | } | |||
11859 | ||||
11860 | void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, | |||
11861 | CXXMethodDecl *MoveAssignOperator) { | |||
11862 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11867, __extension__ __PRETTY_FUNCTION__)) | |||
11863 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11867, __extension__ __PRETTY_FUNCTION__)) | |||
11864 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11867, __extension__ __PRETTY_FUNCTION__)) | |||
11865 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11867, __extension__ __PRETTY_FUNCTION__)) | |||
11866 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11867, __extension__ __PRETTY_FUNCTION__)) | |||
11867 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11867, __extension__ __PRETTY_FUNCTION__)); | |||
11868 | if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) | |||
11869 | return; | |||
11870 | ||||
11871 | CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); | |||
11872 | if (ClassDecl->isInvalidDecl()) { | |||
11873 | MoveAssignOperator->setInvalidDecl(); | |||
11874 | return; | |||
11875 | } | |||
11876 | ||||
11877 | // C++0x [class.copy]p28: | |||
11878 | // The implicitly-defined or move assignment operator for a non-union class | |||
11879 | // X performs memberwise move assignment of its subobjects. The direct base | |||
11880 | // classes of X are assigned first, in the order of their declaration in the | |||
11881 | // base-specifier-list, and then the immediate non-static data members of X | |||
11882 | // are assigned, in the order in which they were declared in the class | |||
11883 | // definition. | |||
11884 | ||||
11885 | // Issue a warning if our implicit move assignment operator will move | |||
11886 | // from a virtual base more than once. | |||
11887 | checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); | |||
11888 | ||||
11889 | SynthesizedFunctionScope Scope(*this, MoveAssignOperator); | |||
11890 | ||||
11891 | // The exception specification is needed because we are defining the | |||
11892 | // function. | |||
11893 | ResolveExceptionSpec(CurrentLocation, | |||
11894 | MoveAssignOperator->getType()->castAs<FunctionProtoType>()); | |||
11895 | ||||
11896 | // Add a context note for diagnostics produced after this point. | |||
11897 | Scope.addContextNote(CurrentLocation); | |||
11898 | ||||
11899 | // The statements that form the synthesized function body. | |||
11900 | SmallVector<Stmt*, 8> Statements; | |||
11901 | ||||
11902 | // The parameter for the "other" object, which we are move from. | |||
11903 | ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); | |||
11904 | QualType OtherRefType = Other->getType()-> | |||
11905 | getAs<RValueReferenceType>()->getPointeeType(); | |||
11906 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11907, __extension__ __PRETTY_FUNCTION__)) | |||
11907 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11907, __extension__ __PRETTY_FUNCTION__)); | |||
11908 | ||||
11909 | // Our location for everything implicitly-generated. | |||
11910 | SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() | |||
11911 | ? MoveAssignOperator->getLocEnd() | |||
11912 | : MoveAssignOperator->getLocation(); | |||
11913 | ||||
11914 | // Builds a reference to the "other" object. | |||
11915 | RefBuilder OtherRef(Other, OtherRefType); | |||
11916 | // Cast to rvalue. | |||
11917 | MoveCastBuilder MoveOther(OtherRef); | |||
11918 | ||||
11919 | // Builds the "this" pointer. | |||
11920 | ThisBuilder This; | |||
11921 | ||||
11922 | // Assign base classes. | |||
11923 | bool Invalid = false; | |||
11924 | for (auto &Base : ClassDecl->bases()) { | |||
11925 | // C++11 [class.copy]p28: | |||
11926 | // It is unspecified whether subobjects representing virtual base classes | |||
11927 | // are assigned more than once by the implicitly-defined copy assignment | |||
11928 | // operator. | |||
11929 | // FIXME: Do not assign to a vbase that will be assigned by some other base | |||
11930 | // class. For a move-assignment, this can result in the vbase being moved | |||
11931 | // multiple times. | |||
11932 | ||||
11933 | // Form the assignment: | |||
11934 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); | |||
11935 | QualType BaseType = Base.getType().getUnqualifiedType(); | |||
11936 | if (!BaseType->isRecordType()) { | |||
11937 | Invalid = true; | |||
11938 | continue; | |||
11939 | } | |||
11940 | ||||
11941 | CXXCastPath BasePath; | |||
11942 | BasePath.push_back(&Base); | |||
11943 | ||||
11944 | // Construct the "from" expression, which is an implicit cast to the | |||
11945 | // appropriately-qualified base type. | |||
11946 | CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); | |||
11947 | ||||
11948 | // Dereference "this". | |||
11949 | DerefBuilder DerefThis(This); | |||
11950 | ||||
11951 | // Implicitly cast "this" to the appropriately-qualified base type. | |||
11952 | CastBuilder To(DerefThis, | |||
11953 | Context.getCVRQualifiedType( | |||
11954 | BaseType, MoveAssignOperator->getTypeQualifiers()), | |||
11955 | VK_LValue, BasePath); | |||
11956 | ||||
11957 | // Build the move. | |||
11958 | StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, | |||
11959 | To, From, | |||
11960 | /*CopyingBaseSubobject=*/true, | |||
11961 | /*Copying=*/false); | |||
11962 | if (Move.isInvalid()) { | |||
11963 | MoveAssignOperator->setInvalidDecl(); | |||
11964 | return; | |||
11965 | } | |||
11966 | ||||
11967 | // Success! Record the move. | |||
11968 | Statements.push_back(Move.getAs<Expr>()); | |||
11969 | } | |||
11970 | ||||
11971 | // Assign non-static members. | |||
11972 | for (auto *Field : ClassDecl->fields()) { | |||
11973 | // FIXME: We should form some kind of AST representation for the implied | |||
11974 | // memcpy in a union copy operation. | |||
11975 | if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) | |||
11976 | continue; | |||
11977 | ||||
11978 | if (Field->isInvalidDecl()) { | |||
11979 | Invalid = true; | |||
11980 | continue; | |||
11981 | } | |||
11982 | ||||
11983 | // Check for members of reference type; we can't move those. | |||
11984 | if (Field->getType()->isReferenceType()) { | |||
11985 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
11986 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); | |||
11987 | Diag(Field->getLocation(), diag::note_declared_at); | |||
11988 | Invalid = true; | |||
11989 | continue; | |||
11990 | } | |||
11991 | ||||
11992 | // Check for members of const-qualified, non-class type. | |||
11993 | QualType BaseType = Context.getBaseElementType(Field->getType()); | |||
11994 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { | |||
11995 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
11996 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); | |||
11997 | Diag(Field->getLocation(), diag::note_declared_at); | |||
11998 | Invalid = true; | |||
11999 | continue; | |||
12000 | } | |||
12001 | ||||
12002 | // Suppress assigning zero-width bitfields. | |||
12003 | if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) | |||
12004 | continue; | |||
12005 | ||||
12006 | QualType FieldType = Field->getType().getNonReferenceType(); | |||
12007 | if (FieldType->isIncompleteArrayType()) { | |||
12008 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12009, __extension__ __PRETTY_FUNCTION__)) | |||
12009 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12009, __extension__ __PRETTY_FUNCTION__)); | |||
12010 | continue; | |||
12011 | } | |||
12012 | ||||
12013 | // Build references to the field in the object we're copying from and to. | |||
12014 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, | |||
12015 | LookupMemberName); | |||
12016 | MemberLookup.addDecl(Field); | |||
12017 | MemberLookup.resolveKind(); | |||
12018 | MemberBuilder From(MoveOther, OtherRefType, | |||
12019 | /*IsArrow=*/false, MemberLookup); | |||
12020 | MemberBuilder To(This, getCurrentThisType(), | |||
12021 | /*IsArrow=*/true, MemberLookup); | |||
12022 | ||||
12023 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12025, __extension__ __PRETTY_FUNCTION__)) | |||
12024 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12025, __extension__ __PRETTY_FUNCTION__)) | |||
12025 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12025, __extension__ __PRETTY_FUNCTION__)); | |||
12026 | ||||
12027 | // Build the move of this field. | |||
12028 | StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, | |||
12029 | To, From, | |||
12030 | /*CopyingBaseSubobject=*/false, | |||
12031 | /*Copying=*/false); | |||
12032 | if (Move.isInvalid()) { | |||
12033 | MoveAssignOperator->setInvalidDecl(); | |||
12034 | return; | |||
12035 | } | |||
12036 | ||||
12037 | // Success! Record the copy. | |||
12038 | Statements.push_back(Move.getAs<Stmt>()); | |||
12039 | } | |||
12040 | ||||
12041 | if (!Invalid) { | |||
12042 | // Add a "return *this;" | |||
12043 | ExprResult ThisObj = | |||
12044 | CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); | |||
12045 | ||||
12046 | StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); | |||
12047 | if (Return.isInvalid()) | |||
12048 | Invalid = true; | |||
12049 | else | |||
12050 | Statements.push_back(Return.getAs<Stmt>()); | |||
12051 | } | |||
12052 | ||||
12053 | if (Invalid) { | |||
12054 | MoveAssignOperator->setInvalidDecl(); | |||
12055 | return; | |||
12056 | } | |||
12057 | ||||
12058 | StmtResult Body; | |||
12059 | { | |||
12060 | CompoundScopeRAII CompoundScope(*this); | |||
12061 | Body = ActOnCompoundStmt(Loc, Loc, Statements, | |||
12062 | /*isStmtExpr=*/false); | |||
12063 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12063, __extension__ __PRETTY_FUNCTION__)); | |||
12064 | } | |||
12065 | MoveAssignOperator->setBody(Body.getAs<Stmt>()); | |||
12066 | MoveAssignOperator->markUsed(Context); | |||
12067 | ||||
12068 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12069 | L->CompletedImplicitDefinition(MoveAssignOperator); | |||
12070 | } | |||
12071 | } | |||
12072 | ||||
12073 | CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( | |||
12074 | CXXRecordDecl *ClassDecl) { | |||
12075 | // C++ [class.copy]p4: | |||
12076 | // If the class definition does not explicitly declare a copy | |||
12077 | // constructor, one is declared implicitly. | |||
12078 | assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor ()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12078, __extension__ __PRETTY_FUNCTION__)); | |||
12079 | ||||
12080 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); | |||
12081 | if (DSM.isAlreadyBeingDeclared()) | |||
12082 | return nullptr; | |||
12083 | ||||
12084 | QualType ClassType = Context.getTypeDeclType(ClassDecl); | |||
12085 | QualType ArgType = ClassType; | |||
12086 | bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); | |||
12087 | if (Const) | |||
12088 | ArgType = ArgType.withConst(); | |||
12089 | ArgType = Context.getLValueReferenceType(ArgType); | |||
12090 | ||||
12091 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
12092 | CXXCopyConstructor, | |||
12093 | Const); | |||
12094 | ||||
12095 | DeclarationName Name | |||
12096 | = Context.DeclarationNames.getCXXConstructorName( | |||
12097 | Context.getCanonicalType(ClassType)); | |||
12098 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
12099 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
12100 | ||||
12101 | // An implicitly-declared copy constructor is an inline public | |||
12102 | // member of its class. | |||
12103 | CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( | |||
12104 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, | |||
12105 | /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, | |||
12106 | Constexpr); | |||
12107 | CopyConstructor->setAccess(AS_public); | |||
12108 | CopyConstructor->setDefaulted(); | |||
12109 | ||||
12110 | if (getLangOpts().CUDA) { | |||
12111 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, | |||
12112 | CopyConstructor, | |||
12113 | /* ConstRHS */ Const, | |||
12114 | /* Diagnose */ false); | |||
12115 | } | |||
12116 | ||||
12117 | // Build an exception specification pointing back at this member. | |||
12118 | FunctionProtoType::ExtProtoInfo EPI = | |||
12119 | getImplicitMethodEPI(*this, CopyConstructor); | |||
12120 | CopyConstructor->setType( | |||
12121 | Context.getFunctionType(Context.VoidTy, ArgType, EPI)); | |||
12122 | ||||
12123 | // Add the parameter to the constructor. | |||
12124 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, | |||
12125 | ClassLoc, ClassLoc, | |||
12126 | /*IdentifierInfo=*/nullptr, | |||
12127 | ArgType, /*TInfo=*/nullptr, | |||
12128 | SC_None, nullptr); | |||
12129 | CopyConstructor->setParams(FromParam); | |||
12130 | ||||
12131 | CopyConstructor->setTrivial( | |||
12132 | ClassDecl->needsOverloadResolutionForCopyConstructor() | |||
12133 | ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) | |||
12134 | : ClassDecl->hasTrivialCopyConstructor()); | |||
12135 | ||||
12136 | CopyConstructor->setTrivialForCall( | |||
12137 | ClassDecl->hasAttr<TrivialABIAttr>() || | |||
12138 | (ClassDecl->needsOverloadResolutionForCopyConstructor() | |||
12139 | ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, | |||
12140 | TAH_ConsiderTrivialABI) | |||
12141 | : ClassDecl->hasTrivialCopyConstructorForCall())); | |||
12142 | ||||
12143 | // Note that we have declared this constructor. | |||
12144 | ++ASTContext::NumImplicitCopyConstructorsDeclared; | |||
12145 | ||||
12146 | Scope *S = getScopeForContext(ClassDecl); | |||
12147 | CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); | |||
12148 | ||||
12149 | if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { | |||
12150 | ClassDecl->setImplicitCopyConstructorIsDeleted(); | |||
12151 | SetDeclDeleted(CopyConstructor, ClassLoc); | |||
12152 | } | |||
12153 | ||||
12154 | if (S) | |||
12155 | PushOnScopeChains(CopyConstructor, S, false); | |||
12156 | ClassDecl->addDecl(CopyConstructor); | |||
12157 | ||||
12158 | return CopyConstructor; | |||
12159 | } | |||
12160 | ||||
12161 | void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, | |||
12162 | CXXConstructorDecl *CopyConstructor) { | |||
12163 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12167, __extension__ __PRETTY_FUNCTION__)) | |||
12164 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12167, __extension__ __PRETTY_FUNCTION__)) | |||
12165 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12167, __extension__ __PRETTY_FUNCTION__)) | |||
12166 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12167, __extension__ __PRETTY_FUNCTION__)) | |||
12167 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12167, __extension__ __PRETTY_FUNCTION__)); | |||
12168 | if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) | |||
12169 | return; | |||
12170 | ||||
12171 | CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); | |||
12172 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12172, __extension__ __PRETTY_FUNCTION__)); | |||
12173 | ||||
12174 | SynthesizedFunctionScope Scope(*this, CopyConstructor); | |||
12175 | ||||
12176 | // The exception specification is needed because we are defining the | |||
12177 | // function. | |||
12178 | ResolveExceptionSpec(CurrentLocation, | |||
12179 | CopyConstructor->getType()->castAs<FunctionProtoType>()); | |||
12180 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
12181 | ||||
12182 | // Add a context note for diagnostics produced after this point. | |||
12183 | Scope.addContextNote(CurrentLocation); | |||
12184 | ||||
12185 | // C++11 [class.copy]p7: | |||
12186 | // The [definition of an implicitly declared copy constructor] is | |||
12187 | // deprecated if the class has a user-declared copy assignment operator | |||
12188 | // or a user-declared destructor. | |||
12189 | if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) | |||
12190 | diagnoseDeprecatedCopyOperation(*this, CopyConstructor); | |||
12191 | ||||
12192 | if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { | |||
12193 | CopyConstructor->setInvalidDecl(); | |||
12194 | } else { | |||
12195 | SourceLocation Loc = CopyConstructor->getLocEnd().isValid() | |||
12196 | ? CopyConstructor->getLocEnd() | |||
12197 | : CopyConstructor->getLocation(); | |||
12198 | Sema::CompoundScopeRAII CompoundScope(*this); | |||
12199 | CopyConstructor->setBody( | |||
12200 | ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); | |||
12201 | CopyConstructor->markUsed(Context); | |||
12202 | } | |||
12203 | ||||
12204 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12205 | L->CompletedImplicitDefinition(CopyConstructor); | |||
12206 | } | |||
12207 | } | |||
12208 | ||||
12209 | CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( | |||
12210 | CXXRecordDecl *ClassDecl) { | |||
12211 | assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor ()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12211, __extension__ __PRETTY_FUNCTION__)); | |||
12212 | ||||
12213 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); | |||
12214 | if (DSM.isAlreadyBeingDeclared()) | |||
12215 | return nullptr; | |||
12216 | ||||
12217 | QualType ClassType = Context.getTypeDeclType(ClassDecl); | |||
12218 | QualType ArgType = Context.getRValueReferenceType(ClassType); | |||
12219 | ||||
12220 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
12221 | CXXMoveConstructor, | |||
12222 | false); | |||
12223 | ||||
12224 | DeclarationName Name | |||
12225 | = Context.DeclarationNames.getCXXConstructorName( | |||
12226 | Context.getCanonicalType(ClassType)); | |||
12227 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
12228 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
12229 | ||||
12230 | // C++11 [class.copy]p11: | |||
12231 | // An implicitly-declared copy/move constructor is an inline public | |||
12232 | // member of its class. | |||
12233 | CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( | |||
12234 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, | |||
12235 | /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, | |||
12236 | Constexpr); | |||
12237 | MoveConstructor->setAccess(AS_public); | |||
12238 | MoveConstructor->setDefaulted(); | |||
12239 | ||||
12240 | if (getLangOpts().CUDA) { | |||
12241 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, | |||
12242 | MoveConstructor, | |||
12243 | /* ConstRHS */ false, | |||
12244 | /* Diagnose */ false); | |||
12245 | } | |||
12246 | ||||
12247 | // Build an exception specification pointing back at this member. | |||
12248 | FunctionProtoType::ExtProtoInfo EPI = | |||
12249 | getImplicitMethodEPI(*this, MoveConstructor); | |||
12250 | MoveConstructor->setType( | |||
12251 | Context.getFunctionType(Context.VoidTy, ArgType, EPI)); | |||
12252 | ||||
12253 | // Add the parameter to the constructor. | |||
12254 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, | |||
12255 | ClassLoc, ClassLoc, | |||
12256 | /*IdentifierInfo=*/nullptr, | |||
12257 | ArgType, /*TInfo=*/nullptr, | |||
12258 | SC_None, nullptr); | |||
12259 | MoveConstructor->setParams(FromParam); | |||
12260 | ||||
12261 | MoveConstructor->setTrivial( | |||
12262 | ClassDecl->needsOverloadResolutionForMoveConstructor() | |||
12263 | ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) | |||
12264 | : ClassDecl->hasTrivialMoveConstructor()); | |||
12265 | ||||
12266 | MoveConstructor->setTrivialForCall( | |||
12267 | ClassDecl->hasAttr<TrivialABIAttr>() || | |||
12268 | (ClassDecl->needsOverloadResolutionForMoveConstructor() | |||
12269 | ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, | |||
12270 | TAH_ConsiderTrivialABI) | |||
12271 | : ClassDecl->hasTrivialMoveConstructorForCall())); | |||
12272 | ||||
12273 | // Note that we have declared this constructor. | |||
12274 | ++ASTContext::NumImplicitMoveConstructorsDeclared; | |||
12275 | ||||
12276 | Scope *S = getScopeForContext(ClassDecl); | |||
12277 | CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); | |||
12278 | ||||
12279 | if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { | |||
12280 | ClassDecl->setImplicitMoveConstructorIsDeleted(); | |||
12281 | SetDeclDeleted(MoveConstructor, ClassLoc); | |||
12282 | } | |||
12283 | ||||
12284 | if (S) | |||
12285 | PushOnScopeChains(MoveConstructor, S, false); | |||
12286 | ClassDecl->addDecl(MoveConstructor); | |||
12287 | ||||
12288 | return MoveConstructor; | |||
12289 | } | |||
12290 | ||||
12291 | void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, | |||
12292 | CXXConstructorDecl *MoveConstructor) { | |||
12293 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12297, __extension__ __PRETTY_FUNCTION__)) | |||
12294 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12297, __extension__ __PRETTY_FUNCTION__)) | |||
12295 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12297, __extension__ __PRETTY_FUNCTION__)) | |||
12296 | !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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12297, __extension__ __PRETTY_FUNCTION__)) | |||
12297 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12297, __extension__ __PRETTY_FUNCTION__)); | |||
12298 | if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) | |||
12299 | return; | |||
12300 | ||||
12301 | CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); | |||
12302 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12302, __extension__ __PRETTY_FUNCTION__)); | |||
12303 | ||||
12304 | SynthesizedFunctionScope Scope(*this, MoveConstructor); | |||
12305 | ||||
12306 | // The exception specification is needed because we are defining the | |||
12307 | // function. | |||
12308 | ResolveExceptionSpec(CurrentLocation, | |||
12309 | MoveConstructor->getType()->castAs<FunctionProtoType>()); | |||
12310 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
12311 | ||||
12312 | // Add a context note for diagnostics produced after this point. | |||
12313 | Scope.addContextNote(CurrentLocation); | |||
12314 | ||||
12315 | if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { | |||
12316 | MoveConstructor->setInvalidDecl(); | |||
12317 | } else { | |||
12318 | SourceLocation Loc = MoveConstructor->getLocEnd().isValid() | |||
12319 | ? MoveConstructor->getLocEnd() | |||
12320 | : MoveConstructor->getLocation(); | |||
12321 | Sema::CompoundScopeRAII CompoundScope(*this); | |||
12322 | MoveConstructor->setBody(ActOnCompoundStmt( | |||
12323 | Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); | |||
12324 | MoveConstructor->markUsed(Context); | |||
12325 | } | |||
12326 | ||||
12327 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12328 | L->CompletedImplicitDefinition(MoveConstructor); | |||
12329 | } | |||
12330 | } | |||
12331 | ||||
12332 | bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { | |||
12333 | return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); | |||
12334 | } | |||
12335 | ||||
12336 | void Sema::DefineImplicitLambdaToFunctionPointerConversion( | |||
12337 | SourceLocation CurrentLocation, | |||
12338 | CXXConversionDecl *Conv) { | |||
12339 | SynthesizedFunctionScope Scope(*this, Conv); | |||
12340 | assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType ()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12340, __extension__ __PRETTY_FUNCTION__)); | |||
12341 | ||||
12342 | CXXRecordDecl *Lambda = Conv->getParent(); | |||
12343 | FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); | |||
12344 | FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); | |||
12345 | ||||
12346 | if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { | |||
12347 | CallOp = InstantiateFunctionDeclaration( | |||
12348 | CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); | |||
12349 | if (!CallOp) | |||
12350 | return; | |||
12351 | ||||
12352 | Invoker = InstantiateFunctionDeclaration( | |||
12353 | Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); | |||
12354 | if (!Invoker) | |||
12355 | return; | |||
12356 | } | |||
12357 | ||||
12358 | if (CallOp->isInvalidDecl()) | |||
12359 | return; | |||
12360 | ||||
12361 | // Mark the call operator referenced (and add to pending instantiations | |||
12362 | // if necessary). | |||
12363 | // For both the conversion and static-invoker template specializations | |||
12364 | // we construct their body's in this function, so no need to add them | |||
12365 | // to the PendingInstantiations. | |||
12366 | MarkFunctionReferenced(CurrentLocation, CallOp); | |||
12367 | ||||
12368 | // Fill in the __invoke function with a dummy implementation. IR generation | |||
12369 | // will fill in the actual details. Update its type in case it contained | |||
12370 | // an 'auto'. | |||
12371 | Invoker->markUsed(Context); | |||
12372 | Invoker->setReferenced(); | |||
12373 | Invoker->setType(Conv->getReturnType()->getPointeeType()); | |||
12374 | Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); | |||
12375 | ||||
12376 | // Construct the body of the conversion function { return __invoke; }. | |||
12377 | Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), | |||
12378 | VK_LValue, Conv->getLocation()).get(); | |||
12379 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12379, __extension__ __PRETTY_FUNCTION__)); | |||
12380 | Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); | |||
12381 | Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), | |||
12382 | Conv->getLocation())); | |||
12383 | Conv->markUsed(Context); | |||
12384 | Conv->setReferenced(); | |||
12385 | ||||
12386 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12387 | L->CompletedImplicitDefinition(Conv); | |||
12388 | L->CompletedImplicitDefinition(Invoker); | |||
12389 | } | |||
12390 | } | |||
12391 | ||||
12392 | ||||
12393 | ||||
12394 | void Sema::DefineImplicitLambdaToBlockPointerConversion( | |||
12395 | SourceLocation CurrentLocation, | |||
12396 | CXXConversionDecl *Conv) | |||
12397 | { | |||
12398 | assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda ()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12398, __extension__ __PRETTY_FUNCTION__)); | |||
12399 | ||||
12400 | SynthesizedFunctionScope Scope(*this, Conv); | |||
12401 | ||||
12402 | // Copy-initialize the lambda object as needed to capture it. | |||
12403 | Expr *This = ActOnCXXThis(CurrentLocation).get(); | |||
12404 | Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); | |||
12405 | ||||
12406 | ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, | |||
12407 | Conv->getLocation(), | |||
12408 | Conv, DerefThis); | |||
12409 | ||||
12410 | // If we're not under ARC, make sure we still get the _Block_copy/autorelease | |||
12411 | // behavior. Note that only the general conversion function does this | |||
12412 | // (since it's unusable otherwise); in the case where we inline the | |||
12413 | // block literal, it has block literal lifetime semantics. | |||
12414 | if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) | |||
12415 | BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), | |||
12416 | CK_CopyAndAutoreleaseBlockObject, | |||
12417 | BuildBlock.get(), nullptr, VK_RValue); | |||
12418 | ||||
12419 | if (BuildBlock.isInvalid()) { | |||
12420 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); | |||
12421 | Conv->setInvalidDecl(); | |||
12422 | return; | |||
12423 | } | |||
12424 | ||||
12425 | // Create the return statement that returns the block from the conversion | |||
12426 | // function. | |||
12427 | StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); | |||
12428 | if (Return.isInvalid()) { | |||
12429 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); | |||
12430 | Conv->setInvalidDecl(); | |||
12431 | return; | |||
12432 | } | |||
12433 | ||||
12434 | // Set the body of the conversion function. | |||
12435 | Stmt *ReturnS = Return.get(); | |||
12436 | Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), | |||
12437 | Conv->getLocation())); | |||
12438 | Conv->markUsed(Context); | |||
12439 | ||||
12440 | // We're done; notify the mutation listener, if any. | |||
12441 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12442 | L->CompletedImplicitDefinition(Conv); | |||
12443 | } | |||
12444 | } | |||
12445 | ||||
12446 | /// \brief Determine whether the given list arguments contains exactly one | |||
12447 | /// "real" (non-default) argument. | |||
12448 | static bool hasOneRealArgument(MultiExprArg Args) { | |||
12449 | switch (Args.size()) { | |||
12450 | case 0: | |||
12451 | return false; | |||
12452 | ||||
12453 | default: | |||
12454 | if (!Args[1]->isDefaultArgument()) | |||
12455 | return false; | |||
12456 | ||||
12457 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
12458 | case 1: | |||
12459 | return !Args[0]->isDefaultArgument(); | |||
12460 | } | |||
12461 | ||||
12462 | return false; | |||
12463 | } | |||
12464 | ||||
12465 | ExprResult | |||
12466 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
12467 | NamedDecl *FoundDecl, | |||
12468 | CXXConstructorDecl *Constructor, | |||
12469 | MultiExprArg ExprArgs, | |||
12470 | bool HadMultipleCandidates, | |||
12471 | bool IsListInitialization, | |||
12472 | bool IsStdInitListInitialization, | |||
12473 | bool RequiresZeroInit, | |||
12474 | unsigned ConstructKind, | |||
12475 | SourceRange ParenRange) { | |||
12476 | bool Elidable = false; | |||
12477 | ||||
12478 | // C++0x [class.copy]p34: | |||
12479 | // When certain criteria are met, an implementation is allowed to | |||
12480 | // omit the copy/move construction of a class object, even if the | |||
12481 | // copy/move constructor and/or destructor for the object have | |||
12482 | // side effects. [...] | |||
12483 | // - when a temporary class object that has not been bound to a | |||
12484 | // reference (12.2) would be copied/moved to a class object | |||
12485 | // with the same cv-unqualified type, the copy/move operation | |||
12486 | // can be omitted by constructing the temporary object | |||
12487 | // directly into the target of the omitted copy/move | |||
12488 | if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && | |||
12489 | Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { | |||
12490 | Expr *SubExpr = ExprArgs[0]; | |||
12491 | Elidable = SubExpr->isTemporaryObject( | |||
12492 | Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | |||
12493 | } | |||
12494 | ||||
12495 | return BuildCXXConstructExpr(ConstructLoc, DeclInitType, | |||
12496 | FoundDecl, Constructor, | |||
12497 | Elidable, ExprArgs, HadMultipleCandidates, | |||
12498 | IsListInitialization, | |||
12499 | IsStdInitListInitialization, RequiresZeroInit, | |||
12500 | ConstructKind, ParenRange); | |||
12501 | } | |||
12502 | ||||
12503 | ExprResult | |||
12504 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
12505 | NamedDecl *FoundDecl, | |||
12506 | CXXConstructorDecl *Constructor, | |||
12507 | bool Elidable, | |||
12508 | MultiExprArg ExprArgs, | |||
12509 | bool HadMultipleCandidates, | |||
12510 | bool IsListInitialization, | |||
12511 | bool IsStdInitListInitialization, | |||
12512 | bool RequiresZeroInit, | |||
12513 | unsigned ConstructKind, | |||
12514 | SourceRange ParenRange) { | |||
12515 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { | |||
12516 | Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); | |||
12517 | if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) | |||
12518 | return ExprError(); | |||
12519 | } | |||
12520 | ||||
12521 | return BuildCXXConstructExpr( | |||
12522 | ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, | |||
12523 | HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, | |||
12524 | RequiresZeroInit, ConstructKind, ParenRange); | |||
12525 | } | |||
12526 | ||||
12527 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, | |||
12528 | /// including handling of its default argument expressions. | |||
12529 | ExprResult | |||
12530 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
12531 | CXXConstructorDecl *Constructor, | |||
12532 | bool Elidable, | |||
12533 | MultiExprArg ExprArgs, | |||
12534 | bool HadMultipleCandidates, | |||
12535 | bool IsListInitialization, | |||
12536 | bool IsStdInitListInitialization, | |||
12537 | bool RequiresZeroInit, | |||
12538 | unsigned ConstructKind, | |||
12539 | SourceRange ParenRange) { | |||
12540 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12543, __extension__ __PRETTY_FUNCTION__)) | |||
12541 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12543, __extension__ __PRETTY_FUNCTION__)) | |||
12542 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12543, __extension__ __PRETTY_FUNCTION__)) | |||
12543 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12543, __extension__ __PRETTY_FUNCTION__)); | |||
12544 | MarkFunctionReferenced(ConstructLoc, Constructor); | |||
12545 | if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) | |||
12546 | return ExprError(); | |||
12547 | ||||
12548 | return CXXConstructExpr::Create( | |||
12549 | Context, DeclInitType, ConstructLoc, Constructor, Elidable, | |||
12550 | ExprArgs, HadMultipleCandidates, IsListInitialization, | |||
12551 | IsStdInitListInitialization, RequiresZeroInit, | |||
12552 | static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), | |||
12553 | ParenRange); | |||
12554 | } | |||
12555 | ||||
12556 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { | |||
12557 | assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer()) ? void (0) : __assert_fail ("Field->hasInClassInitializer()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12557, __extension__ __PRETTY_FUNCTION__)); | |||
12558 | ||||
12559 | // If we already have the in-class initializer nothing needs to be done. | |||
12560 | if (Field->getInClassInitializer()) | |||
12561 | return CXXDefaultInitExpr::Create(Context, Loc, Field); | |||
12562 | ||||
12563 | // If we might have already tried and failed to instantiate, don't try again. | |||
12564 | if (Field->isInvalidDecl()) | |||
12565 | return ExprError(); | |||
12566 | ||||
12567 | // Maybe we haven't instantiated the in-class initializer. Go check the | |||
12568 | // pattern FieldDecl to see if it has one. | |||
12569 | CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); | |||
12570 | ||||
12571 | if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { | |||
12572 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); | |||
12573 | DeclContext::lookup_result Lookup = | |||
12574 | ClassPattern->lookup(Field->getDeclName()); | |||
12575 | ||||
12576 | // Lookup can return at most two results: the pattern for the field, or the | |||
12577 | // injected class name of the parent record. No other member can have the | |||
12578 | // same name as the field. | |||
12579 | // In modules mode, lookup can return multiple results (coming from | |||
12580 | // different modules). | |||
12581 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12582, __extension__ __PRETTY_FUNCTION__)) | |||
12582 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12582, __extension__ __PRETTY_FUNCTION__)); | |||
12583 | FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); | |||
12584 | if (!Pattern) { | |||
12585 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12586, __extension__ __PRETTY_FUNCTION__)) | |||
12586 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12586, __extension__ __PRETTY_FUNCTION__)); | |||
12587 | for (auto L : Lookup) | |||
12588 | if (isa<FieldDecl>(L)) { | |||
12589 | Pattern = cast<FieldDecl>(L); | |||
12590 | break; | |||
12591 | } | |||
12592 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12592, __extension__ __PRETTY_FUNCTION__)); | |||
12593 | } | |||
12594 | ||||
12595 | if (!Pattern->hasInClassInitializer() || | |||
12596 | InstantiateInClassInitializer(Loc, Field, Pattern, | |||
12597 | getTemplateInstantiationArgs(Field))) { | |||
12598 | // Don't diagnose this again. | |||
12599 | Field->setInvalidDecl(); | |||
12600 | return ExprError(); | |||
12601 | } | |||
12602 | return CXXDefaultInitExpr::Create(Context, Loc, Field); | |||
12603 | } | |||
12604 | ||||
12605 | // DR1351: | |||
12606 | // If the brace-or-equal-initializer of a non-static data member | |||
12607 | // invokes a defaulted default constructor of its class or of an | |||
12608 | // enclosing class in a potentially evaluated subexpression, the | |||
12609 | // program is ill-formed. | |||
12610 | // | |||
12611 | // This resolution is unworkable: the exception specification of the | |||
12612 | // default constructor can be needed in an unevaluated context, in | |||
12613 | // particular, in the operand of a noexcept-expression, and we can be | |||
12614 | // unable to compute an exception specification for an enclosed class. | |||
12615 | // | |||
12616 | // Any attempt to resolve the exception specification of a defaulted default | |||
12617 | // constructor before the initializer is lexically complete will ultimately | |||
12618 | // come here at which point we can diagnose it. | |||
12619 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); | |||
12620 | Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) | |||
12621 | << OutermostClass << Field; | |||
12622 | Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); | |||
12623 | // Recover by marking the field invalid, unless we're in a SFINAE context. | |||
12624 | if (!isSFINAEContext()) | |||
12625 | Field->setInvalidDecl(); | |||
12626 | return ExprError(); | |||
12627 | } | |||
12628 | ||||
12629 | void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { | |||
12630 | if (VD->isInvalidDecl()) return; | |||
12631 | ||||
12632 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); | |||
12633 | if (ClassDecl->isInvalidDecl()) return; | |||
12634 | if (ClassDecl->hasIrrelevantDestructor()) return; | |||
12635 | if (ClassDecl->isDependentContext()) return; | |||
12636 | ||||
12637 | CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); | |||
12638 | MarkFunctionReferenced(VD->getLocation(), Destructor); | |||
12639 | CheckDestructorAccess(VD->getLocation(), Destructor, | |||
12640 | PDiag(diag::err_access_dtor_var) | |||
12641 | << VD->getDeclName() | |||
12642 | << VD->getType()); | |||
12643 | DiagnoseUseOfDecl(Destructor, VD->getLocation()); | |||
12644 | ||||
12645 | if (Destructor->isTrivial()) return; | |||
12646 | if (!VD->hasGlobalStorage()) return; | |||
12647 | ||||
12648 | // Emit warning for non-trivial dtor in global scope (a real global, | |||
12649 | // class-static, function-static). | |||
12650 | Diag(VD->getLocation(), diag::warn_exit_time_destructor); | |||
12651 | ||||
12652 | // TODO: this should be re-enabled for static locals by !CXAAtExit | |||
12653 | if (!VD->isStaticLocal()) | |||
12654 | Diag(VD->getLocation(), diag::warn_global_destructor); | |||
12655 | } | |||
12656 | ||||
12657 | /// \brief Given a constructor and the set of arguments provided for the | |||
12658 | /// constructor, convert the arguments and add any required default arguments | |||
12659 | /// to form a proper call to this constructor. | |||
12660 | /// | |||
12661 | /// \returns true if an error occurred, false otherwise. | |||
12662 | bool | |||
12663 | Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, | |||
12664 | MultiExprArg ArgsPtr, | |||
12665 | SourceLocation Loc, | |||
12666 | SmallVectorImpl<Expr*> &ConvertedArgs, | |||
12667 | bool AllowExplicit, | |||
12668 | bool IsListInitialization) { | |||
12669 | // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. | |||
12670 | unsigned NumArgs = ArgsPtr.size(); | |||
12671 | Expr **Args = ArgsPtr.data(); | |||
12672 | ||||
12673 | const FunctionProtoType *Proto | |||
12674 | = Constructor->getType()->getAs<FunctionProtoType>(); | |||
12675 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12675, __extension__ __PRETTY_FUNCTION__)); | |||
12676 | unsigned NumParams = Proto->getNumParams(); | |||
12677 | ||||
12678 | // If too few arguments are available, we'll fill in the rest with defaults. | |||
12679 | if (NumArgs < NumParams) | |||
12680 | ConvertedArgs.reserve(NumParams); | |||
12681 | else | |||
12682 | ConvertedArgs.reserve(NumArgs); | |||
12683 | ||||
12684 | VariadicCallType CallType = | |||
12685 | Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; | |||
12686 | SmallVector<Expr *, 8> AllArgs; | |||
12687 | bool Invalid = GatherArgumentsForCall(Loc, Constructor, | |||
12688 | Proto, 0, | |||
12689 | llvm::makeArrayRef(Args, NumArgs), | |||
12690 | AllArgs, | |||
12691 | CallType, AllowExplicit, | |||
12692 | IsListInitialization); | |||
12693 | ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); | |||
12694 | ||||
12695 | DiagnoseSentinelCalls(Constructor, Loc, AllArgs); | |||
12696 | ||||
12697 | CheckConstructorCall(Constructor, | |||
12698 | llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), | |||
12699 | Proto, Loc); | |||
12700 | ||||
12701 | return Invalid; | |||
12702 | } | |||
12703 | ||||
12704 | static inline bool | |||
12705 | CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, | |||
12706 | const FunctionDecl *FnDecl) { | |||
12707 | const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); | |||
12708 | if (isa<NamespaceDecl>(DC)) { | |||
12709 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12710 | diag::err_operator_new_delete_declared_in_namespace) | |||
12711 | << FnDecl->getDeclName(); | |||
12712 | } | |||
12713 | ||||
12714 | if (isa<TranslationUnitDecl>(DC) && | |||
12715 | FnDecl->getStorageClass() == SC_Static) { | |||
12716 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12717 | diag::err_operator_new_delete_declared_static) | |||
12718 | << FnDecl->getDeclName(); | |||
12719 | } | |||
12720 | ||||
12721 | return false; | |||
12722 | } | |||
12723 | ||||
12724 | static inline bool | |||
12725 | CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, | |||
12726 | CanQualType ExpectedResultType, | |||
12727 | CanQualType ExpectedFirstParamType, | |||
12728 | unsigned DependentParamTypeDiag, | |||
12729 | unsigned InvalidParamTypeDiag) { | |||
12730 | QualType ResultType = | |||
12731 | FnDecl->getType()->getAs<FunctionType>()->getReturnType(); | |||
12732 | ||||
12733 | // Check that the result type is not dependent. | |||
12734 | if (ResultType->isDependentType()) | |||
12735 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12736 | diag::err_operator_new_delete_dependent_result_type) | |||
12737 | << FnDecl->getDeclName() << ExpectedResultType; | |||
12738 | ||||
12739 | // Check that the result type is what we expect. | |||
12740 | if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) | |||
12741 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12742 | diag::err_operator_new_delete_invalid_result_type) | |||
12743 | << FnDecl->getDeclName() << ExpectedResultType; | |||
12744 | ||||
12745 | // A function template must have at least 2 parameters. | |||
12746 | if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) | |||
12747 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12748 | diag::err_operator_new_delete_template_too_few_parameters) | |||
12749 | << FnDecl->getDeclName(); | |||
12750 | ||||
12751 | // The function decl must have at least 1 parameter. | |||
12752 | if (FnDecl->getNumParams() == 0) | |||
12753 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12754 | diag::err_operator_new_delete_too_few_parameters) | |||
12755 | << FnDecl->getDeclName(); | |||
12756 | ||||
12757 | // Check the first parameter type is not dependent. | |||
12758 | QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); | |||
12759 | if (FirstParamType->isDependentType()) | |||
12760 | return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) | |||
12761 | << FnDecl->getDeclName() << ExpectedFirstParamType; | |||
12762 | ||||
12763 | // Check that the first parameter type is what we expect. | |||
12764 | if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != | |||
12765 | ExpectedFirstParamType) | |||
12766 | return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) | |||
12767 | << FnDecl->getDeclName() << ExpectedFirstParamType; | |||
12768 | ||||
12769 | return false; | |||
12770 | } | |||
12771 | ||||
12772 | static bool | |||
12773 | CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { | |||
12774 | // C++ [basic.stc.dynamic.allocation]p1: | |||
12775 | // A program is ill-formed if an allocation function is declared in a | |||
12776 | // namespace scope other than global scope or declared static in global | |||
12777 | // scope. | |||
12778 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) | |||
12779 | return true; | |||
12780 | ||||
12781 | CanQualType SizeTy = | |||
12782 | SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); | |||
12783 | ||||
12784 | // C++ [basic.stc.dynamic.allocation]p1: | |||
12785 | // The return type shall be void*. The first parameter shall have type | |||
12786 | // std::size_t. | |||
12787 | if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, | |||
12788 | SizeTy, | |||
12789 | diag::err_operator_new_dependent_param_type, | |||
12790 | diag::err_operator_new_param_type)) | |||
12791 | return true; | |||
12792 | ||||
12793 | // C++ [basic.stc.dynamic.allocation]p1: | |||
12794 | // The first parameter shall not have an associated default argument. | |||
12795 | if (FnDecl->getParamDecl(0)->hasDefaultArg()) | |||
12796 | return SemaRef.Diag(FnDecl->getLocation(), | |||
12797 | diag::err_operator_new_default_arg) | |||
12798 | << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); | |||
12799 | ||||
12800 | return false; | |||
12801 | } | |||
12802 | ||||
12803 | static bool | |||
12804 | CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { | |||
12805 | // C++ [basic.stc.dynamic.deallocation]p1: | |||
12806 | // A program is ill-formed if deallocation functions are declared in a | |||
12807 | // namespace scope other than global scope or declared static in global | |||
12808 | // scope. | |||
12809 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) | |||
12810 | return true; | |||
12811 | ||||
12812 | auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); | |||
12813 | ||||
12814 | // C++ P0722: | |||
12815 | // Within a class C, the first parameter of a destroying operator delete | |||
12816 | // shall be of type C *. The first parameter of any other deallocation | |||
12817 | // function shall be of type void *. | |||
12818 | CanQualType ExpectedFirstParamType = | |||
12819 | MD && MD->isDestroyingOperatorDelete() | |||
12820 | ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( | |||
12821 | SemaRef.Context.getRecordType(MD->getParent()))) | |||
12822 | : SemaRef.Context.VoidPtrTy; | |||
12823 | ||||
12824 | // C++ [basic.stc.dynamic.deallocation]p2: | |||
12825 | // Each deallocation function shall return void | |||
12826 | if (CheckOperatorNewDeleteTypes( | |||
12827 | SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, | |||
12828 | diag::err_operator_delete_dependent_param_type, | |||
12829 | diag::err_operator_delete_param_type)) | |||
12830 | return true; | |||
12831 | ||||
12832 | // C++ P0722: | |||
12833 | // A destroying operator delete shall be a usual deallocation function. | |||
12834 | if (MD && !MD->getParent()->isDependentContext() && | |||
12835 | MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { | |||
12836 | SemaRef.Diag(MD->getLocation(), | |||
12837 | diag::err_destroying_operator_delete_not_usual); | |||
12838 | return true; | |||
12839 | } | |||
12840 | ||||
12841 | return false; | |||
12842 | } | |||
12843 | ||||
12844 | /// CheckOverloadedOperatorDeclaration - Check whether the declaration | |||
12845 | /// of this overloaded operator is well-formed. If so, returns false; | |||
12846 | /// otherwise, emits appropriate diagnostics and returns true. | |||
12847 | bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { | |||
12848 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12849, __extension__ __PRETTY_FUNCTION__)) | |||
12849 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12849, __extension__ __PRETTY_FUNCTION__)); | |||
12850 | ||||
12851 | OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); | |||
12852 | ||||
12853 | // C++ [over.oper]p5: | |||
12854 | // The allocation and deallocation functions, operator new, | |||
12855 | // operator new[], operator delete and operator delete[], are | |||
12856 | // described completely in 3.7.3. The attributes and restrictions | |||
12857 | // found in the rest of this subclause do not apply to them unless | |||
12858 | // explicitly stated in 3.7.3. | |||
12859 | if (Op == OO_Delete || Op == OO_Array_Delete) | |||
12860 | return CheckOperatorDeleteDeclaration(*this, FnDecl); | |||
12861 | ||||
12862 | if (Op == OO_New || Op == OO_Array_New) | |||
12863 | return CheckOperatorNewDeclaration(*this, FnDecl); | |||
12864 | ||||
12865 | // C++ [over.oper]p6: | |||
12866 | // An operator function shall either be a non-static member | |||
12867 | // function or be a non-member function and have at least one | |||
12868 | // parameter whose type is a class, a reference to a class, an | |||
12869 | // enumeration, or a reference to an enumeration. | |||
12870 | if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { | |||
12871 | if (MethodDecl->isStatic()) | |||
12872 | return Diag(FnDecl->getLocation(), | |||
12873 | diag::err_operator_overload_static) << FnDecl->getDeclName(); | |||
12874 | } else { | |||
12875 | bool ClassOrEnumParam = false; | |||
12876 | for (auto Param : FnDecl->parameters()) { | |||
12877 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
12878 | if (ParamType->isDependentType() || ParamType->isRecordType() || | |||
12879 | ParamType->isEnumeralType()) { | |||
12880 | ClassOrEnumParam = true; | |||
12881 | break; | |||
12882 | } | |||
12883 | } | |||
12884 | ||||
12885 | if (!ClassOrEnumParam) | |||
12886 | return Diag(FnDecl->getLocation(), | |||
12887 | diag::err_operator_overload_needs_class_or_enum) | |||
12888 | << FnDecl->getDeclName(); | |||
12889 | } | |||
12890 | ||||
12891 | // C++ [over.oper]p8: | |||
12892 | // An operator function cannot have default arguments (8.3.6), | |||
12893 | // except where explicitly stated below. | |||
12894 | // | |||
12895 | // Only the function-call operator allows default arguments | |||
12896 | // (C++ [over.call]p1). | |||
12897 | if (Op != OO_Call) { | |||
12898 | for (auto Param : FnDecl->parameters()) { | |||
12899 | if (Param->hasDefaultArg()) | |||
12900 | return Diag(Param->getLocation(), | |||
12901 | diag::err_operator_overload_default_arg) | |||
12902 | << FnDecl->getDeclName() << Param->getDefaultArgRange(); | |||
12903 | } | |||
12904 | } | |||
12905 | ||||
12906 | static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { | |||
12907 | { false, false, false } | |||
12908 | #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ | |||
12909 | , { Unary, Binary, MemberOnly } | |||
12910 | #include "clang/Basic/OperatorKinds.def" | |||
12911 | }; | |||
12912 | ||||
12913 | bool CanBeUnaryOperator = OperatorUses[Op][0]; | |||
12914 | bool CanBeBinaryOperator = OperatorUses[Op][1]; | |||
12915 | bool MustBeMemberOperator = OperatorUses[Op][2]; | |||
12916 | ||||
12917 | // C++ [over.oper]p8: | |||
12918 | // [...] Operator functions cannot have more or fewer parameters | |||
12919 | // than the number required for the corresponding operator, as | |||
12920 | // described in the rest of this subclause. | |||
12921 | unsigned NumParams = FnDecl->getNumParams() | |||
12922 | + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); | |||
12923 | if (Op != OO_Call && | |||
12924 | ((NumParams == 1 && !CanBeUnaryOperator) || | |||
12925 | (NumParams == 2 && !CanBeBinaryOperator) || | |||
12926 | (NumParams < 1) || (NumParams > 2))) { | |||
12927 | // We have the wrong number of parameters. | |||
12928 | unsigned ErrorKind; | |||
12929 | if (CanBeUnaryOperator && CanBeBinaryOperator) { | |||
12930 | ErrorKind = 2; // 2 -> unary or binary. | |||
12931 | } else if (CanBeUnaryOperator) { | |||
12932 | ErrorKind = 0; // 0 -> unary | |||
12933 | } else { | |||
12934 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12935, __extension__ __PRETTY_FUNCTION__)) | |||
12935 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12935, __extension__ __PRETTY_FUNCTION__)); | |||
12936 | ErrorKind = 1; // 1 -> binary | |||
12937 | } | |||
12938 | ||||
12939 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) | |||
12940 | << FnDecl->getDeclName() << NumParams << ErrorKind; | |||
12941 | } | |||
12942 | ||||
12943 | // Overloaded operators other than operator() cannot be variadic. | |||
12944 | if (Op != OO_Call && | |||
12945 | FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { | |||
12946 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) | |||
12947 | << FnDecl->getDeclName(); | |||
12948 | } | |||
12949 | ||||
12950 | // Some operators must be non-static member functions. | |||
12951 | if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { | |||
12952 | return Diag(FnDecl->getLocation(), | |||
12953 | diag::err_operator_overload_must_be_member) | |||
12954 | << FnDecl->getDeclName(); | |||
12955 | } | |||
12956 | ||||
12957 | // C++ [over.inc]p1: | |||
12958 | // The user-defined function called operator++ implements the | |||
12959 | // prefix and postfix ++ operator. If this function is a member | |||
12960 | // function with no parameters, or a non-member function with one | |||
12961 | // parameter of class or enumeration type, it defines the prefix | |||
12962 | // increment operator ++ for objects of that type. If the function | |||
12963 | // is a member function with one parameter (which shall be of type | |||
12964 | // int) or a non-member function with two parameters (the second | |||
12965 | // of which shall be of type int), it defines the postfix | |||
12966 | // increment operator ++ for objects of that type. | |||
12967 | if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { | |||
12968 | ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); | |||
12969 | QualType ParamType = LastParam->getType(); | |||
12970 | ||||
12971 | if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && | |||
12972 | !ParamType->isDependentType()) | |||
12973 | return Diag(LastParam->getLocation(), | |||
12974 | diag::err_operator_overload_post_incdec_must_be_int) | |||
12975 | << LastParam->getType() << (Op == OO_MinusMinus); | |||
12976 | } | |||
12977 | ||||
12978 | return false; | |||
12979 | } | |||
12980 | ||||
12981 | static bool | |||
12982 | checkLiteralOperatorTemplateParameterList(Sema &SemaRef, | |||
12983 | FunctionTemplateDecl *TpDecl) { | |||
12984 | TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); | |||
12985 | ||||
12986 | // Must have one or two template parameters. | |||
12987 | if (TemplateParams->size() == 1) { | |||
12988 | NonTypeTemplateParmDecl *PmDecl = | |||
12989 | dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); | |||
12990 | ||||
12991 | // The template parameter must be a char parameter pack. | |||
12992 | if (PmDecl && PmDecl->isTemplateParameterPack() && | |||
12993 | SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) | |||
12994 | return false; | |||
12995 | ||||
12996 | } else if (TemplateParams->size() == 2) { | |||
12997 | TemplateTypeParmDecl *PmType = | |||
12998 | dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); | |||
12999 | NonTypeTemplateParmDecl *PmArgs = | |||
13000 | dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); | |||
13001 | ||||
13002 | // The second template parameter must be a parameter pack with the | |||
13003 | // first template parameter as its type. | |||
13004 | if (PmType && PmArgs && !PmType->isTemplateParameterPack() && | |||
13005 | PmArgs->isTemplateParameterPack()) { | |||
13006 | const TemplateTypeParmType *TArgs = | |||
13007 | PmArgs->getType()->getAs<TemplateTypeParmType>(); | |||
13008 | if (TArgs && TArgs->getDepth() == PmType->getDepth() && | |||
13009 | TArgs->getIndex() == PmType->getIndex()) { | |||
13010 | if (!SemaRef.inTemplateInstantiation()) | |||
13011 | SemaRef.Diag(TpDecl->getLocation(), | |||
13012 | diag::ext_string_literal_operator_template); | |||
13013 | return false; | |||
13014 | } | |||
13015 | } | |||
13016 | } | |||
13017 | ||||
13018 | SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), | |||
13019 | diag::err_literal_operator_template) | |||
13020 | << TpDecl->getTemplateParameters()->getSourceRange(); | |||
13021 | return true; | |||
13022 | } | |||
13023 | ||||
13024 | /// CheckLiteralOperatorDeclaration - Check whether the declaration | |||
13025 | /// of this literal operator function is well-formed. If so, returns | |||
13026 | /// false; otherwise, emits appropriate diagnostics and returns true. | |||
13027 | bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { | |||
13028 | if (isa<CXXMethodDecl>(FnDecl)) { | |||
13029 | Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) | |||
13030 | << FnDecl->getDeclName(); | |||
13031 | return true; | |||
13032 | } | |||
13033 | ||||
13034 | if (FnDecl->isExternC()) { | |||
13035 | Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); | |||
13036 | if (const LinkageSpecDecl *LSD = | |||
13037 | FnDecl->getDeclContext()->getExternCContext()) | |||
13038 | Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); | |||
13039 | return true; | |||
13040 | } | |||
13041 | ||||
13042 | // This might be the definition of a literal operator template. | |||
13043 | FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); | |||
13044 | ||||
13045 | // This might be a specialization of a literal operator template. | |||
13046 | if (!TpDecl) | |||
13047 | TpDecl = FnDecl->getPrimaryTemplate(); | |||
13048 | ||||
13049 | // template <char...> type operator "" name() and | |||
13050 | // template <class T, T...> type operator "" name() are the only valid | |||
13051 | // template signatures, and the only valid signatures with no parameters. | |||
13052 | if (TpDecl) { | |||
13053 | if (FnDecl->param_size() != 0) { | |||
13054 | Diag(FnDecl->getLocation(), | |||
13055 | diag::err_literal_operator_template_with_params); | |||
13056 | return true; | |||
13057 | } | |||
13058 | ||||
13059 | if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) | |||
13060 | return true; | |||
13061 | ||||
13062 | } else if (FnDecl->param_size() == 1) { | |||
13063 | const ParmVarDecl *Param = FnDecl->getParamDecl(0); | |||
13064 | ||||
13065 | QualType ParamType = Param->getType().getUnqualifiedType(); | |||
13066 | ||||
13067 | // Only unsigned long long int, long double, any character type, and const | |||
13068 | // char * are allowed as the only parameters. | |||
13069 | if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || | |||
13070 | ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || | |||
13071 | Context.hasSameType(ParamType, Context.CharTy) || | |||
13072 | Context.hasSameType(ParamType, Context.WideCharTy) || | |||
13073 | Context.hasSameType(ParamType, Context.Char16Ty) || | |||
13074 | Context.hasSameType(ParamType, Context.Char32Ty)) { | |||
13075 | } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { | |||
13076 | QualType InnerType = Ptr->getPointeeType(); | |||
13077 | ||||
13078 | // Pointer parameter must be a const char *. | |||
13079 | if (!(Context.hasSameType(InnerType.getUnqualifiedType(), | |||
13080 | Context.CharTy) && | |||
13081 | InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { | |||
13082 | Diag(Param->getSourceRange().getBegin(), | |||
13083 | diag::err_literal_operator_param) | |||
13084 | << ParamType << "'const char *'" << Param->getSourceRange(); | |||
13085 | return true; | |||
13086 | } | |||
13087 | ||||
13088 | } else if (ParamType->isRealFloatingType()) { | |||
13089 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) | |||
13090 | << ParamType << Context.LongDoubleTy << Param->getSourceRange(); | |||
13091 | return true; | |||
13092 | ||||
13093 | } else if (ParamType->isIntegerType()) { | |||
13094 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) | |||
13095 | << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); | |||
13096 | return true; | |||
13097 | ||||
13098 | } else { | |||
13099 | Diag(Param->getSourceRange().getBegin(), | |||
13100 | diag::err_literal_operator_invalid_param) | |||
13101 | << ParamType << Param->getSourceRange(); | |||
13102 | return true; | |||
13103 | } | |||
13104 | ||||
13105 | } else if (FnDecl->param_size() == 2) { | |||
13106 | FunctionDecl::param_iterator Param = FnDecl->param_begin(); | |||
13107 | ||||
13108 | // First, verify that the first parameter is correct. | |||
13109 | ||||
13110 | QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); | |||
13111 | ||||
13112 | // Two parameter function must have a pointer to const as a | |||
13113 | // first parameter; let's strip those qualifiers. | |||
13114 | const PointerType *PT = FirstParamType->getAs<PointerType>(); | |||
13115 | ||||
13116 | if (!PT) { | |||
13117 | Diag((*Param)->getSourceRange().getBegin(), | |||
13118 | diag::err_literal_operator_param) | |||
13119 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | |||
13120 | return true; | |||
13121 | } | |||
13122 | ||||
13123 | QualType PointeeType = PT->getPointeeType(); | |||
13124 | // First parameter must be const | |||
13125 | if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { | |||
13126 | Diag((*Param)->getSourceRange().getBegin(), | |||
13127 | diag::err_literal_operator_param) | |||
13128 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | |||
13129 | return true; | |||
13130 | } | |||
13131 | ||||
13132 | QualType InnerType = PointeeType.getUnqualifiedType(); | |||
13133 | // Only const char *, const wchar_t*, const char16_t*, and const char32_t* | |||
13134 | // are allowed as the first parameter to a two-parameter function | |||
13135 | if (!(Context.hasSameType(InnerType, Context.CharTy) || | |||
13136 | Context.hasSameType(InnerType, Context.WideCharTy) || | |||
13137 | Context.hasSameType(InnerType, Context.Char16Ty) || | |||
13138 | Context.hasSameType(InnerType, Context.Char32Ty))) { | |||
13139 | Diag((*Param)->getSourceRange().getBegin(), | |||
13140 | diag::err_literal_operator_param) | |||
13141 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | |||
13142 | return true; | |||
13143 | } | |||
13144 | ||||
13145 | // Move on to the second and final parameter. | |||
13146 | ++Param; | |||
13147 | ||||
13148 | // The second parameter must be a std::size_t. | |||
13149 | QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); | |||
13150 | if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { | |||
13151 | Diag((*Param)->getSourceRange().getBegin(), | |||
13152 | diag::err_literal_operator_param) | |||
13153 | << SecondParamType << Context.getSizeType() | |||
13154 | << (*Param)->getSourceRange(); | |||
13155 | return true; | |||
13156 | } | |||
13157 | } else { | |||
13158 | Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); | |||
13159 | return true; | |||
13160 | } | |||
13161 | ||||
13162 | // Parameters are good. | |||
13163 | ||||
13164 | // A parameter-declaration-clause containing a default argument is not | |||
13165 | // equivalent to any of the permitted forms. | |||
13166 | for (auto Param : FnDecl->parameters()) { | |||
13167 | if (Param->hasDefaultArg()) { | |||
13168 | Diag(Param->getDefaultArgRange().getBegin(), | |||
13169 | diag::err_literal_operator_default_argument) | |||
13170 | << Param->getDefaultArgRange(); | |||
13171 | break; | |||
13172 | } | |||
13173 | } | |||
13174 | ||||
13175 | StringRef LiteralName | |||
13176 | = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); | |||
13177 | if (LiteralName[0] != '_' && | |||
13178 | !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { | |||
13179 | // C++11 [usrlit.suffix]p1: | |||
13180 | // Literal suffix identifiers that do not start with an underscore | |||
13181 | // are reserved for future standardization. | |||
13182 | Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) | |||
13183 | << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); | |||
13184 | } | |||
13185 | ||||
13186 | return false; | |||
13187 | } | |||
13188 | ||||
13189 | /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ | |||
13190 | /// linkage specification, including the language and (if present) | |||
13191 | /// the '{'. ExternLoc is the location of the 'extern', Lang is the | |||
13192 | /// language string literal. LBraceLoc, if valid, provides the location of | |||
13193 | /// the '{' brace. Otherwise, this linkage specification does not | |||
13194 | /// have any braces. | |||
13195 | Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, | |||
13196 | Expr *LangStr, | |||
13197 | SourceLocation LBraceLoc) { | |||
13198 | StringLiteral *Lit = cast<StringLiteral>(LangStr); | |||
13199 | if (!Lit->isAscii()) { | |||
13200 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) | |||
13201 | << LangStr->getSourceRange(); | |||
13202 | return nullptr; | |||
13203 | } | |||
13204 | ||||
13205 | StringRef Lang = Lit->getString(); | |||
13206 | LinkageSpecDecl::LanguageIDs Language; | |||
13207 | if (Lang == "C") | |||
13208 | Language = LinkageSpecDecl::lang_c; | |||
13209 | else if (Lang == "C++") | |||
13210 | Language = LinkageSpecDecl::lang_cxx; | |||
13211 | else { | |||
13212 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) | |||
13213 | << LangStr->getSourceRange(); | |||
13214 | return nullptr; | |||
13215 | } | |||
13216 | ||||
13217 | // FIXME: Add all the various semantics of linkage specifications | |||
13218 | ||||
13219 | LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, | |||
13220 | LangStr->getExprLoc(), Language, | |||
13221 | LBraceLoc.isValid()); | |||
13222 | CurContext->addDecl(D); | |||
13223 | PushDeclContext(S, D); | |||
13224 | return D; | |||
13225 | } | |||
13226 | ||||
13227 | /// ActOnFinishLinkageSpecification - Complete the definition of | |||
13228 | /// the C++ linkage specification LinkageSpec. If RBraceLoc is | |||
13229 | /// valid, it's the position of the closing '}' brace in a linkage | |||
13230 | /// specification that uses braces. | |||
13231 | Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, | |||
13232 | Decl *LinkageSpec, | |||
13233 | SourceLocation RBraceLoc) { | |||
13234 | if (RBraceLoc.isValid()) { | |||
13235 | LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); | |||
13236 | LSDecl->setRBraceLoc(RBraceLoc); | |||
13237 | } | |||
13238 | PopDeclContext(); | |||
13239 | return LinkageSpec; | |||
13240 | } | |||
13241 | ||||
13242 | Decl *Sema::ActOnEmptyDeclaration(Scope *S, | |||
13243 | AttributeList *AttrList, | |||
13244 | SourceLocation SemiLoc) { | |||
13245 | Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); | |||
13246 | // Attribute declarations appertain to empty declaration so we handle | |||
13247 | // them here. | |||
13248 | if (AttrList) | |||
13249 | ProcessDeclAttributeList(S, ED, AttrList); | |||
13250 | ||||
13251 | CurContext->addDecl(ED); | |||
13252 | return ED; | |||
13253 | } | |||
13254 | ||||
13255 | /// \brief Perform semantic analysis for the variable declaration that | |||
13256 | /// occurs within a C++ catch clause, returning the newly-created | |||
13257 | /// variable. | |||
13258 | VarDecl *Sema::BuildExceptionDeclaration(Scope *S, | |||
13259 | TypeSourceInfo *TInfo, | |||
13260 | SourceLocation StartLoc, | |||
13261 | SourceLocation Loc, | |||
13262 | IdentifierInfo *Name) { | |||
13263 | bool Invalid = false; | |||
13264 | QualType ExDeclType = TInfo->getType(); | |||
13265 | ||||
13266 | // Arrays and functions decay. | |||
13267 | if (ExDeclType->isArrayType()) | |||
13268 | ExDeclType = Context.getArrayDecayedType(ExDeclType); | |||
13269 | else if (ExDeclType->isFunctionType()) | |||
13270 | ExDeclType = Context.getPointerType(ExDeclType); | |||
13271 | ||||
13272 | // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. | |||
13273 | // The exception-declaration shall not denote a pointer or reference to an | |||
13274 | // incomplete type, other than [cv] void*. | |||
13275 | // N2844 forbids rvalue references. | |||
13276 | if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { | |||
13277 | Diag(Loc, diag::err_catch_rvalue_ref); | |||
13278 | Invalid = true; | |||
13279 | } | |||
13280 | ||||
13281 | if (ExDeclType->isVariablyModifiedType()) { | |||
13282 | Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; | |||
13283 | Invalid = true; | |||
13284 | } | |||
13285 | ||||
13286 | QualType BaseType = ExDeclType; | |||
13287 | int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference | |||
13288 | unsigned DK = diag::err_catch_incomplete; | |||
13289 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { | |||
13290 | BaseType = Ptr->getPointeeType(); | |||
13291 | Mode = 1; | |||
13292 | DK = diag::err_catch_incomplete_ptr; | |||
13293 | } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { | |||
13294 | // For the purpose of error recovery, we treat rvalue refs like lvalue refs. | |||
13295 | BaseType = Ref->getPointeeType(); | |||
13296 | Mode = 2; | |||
13297 | DK = diag::err_catch_incomplete_ref; | |||
13298 | } | |||
13299 | if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && | |||
13300 | !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) | |||
13301 | Invalid = true; | |||
13302 | ||||
13303 | if (!Invalid && !ExDeclType->isDependentType() && | |||
13304 | RequireNonAbstractType(Loc, ExDeclType, | |||
13305 | diag::err_abstract_type_in_decl, | |||
13306 | AbstractVariableType)) | |||
13307 | Invalid = true; | |||
13308 | ||||
13309 | // Only the non-fragile NeXT runtime currently supports C++ catches | |||
13310 | // of ObjC types, and no runtime supports catching ObjC types by value. | |||
13311 | if (!Invalid && getLangOpts().ObjC1) { | |||
13312 | QualType T = ExDeclType; | |||
13313 | if (const ReferenceType *RT = T->getAs<ReferenceType>()) | |||
13314 | T = RT->getPointeeType(); | |||
13315 | ||||
13316 | if (T->isObjCObjectType()) { | |||
13317 | Diag(Loc, diag::err_objc_object_catch); | |||
13318 | Invalid = true; | |||
13319 | } else if (T->isObjCObjectPointerType()) { | |||
13320 | // FIXME: should this be a test for macosx-fragile specifically? | |||
13321 | if (getLangOpts().ObjCRuntime.isFragile()) | |||
13322 | Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); | |||
13323 | } | |||
13324 | } | |||
13325 | ||||
13326 | VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, | |||
13327 | ExDeclType, TInfo, SC_None); | |||
13328 | ExDecl->setExceptionVariable(true); | |||
13329 | ||||
13330 | // In ARC, infer 'retaining' for variables of retainable type. | |||
13331 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) | |||
13332 | Invalid = true; | |||
13333 | ||||
13334 | if (!Invalid && !ExDeclType->isDependentType()) { | |||
13335 | if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { | |||
13336 | // Insulate this from anything else we might currently be parsing. | |||
13337 | EnterExpressionEvaluationContext scope( | |||
13338 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | |||
13339 | ||||
13340 | // C++ [except.handle]p16: | |||
13341 | // The object declared in an exception-declaration or, if the | |||
13342 | // exception-declaration does not specify a name, a temporary (12.2) is | |||
13343 | // copy-initialized (8.5) from the exception object. [...] | |||
13344 | // The object is destroyed when the handler exits, after the destruction | |||
13345 | // of any automatic objects initialized within the handler. | |||
13346 | // | |||
13347 | // We just pretend to initialize the object with itself, then make sure | |||
13348 | // it can be destroyed later. | |||
13349 | QualType initType = Context.getExceptionObjectType(ExDeclType); | |||
13350 | ||||
13351 | InitializedEntity entity = | |||
13352 | InitializedEntity::InitializeVariable(ExDecl); | |||
13353 | InitializationKind initKind = | |||
13354 | InitializationKind::CreateCopy(Loc, SourceLocation()); | |||
13355 | ||||
13356 | Expr *opaqueValue = | |||
13357 | new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); | |||
13358 | InitializationSequence sequence(*this, entity, initKind, opaqueValue); | |||
13359 | ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); | |||
13360 | if (result.isInvalid()) | |||
13361 | Invalid = true; | |||
13362 | else { | |||
13363 | // If the constructor used was non-trivial, set this as the | |||
13364 | // "initializer". | |||
13365 | CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); | |||
13366 | if (!construct->getConstructor()->isTrivial()) { | |||
13367 | Expr *init = MaybeCreateExprWithCleanups(construct); | |||
13368 | ExDecl->setInit(init); | |||
13369 | } | |||
13370 | ||||
13371 | // And make sure it's destructable. | |||
13372 | FinalizeVarWithDestructor(ExDecl, recordType); | |||
13373 | } | |||
13374 | } | |||
13375 | } | |||
13376 | ||||
13377 | if (Invalid) | |||
13378 | ExDecl->setInvalidDecl(); | |||
13379 | ||||
13380 | return ExDecl; | |||
13381 | } | |||
13382 | ||||
13383 | /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch | |||
13384 | /// handler. | |||
13385 | Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { | |||
13386 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
13387 | bool Invalid = D.isInvalidType(); | |||
13388 | ||||
13389 | // Check for unexpanded parameter packs. | |||
13390 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
13391 | UPPC_ExceptionType)) { | |||
13392 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | |||
13393 | D.getIdentifierLoc()); | |||
13394 | Invalid = true; | |||
13395 | } | |||
13396 | ||||
13397 | IdentifierInfo *II = D.getIdentifier(); | |||
13398 | if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), | |||
13399 | LookupOrdinaryName, | |||
13400 | ForVisibleRedeclaration)) { | |||
13401 | // The scope should be freshly made just for us. There is just no way | |||
13402 | // it contains any previous declaration, except for function parameters in | |||
13403 | // a function-try-block's catch statement. | |||
13404 | assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void (0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13404, __extension__ __PRETTY_FUNCTION__)); | |||
13405 | if (isDeclInScope(PrevDecl, CurContext, S)) { | |||
13406 | Diag(D.getIdentifierLoc(), diag::err_redefinition) | |||
13407 | << D.getIdentifier(); | |||
13408 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
13409 | Invalid = true; | |||
13410 | } else if (PrevDecl->isTemplateParameter()) | |||
13411 | // Maybe we will complain about the shadowed template parameter. | |||
13412 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
13413 | } | |||
13414 | ||||
13415 | if (D.getCXXScopeSpec().isSet() && !Invalid) { | |||
13416 | Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) | |||
13417 | << D.getCXXScopeSpec().getRange(); | |||
13418 | Invalid = true; | |||
13419 | } | |||
13420 | ||||
13421 | VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, | |||
13422 | D.getLocStart(), | |||
13423 | D.getIdentifierLoc(), | |||
13424 | D.getIdentifier()); | |||
13425 | if (Invalid) | |||
13426 | ExDecl->setInvalidDecl(); | |||
13427 | ||||
13428 | // Add the exception declaration into this scope. | |||
13429 | if (II) | |||
13430 | PushOnScopeChains(ExDecl, S); | |||
13431 | else | |||
13432 | CurContext->addDecl(ExDecl); | |||
13433 | ||||
13434 | ProcessDeclAttributes(S, ExDecl, D); | |||
13435 | return ExDecl; | |||
13436 | } | |||
13437 | ||||
13438 | Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, | |||
13439 | Expr *AssertExpr, | |||
13440 | Expr *AssertMessageExpr, | |||
13441 | SourceLocation RParenLoc) { | |||
13442 | StringLiteral *AssertMessage = | |||
13443 | AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; | |||
13444 | ||||
13445 | if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) | |||
13446 | return nullptr; | |||
13447 | ||||
13448 | return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, | |||
13449 | AssertMessage, RParenLoc, false); | |||
13450 | } | |||
13451 | ||||
13452 | Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, | |||
13453 | Expr *AssertExpr, | |||
13454 | StringLiteral *AssertMessage, | |||
13455 | SourceLocation RParenLoc, | |||
13456 | bool Failed) { | |||
13457 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13457, __extension__ __PRETTY_FUNCTION__)); | |||
13458 | if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && | |||
13459 | !Failed) { | |||
13460 | // In a static_assert-declaration, the constant-expression shall be a | |||
13461 | // constant expression that can be contextually converted to bool. | |||
13462 | ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); | |||
13463 | if (Converted.isInvalid()) | |||
13464 | Failed = true; | |||
13465 | ||||
13466 | llvm::APSInt Cond; | |||
13467 | if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, | |||
13468 | diag::err_static_assert_expression_is_not_constant, | |||
13469 | /*AllowFold=*/false).isInvalid()) | |||
13470 | Failed = true; | |||
13471 | ||||
13472 | if (!Failed && !Cond) { | |||
13473 | SmallString<256> MsgBuffer; | |||
13474 | llvm::raw_svector_ostream Msg(MsgBuffer); | |||
13475 | if (AssertMessage) | |||
13476 | AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); | |||
13477 | ||||
13478 | Expr *InnerCond = nullptr; | |||
13479 | std::string InnerCondDescription; | |||
13480 | std::tie(InnerCond, InnerCondDescription) = | |||
13481 | findFailedBooleanCondition(Converted.get(), | |||
13482 | /*AllowTopLevelCond=*/false); | |||
13483 | if (InnerCond) { | |||
13484 | Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) | |||
13485 | << InnerCondDescription << !AssertMessage | |||
13486 | << Msg.str() << InnerCond->getSourceRange(); | |||
13487 | } else { | |||
13488 | Diag(StaticAssertLoc, diag::err_static_assert_failed) | |||
13489 | << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); | |||
13490 | } | |||
13491 | Failed = true; | |||
13492 | } | |||
13493 | } | |||
13494 | ||||
13495 | ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, | |||
13496 | /*DiscardedValue*/false, | |||
13497 | /*IsConstexpr*/true); | |||
13498 | if (FullAssertExpr.isInvalid()) | |||
13499 | Failed = true; | |||
13500 | else | |||
13501 | AssertExpr = FullAssertExpr.get(); | |||
13502 | ||||
13503 | Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, | |||
13504 | AssertExpr, AssertMessage, RParenLoc, | |||
13505 | Failed); | |||
13506 | ||||
13507 | CurContext->addDecl(Decl); | |||
13508 | return Decl; | |||
13509 | } | |||
13510 | ||||
13511 | /// \brief Perform semantic analysis of the given friend type declaration. | |||
13512 | /// | |||
13513 | /// \returns A friend declaration that. | |||
13514 | FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, | |||
13515 | SourceLocation FriendLoc, | |||
13516 | TypeSourceInfo *TSInfo) { | |||
13517 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13517, __extension__ __PRETTY_FUNCTION__)); | |||
13518 | ||||
13519 | QualType T = TSInfo->getType(); | |||
13520 | SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); | |||
13521 | ||||
13522 | // C++03 [class.friend]p2: | |||
13523 | // An elaborated-type-specifier shall be used in a friend declaration | |||
13524 | // for a class.* | |||
13525 | // | |||
13526 | // * The class-key of the elaborated-type-specifier is required. | |||
13527 | if (!CodeSynthesisContexts.empty()) { | |||
13528 | // Do not complain about the form of friend template types during any kind | |||
13529 | // of code synthesis. For template instantiation, we will have complained | |||
13530 | // when the template was defined. | |||
13531 | } else { | |||
13532 | if (!T->isElaboratedTypeSpecifier()) { | |||
13533 | // If we evaluated the type to a record type, suggest putting | |||
13534 | // a tag in front. | |||
13535 | if (const RecordType *RT = T->getAs<RecordType>()) { | |||
13536 | RecordDecl *RD = RT->getDecl(); | |||
13537 | ||||
13538 | SmallString<16> InsertionText(" "); | |||
13539 | InsertionText += RD->getKindName(); | |||
13540 | ||||
13541 | Diag(TypeRange.getBegin(), | |||
13542 | getLangOpts().CPlusPlus11 ? | |||
13543 | diag::warn_cxx98_compat_unelaborated_friend_type : | |||
13544 | diag::ext_unelaborated_friend_type) | |||
13545 | << (unsigned) RD->getTagKind() | |||
13546 | << T | |||
13547 | << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), | |||
13548 | InsertionText); | |||
13549 | } else { | |||
13550 | Diag(FriendLoc, | |||
13551 | getLangOpts().CPlusPlus11 ? | |||
13552 | diag::warn_cxx98_compat_nonclass_type_friend : | |||
13553 | diag::ext_nonclass_type_friend) | |||
13554 | << T | |||
13555 | << TypeRange; | |||
13556 | } | |||
13557 | } else if (T->getAs<EnumType>()) { | |||
13558 | Diag(FriendLoc, | |||
13559 | getLangOpts().CPlusPlus11 ? | |||
13560 | diag::warn_cxx98_compat_enum_friend : | |||
13561 | diag::ext_enum_friend) | |||
13562 | << T | |||
13563 | << TypeRange; | |||
13564 | } | |||
13565 | ||||
13566 | // C++11 [class.friend]p3: | |||
13567 | // A friend declaration that does not declare a function shall have one | |||
13568 | // of the following forms: | |||
13569 | // friend elaborated-type-specifier ; | |||
13570 | // friend simple-type-specifier ; | |||
13571 | // friend typename-specifier ; | |||
13572 | if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) | |||
13573 | Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; | |||
13574 | } | |||
13575 | ||||
13576 | // If the type specifier in a friend declaration designates a (possibly | |||
13577 | // cv-qualified) class type, that class is declared as a friend; otherwise, | |||
13578 | // the friend declaration is ignored. | |||
13579 | return FriendDecl::Create(Context, CurContext, | |||
13580 | TSInfo->getTypeLoc().getLocStart(), TSInfo, | |||
13581 | FriendLoc); | |||
13582 | } | |||
13583 | ||||
13584 | /// Handle a friend tag declaration where the scope specifier was | |||
13585 | /// templated. | |||
13586 | Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, | |||
13587 | unsigned TagSpec, SourceLocation TagLoc, | |||
13588 | CXXScopeSpec &SS, | |||
13589 | IdentifierInfo *Name, | |||
13590 | SourceLocation NameLoc, | |||
13591 | AttributeList *Attr, | |||
13592 | MultiTemplateParamsArg TempParamLists) { | |||
13593 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | |||
13594 | ||||
13595 | bool IsMemberSpecialization = false; | |||
13596 | bool Invalid = false; | |||
13597 | ||||
13598 | if (TemplateParameterList *TemplateParams = | |||
13599 | MatchTemplateParametersToScopeSpecifier( | |||
13600 | TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, | |||
13601 | IsMemberSpecialization, Invalid)) { | |||
13602 | if (TemplateParams->size() > 0) { | |||
13603 | // This is a declaration of a class template. | |||
13604 | if (Invalid) | |||
13605 | return nullptr; | |||
13606 | ||||
13607 | return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, | |||
13608 | NameLoc, Attr, TemplateParams, AS_public, | |||
13609 | /*ModulePrivateLoc=*/SourceLocation(), | |||
13610 | FriendLoc, TempParamLists.size() - 1, | |||
13611 | TempParamLists.data()).get(); | |||
13612 | } else { | |||
13613 | // The "template<>" header is extraneous. | |||
13614 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | |||
13615 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | |||
13616 | IsMemberSpecialization = true; | |||
13617 | } | |||
13618 | } | |||
13619 | ||||
13620 | if (Invalid) return nullptr; | |||
13621 | ||||
13622 | bool isAllExplicitSpecializations = true; | |||
13623 | for (unsigned I = TempParamLists.size(); I-- > 0; ) { | |||
13624 | if (TempParamLists[I]->size()) { | |||
13625 | isAllExplicitSpecializations = false; | |||
13626 | break; | |||
13627 | } | |||
13628 | } | |||
13629 | ||||
13630 | // FIXME: don't ignore attributes. | |||
13631 | ||||
13632 | // If it's explicit specializations all the way down, just forget | |||
13633 | // about the template header and build an appropriate non-templated | |||
13634 | // friend. TODO: for source fidelity, remember the headers. | |||
13635 | if (isAllExplicitSpecializations) { | |||
13636 | if (SS.isEmpty()) { | |||
13637 | bool Owned = false; | |||
13638 | bool IsDependent = false; | |||
13639 | return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, | |||
13640 | Attr, AS_public, | |||
13641 | /*ModulePrivateLoc=*/SourceLocation(), | |||
13642 | MultiTemplateParamsArg(), Owned, IsDependent, | |||
13643 | /*ScopedEnumKWLoc=*/SourceLocation(), | |||
13644 | /*ScopedEnumUsesClassTag=*/false, | |||
13645 | /*UnderlyingType=*/TypeResult(), | |||
13646 | /*IsTypeSpecifier=*/false, | |||
13647 | /*IsTemplateParamOrArg=*/false); | |||
13648 | } | |||
13649 | ||||
13650 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | |||
13651 | ElaboratedTypeKeyword Keyword | |||
13652 | = TypeWithKeyword::getKeywordForTagTypeKind(Kind); | |||
13653 | QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, | |||
13654 | *Name, NameLoc); | |||
13655 | if (T.isNull()) | |||
13656 | return nullptr; | |||
13657 | ||||
13658 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); | |||
13659 | if (isa<DependentNameType>(T)) { | |||
13660 | DependentNameTypeLoc TL = | |||
13661 | TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
13662 | TL.setElaboratedKeywordLoc(TagLoc); | |||
13663 | TL.setQualifierLoc(QualifierLoc); | |||
13664 | TL.setNameLoc(NameLoc); | |||
13665 | } else { | |||
13666 | ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); | |||
13667 | TL.setElaboratedKeywordLoc(TagLoc); | |||
13668 | TL.setQualifierLoc(QualifierLoc); | |||
13669 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); | |||
13670 | } | |||
13671 | ||||
13672 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, | |||
13673 | TSI, FriendLoc, TempParamLists); | |||
13674 | Friend->setAccess(AS_public); | |||
13675 | CurContext->addDecl(Friend); | |||
13676 | return Friend; | |||
13677 | } | |||
13678 | ||||
13679 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13679, __extension__ __PRETTY_FUNCTION__)); | |||
13680 | ||||
13681 | ||||
13682 | ||||
13683 | // Handle the case of a templated-scope friend class. e.g. | |||
13684 | // template <class T> class A<T>::B; | |||
13685 | // FIXME: we don't support these right now. | |||
13686 | Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) | |||
13687 | << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); | |||
13688 | ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); | |||
13689 | QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); | |||
13690 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); | |||
13691 | DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
13692 | TL.setElaboratedKeywordLoc(TagLoc); | |||
13693 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
13694 | TL.setNameLoc(NameLoc); | |||
13695 | ||||
13696 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, | |||
13697 | TSI, FriendLoc, TempParamLists); | |||
13698 | Friend->setAccess(AS_public); | |||
13699 | Friend->setUnsupportedFriend(true); | |||
13700 | CurContext->addDecl(Friend); | |||
13701 | return Friend; | |||
13702 | } | |||
13703 | ||||
13704 | ||||
13705 | /// Handle a friend type declaration. This works in tandem with | |||
13706 | /// ActOnTag. | |||
13707 | /// | |||
13708 | /// Notes on friend class templates: | |||
13709 | /// | |||
13710 | /// We generally treat friend class declarations as if they were | |||
13711 | /// declaring a class. So, for example, the elaborated type specifier | |||
13712 | /// in a friend declaration is required to obey the restrictions of a | |||
13713 | /// class-head (i.e. no typedefs in the scope chain), template | |||
13714 | /// parameters are required to match up with simple template-ids, &c. | |||
13715 | /// However, unlike when declaring a template specialization, it's | |||
13716 | /// okay to refer to a template specialization without an empty | |||
13717 | /// template parameter declaration, e.g. | |||
13718 | /// friend class A<T>::B<unsigned>; | |||
13719 | /// We permit this as a special case; if there are any template | |||
13720 | /// parameters present at all, require proper matching, i.e. | |||
13721 | /// template <> template \<class T> friend class A<int>::B; | |||
13722 | Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, | |||
13723 | MultiTemplateParamsArg TempParams) { | |||
13724 | SourceLocation Loc = DS.getLocStart(); | |||
13725 | ||||
13726 | assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0) : __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13726, __extension__ __PRETTY_FUNCTION__)); | |||
13727 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13727, __extension__ __PRETTY_FUNCTION__)); | |||
13728 | ||||
13729 | // Try to convert the decl specifier to a type. This works for | |||
13730 | // friend templates because ActOnTag never produces a ClassTemplateDecl | |||
13731 | // for a TUK_Friend. | |||
13732 | Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); | |||
13733 | TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); | |||
13734 | QualType T = TSI->getType(); | |||
13735 | if (TheDeclarator.isInvalidType()) | |||
13736 | return nullptr; | |||
13737 | ||||
13738 | if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) | |||
13739 | return nullptr; | |||
13740 | ||||
13741 | // This is definitely an error in C++98. It's probably meant to | |||
13742 | // be forbidden in C++0x, too, but the specification is just | |||
13743 | // poorly written. | |||
13744 | // | |||
13745 | // The problem is with declarations like the following: | |||
13746 | // template <T> friend A<T>::foo; | |||
13747 | // where deciding whether a class C is a friend or not now hinges | |||
13748 | // on whether there exists an instantiation of A that causes | |||
13749 | // 'foo' to equal C. There are restrictions on class-heads | |||
13750 | // (which we declare (by fiat) elaborated friend declarations to | |||
13751 | // be) that makes this tractable. | |||
13752 | // | |||
13753 | // FIXME: handle "template <> friend class A<T>;", which | |||
13754 | // is possibly well-formed? Who even knows? | |||
13755 | if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { | |||
13756 | Diag(Loc, diag::err_tagless_friend_type_template) | |||
13757 | << DS.getSourceRange(); | |||
13758 | return nullptr; | |||
13759 | } | |||
13760 | ||||
13761 | // C++98 [class.friend]p1: A friend of a class is a function | |||
13762 | // or class that is not a member of the class . . . | |||
13763 | // This is fixed in DR77, which just barely didn't make the C++03 | |||
13764 | // deadline. It's also a very silly restriction that seriously | |||
13765 | // affects inner classes and which nobody else seems to implement; | |||
13766 | // thus we never diagnose it, not even in -pedantic. | |||
13767 | // | |||
13768 | // But note that we could warn about it: it's always useless to | |||
13769 | // friend one of your own members (it's not, however, worthless to | |||
13770 | // friend a member of an arbitrary specialization of your template). | |||
13771 | ||||
13772 | Decl *D; | |||
13773 | if (!TempParams.empty()) | |||
13774 | D = FriendTemplateDecl::Create(Context, CurContext, Loc, | |||
13775 | TempParams, | |||
13776 | TSI, | |||
13777 | DS.getFriendSpecLoc()); | |||
13778 | else | |||
13779 | D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); | |||
13780 | ||||
13781 | if (!D) | |||
13782 | return nullptr; | |||
13783 | ||||
13784 | D->setAccess(AS_public); | |||
13785 | CurContext->addDecl(D); | |||
13786 | ||||
13787 | return D; | |||
13788 | } | |||
13789 | ||||
13790 | NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, | |||
13791 | MultiTemplateParamsArg TemplateParams) { | |||
13792 | const DeclSpec &DS = D.getDeclSpec(); | |||
13793 | ||||
13794 | assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0) : __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13794, __extension__ __PRETTY_FUNCTION__)); | |||
13795 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13795, __extension__ __PRETTY_FUNCTION__)); | |||
13796 | ||||
13797 | SourceLocation Loc = D.getIdentifierLoc(); | |||
13798 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
13799 | ||||
13800 | // C++ [class.friend]p1 | |||
13801 | // A friend of a class is a function or class.... | |||
13802 | // Note that this sees through typedefs, which is intended. | |||
13803 | // It *doesn't* see through dependent types, which is correct | |||
13804 | // according to [temp.arg.type]p3: | |||
13805 | // If a declaration acquires a function type through a | |||
13806 | // type dependent on a template-parameter and this causes | |||
13807 | // a declaration that does not use the syntactic form of a | |||
13808 | // function declarator to have a function type, the program | |||
13809 | // is ill-formed. | |||
13810 | if (!TInfo->getType()->isFunctionType()) { | |||
13811 | Diag(Loc, diag::err_unexpected_friend); | |||
13812 | ||||
13813 | // It might be worthwhile to try to recover by creating an | |||
13814 | // appropriate declaration. | |||
13815 | return nullptr; | |||
13816 | } | |||
13817 | ||||
13818 | // C++ [namespace.memdef]p3 | |||
13819 | // - If a friend declaration in a non-local class first declares a | |||
13820 | // class or function, the friend class or function is a member | |||
13821 | // of the innermost enclosing namespace. | |||
13822 | // - The name of the friend is not found by simple name lookup | |||
13823 | // until a matching declaration is provided in that namespace | |||
13824 | // scope (either before or after the class declaration granting | |||
13825 | // friendship). | |||
13826 | // - If a friend function is called, its name may be found by the | |||
13827 | // name lookup that considers functions from namespaces and | |||
13828 | // classes associated with the types of the function arguments. | |||
13829 | // - When looking for a prior declaration of a class or a function | |||
13830 | // declared as a friend, scopes outside the innermost enclosing | |||
13831 | // namespace scope are not considered. | |||
13832 | ||||
13833 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
13834 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
13835 | DeclarationName Name = NameInfo.getName(); | |||
13836 | assert(Name)(static_cast <bool> (Name) ? void (0) : __assert_fail ( "Name", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13836, __extension__ __PRETTY_FUNCTION__)); | |||
13837 | ||||
13838 | // Check for unexpanded parameter packs. | |||
13839 | if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || | |||
13840 | DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || | |||
13841 | DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) | |||
13842 | return nullptr; | |||
13843 | ||||
13844 | // The context we found the declaration in, or in which we should | |||
13845 | // create the declaration. | |||
13846 | DeclContext *DC; | |||
13847 | Scope *DCScope = S; | |||
13848 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
13849 | ForExternalRedeclaration); | |||
13850 | ||||
13851 | // There are five cases here. | |||
13852 | // - There's no scope specifier and we're in a local class. Only look | |||
13853 | // for functions declared in the immediately-enclosing block scope. | |||
13854 | // We recover from invalid scope qualifiers as if they just weren't there. | |||
13855 | FunctionDecl *FunctionContainingLocalClass = nullptr; | |||
13856 | if ((SS.isInvalid() || !SS.isSet()) && | |||
13857 | (FunctionContainingLocalClass = | |||
13858 | cast<CXXRecordDecl>(CurContext)->isLocalClass())) { | |||
13859 | // C++11 [class.friend]p11: | |||
13860 | // If a friend declaration appears in a local class and the name | |||
13861 | // specified is an unqualified name, a prior declaration is | |||
13862 | // looked up without considering scopes that are outside the | |||
13863 | // innermost enclosing non-class scope. For a friend function | |||
13864 | // declaration, if there is no prior declaration, the program is | |||
13865 | // ill-formed. | |||
13866 | ||||
13867 | // Find the innermost enclosing non-class scope. This is the block | |||
13868 | // scope containing the local class definition (or for a nested class, | |||
13869 | // the outer local class). | |||
13870 | DCScope = S->getFnParent(); | |||
13871 | ||||
13872 | // Look up the function name in the scope. | |||
13873 | Previous.clear(LookupLocalFriendName); | |||
13874 | LookupName(Previous, S, /*AllowBuiltinCreation*/false); | |||
13875 | ||||
13876 | if (!Previous.empty()) { | |||
13877 | // All possible previous declarations must have the same context: | |||
13878 | // either they were declared at block scope or they are members of | |||
13879 | // one of the enclosing local classes. | |||
13880 | DC = Previous.getRepresentativeDecl()->getDeclContext(); | |||
13881 | } else { | |||
13882 | // This is ill-formed, but provide the context that we would have | |||
13883 | // declared the function in, if we were permitted to, for error recovery. | |||
13884 | DC = FunctionContainingLocalClass; | |||
13885 | } | |||
13886 | adjustContextForLocalExternDecl(DC); | |||
13887 | ||||
13888 | // C++ [class.friend]p6: | |||
13889 | // A function can be defined in a friend declaration of a class if and | |||
13890 | // only if the class is a non-local class (9.8), the function name is | |||
13891 | // unqualified, and the function has namespace scope. | |||
13892 | if (D.isFunctionDefinition()) { | |||
13893 | Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); | |||
13894 | } | |||
13895 | ||||
13896 | // - There's no scope specifier, in which case we just go to the | |||
13897 | // appropriate scope and look for a function or function template | |||
13898 | // there as appropriate. | |||
13899 | } else if (SS.isInvalid() || !SS.isSet()) { | |||
13900 | // C++11 [namespace.memdef]p3: | |||
13901 | // If the name in a friend declaration is neither qualified nor | |||
13902 | // a template-id and the declaration is a function or an | |||
13903 | // elaborated-type-specifier, the lookup to determine whether | |||
13904 | // the entity has been previously declared shall not consider | |||
13905 | // any scopes outside the innermost enclosing namespace. | |||
13906 | bool isTemplateId = | |||
13907 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; | |||
13908 | ||||
13909 | // Find the appropriate context according to the above. | |||
13910 | DC = CurContext; | |||
13911 | ||||
13912 | // Skip class contexts. If someone can cite chapter and verse | |||
13913 | // for this behavior, that would be nice --- it's what GCC and | |||
13914 | // EDG do, and it seems like a reasonable intent, but the spec | |||
13915 | // really only says that checks for unqualified existing | |||
13916 | // declarations should stop at the nearest enclosing namespace, | |||
13917 | // not that they should only consider the nearest enclosing | |||
13918 | // namespace. | |||
13919 | while (DC->isRecord()) | |||
13920 | DC = DC->getParent(); | |||
13921 | ||||
13922 | DeclContext *LookupDC = DC; | |||
13923 | while (LookupDC->isTransparentContext()) | |||
13924 | LookupDC = LookupDC->getParent(); | |||
13925 | ||||
13926 | while (true) { | |||
13927 | LookupQualifiedName(Previous, LookupDC); | |||
13928 | ||||
13929 | if (!Previous.empty()) { | |||
13930 | DC = LookupDC; | |||
13931 | break; | |||
13932 | } | |||
13933 | ||||
13934 | if (isTemplateId) { | |||
13935 | if (isa<TranslationUnitDecl>(LookupDC)) break; | |||
13936 | } else { | |||
13937 | if (LookupDC->isFileContext()) break; | |||
13938 | } | |||
13939 | LookupDC = LookupDC->getParent(); | |||
13940 | } | |||
13941 | ||||
13942 | DCScope = getScopeForDeclContext(S, DC); | |||
13943 | ||||
13944 | // - There's a non-dependent scope specifier, in which case we | |||
13945 | // compute it and do a previous lookup there for a function | |||
13946 | // or function template. | |||
13947 | } else if (!SS.getScopeRep()->isDependent()) { | |||
13948 | DC = computeDeclContext(SS); | |||
13949 | if (!DC) return nullptr; | |||
13950 | ||||
13951 | if (RequireCompleteDeclContext(SS, DC)) return nullptr; | |||
13952 | ||||
13953 | LookupQualifiedName(Previous, DC); | |||
13954 | ||||
13955 | // Ignore things found implicitly in the wrong scope. | |||
13956 | // TODO: better diagnostics for this case. Suggesting the right | |||
13957 | // qualified scope would be nice... | |||
13958 | LookupResult::Filter F = Previous.makeFilter(); | |||
13959 | while (F.hasNext()) { | |||
13960 | NamedDecl *D = F.next(); | |||
13961 | if (!DC->InEnclosingNamespaceSetOf( | |||
13962 | D->getDeclContext()->getRedeclContext())) | |||
13963 | F.erase(); | |||
13964 | } | |||
13965 | F.done(); | |||
13966 | ||||
13967 | if (Previous.empty()) { | |||
13968 | D.setInvalidType(); | |||
13969 | Diag(Loc, diag::err_qualified_friend_not_found) | |||
13970 | << Name << TInfo->getType(); | |||
13971 | return nullptr; | |||
13972 | } | |||
13973 | ||||
13974 | // C++ [class.friend]p1: A friend of a class is a function or | |||
13975 | // class that is not a member of the class . . . | |||
13976 | if (DC->Equals(CurContext)) | |||
13977 | Diag(DS.getFriendSpecLoc(), | |||
13978 | getLangOpts().CPlusPlus11 ? | |||
13979 | diag::warn_cxx98_compat_friend_is_member : | |||
13980 | diag::err_friend_is_member); | |||
13981 | ||||
13982 | if (D.isFunctionDefinition()) { | |||
13983 | // C++ [class.friend]p6: | |||
13984 | // A function can be defined in a friend declaration of a class if and | |||
13985 | // only if the class is a non-local class (9.8), the function name is | |||
13986 | // unqualified, and the function has namespace scope. | |||
13987 | SemaDiagnosticBuilder DB | |||
13988 | = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); | |||
13989 | ||||
13990 | DB << SS.getScopeRep(); | |||
13991 | if (DC->isFileContext()) | |||
13992 | DB << FixItHint::CreateRemoval(SS.getRange()); | |||
13993 | SS.clear(); | |||
13994 | } | |||
13995 | ||||
13996 | // - There's a scope specifier that does not match any template | |||
13997 | // parameter lists, in which case we use some arbitrary context, | |||
13998 | // create a method or method template, and wait for instantiation. | |||
13999 | // - There's a scope specifier that does match some template | |||
14000 | // parameter lists, which we don't handle right now. | |||
14001 | } else { | |||
14002 | if (D.isFunctionDefinition()) { | |||
14003 | // C++ [class.friend]p6: | |||
14004 | // A function can be defined in a friend declaration of a class if and | |||
14005 | // only if the class is a non-local class (9.8), the function name is | |||
14006 | // unqualified, and the function has namespace scope. | |||
14007 | Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) | |||
14008 | << SS.getScopeRep(); | |||
14009 | } | |||
14010 | ||||
14011 | DC = CurContext; | |||
14012 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14012, __extension__ __PRETTY_FUNCTION__)); | |||
14013 | } | |||
14014 | ||||
14015 | if (!DC->isRecord()) { | |||
14016 | int DiagArg = -1; | |||
14017 | switch (D.getName().getKind()) { | |||
14018 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
14019 | case UnqualifiedIdKind::IK_ConstructorName: | |||
14020 | DiagArg = 0; | |||
14021 | break; | |||
14022 | case UnqualifiedIdKind::IK_DestructorName: | |||
14023 | DiagArg = 1; | |||
14024 | break; | |||
14025 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
14026 | DiagArg = 2; | |||
14027 | break; | |||
14028 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
14029 | DiagArg = 3; | |||
14030 | break; | |||
14031 | case UnqualifiedIdKind::IK_Identifier: | |||
14032 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
14033 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
14034 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
14035 | case UnqualifiedIdKind::IK_TemplateId: | |||
14036 | break; | |||
14037 | } | |||
14038 | // This implies that it has to be an operator or function. | |||
14039 | if (DiagArg >= 0) { | |||
14040 | Diag(Loc, diag::err_introducing_special_friend) << DiagArg; | |||
14041 | return nullptr; | |||
14042 | } | |||
14043 | } | |||
14044 | ||||
14045 | // FIXME: This is an egregious hack to cope with cases where the scope stack | |||
14046 | // does not contain the declaration context, i.e., in an out-of-line | |||
14047 | // definition of a class. | |||
14048 | Scope FakeDCScope(S, Scope::DeclScope, Diags); | |||
14049 | if (!DCScope) { | |||
14050 | FakeDCScope.setEntity(DC); | |||
14051 | DCScope = &FakeDCScope; | |||
14052 | } | |||
14053 | ||||
14054 | bool AddToScope = true; | |||
14055 | NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, | |||
14056 | TemplateParams, AddToScope); | |||
14057 | if (!ND) return nullptr; | |||
14058 | ||||
14059 | assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext ) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14059, __extension__ __PRETTY_FUNCTION__)); | |||
14060 | ||||
14061 | // If we performed typo correction, we might have added a scope specifier | |||
14062 | // and changed the decl context. | |||
14063 | DC = ND->getDeclContext(); | |||
14064 | ||||
14065 | // Add the function declaration to the appropriate lookup tables, | |||
14066 | // adjusting the redeclarations list as necessary. We don't | |||
14067 | // want to do this yet if the friending class is dependent. | |||
14068 | // | |||
14069 | // Also update the scope-based lookup if the target context's | |||
14070 | // lookup context is in lexical scope. | |||
14071 | if (!CurContext->isDependentContext()) { | |||
14072 | DC = DC->getRedeclContext(); | |||
14073 | DC->makeDeclVisibleInContext(ND); | |||
14074 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | |||
14075 | PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); | |||
14076 | } | |||
14077 | ||||
14078 | FriendDecl *FrD = FriendDecl::Create(Context, CurContext, | |||
14079 | D.getIdentifierLoc(), ND, | |||
14080 | DS.getFriendSpecLoc()); | |||
14081 | FrD->setAccess(AS_public); | |||
14082 | CurContext->addDecl(FrD); | |||
14083 | ||||
14084 | if (ND->isInvalidDecl()) { | |||
14085 | FrD->setInvalidDecl(); | |||
14086 | } else { | |||
14087 | if (DC->isRecord()) CheckFriendAccess(ND); | |||
14088 | ||||
14089 | FunctionDecl *FD; | |||
14090 | if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) | |||
14091 | FD = FTD->getTemplatedDecl(); | |||
14092 | else | |||
14093 | FD = cast<FunctionDecl>(ND); | |||
14094 | ||||
14095 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a | |||
14096 | // default argument expression, that declaration shall be a definition | |||
14097 | // and shall be the only declaration of the function or function | |||
14098 | // template in the translation unit. | |||
14099 | if (functionDeclHasDefaultArgument(FD)) { | |||
14100 | // We can't look at FD->getPreviousDecl() because it may not have been set | |||
14101 | // if we're in a dependent context. If the function is known to be a | |||
14102 | // redeclaration, we will have narrowed Previous down to the right decl. | |||
14103 | if (D.isRedeclaration()) { | |||
14104 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); | |||
14105 | Diag(Previous.getRepresentativeDecl()->getLocation(), | |||
14106 | diag::note_previous_declaration); | |||
14107 | } else if (!D.isFunctionDefinition()) | |||
14108 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); | |||
14109 | } | |||
14110 | ||||
14111 | // Mark templated-scope function declarations as unsupported. | |||
14112 | if (FD->getNumTemplateParameterLists() && SS.isValid()) { | |||
14113 | Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) | |||
14114 | << SS.getScopeRep() << SS.getRange() | |||
14115 | << cast<CXXRecordDecl>(CurContext); | |||
14116 | FrD->setUnsupportedFriend(true); | |||
14117 | } | |||
14118 | } | |||
14119 | ||||
14120 | return ND; | |||
14121 | } | |||
14122 | ||||
14123 | void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { | |||
14124 | AdjustDeclIfTemplate(Dcl); | |||
14125 | ||||
14126 | FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); | |||
14127 | if (!Fn) { | |||
14128 | Diag(DelLoc, diag::err_deleted_non_function); | |||
14129 | return; | |||
14130 | } | |||
14131 | ||||
14132 | // Deleted function does not have a body. | |||
14133 | Fn->setWillHaveBody(false); | |||
14134 | ||||
14135 | if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { | |||
14136 | // Don't consider the implicit declaration we generate for explicit | |||
14137 | // specializations. FIXME: Do not generate these implicit declarations. | |||
14138 | if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || | |||
14139 | Prev->getPreviousDecl()) && | |||
14140 | !Prev->isDefined()) { | |||
14141 | Diag(DelLoc, diag::err_deleted_decl_not_first); | |||
14142 | Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), | |||
14143 | Prev->isImplicit() ? diag::note_previous_implicit_declaration | |||
14144 | : diag::note_previous_declaration); | |||
14145 | } | |||
14146 | // If the declaration wasn't the first, we delete the function anyway for | |||
14147 | // recovery. | |||
14148 | Fn = Fn->getCanonicalDecl(); | |||
14149 | } | |||
14150 | ||||
14151 | // dllimport/dllexport cannot be deleted. | |||
14152 | if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { | |||
14153 | Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; | |||
14154 | Fn->setInvalidDecl(); | |||
14155 | } | |||
14156 | ||||
14157 | if (Fn->isDeleted()) | |||
14158 | return; | |||
14159 | ||||
14160 | // See if we're deleting a function which is already known to override a | |||
14161 | // non-deleted virtual function. | |||
14162 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { | |||
14163 | bool IssuedDiagnostic = false; | |||
14164 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | |||
14165 | if (!(*MD->begin_overridden_methods())->isDeleted()) { | |||
14166 | if (!IssuedDiagnostic) { | |||
14167 | Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); | |||
14168 | IssuedDiagnostic = true; | |||
14169 | } | |||
14170 | Diag(O->getLocation(), diag::note_overridden_virtual_function); | |||
14171 | } | |||
14172 | } | |||
14173 | // If this function was implicitly deleted because it was defaulted, | |||
14174 | // explain why it was deleted. | |||
14175 | if (IssuedDiagnostic && MD->isDefaulted()) | |||
14176 | ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, | |||
14177 | /*Diagnose*/true); | |||
14178 | } | |||
14179 | ||||
14180 | // C++11 [basic.start.main]p3: | |||
14181 | // A program that defines main as deleted [...] is ill-formed. | |||
14182 | if (Fn->isMain()) | |||
14183 | Diag(DelLoc, diag::err_deleted_main); | |||
14184 | ||||
14185 | // C++11 [dcl.fct.def.delete]p4: | |||
14186 | // A deleted function is implicitly inline. | |||
14187 | Fn->setImplicitlyInline(); | |||
14188 | Fn->setDeletedAsWritten(); | |||
14189 | } | |||
14190 | ||||
14191 | void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { | |||
14192 | CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); | |||
14193 | ||||
14194 | if (MD) { | |||
14195 | if (MD->getParent()->isDependentType()) { | |||
14196 | MD->setDefaulted(); | |||
14197 | MD->setExplicitlyDefaulted(); | |||
14198 | return; | |||
14199 | } | |||
14200 | ||||
14201 | CXXSpecialMember Member = getSpecialMember(MD); | |||
14202 | if (Member == CXXInvalid) { | |||
14203 | if (!MD->isInvalidDecl()) | |||
14204 | Diag(DefaultLoc, diag::err_default_special_members); | |||
14205 | return; | |||
14206 | } | |||
14207 | ||||
14208 | MD->setDefaulted(); | |||
14209 | MD->setExplicitlyDefaulted(); | |||
14210 | ||||
14211 | // Unset that we will have a body for this function. We might not, | |||
14212 | // if it turns out to be trivial, and we don't need this marking now | |||
14213 | // that we've marked it as defaulted. | |||
14214 | MD->setWillHaveBody(false); | |||
14215 | ||||
14216 | // If this definition appears within the record, do the checking when | |||
14217 | // the record is complete. | |||
14218 | const FunctionDecl *Primary = MD; | |||
14219 | if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) | |||
14220 | // Ask the template instantiation pattern that actually had the | |||
14221 | // '= default' on it. | |||
14222 | Primary = Pattern; | |||
14223 | ||||
14224 | // If the method was defaulted on its first declaration, we will have | |||
14225 | // already performed the checking in CheckCompletedCXXClass. Such a | |||
14226 | // declaration doesn't trigger an implicit definition. | |||
14227 | if (Primary->getCanonicalDecl()->isDefaulted()) | |||
14228 | return; | |||
14229 | ||||
14230 | CheckExplicitlyDefaultedSpecialMember(MD); | |||
14231 | ||||
14232 | if (!MD->isInvalidDecl()) | |||
14233 | DefineImplicitSpecialMember(*this, MD, DefaultLoc); | |||
14234 | } else { | |||
14235 | Diag(DefaultLoc, diag::err_default_special_members); | |||
14236 | } | |||
14237 | } | |||
14238 | ||||
14239 | static void SearchForReturnInStmt(Sema &Self, Stmt *S) { | |||
14240 | for (Stmt *SubStmt : S->children()) { | |||
14241 | if (!SubStmt) | |||
14242 | continue; | |||
14243 | if (isa<ReturnStmt>(SubStmt)) | |||
14244 | Self.Diag(SubStmt->getLocStart(), | |||
14245 | diag::err_return_in_constructor_handler); | |||
14246 | if (!isa<Expr>(SubStmt)) | |||
14247 | SearchForReturnInStmt(Self, SubStmt); | |||
14248 | } | |||
14249 | } | |||
14250 | ||||
14251 | void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { | |||
14252 | for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { | |||
14253 | CXXCatchStmt *Handler = TryBlock->getHandler(I); | |||
14254 | SearchForReturnInStmt(*this, Handler); | |||
14255 | } | |||
14256 | } | |||
14257 | ||||
14258 | bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, | |||
14259 | const CXXMethodDecl *Old) { | |||
14260 | const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); | |||
14261 | const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); | |||
14262 | ||||
14263 | if (OldFT->hasExtParameterInfos()) { | |||
14264 | for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) | |||
14265 | // A parameter of the overriding method should be annotated with noescape | |||
14266 | // if the corresponding parameter of the overridden method is annotated. | |||
14267 | if (OldFT->getExtParameterInfo(I).isNoEscape() && | |||
14268 | !NewFT->getExtParameterInfo(I).isNoEscape()) { | |||
14269 | Diag(New->getParamDecl(I)->getLocation(), | |||
14270 | diag::warn_overriding_method_missing_noescape); | |||
14271 | Diag(Old->getParamDecl(I)->getLocation(), | |||
14272 | diag::note_overridden_marked_noescape); | |||
14273 | } | |||
14274 | } | |||
14275 | ||||
14276 | CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); | |||
14277 | ||||
14278 | // If the calling conventions match, everything is fine | |||
14279 | if (NewCC == OldCC) | |||
14280 | return false; | |||
14281 | ||||
14282 | // If the calling conventions mismatch because the new function is static, | |||
14283 | // suppress the calling convention mismatch error; the error about static | |||
14284 | // function override (err_static_overrides_virtual from | |||
14285 | // Sema::CheckFunctionDeclaration) is more clear. | |||
14286 | if (New->getStorageClass() == SC_Static) | |||
14287 | return false; | |||
14288 | ||||
14289 | Diag(New->getLocation(), | |||
14290 | diag::err_conflicting_overriding_cc_attributes) | |||
14291 | << New->getDeclName() << New->getType() << Old->getType(); | |||
14292 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); | |||
14293 | return true; | |||
14294 | } | |||
14295 | ||||
14296 | bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, | |||
14297 | const CXXMethodDecl *Old) { | |||
14298 | QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); | |||
14299 | QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); | |||
14300 | ||||
14301 | if (Context.hasSameType(NewTy, OldTy) || | |||
14302 | NewTy->isDependentType() || OldTy->isDependentType()) | |||
14303 | return false; | |||
14304 | ||||
14305 | // Check if the return types are covariant | |||
14306 | QualType NewClassTy, OldClassTy; | |||
14307 | ||||
14308 | /// Both types must be pointers or references to classes. | |||
14309 | if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { | |||
14310 | if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { | |||
14311 | NewClassTy = NewPT->getPointeeType(); | |||
14312 | OldClassTy = OldPT->getPointeeType(); | |||
14313 | } | |||
14314 | } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { | |||
14315 | if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { | |||
14316 | if (NewRT->getTypeClass() == OldRT->getTypeClass()) { | |||
14317 | NewClassTy = NewRT->getPointeeType(); | |||
14318 | OldClassTy = OldRT->getPointeeType(); | |||
14319 | } | |||
14320 | } | |||
14321 | } | |||
14322 | ||||
14323 | // The return types aren't either both pointers or references to a class type. | |||
14324 | if (NewClassTy.isNull()) { | |||
14325 | Diag(New->getLocation(), | |||
14326 | diag::err_different_return_type_for_overriding_virtual_function) | |||
14327 | << New->getDeclName() << NewTy << OldTy | |||
14328 | << New->getReturnTypeSourceRange(); | |||
14329 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14330 | << Old->getReturnTypeSourceRange(); | |||
14331 | ||||
14332 | return true; | |||
14333 | } | |||
14334 | ||||
14335 | if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { | |||
14336 | // C++14 [class.virtual]p8: | |||
14337 | // If the class type in the covariant return type of D::f differs from | |||
14338 | // that of B::f, the class type in the return type of D::f shall be | |||
14339 | // complete at the point of declaration of D::f or shall be the class | |||
14340 | // type D. | |||
14341 | if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { | |||
14342 | if (!RT->isBeingDefined() && | |||
14343 | RequireCompleteType(New->getLocation(), NewClassTy, | |||
14344 | diag::err_covariant_return_incomplete, | |||
14345 | New->getDeclName())) | |||
14346 | return true; | |||
14347 | } | |||
14348 | ||||
14349 | // Check if the new class derives from the old class. | |||
14350 | if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { | |||
14351 | Diag(New->getLocation(), diag::err_covariant_return_not_derived) | |||
14352 | << New->getDeclName() << NewTy << OldTy | |||
14353 | << New->getReturnTypeSourceRange(); | |||
14354 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14355 | << Old->getReturnTypeSourceRange(); | |||
14356 | return true; | |||
14357 | } | |||
14358 | ||||
14359 | // Check if we the conversion from derived to base is valid. | |||
14360 | if (CheckDerivedToBaseConversion( | |||
14361 | NewClassTy, OldClassTy, | |||
14362 | diag::err_covariant_return_inaccessible_base, | |||
14363 | diag::err_covariant_return_ambiguous_derived_to_base_conv, | |||
14364 | New->getLocation(), New->getReturnTypeSourceRange(), | |||
14365 | New->getDeclName(), nullptr)) { | |||
14366 | // FIXME: this note won't trigger for delayed access control | |||
14367 | // diagnostics, and it's impossible to get an undelayed error | |||
14368 | // here from access control during the original parse because | |||
14369 | // the ParsingDeclSpec/ParsingDeclarator are still in scope. | |||
14370 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14371 | << Old->getReturnTypeSourceRange(); | |||
14372 | return true; | |||
14373 | } | |||
14374 | } | |||
14375 | ||||
14376 | // The qualifiers of the return types must be the same. | |||
14377 | if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { | |||
14378 | Diag(New->getLocation(), | |||
14379 | diag::err_covariant_return_type_different_qualifications) | |||
14380 | << New->getDeclName() << NewTy << OldTy | |||
14381 | << New->getReturnTypeSourceRange(); | |||
14382 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14383 | << Old->getReturnTypeSourceRange(); | |||
14384 | return true; | |||
14385 | } | |||
14386 | ||||
14387 | ||||
14388 | // The new class type must have the same or less qualifiers as the old type. | |||
14389 | if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { | |||
14390 | Diag(New->getLocation(), | |||
14391 | diag::err_covariant_return_type_class_type_more_qualified) | |||
14392 | << New->getDeclName() << NewTy << OldTy | |||
14393 | << New->getReturnTypeSourceRange(); | |||
14394 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14395 | << Old->getReturnTypeSourceRange(); | |||
14396 | return true; | |||
14397 | } | |||
14398 | ||||
14399 | return false; | |||
14400 | } | |||
14401 | ||||
14402 | /// \brief Mark the given method pure. | |||
14403 | /// | |||
14404 | /// \param Method the method to be marked pure. | |||
14405 | /// | |||
14406 | /// \param InitRange the source range that covers the "0" initializer. | |||
14407 | bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { | |||
14408 | SourceLocation EndLoc = InitRange.getEnd(); | |||
14409 | if (EndLoc.isValid()) | |||
14410 | Method->setRangeEnd(EndLoc); | |||
14411 | ||||
14412 | if (Method->isVirtual() || Method->getParent()->isDependentContext()) { | |||
14413 | Method->setPure(); | |||
14414 | return false; | |||
14415 | } | |||
14416 | ||||
14417 | if (!Method->isInvalidDecl()) | |||
14418 | Diag(Method->getLocation(), diag::err_non_virtual_pure) | |||
14419 | << Method->getDeclName() << InitRange; | |||
14420 | return true; | |||
14421 | } | |||
14422 | ||||
14423 | void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { | |||
14424 | if (D->getFriendObjectKind()) | |||
14425 | Diag(D->getLocation(), diag::err_pure_friend); | |||
14426 | else if (auto *M = dyn_cast<CXXMethodDecl>(D)) | |||
14427 | CheckPureMethod(M, ZeroLoc); | |||
14428 | else | |||
14429 | Diag(D->getLocation(), diag::err_illegal_initializer); | |||
14430 | } | |||
14431 | ||||
14432 | /// \brief Determine whether the given declaration is a global variable or | |||
14433 | /// static data member. | |||
14434 | static bool isNonlocalVariable(const Decl *D) { | |||
14435 | if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) | |||
14436 | return Var->hasGlobalStorage(); | |||
14437 | ||||
14438 | return false; | |||
14439 | } | |||
14440 | ||||
14441 | /// Invoked when we are about to parse an initializer for the declaration | |||
14442 | /// 'Dcl'. | |||
14443 | /// | |||
14444 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a | |||
14445 | /// static data member of class X, names should be looked up in the scope of | |||
14446 | /// class X. If the declaration had a scope specifier, a scope will have | |||
14447 | /// been created and passed in for this purpose. Otherwise, S will be null. | |||
14448 | void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { | |||
14449 | // If there is no declaration, there was an error parsing it. | |||
14450 | if (!D || D->isInvalidDecl()) | |||
14451 | return; | |||
14452 | ||||
14453 | // We will always have a nested name specifier here, but this declaration | |||
14454 | // might not be out of line if the specifier names the current namespace: | |||
14455 | // extern int n; | |||
14456 | // int ::n = 0; | |||
14457 | if (S && D->isOutOfLine()) | |||
14458 | EnterDeclaratorContext(S, D->getDeclContext()); | |||
14459 | ||||
14460 | // If we are parsing the initializer for a static data member, push a | |||
14461 | // new expression evaluation context that is associated with this static | |||
14462 | // data member. | |||
14463 | if (isNonlocalVariable(D)) | |||
14464 | PushExpressionEvaluationContext( | |||
14465 | ExpressionEvaluationContext::PotentiallyEvaluated, D); | |||
14466 | } | |||
14467 | ||||
14468 | /// Invoked after we are finished parsing an initializer for the declaration D. | |||
14469 | void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { | |||
14470 | // If there is no declaration, there was an error parsing it. | |||
14471 | if (!D || D->isInvalidDecl()) | |||
14472 | return; | |||
14473 | ||||
14474 | if (isNonlocalVariable(D)) | |||
14475 | PopExpressionEvaluationContext(); | |||
14476 | ||||
14477 | if (S && D->isOutOfLine()) | |||
14478 | ExitDeclaratorContext(S); | |||
14479 | } | |||
14480 | ||||
14481 | /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a | |||
14482 | /// C++ if/switch/while/for statement. | |||
14483 | /// e.g: "if (int x = f()) {...}" | |||
14484 | DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { | |||
14485 | // C++ 6.4p2: | |||
14486 | // The declarator shall not specify a function or an array. | |||
14487 | // The type-specifier-seq shall not contain typedef and shall not declare a | |||
14488 | // new class or enumeration. | |||
14489 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14490, __extension__ __PRETTY_FUNCTION__)) | |||
14490 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14490, __extension__ __PRETTY_FUNCTION__)); | |||
14491 | ||||
14492 | Decl *Dcl = ActOnDeclarator(S, D); | |||
14493 | if (!Dcl) | |||
14494 | return true; | |||
14495 | ||||
14496 | if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. | |||
14497 | Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) | |||
14498 | << D.getSourceRange(); | |||
14499 | return true; | |||
14500 | } | |||
14501 | ||||
14502 | return Dcl; | |||
14503 | } | |||
14504 | ||||
14505 | void Sema::LoadExternalVTableUses() { | |||
14506 | if (!ExternalSource) | |||
14507 | return; | |||
14508 | ||||
14509 | SmallVector<ExternalVTableUse, 4> VTables; | |||
14510 | ExternalSource->ReadUsedVTables(VTables); | |||
14511 | SmallVector<VTableUse, 4> NewUses; | |||
14512 | for (unsigned I = 0, N = VTables.size(); I != N; ++I) { | |||
14513 | llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos | |||
14514 | = VTablesUsed.find(VTables[I].Record); | |||
14515 | // Even if a definition wasn't required before, it may be required now. | |||
14516 | if (Pos != VTablesUsed.end()) { | |||
14517 | if (!Pos->second && VTables[I].DefinitionRequired) | |||
14518 | Pos->second = true; | |||
14519 | continue; | |||
14520 | } | |||
14521 | ||||
14522 | VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; | |||
14523 | NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); | |||
14524 | } | |||
14525 | ||||
14526 | VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); | |||
14527 | } | |||
14528 | ||||
14529 | void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, | |||
14530 | bool DefinitionRequired) { | |||
14531 | // Ignore any vtable uses in unevaluated operands or for classes that do | |||
14532 | // not have a vtable. | |||
14533 | if (!Class->isDynamicClass() || Class->isDependentContext() || | |||
14534 | CurContext->isDependentContext() || isUnevaluatedContext()) | |||
14535 | return; | |||
14536 | ||||
14537 | // Try to insert this class into the map. | |||
14538 | LoadExternalVTableUses(); | |||
14539 | Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); | |||
14540 | std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> | |||
14541 | Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); | |||
14542 | if (!Pos.second) { | |||
14543 | // If we already had an entry, check to see if we are promoting this vtable | |||
14544 | // to require a definition. If so, we need to reappend to the VTableUses | |||
14545 | // list, since we may have already processed the first entry. | |||
14546 | if (DefinitionRequired && !Pos.first->second) { | |||
14547 | Pos.first->second = true; | |||
14548 | } else { | |||
14549 | // Otherwise, we can early exit. | |||
14550 | return; | |||
14551 | } | |||
14552 | } else { | |||
14553 | // The Microsoft ABI requires that we perform the destructor body | |||
14554 | // checks (i.e. operator delete() lookup) when the vtable is marked used, as | |||
14555 | // the deleting destructor is emitted with the vtable, not with the | |||
14556 | // destructor definition as in the Itanium ABI. | |||
14557 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
14558 | CXXDestructorDecl *DD = Class->getDestructor(); | |||
14559 | if (DD && DD->isVirtual() && !DD->isDeleted()) { | |||
14560 | if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { | |||
14561 | // If this is an out-of-line declaration, marking it referenced will | |||
14562 | // not do anything. Manually call CheckDestructor to look up operator | |||
14563 | // delete(). | |||
14564 | ContextRAII SavedContext(*this, DD); | |||
14565 | CheckDestructor(DD); | |||
14566 | } else { | |||
14567 | MarkFunctionReferenced(Loc, Class->getDestructor()); | |||
14568 | } | |||
14569 | } | |||
14570 | } | |||
14571 | } | |||
14572 | ||||
14573 | // Local classes need to have their virtual members marked | |||
14574 | // immediately. For all other classes, we mark their virtual members | |||
14575 | // at the end of the translation unit. | |||
14576 | if (Class->isLocalClass()) | |||
14577 | MarkVirtualMembersReferenced(Loc, Class); | |||
14578 | else | |||
14579 | VTableUses.push_back(std::make_pair(Class, Loc)); | |||
14580 | } | |||
14581 | ||||
14582 | bool Sema::DefineUsedVTables() { | |||
14583 | LoadExternalVTableUses(); | |||
14584 | if (VTableUses.empty()) | |||
14585 | return false; | |||
14586 | ||||
14587 | // Note: The VTableUses vector could grow as a result of marking | |||
14588 | // the members of a class as "used", so we check the size each | |||
14589 | // time through the loop and prefer indices (which are stable) to | |||
14590 | // iterators (which are not). | |||
14591 | bool DefinedAnything = false; | |||
14592 | for (unsigned I = 0; I != VTableUses.size(); ++I) { | |||
14593 | CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); | |||
14594 | if (!Class) | |||
14595 | continue; | |||
14596 | TemplateSpecializationKind ClassTSK = | |||
14597 | Class->getTemplateSpecializationKind(); | |||
14598 | ||||
14599 | SourceLocation Loc = VTableUses[I].second; | |||
14600 | ||||
14601 | bool DefineVTable = true; | |||
14602 | ||||
14603 | // If this class has a key function, but that key function is | |||
14604 | // defined in another translation unit, we don't need to emit the | |||
14605 | // vtable even though we're using it. | |||
14606 | const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); | |||
14607 | if (KeyFunction && !KeyFunction->hasBody()) { | |||
14608 | // The key function is in another translation unit. | |||
14609 | DefineVTable = false; | |||
14610 | TemplateSpecializationKind TSK = | |||
14611 | KeyFunction->getTemplateSpecializationKind(); | |||
14612 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14614, __extension__ __PRETTY_FUNCTION__)) | |||
14613 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14614, __extension__ __PRETTY_FUNCTION__)) | |||
14614 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14614, __extension__ __PRETTY_FUNCTION__)); | |||
14615 | (void)TSK; | |||
14616 | } else if (!KeyFunction) { | |||
14617 | // If we have a class with no key function that is the subject | |||
14618 | // of an explicit instantiation declaration, suppress the | |||
14619 | // vtable; it will live with the explicit instantiation | |||
14620 | // definition. | |||
14621 | bool IsExplicitInstantiationDeclaration = | |||
14622 | ClassTSK == TSK_ExplicitInstantiationDeclaration; | |||
14623 | for (auto R : Class->redecls()) { | |||
14624 | TemplateSpecializationKind TSK | |||
14625 | = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); | |||
14626 | if (TSK == TSK_ExplicitInstantiationDeclaration) | |||
14627 | IsExplicitInstantiationDeclaration = true; | |||
14628 | else if (TSK == TSK_ExplicitInstantiationDefinition) { | |||
14629 | IsExplicitInstantiationDeclaration = false; | |||
14630 | break; | |||
14631 | } | |||
14632 | } | |||
14633 | ||||
14634 | if (IsExplicitInstantiationDeclaration) | |||
14635 | DefineVTable = false; | |||
14636 | } | |||
14637 | ||||
14638 | // The exception specifications for all virtual members may be needed even | |||
14639 | // if we are not providing an authoritative form of the vtable in this TU. | |||
14640 | // We may choose to emit it available_externally anyway. | |||
14641 | if (!DefineVTable) { | |||
14642 | MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); | |||
14643 | continue; | |||
14644 | } | |||
14645 | ||||
14646 | // Mark all of the virtual members of this class as referenced, so | |||
14647 | // that we can build a vtable. Then, tell the AST consumer that a | |||
14648 | // vtable for this class is required. | |||
14649 | DefinedAnything = true; | |||
14650 | MarkVirtualMembersReferenced(Loc, Class); | |||
14651 | CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); | |||
14652 | if (VTablesUsed[Canonical]) | |||
14653 | Consumer.HandleVTable(Class); | |||
14654 | ||||
14655 | // Warn if we're emitting a weak vtable. The vtable will be weak if there is | |||
14656 | // no key function or the key function is inlined. Don't warn in C++ ABIs | |||
14657 | // that lack key functions, since the user won't be able to make one. | |||
14658 | if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && | |||
14659 | Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { | |||
14660 | const FunctionDecl *KeyFunctionDef = nullptr; | |||
14661 | if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && | |||
14662 | KeyFunctionDef->isInlined())) { | |||
14663 | Diag(Class->getLocation(), | |||
14664 | ClassTSK == TSK_ExplicitInstantiationDefinition | |||
14665 | ? diag::warn_weak_template_vtable | |||
14666 | : diag::warn_weak_vtable) | |||
14667 | << Class; | |||
14668 | } | |||
14669 | } | |||
14670 | } | |||
14671 | VTableUses.clear(); | |||
14672 | ||||
14673 | return DefinedAnything; | |||
14674 | } | |||
14675 | ||||
14676 | void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, | |||
14677 | const CXXRecordDecl *RD) { | |||
14678 | for (const auto *I : RD->methods()) | |||
14679 | if (I->isVirtual() && !I->isPure()) | |||
14680 | ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); | |||
14681 | } | |||
14682 | ||||
14683 | void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, | |||
14684 | const CXXRecordDecl *RD) { | |||
14685 | // Mark all functions which will appear in RD's vtable as used. | |||
14686 | CXXFinalOverriderMap FinalOverriders; | |||
14687 | RD->getFinalOverriders(FinalOverriders); | |||
14688 | for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), | |||
14689 | E = FinalOverriders.end(); | |||
14690 | I != E; ++I) { | |||
14691 | for (OverridingMethods::const_iterator OI = I->second.begin(), | |||
14692 | OE = I->second.end(); | |||
14693 | OI != OE; ++OI) { | |||
14694 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14694, __extension__ __PRETTY_FUNCTION__)); | |||
14695 | CXXMethodDecl *Overrider = OI->second.front().Method; | |||
14696 | ||||
14697 | // C++ [basic.def.odr]p2: | |||
14698 | // [...] A virtual member function is used if it is not pure. [...] | |||
14699 | if (!Overrider->isPure()) | |||
14700 | MarkFunctionReferenced(Loc, Overrider); | |||
14701 | } | |||
14702 | } | |||
14703 | ||||
14704 | // Only classes that have virtual bases need a VTT. | |||
14705 | if (RD->getNumVBases() == 0) | |||
14706 | return; | |||
14707 | ||||
14708 | for (const auto &I : RD->bases()) { | |||
14709 | const CXXRecordDecl *Base = | |||
14710 | cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); | |||
14711 | if (Base->getNumVBases() == 0) | |||
14712 | continue; | |||
14713 | MarkVirtualMembersReferenced(Loc, Base); | |||
14714 | } | |||
14715 | } | |||
14716 | ||||
14717 | /// SetIvarInitializers - This routine builds initialization ASTs for the | |||
14718 | /// Objective-C implementation whose ivars need be initialized. | |||
14719 | void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { | |||
14720 | if (!getLangOpts().CPlusPlus) | |||
14721 | return; | |||
14722 | if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { | |||
14723 | SmallVector<ObjCIvarDecl*, 8> ivars; | |||
14724 | CollectIvarsToConstructOrDestruct(OID, ivars); | |||
14725 | if (ivars.empty()) | |||
14726 | return; | |||
14727 | SmallVector<CXXCtorInitializer*, 32> AllToInit; | |||
14728 | for (unsigned i = 0; i < ivars.size(); i++) { | |||
14729 | FieldDecl *Field = ivars[i]; | |||
14730 | if (Field->isInvalidDecl()) | |||
14731 | continue; | |||
14732 | ||||
14733 | CXXCtorInitializer *Member; | |||
14734 | InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); | |||
14735 | InitializationKind InitKind = | |||
14736 | InitializationKind::CreateDefault(ObjCImplementation->getLocation()); | |||
14737 | ||||
14738 | InitializationSequence InitSeq(*this, InitEntity, InitKind, None); | |||
14739 | ExprResult MemberInit = | |||
14740 | InitSeq.Perform(*this, InitEntity, InitKind, None); | |||
14741 | MemberInit = MaybeCreateExprWithCleanups(MemberInit); | |||
14742 | // Note, MemberInit could actually come back empty if no initialization | |||
14743 | // is required (e.g., because it would call a trivial default constructor) | |||
14744 | if (!MemberInit.get() || MemberInit.isInvalid()) | |||
14745 | continue; | |||
14746 | ||||
14747 | Member = | |||
14748 | new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), | |||
14749 | SourceLocation(), | |||
14750 | MemberInit.getAs<Expr>(), | |||
14751 | SourceLocation()); | |||
14752 | AllToInit.push_back(Member); | |||
14753 | ||||
14754 | // Be sure that the destructor is accessible and is marked as referenced. | |||
14755 | if (const RecordType *RecordTy = | |||
14756 | Context.getBaseElementType(Field->getType()) | |||
14757 | ->getAs<RecordType>()) { | |||
14758 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
14759 | if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { | |||
14760 | MarkFunctionReferenced(Field->getLocation(), Destructor); | |||
14761 | CheckDestructorAccess(Field->getLocation(), Destructor, | |||
14762 | PDiag(diag::err_access_dtor_ivar) | |||
14763 | << Context.getBaseElementType(Field->getType())); | |||
14764 | } | |||
14765 | } | |||
14766 | } | |||
14767 | ObjCImplementation->setIvarInitializers(Context, | |||
14768 | AllToInit.data(), AllToInit.size()); | |||
14769 | } | |||
14770 | } | |||
14771 | ||||
14772 | static | |||
14773 | void DelegatingCycleHelper(CXXConstructorDecl* Ctor, | |||
14774 | llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, | |||
14775 | llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, | |||
14776 | llvm::SmallSet<CXXConstructorDecl*, 4> &Current, | |||
14777 | Sema &S) { | |||
14778 | if (Ctor->isInvalidDecl()) | |||
14779 | return; | |||
14780 | ||||
14781 | CXXConstructorDecl *Target = Ctor->getTargetConstructor(); | |||
14782 | ||||
14783 | // Target may not be determinable yet, for instance if this is a dependent | |||
14784 | // call in an uninstantiated template. | |||
14785 | if (Target) { | |||
14786 | const FunctionDecl *FNTarget = nullptr; | |||
14787 | (void)Target->hasBody(FNTarget); | |||
14788 | Target = const_cast<CXXConstructorDecl*>( | |||
14789 | cast_or_null<CXXConstructorDecl>(FNTarget)); | |||
14790 | } | |||
14791 | ||||
14792 | CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), | |||
14793 | // Avoid dereferencing a null pointer here. | |||
14794 | *TCanonical = Target? Target->getCanonicalDecl() : nullptr; | |||
14795 | ||||
14796 | if (!Current.insert(Canonical).second) | |||
14797 | return; | |||
14798 | ||||
14799 | // We know that beyond here, we aren't chaining into a cycle. | |||
14800 | if (!Target || !Target->isDelegatingConstructor() || | |||
14801 | Target->isInvalidDecl() || Valid.count(TCanonical)) { | |||
14802 | Valid.insert(Current.begin(), Current.end()); | |||
14803 | Current.clear(); | |||
14804 | // We've hit a cycle. | |||
14805 | } else if (TCanonical == Canonical || Invalid.count(TCanonical) || | |||
14806 | Current.count(TCanonical)) { | |||
14807 | // If we haven't diagnosed this cycle yet, do so now. | |||
14808 | if (!Invalid.count(TCanonical)) { | |||
14809 | S.Diag((*Ctor->init_begin())->getSourceLocation(), | |||
14810 | diag::warn_delegating_ctor_cycle) | |||
14811 | << Ctor; | |||
14812 | ||||
14813 | // Don't add a note for a function delegating directly to itself. | |||
14814 | if (TCanonical != Canonical) | |||
14815 | S.Diag(Target->getLocation(), diag::note_it_delegates_to); | |||
14816 | ||||
14817 | CXXConstructorDecl *C = Target; | |||
14818 | while (C->getCanonicalDecl() != Canonical) { | |||
14819 | const FunctionDecl *FNTarget = nullptr; | |||
14820 | (void)C->getTargetConstructor()->hasBody(FNTarget); | |||
14821 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14821, __extension__ __PRETTY_FUNCTION__)); | |||
14822 | ||||
14823 | C = const_cast<CXXConstructorDecl*>( | |||
14824 | cast<CXXConstructorDecl>(FNTarget)); | |||
14825 | S.Diag(C->getLocation(), diag::note_which_delegates_to); | |||
14826 | } | |||
14827 | } | |||
14828 | ||||
14829 | Invalid.insert(Current.begin(), Current.end()); | |||
14830 | Current.clear(); | |||
14831 | } else { | |||
14832 | DelegatingCycleHelper(Target, Valid, Invalid, Current, S); | |||
14833 | } | |||
14834 | } | |||
14835 | ||||
14836 | ||||
14837 | void Sema::CheckDelegatingCtorCycles() { | |||
14838 | llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; | |||
14839 | ||||
14840 | for (DelegatingCtorDeclsType::iterator | |||
14841 | I = DelegatingCtorDecls.begin(ExternalSource), | |||
14842 | E = DelegatingCtorDecls.end(); | |||
14843 | I != E; ++I) | |||
14844 | DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); | |||
14845 | ||||
14846 | for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), | |||
14847 | CE = Invalid.end(); | |||
14848 | CI != CE; ++CI) | |||
14849 | (*CI)->setInvalidDecl(); | |||
14850 | } | |||
14851 | ||||
14852 | namespace { | |||
14853 | /// \brief AST visitor that finds references to the 'this' expression. | |||
14854 | class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { | |||
14855 | Sema &S; | |||
14856 | ||||
14857 | public: | |||
14858 | explicit FindCXXThisExpr(Sema &S) : S(S) { } | |||
14859 | ||||
14860 | bool VisitCXXThisExpr(CXXThisExpr *E) { | |||
14861 | S.Diag(E->getLocation(), diag::err_this_static_member_func) | |||
14862 | << E->isImplicit(); | |||
14863 | return false; | |||
14864 | } | |||
14865 | }; | |||
14866 | } | |||
14867 | ||||
14868 | bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { | |||
14869 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); | |||
14870 | if (!TSInfo) | |||
14871 | return false; | |||
14872 | ||||
14873 | TypeLoc TL = TSInfo->getTypeLoc(); | |||
14874 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); | |||
14875 | if (!ProtoTL) | |||
14876 | return false; | |||
14877 | ||||
14878 | // C++11 [expr.prim.general]p3: | |||
14879 | // [The expression this] shall not appear before the optional | |||
14880 | // cv-qualifier-seq and it shall not appear within the declaration of a | |||
14881 | // static member function (although its type and value category are defined | |||
14882 | // within a static member function as they are within a non-static member | |||
14883 | // function). [ Note: this is because declaration matching does not occur | |||
14884 | // until the complete declarator is known. - end note ] | |||
14885 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); | |||
14886 | FindCXXThisExpr Finder(*this); | |||
14887 | ||||
14888 | // If the return type came after the cv-qualifier-seq, check it now. | |||
14889 | if (Proto->hasTrailingReturn() && | |||
14890 | !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) | |||
14891 | return true; | |||
14892 | ||||
14893 | // Check the exception specification. | |||
14894 | if (checkThisInStaticMemberFunctionExceptionSpec(Method)) | |||
14895 | return true; | |||
14896 | ||||
14897 | return checkThisInStaticMemberFunctionAttributes(Method); | |||
14898 | } | |||
14899 | ||||
14900 | bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { | |||
14901 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); | |||
14902 | if (!TSInfo) | |||
14903 | return false; | |||
14904 | ||||
14905 | TypeLoc TL = TSInfo->getTypeLoc(); | |||
14906 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); | |||
14907 | if (!ProtoTL) | |||
14908 | return false; | |||
14909 | ||||
14910 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); | |||
14911 | FindCXXThisExpr Finder(*this); | |||
14912 | ||||
14913 | switch (Proto->getExceptionSpecType()) { | |||
14914 | case EST_Unparsed: | |||
14915 | case EST_Uninstantiated: | |||
14916 | case EST_Unevaluated: | |||
14917 | case EST_BasicNoexcept: | |||
14918 | case EST_DynamicNone: | |||
14919 | case EST_MSAny: | |||
14920 | case EST_None: | |||
14921 | break; | |||
14922 | ||||
14923 | case EST_ComputedNoexcept: | |||
14924 | if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) | |||
14925 | return true; | |||
14926 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
14927 | ||||
14928 | case EST_Dynamic: | |||
14929 | for (const auto &E : Proto->exceptions()) { | |||
14930 | if (!Finder.TraverseType(E)) | |||
14931 | return true; | |||
14932 | } | |||
14933 | break; | |||
14934 | } | |||
14935 | ||||
14936 | return false; | |||
14937 | } | |||
14938 | ||||
14939 | bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { | |||
14940 | FindCXXThisExpr Finder(*this); | |||
14941 | ||||
14942 | // Check attributes. | |||
14943 | for (const auto *A : Method->attrs()) { | |||
14944 | // FIXME: This should be emitted by tblgen. | |||
14945 | Expr *Arg = nullptr; | |||
14946 | ArrayRef<Expr *> Args; | |||
14947 | if (const auto *G = dyn_cast<GuardedByAttr>(A)) | |||
14948 | Arg = G->getArg(); | |||
14949 | else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) | |||
14950 | Arg = G->getArg(); | |||
14951 | else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) | |||
14952 | Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); | |||
14953 | else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) | |||
14954 | Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); | |||
14955 | else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { | |||
14956 | Arg = ETLF->getSuccessValue(); | |||
14957 | Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); | |||
14958 | } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { | |||
14959 | Arg = STLF->getSuccessValue(); | |||
14960 | Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); | |||
14961 | } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) | |||
14962 | Arg = LR->getArg(); | |||
14963 | else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) | |||
14964 | Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); | |||
14965 | else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) | |||
14966 | Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); | |||
14967 | else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) | |||
14968 | Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); | |||
14969 | else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) | |||
14970 | Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); | |||
14971 | else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) | |||
14972 | Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); | |||
14973 | ||||
14974 | if (Arg && !Finder.TraverseStmt(Arg)) | |||
14975 | return true; | |||
14976 | ||||
14977 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
14978 | if (!Finder.TraverseStmt(Args[I])) | |||
14979 | return true; | |||
14980 | } | |||
14981 | } | |||
14982 | ||||
14983 | return false; | |||
14984 | } | |||
14985 | ||||
14986 | void Sema::checkExceptionSpecification( | |||
14987 | bool IsTopLevel, ExceptionSpecificationType EST, | |||
14988 | ArrayRef<ParsedType> DynamicExceptions, | |||
14989 | ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, | |||
14990 | SmallVectorImpl<QualType> &Exceptions, | |||
14991 | FunctionProtoType::ExceptionSpecInfo &ESI) { | |||
14992 | Exceptions.clear(); | |||
14993 | ESI.Type = EST; | |||
14994 | if (EST == EST_Dynamic) { | |||
14995 | Exceptions.reserve(DynamicExceptions.size()); | |||
14996 | for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { | |||
14997 | // FIXME: Preserve type source info. | |||
14998 | QualType ET = GetTypeFromParser(DynamicExceptions[ei]); | |||
14999 | ||||
15000 | if (IsTopLevel) { | |||
15001 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; | |||
15002 | collectUnexpandedParameterPacks(ET, Unexpanded); | |||
15003 | if (!Unexpanded.empty()) { | |||
15004 | DiagnoseUnexpandedParameterPacks( | |||
15005 | DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, | |||
15006 | Unexpanded); | |||
15007 | continue; | |||
15008 | } | |||
15009 | } | |||
15010 | ||||
15011 | // Check that the type is valid for an exception spec, and | |||
15012 | // drop it if not. | |||
15013 | if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) | |||
15014 | Exceptions.push_back(ET); | |||
15015 | } | |||
15016 | ESI.Exceptions = Exceptions; | |||
15017 | return; | |||
15018 | } | |||
15019 | ||||
15020 | if (EST == EST_ComputedNoexcept) { | |||
15021 | // If an error occurred, there's no expression here. | |||
15022 | if (NoexceptExpr) { | |||
15023 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15026, __extension__ __PRETTY_FUNCTION__)) | |||
15024 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15026, __extension__ __PRETTY_FUNCTION__)) | |||
15025 | 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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15026, __extension__ __PRETTY_FUNCTION__)) | |||
15026 | "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~svn326246/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15026, __extension__ __PRETTY_FUNCTION__)); | |||
15027 | if (IsTopLevel && NoexceptExpr && | |||
15028 | DiagnoseUnexpandedParameterPack(NoexceptExpr)) { | |||
15029 | ESI.Type = EST_BasicNoexcept; | |||
15030 | return; | |||
15031 | } | |||
15032 | ||||
15033 | if (!NoexceptExpr->isValueDependent()) { | |||
15034 | ExprResult Result = VerifyIntegerConstantExpression( | |||
15035 | NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression, | |||
15036 | /*AllowFold*/ false); | |||
15037 | if (Result.isInvalid()) { | |||
15038 | ESI.Type = EST_BasicNoexcept; | |||
15039 | return; | |||
15040 | } | |||
15041 | NoexceptExpr = Result.get(); | |||
15042 | } | |||
15043 | ESI.NoexceptExpr = NoexceptExpr; | |||
15044 | } | |||
15045 | return; | |||
15046 | } | |||
15047 | } | |||
15048 | ||||
15049 | void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, | |||
15050 | ExceptionSpecificationType EST, | |||
15051 | SourceRange SpecificationRange, | |||
15052 | ArrayRef<ParsedType> DynamicExceptions, | |||
15053 | ArrayRef<SourceRange> DynamicExceptionRanges, | |||
15054 | Expr *NoexceptExpr) { | |||
15055 | if (!MethodD) | |||
15056 | return; | |||
15057 | ||||
15058 | // Dig out the method we're referring to. | |||
15059 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) | |||
15060 | MethodD = FunTmpl->getTemplatedDecl(); | |||
15061 | ||||
15062 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); | |||
15063 | if (!Method) | |||
15064 | return; | |||
15065 | ||||
15066 | // Check the exception specification. | |||
15067 | llvm::SmallVector<QualType, 4> Exceptions; | |||
15068 | FunctionProtoType::ExceptionSpecInfo ESI; | |||
15069 | checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, | |||
15070 | DynamicExceptionRanges, NoexceptExpr, Exceptions, | |||
15071 | ESI); | |||
15072 | ||||
15073 | // Update the exception specification on the function type. | |||
15074 | Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); | |||
15075 | ||||
15076 | if (Method->isStatic()) | |||
15077 | checkThisInStaticMemberFunctionExceptionSpec(Method); | |||
15078 | ||||
15079 | if (Method->isVirtual()) { | |||
15080 | // Check overrides, which we previously had to delay. | |||
15081 | for (const CXXMethodDecl *O : Method->overridden_methods()) | |||
15082 | CheckOverridingFunctionExceptionSpec(Method, O); | |||
15083 | } | |||
15084 | } | |||
15085 | ||||
15086 | /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. | |||
15087 | /// | |||
15088 | MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, | |||
15089 | SourceLocation DeclStart, | |||
15090 | Declarator &D, Expr *BitWidth, | |||
15091 | InClassInitStyle InitStyle, | |||
15092 | AccessSpecifier AS, | |||
15093 | AttributeList *MSPropertyAttr) { | |||
15094 | IdentifierInfo *II = D.getIdentifier(); | |||
15095 | if (!II) { | |||
15096 | Diag(DeclStart, diag::err_anonymous_property); | |||
15097 | return nullptr; | |||
15098 | } | |||
15099 | SourceLocation Loc = D.getIdentifierLoc(); | |||
15100 | ||||
15101 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
15102 | QualType T = TInfo->getType(); | |||
15103 | if (getLangOpts().CPlusPlus) { | |||
15104 | CheckExtraCXXDefaultArguments(D); | |||
15105 | ||||
15106 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
15107 | UPPC_DataMemberType)) { | |||
15108 | D.setInvalidType(); | |||
15109 | T = Context.IntTy; | |||
15110 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
15111 | } | |||
15112 | } | |||
15113 | ||||
15114 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
15115 | ||||
15116 | if (D.getDeclSpec().isInlineSpecified()) | |||
15117 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
15118 | << getLangOpts().CPlusPlus17; | |||
15119 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
15120 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
15121 | diag::err_invalid_thread) | |||
15122 | << DeclSpec::getSpecifierName(TSCS); | |||
15123 | ||||
15124 | // Check to see if this name was declared as a member previously | |||
15125 | NamedDecl *PrevDecl = nullptr; | |||
15126 | LookupResult Previous(*this, II, Loc, LookupMemberName, | |||
15127 | ForVisibleRedeclaration); | |||
15128 | LookupName(Previous, S); | |||
15129 | switch (Previous.getResultKind()) { | |||
15130 | case LookupResult::Found: | |||
15131 | case LookupResult::FoundUnresolvedValue: | |||
15132 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | |||
15133 | break; | |||
15134 | ||||
15135 | case LookupResult::FoundOverloaded: | |||
15136 | PrevDecl = Previous.getRepresentativeDecl(); | |||
15137 | break; | |||
15138 | ||||
15139 | case LookupResult::NotFound: | |||
15140 | case LookupResult::NotFoundInCurrentInstantiation: | |||
15141 | case LookupResult::Ambiguous: | |||
15142 | break; | |||
15143 | } | |||
15144 | ||||
15145 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
15146 | // Maybe we will complain about the shadowed template parameter. | |||
15147 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
15148 | // Just pretend that we didn't see the previous declaration. | |||
15149 | PrevDecl = nullptr; | |||
15150 | } | |||
15151 | ||||
15152 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | |||
15153 | PrevDecl = nullptr; | |||
15154 | ||||
15155 | SourceLocation TSSL = D.getLocStart(); | |||
15156 | const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); | |||
15157 | MSPropertyDecl *NewPD = MSPropertyDecl::Create( | |||
15158 | Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); | |||
15159 | ProcessDeclAttributes(TUScope, NewPD, D); | |||
15160 | NewPD->setAccess(AS); | |||
15161 | ||||
15162 | if (NewPD->isInvalidDecl()) | |||
15163 | Record->setInvalidDecl(); | |||
15164 | ||||
15165 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
15166 | NewPD->setModulePrivate(); | |||
15167 | ||||
15168 | if (NewPD->isInvalidDecl() && PrevDecl) { | |||
15169 | // Don't introduce NewFD into scope; there's already something | |||
15170 | // with the same name in the same scope. | |||
15171 | } else if (II) { | |||
15172 | PushOnScopeChains(NewPD, S); | |||
15173 | } else | |||
15174 | Record->addDecl(NewPD); | |||
15175 | ||||
15176 | return NewPD; | |||
15177 | } |
1 | //===- DeclCXX.h - Classes for representing C++ declarations --*- 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 Defines the C++ Decl subclasses, other than those for templates |
12 | /// (found in DeclTemplate.h) and friends (in DeclFriend.h). |
13 | // |
14 | //===----------------------------------------------------------------------===// |
15 | |
16 | #ifndef LLVM_CLANG_AST_DECLCXX_H |
17 | #define LLVM_CLANG_AST_DECLCXX_H |
18 | |
19 | #include "clang/AST/ASTContext.h" |
20 | #include "clang/AST/ASTUnresolvedSet.h" |
21 | #include "clang/AST/Attr.h" |
22 | #include "clang/AST/Decl.h" |
23 | #include "clang/AST/DeclarationName.h" |
24 | #include "clang/AST/Expr.h" |
25 | #include "clang/AST/ExternalASTSource.h" |
26 | #include "clang/AST/LambdaCapture.h" |
27 | #include "clang/AST/NestedNameSpecifier.h" |
28 | #include "clang/AST/Redeclarable.h" |
29 | #include "clang/AST/Stmt.h" |
30 | #include "clang/AST/Type.h" |
31 | #include "clang/AST/TypeLoc.h" |
32 | #include "clang/AST/UnresolvedSet.h" |
33 | #include "clang/Basic/LLVM.h" |
34 | #include "clang/Basic/Lambda.h" |
35 | #include "clang/Basic/LangOptions.h" |
36 | #include "clang/Basic/OperatorKinds.h" |
37 | #include "clang/Basic/SourceLocation.h" |
38 | #include "clang/Basic/Specifiers.h" |
39 | #include "llvm/ADT/ArrayRef.h" |
40 | #include "llvm/ADT/DenseMap.h" |
41 | #include "llvm/ADT/PointerIntPair.h" |
42 | #include "llvm/ADT/PointerUnion.h" |
43 | #include "llvm/ADT/STLExtras.h" |
44 | #include "llvm/ADT/iterator_range.h" |
45 | #include "llvm/Support/Casting.h" |
46 | #include "llvm/Support/Compiler.h" |
47 | #include "llvm/Support/PointerLikeTypeTraits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include <cassert> |
50 | #include <cstddef> |
51 | #include <iterator> |
52 | #include <memory> |
53 | #include <vector> |
54 | |
55 | namespace clang { |
56 | |
57 | class ClassTemplateDecl; |
58 | class ConstructorUsingShadowDecl; |
59 | class CXXBasePath; |
60 | class CXXBasePaths; |
61 | class CXXConstructorDecl; |
62 | class CXXDestructorDecl; |
63 | class CXXFinalOverriderMap; |
64 | class CXXIndirectPrimaryBaseSet; |
65 | class CXXMethodDecl; |
66 | class DiagnosticBuilder; |
67 | class FriendDecl; |
68 | class FunctionTemplateDecl; |
69 | class IdentifierInfo; |
70 | class MemberSpecializationInfo; |
71 | class TemplateDecl; |
72 | class TemplateParameterList; |
73 | class UsingDecl; |
74 | |
75 | /// \brief Represents any kind of function declaration, whether it is a |
76 | /// concrete function or a function template. |
77 | class AnyFunctionDecl { |
78 | NamedDecl *Function; |
79 | |
80 | AnyFunctionDecl(NamedDecl *ND) : Function(ND) {} |
81 | |
82 | public: |
83 | AnyFunctionDecl(FunctionDecl *FD) : Function(FD) {} |
84 | AnyFunctionDecl(FunctionTemplateDecl *FTD); |
85 | |
86 | /// \brief Implicily converts any function or function template into a |
87 | /// named declaration. |
88 | operator NamedDecl *() const { return Function; } |
89 | |
90 | /// \brief Retrieve the underlying function or function template. |
91 | NamedDecl *get() const { return Function; } |
92 | |
93 | static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) { |
94 | return AnyFunctionDecl(ND); |
95 | } |
96 | }; |
97 | |
98 | } // namespace clang |
99 | |
100 | namespace llvm { |
101 | |
102 | // Provide PointerLikeTypeTraits for non-cvr pointers. |
103 | template<> |
104 | struct PointerLikeTypeTraits< ::clang::AnyFunctionDecl> { |
105 | static void *getAsVoidPointer(::clang::AnyFunctionDecl F) { |
106 | return F.get(); |
107 | } |
108 | |
109 | static ::clang::AnyFunctionDecl getFromVoidPointer(void *P) { |
110 | return ::clang::AnyFunctionDecl::getFromNamedDecl( |
111 | static_cast< ::clang::NamedDecl*>(P)); |
112 | } |
113 | |
114 | enum { NumLowBitsAvailable = 2 }; |
115 | }; |
116 | |
117 | } // namespace llvm |
118 | |
119 | namespace clang { |
120 | |
121 | /// \brief Represents an access specifier followed by colon ':'. |
122 | /// |
123 | /// An objects of this class represents sugar for the syntactic occurrence |
124 | /// of an access specifier followed by a colon in the list of member |
125 | /// specifiers of a C++ class definition. |
126 | /// |
127 | /// Note that they do not represent other uses of access specifiers, |
128 | /// such as those occurring in a list of base specifiers. |
129 | /// Also note that this class has nothing to do with so-called |
130 | /// "access declarations" (C++98 11.3 [class.access.dcl]). |
131 | class AccessSpecDecl : public Decl { |
132 | /// \brief The location of the ':'. |
133 | SourceLocation ColonLoc; |
134 | |
135 | AccessSpecDecl(AccessSpecifier AS, DeclContext *DC, |
136 | SourceLocation ASLoc, SourceLocation ColonLoc) |
137 | : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) { |
138 | setAccess(AS); |
139 | } |
140 | |
141 | AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {} |
142 | |
143 | virtual void anchor(); |
144 | |
145 | public: |
146 | /// \brief The location of the access specifier. |
147 | SourceLocation getAccessSpecifierLoc() const { return getLocation(); } |
148 | |
149 | /// \brief Sets the location of the access specifier. |
150 | void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); } |
151 | |
152 | /// \brief The location of the colon following the access specifier. |
153 | SourceLocation getColonLoc() const { return ColonLoc; } |
154 | |
155 | /// \brief Sets the location of the colon. |
156 | void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; } |
157 | |
158 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
159 | return SourceRange(getAccessSpecifierLoc(), getColonLoc()); |
160 | } |
161 | |
162 | static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS, |
163 | DeclContext *DC, SourceLocation ASLoc, |
164 | SourceLocation ColonLoc) { |
165 | return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc); |
166 | } |
167 | |
168 | static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
169 | |
170 | // Implement isa/cast/dyncast/etc. |
171 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
172 | static bool classofKind(Kind K) { return K == AccessSpec; } |
173 | }; |
174 | |
175 | /// \brief Represents a base class of a C++ class. |
176 | /// |
177 | /// Each CXXBaseSpecifier represents a single, direct base class (or |
178 | /// struct) of a C++ class (or struct). It specifies the type of that |
179 | /// base class, whether it is a virtual or non-virtual base, and what |
180 | /// level of access (public, protected, private) is used for the |
181 | /// derivation. For example: |
182 | /// |
183 | /// \code |
184 | /// class A { }; |
185 | /// class B { }; |
186 | /// class C : public virtual A, protected B { }; |
187 | /// \endcode |
188 | /// |
189 | /// In this code, C will have two CXXBaseSpecifiers, one for "public |
190 | /// virtual A" and the other for "protected B". |
191 | class CXXBaseSpecifier { |
192 | /// \brief The source code range that covers the full base |
193 | /// specifier, including the "virtual" (if present) and access |
194 | /// specifier (if present). |
195 | SourceRange Range; |
196 | |
197 | /// \brief The source location of the ellipsis, if this is a pack |
198 | /// expansion. |
199 | SourceLocation EllipsisLoc; |
200 | |
201 | /// \brief Whether this is a virtual base class or not. |
202 | unsigned Virtual : 1; |
203 | |
204 | /// \brief Whether this is the base of a class (true) or of a struct (false). |
205 | /// |
206 | /// This determines the mapping from the access specifier as written in the |
207 | /// source code to the access specifier used for semantic analysis. |
208 | unsigned BaseOfClass : 1; |
209 | |
210 | /// \brief Access specifier as written in the source code (may be AS_none). |
211 | /// |
212 | /// The actual type of data stored here is an AccessSpecifier, but we use |
213 | /// "unsigned" here to work around a VC++ bug. |
214 | unsigned Access : 2; |
215 | |
216 | /// \brief Whether the class contains a using declaration |
217 | /// to inherit the named class's constructors. |
218 | unsigned InheritConstructors : 1; |
219 | |
220 | /// \brief The type of the base class. |
221 | /// |
222 | /// This will be a class or struct (or a typedef of such). The source code |
223 | /// range does not include the \c virtual or the access specifier. |
224 | TypeSourceInfo *BaseTypeInfo; |
225 | |
226 | public: |
227 | CXXBaseSpecifier() = default; |
228 | CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A, |
229 | TypeSourceInfo *TInfo, SourceLocation EllipsisLoc) |
230 | : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC), |
231 | Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {} |
232 | |
233 | /// \brief Retrieves the source range that contains the entire base specifier. |
234 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
235 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
236 | SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
237 | |
238 | /// \brief Get the location at which the base class type was written. |
239 | SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) { |
240 | return BaseTypeInfo->getTypeLoc().getLocStart(); |
241 | } |
242 | |
243 | /// \brief Determines whether the base class is a virtual base class (or not). |
244 | bool isVirtual() const { return Virtual; } |
245 | |
246 | /// \brief Determine whether this base class is a base of a class declared |
247 | /// with the 'class' keyword (vs. one declared with the 'struct' keyword). |
248 | bool isBaseOfClass() const { return BaseOfClass; } |
249 | |
250 | /// \brief Determine whether this base specifier is a pack expansion. |
251 | bool isPackExpansion() const { return EllipsisLoc.isValid(); } |
252 | |
253 | /// \brief Determine whether this base class's constructors get inherited. |
254 | bool getInheritConstructors() const { return InheritConstructors; } |
255 | |
256 | /// \brief Set that this base class's constructors should be inherited. |
257 | void setInheritConstructors(bool Inherit = true) { |
258 | InheritConstructors = Inherit; |
259 | } |
260 | |
261 | /// \brief For a pack expansion, determine the location of the ellipsis. |
262 | SourceLocation getEllipsisLoc() const { |
263 | return EllipsisLoc; |
264 | } |
265 | |
266 | /// \brief Returns the access specifier for this base specifier. |
267 | /// |
268 | /// This is the actual base specifier as used for semantic analysis, so |
269 | /// the result can never be AS_none. To retrieve the access specifier as |
270 | /// written in the source code, use getAccessSpecifierAsWritten(). |
271 | AccessSpecifier getAccessSpecifier() const { |
272 | if ((AccessSpecifier)Access == AS_none) |
273 | return BaseOfClass? AS_private : AS_public; |
274 | else |
275 | return (AccessSpecifier)Access; |
276 | } |
277 | |
278 | /// \brief Retrieves the access specifier as written in the source code |
279 | /// (which may mean that no access specifier was explicitly written). |
280 | /// |
281 | /// Use getAccessSpecifier() to retrieve the access specifier for use in |
282 | /// semantic analysis. |
283 | AccessSpecifier getAccessSpecifierAsWritten() const { |
284 | return (AccessSpecifier)Access; |
285 | } |
286 | |
287 | /// \brief Retrieves the type of the base class. |
288 | /// |
289 | /// This type will always be an unqualified class type. |
290 | QualType getType() const { |
291 | return BaseTypeInfo->getType().getUnqualifiedType(); |
292 | } |
293 | |
294 | /// \brief Retrieves the type and source location of the base class. |
295 | TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; } |
296 | }; |
297 | |
298 | /// \brief Represents a C++ struct/union/class. |
299 | class CXXRecordDecl : public RecordDecl { |
300 | friend class ASTDeclReader; |
301 | friend class ASTDeclWriter; |
302 | friend class ASTNodeImporter; |
303 | friend class ASTReader; |
304 | friend class ASTRecordWriter; |
305 | friend class ASTWriter; |
306 | friend class DeclContext; |
307 | friend class LambdaExpr; |
308 | |
309 | friend void FunctionDecl::setPure(bool); |
310 | friend void TagDecl::startDefinition(); |
311 | |
312 | /// Values used in DefinitionData fields to represent special members. |
313 | enum SpecialMemberFlags { |
314 | SMF_DefaultConstructor = 0x1, |
315 | SMF_CopyConstructor = 0x2, |
316 | SMF_MoveConstructor = 0x4, |
317 | SMF_CopyAssignment = 0x8, |
318 | SMF_MoveAssignment = 0x10, |
319 | SMF_Destructor = 0x20, |
320 | SMF_All = 0x3f |
321 | }; |
322 | |
323 | struct DefinitionData { |
324 | /// \brief True if this class has any user-declared constructors. |
325 | unsigned UserDeclaredConstructor : 1; |
326 | |
327 | /// \brief The user-declared special members which this class has. |
328 | unsigned UserDeclaredSpecialMembers : 6; |
329 | |
330 | /// \brief True when this class is an aggregate. |
331 | unsigned Aggregate : 1; |
332 | |
333 | /// \brief True when this class is a POD-type. |
334 | unsigned PlainOldData : 1; |
335 | |
336 | /// true when this class is empty for traits purposes, |
337 | /// i.e. has no data members other than 0-width bit-fields, has no |
338 | /// virtual function/base, and doesn't inherit from a non-empty |
339 | /// class. Doesn't take union-ness into account. |
340 | unsigned Empty : 1; |
341 | |
342 | /// \brief True when this class is polymorphic, i.e., has at |
343 | /// least one virtual member or derives from a polymorphic class. |
344 | unsigned Polymorphic : 1; |
345 | |
346 | /// \brief True when this class is abstract, i.e., has at least |
347 | /// one pure virtual function, (that can come from a base class). |
348 | unsigned Abstract : 1; |
349 | |
350 | /// \brief True when this class has standard layout. |
351 | /// |
352 | /// C++11 [class]p7. A standard-layout class is a class that: |
353 | /// * has no non-static data members of type non-standard-layout class (or |
354 | /// array of such types) or reference, |
355 | /// * has no virtual functions (10.3) and no virtual base classes (10.1), |
356 | /// * has the same access control (Clause 11) for all non-static data |
357 | /// members |
358 | /// * has no non-standard-layout base classes, |
359 | /// * either has no non-static data members in the most derived class and at |
360 | /// most one base class with non-static data members, or has no base |
361 | /// classes with non-static data members, and |
362 | /// * has no base classes of the same type as the first non-static data |
363 | /// member. |
364 | unsigned IsStandardLayout : 1; |
365 | |
366 | /// \brief True when there are no non-empty base classes. |
367 | /// |
368 | /// This is a helper bit of state used to implement IsStandardLayout more |
369 | /// efficiently. |
370 | unsigned HasNoNonEmptyBases : 1; |
371 | |
372 | /// \brief True when there are private non-static data members. |
373 | unsigned HasPrivateFields : 1; |
374 | |
375 | /// \brief True when there are protected non-static data members. |
376 | unsigned HasProtectedFields : 1; |
377 | |
378 | /// \brief True when there are private non-static data members. |
379 | unsigned HasPublicFields : 1; |
380 | |
381 | /// \brief True if this class (or any subobject) has mutable fields. |
382 | unsigned HasMutableFields : 1; |
383 | |
384 | /// \brief True if this class (or any nested anonymous struct or union) |
385 | /// has variant members. |
386 | unsigned HasVariantMembers : 1; |
387 | |
388 | /// \brief True if there no non-field members declared by the user. |
389 | unsigned HasOnlyCMembers : 1; |
390 | |
391 | /// \brief True if any field has an in-class initializer, including those |
392 | /// within anonymous unions or structs. |
393 | unsigned HasInClassInitializer : 1; |
394 | |
395 | /// \brief True if any field is of reference type, and does not have an |
396 | /// in-class initializer. |
397 | /// |
398 | /// In this case, value-initialization of this class is illegal in C++98 |
399 | /// even if the class has a trivial default constructor. |
400 | unsigned HasUninitializedReferenceMember : 1; |
401 | |
402 | /// \brief True if any non-mutable field whose type doesn't have a user- |
403 | /// provided default ctor also doesn't have an in-class initializer. |
404 | unsigned HasUninitializedFields : 1; |
405 | |
406 | /// \brief True if there are any member using-declarations that inherit |
407 | /// constructors from a base class. |
408 | unsigned HasInheritedConstructor : 1; |
409 | |
410 | /// \brief True if there are any member using-declarations named |
411 | /// 'operator='. |
412 | unsigned HasInheritedAssignment : 1; |
413 | |
414 | /// \brief These flags are \c true if a defaulted corresponding special |
415 | /// member can't be fully analyzed without performing overload resolution. |
416 | /// @{ |
417 | unsigned NeedOverloadResolutionForCopyConstructor : 1; |
418 | unsigned NeedOverloadResolutionForMoveConstructor : 1; |
419 | unsigned NeedOverloadResolutionForMoveAssignment : 1; |
420 | unsigned NeedOverloadResolutionForDestructor : 1; |
421 | /// @} |
422 | |
423 | /// \brief These flags are \c true if an implicit defaulted corresponding |
424 | /// special member would be defined as deleted. |
425 | /// @{ |
426 | unsigned DefaultedCopyConstructorIsDeleted : 1; |
427 | unsigned DefaultedMoveConstructorIsDeleted : 1; |
428 | unsigned DefaultedMoveAssignmentIsDeleted : 1; |
429 | unsigned DefaultedDestructorIsDeleted : 1; |
430 | /// @} |
431 | |
432 | /// \brief The trivial special members which this class has, per |
433 | /// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25, |
434 | /// C++11 [class.dtor]p5, or would have if the member were not suppressed. |
435 | /// |
436 | /// This excludes any user-declared but not user-provided special members |
437 | /// which have been declared but not yet defined. |
438 | unsigned HasTrivialSpecialMembers : 6; |
439 | |
440 | /// These bits keep track of the triviality of special functions for the |
441 | /// purpose of calls. Only the bits corresponding to SMF_CopyConstructor, |
442 | /// SMF_MoveConstructor, and SMF_Destructor are meaningful here. |
443 | unsigned HasTrivialSpecialMembersForCall : 6; |
444 | |
445 | /// \brief The declared special members of this class which are known to be |
446 | /// non-trivial. |
447 | /// |
448 | /// This excludes any user-declared but not user-provided special members |
449 | /// which have been declared but not yet defined, and any implicit special |
450 | /// members which have not yet been declared. |
451 | unsigned DeclaredNonTrivialSpecialMembers : 6; |
452 | |
453 | /// These bits keep track of the declared special members that are |
454 | /// non-trivial for the purpose of calls. |
455 | /// Only the bits corresponding to SMF_CopyConstructor, |
456 | /// SMF_MoveConstructor, and SMF_Destructor are meaningful here. |
457 | unsigned DeclaredNonTrivialSpecialMembersForCall : 6; |
458 | |
459 | /// \brief True when this class has a destructor with no semantic effect. |
460 | unsigned HasIrrelevantDestructor : 1; |
461 | |
462 | /// \brief True when this class has at least one user-declared constexpr |
463 | /// constructor which is neither the copy nor move constructor. |
464 | unsigned HasConstexprNonCopyMoveConstructor : 1; |
465 | |
466 | /// \brief True if this class has a (possibly implicit) defaulted default |
467 | /// constructor. |
468 | unsigned HasDefaultedDefaultConstructor : 1; |
469 | |
470 | /// \brief True if this class can be passed in a non-address-preserving |
471 | /// fashion (such as in registers) according to the C++ language rules. |
472 | /// This does not imply anything about how the ABI in use will actually |
473 | /// pass an object of this class. |
474 | unsigned CanPassInRegisters : 1; |
475 | |
476 | /// \brief True if a defaulted default constructor for this class would |
477 | /// be constexpr. |
478 | unsigned DefaultedDefaultConstructorIsConstexpr : 1; |
479 | |
480 | /// \brief True if this class has a constexpr default constructor. |
481 | /// |
482 | /// This is true for either a user-declared constexpr default constructor |
483 | /// or an implicitly declared constexpr default constructor. |
484 | unsigned HasConstexprDefaultConstructor : 1; |
485 | |
486 | /// \brief True when this class contains at least one non-static data |
487 | /// member or base class of non-literal or volatile type. |
488 | unsigned HasNonLiteralTypeFieldsOrBases : 1; |
489 | |
490 | /// \brief True when visible conversion functions are already computed |
491 | /// and are available. |
492 | unsigned ComputedVisibleConversions : 1; |
493 | |
494 | /// \brief Whether we have a C++11 user-provided default constructor (not |
495 | /// explicitly deleted or defaulted). |
496 | unsigned UserProvidedDefaultConstructor : 1; |
497 | |
498 | /// \brief The special members which have been declared for this class, |
499 | /// either by the user or implicitly. |
500 | unsigned DeclaredSpecialMembers : 6; |
501 | |
502 | /// \brief Whether an implicit copy constructor could have a const-qualified |
503 | /// parameter, for initializing virtual bases and for other subobjects. |
504 | unsigned ImplicitCopyConstructorCanHaveConstParamForVBase : 1; |
505 | unsigned ImplicitCopyConstructorCanHaveConstParamForNonVBase : 1; |
506 | |
507 | /// \brief Whether an implicit copy assignment operator would have a |
508 | /// const-qualified parameter. |
509 | unsigned ImplicitCopyAssignmentHasConstParam : 1; |
510 | |
511 | /// \brief Whether any declared copy constructor has a const-qualified |
512 | /// parameter. |
513 | unsigned HasDeclaredCopyConstructorWithConstParam : 1; |
514 | |
515 | /// \brief Whether any declared copy assignment operator has either a |
516 | /// const-qualified reference parameter or a non-reference parameter. |
517 | unsigned HasDeclaredCopyAssignmentWithConstParam : 1; |
518 | |
519 | /// \brief Whether this class describes a C++ lambda. |
520 | unsigned IsLambda : 1; |
521 | |
522 | /// \brief Whether we are currently parsing base specifiers. |
523 | unsigned IsParsingBaseSpecifiers : 1; |
524 | |
525 | unsigned HasODRHash : 1; |
526 | |
527 | /// \brief A hash of parts of the class to help in ODR checking. |
528 | unsigned ODRHash = 0; |
529 | |
530 | /// \brief The number of base class specifiers in Bases. |
531 | unsigned NumBases = 0; |
532 | |
533 | /// \brief The number of virtual base class specifiers in VBases. |
534 | unsigned NumVBases = 0; |
535 | |
536 | /// \brief Base classes of this class. |
537 | /// |
538 | /// FIXME: This is wasted space for a union. |
539 | LazyCXXBaseSpecifiersPtr Bases; |
540 | |
541 | /// \brief direct and indirect virtual base classes of this class. |
542 | LazyCXXBaseSpecifiersPtr VBases; |
543 | |
544 | /// \brief The conversion functions of this C++ class (but not its |
545 | /// inherited conversion functions). |
546 | /// |
547 | /// Each of the entries in this overload set is a CXXConversionDecl. |
548 | LazyASTUnresolvedSet Conversions; |
549 | |
550 | /// \brief The conversion functions of this C++ class and all those |
551 | /// inherited conversion functions that are visible in this class. |
552 | /// |
553 | /// Each of the entries in this overload set is a CXXConversionDecl or a |
554 | /// FunctionTemplateDecl. |
555 | LazyASTUnresolvedSet VisibleConversions; |
556 | |
557 | /// \brief The declaration which defines this record. |
558 | CXXRecordDecl *Definition; |
559 | |
560 | /// \brief The first friend declaration in this class, or null if there |
561 | /// aren't any. |
562 | /// |
563 | /// This is actually currently stored in reverse order. |
564 | LazyDeclPtr FirstFriend; |
565 | |
566 | DefinitionData(CXXRecordDecl *D); |
567 | |
568 | /// \brief Retrieve the set of direct base classes. |
569 | CXXBaseSpecifier *getBases() const { |
570 | if (!Bases.isOffset()) |
571 | return Bases.get(nullptr); |
572 | return getBasesSlowCase(); |
573 | } |
574 | |
575 | /// \brief Retrieve the set of virtual base classes. |
576 | CXXBaseSpecifier *getVBases() const { |
577 | if (!VBases.isOffset()) |
578 | return VBases.get(nullptr); |
579 | return getVBasesSlowCase(); |
580 | } |
581 | |
582 | ArrayRef<CXXBaseSpecifier> bases() const { |
583 | return llvm::makeArrayRef(getBases(), NumBases); |
584 | } |
585 | |
586 | ArrayRef<CXXBaseSpecifier> vbases() const { |
587 | return llvm::makeArrayRef(getVBases(), NumVBases); |
588 | } |
589 | |
590 | private: |
591 | CXXBaseSpecifier *getBasesSlowCase() const; |
592 | CXXBaseSpecifier *getVBasesSlowCase() const; |
593 | }; |
594 | |
595 | struct DefinitionData *DefinitionData; |
596 | |
597 | /// \brief Describes a C++ closure type (generated by a lambda expression). |
598 | struct LambdaDefinitionData : public DefinitionData { |
599 | using Capture = LambdaCapture; |
600 | |
601 | /// \brief Whether this lambda is known to be dependent, even if its |
602 | /// context isn't dependent. |
603 | /// |
604 | /// A lambda with a non-dependent context can be dependent if it occurs |
605 | /// within the default argument of a function template, because the |
606 | /// lambda will have been created with the enclosing context as its |
607 | /// declaration context, rather than function. This is an unfortunate |
608 | /// artifact of having to parse the default arguments before. |
609 | unsigned Dependent : 1; |
610 | |
611 | /// \brief Whether this lambda is a generic lambda. |
612 | unsigned IsGenericLambda : 1; |
613 | |
614 | /// \brief The Default Capture. |
615 | unsigned CaptureDefault : 2; |
616 | |
617 | /// \brief The number of captures in this lambda is limited 2^NumCaptures. |
618 | unsigned NumCaptures : 15; |
619 | |
620 | /// \brief The number of explicit captures in this lambda. |
621 | unsigned NumExplicitCaptures : 13; |
622 | |
623 | /// \brief The number used to indicate this lambda expression for name |
624 | /// mangling in the Itanium C++ ABI. |
625 | unsigned ManglingNumber = 0; |
626 | |
627 | /// \brief The declaration that provides context for this lambda, if the |
628 | /// actual DeclContext does not suffice. This is used for lambdas that |
629 | /// occur within default arguments of function parameters within the class |
630 | /// or within a data member initializer. |
631 | LazyDeclPtr ContextDecl; |
632 | |
633 | /// \brief The list of captures, both explicit and implicit, for this |
634 | /// lambda. |
635 | Capture *Captures = nullptr; |
636 | |
637 | /// \brief The type of the call method. |
638 | TypeSourceInfo *MethodTyInfo; |
639 | |
640 | LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, |
641 | bool Dependent, bool IsGeneric, |
642 | LambdaCaptureDefault CaptureDefault) |
643 | : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric), |
644 | CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0), |
645 | MethodTyInfo(Info) { |
646 | IsLambda = true; |
647 | |
648 | // C++1z [expr.prim.lambda]p4: |
649 | // This class type is not an aggregate type. |
650 | Aggregate = false; |
651 | PlainOldData = false; |
652 | } |
653 | }; |
654 | |
655 | struct DefinitionData *dataPtr() const { |
656 | // Complete the redecl chain (if necessary). |
657 | getMostRecentDecl(); |
658 | return DefinitionData; |
659 | } |
660 | |
661 | struct DefinitionData &data() const { |
662 | auto *DD = dataPtr(); |
663 | assert(DD && "queried property of class with no definition")(static_cast <bool> (DD && "queried property of class with no definition" ) ? void (0) : __assert_fail ("DD && \"queried property of class with no definition\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 663, __extension__ __PRETTY_FUNCTION__)); |
664 | return *DD; |
665 | } |
666 | |
667 | struct LambdaDefinitionData &getLambdaData() const { |
668 | // No update required: a merged definition cannot change any lambda |
669 | // properties. |
670 | auto *DD = DefinitionData; |
671 | assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")(static_cast <bool> (DD && DD->IsLambda && "queried lambda property of non-lambda class") ? void (0) : __assert_fail ("DD && DD->IsLambda && \"queried lambda property of non-lambda class\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 671, __extension__ __PRETTY_FUNCTION__)); |
672 | return static_cast<LambdaDefinitionData&>(*DD); |
673 | } |
674 | |
675 | /// \brief The template or declaration that this declaration |
676 | /// describes or was instantiated from, respectively. |
677 | /// |
678 | /// For non-templates, this value will be null. For record |
679 | /// declarations that describe a class template, this will be a |
680 | /// pointer to a ClassTemplateDecl. For member |
681 | /// classes of class template specializations, this will be the |
682 | /// MemberSpecializationInfo referring to the member class that was |
683 | /// instantiated or specialized. |
684 | llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *> |
685 | TemplateOrInstantiation; |
686 | |
687 | /// \brief Called from setBases and addedMember to notify the class that a |
688 | /// direct or virtual base class or a member of class type has been added. |
689 | void addedClassSubobject(CXXRecordDecl *Base); |
690 | |
691 | /// \brief Notify the class that member has been added. |
692 | /// |
693 | /// This routine helps maintain information about the class based on which |
694 | /// members have been added. It will be invoked by DeclContext::addDecl() |
695 | /// whenever a member is added to this record. |
696 | void addedMember(Decl *D); |
697 | |
698 | void markedVirtualFunctionPure(); |
699 | |
700 | /// \brief Get the head of our list of friend declarations, possibly |
701 | /// deserializing the friends from an external AST source. |
702 | FriendDecl *getFirstFriend() const; |
703 | |
704 | protected: |
705 | CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC, |
706 | SourceLocation StartLoc, SourceLocation IdLoc, |
707 | IdentifierInfo *Id, CXXRecordDecl *PrevDecl); |
708 | |
709 | public: |
710 | /// \brief Iterator that traverses the base classes of a class. |
711 | using base_class_iterator = CXXBaseSpecifier *; |
712 | |
713 | /// \brief Iterator that traverses the base classes of a class. |
714 | using base_class_const_iterator = const CXXBaseSpecifier *; |
715 | |
716 | CXXRecordDecl *getCanonicalDecl() override { |
717 | return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl()); |
718 | } |
719 | |
720 | const CXXRecordDecl *getCanonicalDecl() const { |
721 | return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl(); |
722 | } |
723 | |
724 | CXXRecordDecl *getPreviousDecl() { |
725 | return cast_or_null<CXXRecordDecl>( |
726 | static_cast<RecordDecl *>(this)->getPreviousDecl()); |
727 | } |
728 | |
729 | const CXXRecordDecl *getPreviousDecl() const { |
730 | return const_cast<CXXRecordDecl*>(this)->getPreviousDecl(); |
731 | } |
732 | |
733 | CXXRecordDecl *getMostRecentDecl() { |
734 | return cast<CXXRecordDecl>( |
735 | static_cast<RecordDecl *>(this)->getMostRecentDecl()); |
736 | } |
737 | |
738 | const CXXRecordDecl *getMostRecentDecl() const { |
739 | return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl(); |
740 | } |
741 | |
742 | CXXRecordDecl *getDefinition() const { |
743 | // We only need an update if we don't already know which |
744 | // declaration is the definition. |
745 | auto *DD = DefinitionData ? DefinitionData : dataPtr(); |
746 | return DD ? DD->Definition : nullptr; |
747 | } |
748 | |
749 | bool hasDefinition() const { return DefinitionData || dataPtr(); } |
750 | |
751 | static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
752 | SourceLocation StartLoc, SourceLocation IdLoc, |
753 | IdentifierInfo *Id, |
754 | CXXRecordDecl *PrevDecl = nullptr, |
755 | bool DelayTypeCreation = false); |
756 | static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC, |
757 | TypeSourceInfo *Info, SourceLocation Loc, |
758 | bool DependentLambda, bool IsGeneric, |
759 | LambdaCaptureDefault CaptureDefault); |
760 | static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
761 | |
762 | bool isDynamicClass() const { |
763 | return data().Polymorphic || data().NumVBases != 0; |
764 | } |
765 | |
766 | void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; } |
767 | |
768 | bool isParsingBaseSpecifiers() const { |
769 | return data().IsParsingBaseSpecifiers; |
770 | } |
771 | |
772 | unsigned getODRHash() const; |
773 | |
774 | /// \brief Sets the base classes of this struct or class. |
775 | void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases); |
776 | |
777 | /// \brief Retrieves the number of base classes of this class. |
778 | unsigned getNumBases() const { return data().NumBases; } |
779 | |
780 | using base_class_range = llvm::iterator_range<base_class_iterator>; |
781 | using base_class_const_range = |
782 | llvm::iterator_range<base_class_const_iterator>; |
783 | |
784 | base_class_range bases() { |
785 | return base_class_range(bases_begin(), bases_end()); |
786 | } |
787 | base_class_const_range bases() const { |
788 | return base_class_const_range(bases_begin(), bases_end()); |
789 | } |
790 | |
791 | base_class_iterator bases_begin() { return data().getBases(); } |
792 | base_class_const_iterator bases_begin() const { return data().getBases(); } |
793 | base_class_iterator bases_end() { return bases_begin() + data().NumBases; } |
794 | base_class_const_iterator bases_end() const { |
795 | return bases_begin() + data().NumBases; |
796 | } |
797 | |
798 | /// \brief Retrieves the number of virtual base classes of this class. |
799 | unsigned getNumVBases() const { return data().NumVBases; } |
800 | |
801 | base_class_range vbases() { |
802 | return base_class_range(vbases_begin(), vbases_end()); |
803 | } |
804 | base_class_const_range vbases() const { |
805 | return base_class_const_range(vbases_begin(), vbases_end()); |
806 | } |
807 | |
808 | base_class_iterator vbases_begin() { return data().getVBases(); } |
809 | base_class_const_iterator vbases_begin() const { return data().getVBases(); } |
810 | base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; } |
811 | base_class_const_iterator vbases_end() const { |
812 | return vbases_begin() + data().NumVBases; |
813 | } |
814 | |
815 | /// \brief Determine whether this class has any dependent base classes which |
816 | /// are not the current instantiation. |
817 | bool hasAnyDependentBases() const; |
818 | |
819 | /// Iterator access to method members. The method iterator visits |
820 | /// all method members of the class, including non-instance methods, |
821 | /// special methods, etc. |
822 | using method_iterator = specific_decl_iterator<CXXMethodDecl>; |
823 | using method_range = |
824 | llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>; |
825 | |
826 | method_range methods() const { |
827 | return method_range(method_begin(), method_end()); |
828 | } |
829 | |
830 | /// \brief Method begin iterator. Iterates in the order the methods |
831 | /// were declared. |
832 | method_iterator method_begin() const { |
833 | return method_iterator(decls_begin()); |
834 | } |
835 | |
836 | /// \brief Method past-the-end iterator. |
837 | method_iterator method_end() const { |
838 | return method_iterator(decls_end()); |
839 | } |
840 | |
841 | /// Iterator access to constructor members. |
842 | using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>; |
843 | using ctor_range = |
844 | llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>; |
845 | |
846 | ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); } |
847 | |
848 | ctor_iterator ctor_begin() const { |
849 | return ctor_iterator(decls_begin()); |
850 | } |
851 | |
852 | ctor_iterator ctor_end() const { |
853 | return ctor_iterator(decls_end()); |
854 | } |
855 | |
856 | /// An iterator over friend declarations. All of these are defined |
857 | /// in DeclFriend.h. |
858 | class friend_iterator; |
859 | using friend_range = llvm::iterator_range<friend_iterator>; |
860 | |
861 | friend_range friends() const; |
862 | friend_iterator friend_begin() const; |
863 | friend_iterator friend_end() const; |
864 | void pushFriendDecl(FriendDecl *FD); |
865 | |
866 | /// Determines whether this record has any friends. |
867 | bool hasFriends() const { |
868 | return data().FirstFriend.isValid(); |
869 | } |
870 | |
871 | /// \brief \c true if a defaulted copy constructor for this class would be |
872 | /// deleted. |
873 | bool defaultedCopyConstructorIsDeleted() const { |
874 | assert((!needsOverloadResolutionForCopyConstructor() ||(static_cast <bool> ((!needsOverloadResolutionForCopyConstructor () || (data().DeclaredSpecialMembers & SMF_CopyConstructor )) && "this property has not yet been computed by Sema" ) ? void (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 876, __extension__ __PRETTY_FUNCTION__)) |
875 | (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(static_cast <bool> ((!needsOverloadResolutionForCopyConstructor () || (data().DeclaredSpecialMembers & SMF_CopyConstructor )) && "this property has not yet been computed by Sema" ) ? void (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 876, __extension__ __PRETTY_FUNCTION__)) |
876 | "this property has not yet been computed by Sema")(static_cast <bool> ((!needsOverloadResolutionForCopyConstructor () || (data().DeclaredSpecialMembers & SMF_CopyConstructor )) && "this property has not yet been computed by Sema" ) ? void (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 876, __extension__ __PRETTY_FUNCTION__)); |
877 | return data().DefaultedCopyConstructorIsDeleted; |
878 | } |
879 | |
880 | /// \brief \c true if a defaulted move constructor for this class would be |
881 | /// deleted. |
882 | bool defaultedMoveConstructorIsDeleted() const { |
883 | assert((!needsOverloadResolutionForMoveConstructor() ||(static_cast <bool> ((!needsOverloadResolutionForMoveConstructor () || (data().DeclaredSpecialMembers & SMF_MoveConstructor )) && "this property has not yet been computed by Sema" ) ? void (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 885, __extension__ __PRETTY_FUNCTION__)) |
884 | (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(static_cast <bool> ((!needsOverloadResolutionForMoveConstructor () || (data().DeclaredSpecialMembers & SMF_MoveConstructor )) && "this property has not yet been computed by Sema" ) ? void (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 885, __extension__ __PRETTY_FUNCTION__)) |
885 | "this property has not yet been computed by Sema")(static_cast <bool> ((!needsOverloadResolutionForMoveConstructor () || (data().DeclaredSpecialMembers & SMF_MoveConstructor )) && "this property has not yet been computed by Sema" ) ? void (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 885, __extension__ __PRETTY_FUNCTION__)); |
886 | return data().DefaultedMoveConstructorIsDeleted; |
887 | } |
888 | |
889 | /// \brief \c true if a defaulted destructor for this class would be deleted. |
890 | bool defaultedDestructorIsDeleted() const { |
891 | assert((!needsOverloadResolutionForDestructor() ||(static_cast <bool> ((!needsOverloadResolutionForDestructor () || (data().DeclaredSpecialMembers & SMF_Destructor)) && "this property has not yet been computed by Sema") ? void (0 ) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 893, __extension__ __PRETTY_FUNCTION__)) |
892 | (data().DeclaredSpecialMembers & SMF_Destructor)) &&(static_cast <bool> ((!needsOverloadResolutionForDestructor () || (data().DeclaredSpecialMembers & SMF_Destructor)) && "this property has not yet been computed by Sema") ? void (0 ) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 893, __extension__ __PRETTY_FUNCTION__)) |
893 | "this property has not yet been computed by Sema")(static_cast <bool> ((!needsOverloadResolutionForDestructor () || (data().DeclaredSpecialMembers & SMF_Destructor)) && "this property has not yet been computed by Sema") ? void (0 ) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 893, __extension__ __PRETTY_FUNCTION__)); |
894 | return data().DefaultedDestructorIsDeleted; |
895 | } |
896 | |
897 | /// \brief \c true if we know for sure that this class has a single, |
898 | /// accessible, unambiguous copy constructor that is not deleted. |
899 | bool hasSimpleCopyConstructor() const { |
900 | return !hasUserDeclaredCopyConstructor() && |
901 | !data().DefaultedCopyConstructorIsDeleted; |
902 | } |
903 | |
904 | /// \brief \c true if we know for sure that this class has a single, |
905 | /// accessible, unambiguous move constructor that is not deleted. |
906 | bool hasSimpleMoveConstructor() const { |
907 | return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() && |
908 | !data().DefaultedMoveConstructorIsDeleted; |
909 | } |
910 | |
911 | /// \brief \c true if we know for sure that this class has a single, |
912 | /// accessible, unambiguous move assignment operator that is not deleted. |
913 | bool hasSimpleMoveAssignment() const { |
914 | return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() && |
915 | !data().DefaultedMoveAssignmentIsDeleted; |
916 | } |
917 | |
918 | /// \brief \c true if we know for sure that this class has an accessible |
919 | /// destructor that is not deleted. |
920 | bool hasSimpleDestructor() const { |
921 | return !hasUserDeclaredDestructor() && |
922 | !data().DefaultedDestructorIsDeleted; |
923 | } |
924 | |
925 | /// \brief Determine whether this class has any default constructors. |
926 | bool hasDefaultConstructor() const { |
927 | return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) || |
928 | needsImplicitDefaultConstructor(); |
929 | } |
930 | |
931 | /// \brief Determine if we need to declare a default constructor for |
932 | /// this class. |
933 | /// |
934 | /// This value is used for lazy creation of default constructors. |
935 | bool needsImplicitDefaultConstructor() const { |
936 | return !data().UserDeclaredConstructor && |
937 | !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) && |
938 | // C++14 [expr.prim.lambda]p20: |
939 | // The closure type associated with a lambda-expression has no |
940 | // default constructor. |
941 | !isLambda(); |
942 | } |
943 | |
944 | /// \brief Determine whether this class has any user-declared constructors. |
945 | /// |
946 | /// When true, a default constructor will not be implicitly declared. |
947 | bool hasUserDeclaredConstructor() const { |
948 | return data().UserDeclaredConstructor; |
949 | } |
950 | |
951 | /// \brief Whether this class has a user-provided default constructor |
952 | /// per C++11. |
953 | bool hasUserProvidedDefaultConstructor() const { |
954 | return data().UserProvidedDefaultConstructor; |
955 | } |
956 | |
957 | /// \brief Determine whether this class has a user-declared copy constructor. |
958 | /// |
959 | /// When false, a copy constructor will be implicitly declared. |
960 | bool hasUserDeclaredCopyConstructor() const { |
961 | return data().UserDeclaredSpecialMembers & SMF_CopyConstructor; |
962 | } |
963 | |
964 | /// \brief Determine whether this class needs an implicit copy |
965 | /// constructor to be lazily declared. |
966 | bool needsImplicitCopyConstructor() const { |
967 | return !(data().DeclaredSpecialMembers & SMF_CopyConstructor); |
968 | } |
969 | |
970 | /// \brief Determine whether we need to eagerly declare a defaulted copy |
971 | /// constructor for this class. |
972 | bool needsOverloadResolutionForCopyConstructor() const { |
973 | // C++17 [class.copy.ctor]p6: |
974 | // If the class definition declares a move constructor or move assignment |
975 | // operator, the implicitly declared copy constructor is defined as |
976 | // deleted. |
977 | // In MSVC mode, sometimes a declared move assignment does not delete an |
978 | // implicit copy constructor, so defer this choice to Sema. |
979 | if (data().UserDeclaredSpecialMembers & |
980 | (SMF_MoveConstructor | SMF_MoveAssignment)) |
981 | return true; |
982 | return data().NeedOverloadResolutionForCopyConstructor; |
983 | } |
984 | |
985 | /// \brief Determine whether an implicit copy constructor for this type |
986 | /// would have a parameter with a const-qualified reference type. |
987 | bool implicitCopyConstructorHasConstParam() const { |
988 | return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase && |
989 | (isAbstract() || |
990 | data().ImplicitCopyConstructorCanHaveConstParamForVBase); |
991 | } |
992 | |
993 | /// \brief Determine whether this class has a copy constructor with |
994 | /// a parameter type which is a reference to a const-qualified type. |
995 | bool hasCopyConstructorWithConstParam() const { |
996 | return data().HasDeclaredCopyConstructorWithConstParam || |
997 | (needsImplicitCopyConstructor() && |
998 | implicitCopyConstructorHasConstParam()); |
999 | } |
1000 | |
1001 | /// \brief Whether this class has a user-declared move constructor or |
1002 | /// assignment operator. |
1003 | /// |
1004 | /// When false, a move constructor and assignment operator may be |
1005 | /// implicitly declared. |
1006 | bool hasUserDeclaredMoveOperation() const { |
1007 | return data().UserDeclaredSpecialMembers & |
1008 | (SMF_MoveConstructor | SMF_MoveAssignment); |
1009 | } |
1010 | |
1011 | /// \brief Determine whether this class has had a move constructor |
1012 | /// declared by the user. |
1013 | bool hasUserDeclaredMoveConstructor() const { |
1014 | return data().UserDeclaredSpecialMembers & SMF_MoveConstructor; |
1015 | } |
1016 | |
1017 | /// \brief Determine whether this class has a move constructor. |
1018 | bool hasMoveConstructor() const { |
1019 | return (data().DeclaredSpecialMembers & SMF_MoveConstructor) || |
1020 | needsImplicitMoveConstructor(); |
1021 | } |
1022 | |
1023 | /// \brief Set that we attempted to declare an implicit copy |
1024 | /// constructor, but overload resolution failed so we deleted it. |
1025 | void setImplicitCopyConstructorIsDeleted() { |
1026 | assert((data().DefaultedCopyConstructorIsDeleted ||(static_cast <bool> ((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && "Copy constructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1028, __extension__ __PRETTY_FUNCTION__)) |
1027 | needsOverloadResolutionForCopyConstructor()) &&(static_cast <bool> ((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && "Copy constructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1028, __extension__ __PRETTY_FUNCTION__)) |
1028 | "Copy constructor should not be deleted")(static_cast <bool> ((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && "Copy constructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1028, __extension__ __PRETTY_FUNCTION__)); |
1029 | data().DefaultedCopyConstructorIsDeleted = true; |
1030 | } |
1031 | |
1032 | /// \brief Set that we attempted to declare an implicit move |
1033 | /// constructor, but overload resolution failed so we deleted it. |
1034 | void setImplicitMoveConstructorIsDeleted() { |
1035 | assert((data().DefaultedMoveConstructorIsDeleted ||(static_cast <bool> ((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && "move constructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1037, __extension__ __PRETTY_FUNCTION__)) |
1036 | needsOverloadResolutionForMoveConstructor()) &&(static_cast <bool> ((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && "move constructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1037, __extension__ __PRETTY_FUNCTION__)) |
1037 | "move constructor should not be deleted")(static_cast <bool> ((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && "move constructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1037, __extension__ __PRETTY_FUNCTION__)); |
1038 | data().DefaultedMoveConstructorIsDeleted = true; |
1039 | } |
1040 | |
1041 | /// \brief Set that we attempted to declare an implicit destructor, |
1042 | /// but overload resolution failed so we deleted it. |
1043 | void setImplicitDestructorIsDeleted() { |
1044 | assert((data().DefaultedDestructorIsDeleted ||(static_cast <bool> ((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && "destructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1046, __extension__ __PRETTY_FUNCTION__)) |
1045 | needsOverloadResolutionForDestructor()) &&(static_cast <bool> ((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && "destructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1046, __extension__ __PRETTY_FUNCTION__)) |
1046 | "destructor should not be deleted")(static_cast <bool> ((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && "destructor should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1046, __extension__ __PRETTY_FUNCTION__)); |
1047 | data().DefaultedDestructorIsDeleted = true; |
1048 | } |
1049 | |
1050 | /// \brief Determine whether this class should get an implicit move |
1051 | /// constructor or if any existing special member function inhibits this. |
1052 | bool needsImplicitMoveConstructor() const { |
1053 | return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) && |
1054 | !hasUserDeclaredCopyConstructor() && |
1055 | !hasUserDeclaredCopyAssignment() && |
1056 | !hasUserDeclaredMoveAssignment() && |
1057 | !hasUserDeclaredDestructor(); |
1058 | } |
1059 | |
1060 | /// \brief Determine whether we need to eagerly declare a defaulted move |
1061 | /// constructor for this class. |
1062 | bool needsOverloadResolutionForMoveConstructor() const { |
1063 | return data().NeedOverloadResolutionForMoveConstructor; |
1064 | } |
1065 | |
1066 | /// \brief Determine whether this class has a user-declared copy assignment |
1067 | /// operator. |
1068 | /// |
1069 | /// When false, a copy assigment operator will be implicitly declared. |
1070 | bool hasUserDeclaredCopyAssignment() const { |
1071 | return data().UserDeclaredSpecialMembers & SMF_CopyAssignment; |
1072 | } |
1073 | |
1074 | /// \brief Determine whether this class needs an implicit copy |
1075 | /// assignment operator to be lazily declared. |
1076 | bool needsImplicitCopyAssignment() const { |
1077 | return !(data().DeclaredSpecialMembers & SMF_CopyAssignment); |
1078 | } |
1079 | |
1080 | /// \brief Determine whether we need to eagerly declare a defaulted copy |
1081 | /// assignment operator for this class. |
1082 | bool needsOverloadResolutionForCopyAssignment() const { |
1083 | return data().HasMutableFields; |
1084 | } |
1085 | |
1086 | /// \brief Determine whether an implicit copy assignment operator for this |
1087 | /// type would have a parameter with a const-qualified reference type. |
1088 | bool implicitCopyAssignmentHasConstParam() const { |
1089 | return data().ImplicitCopyAssignmentHasConstParam; |
1090 | } |
1091 | |
1092 | /// \brief Determine whether this class has a copy assignment operator with |
1093 | /// a parameter type which is a reference to a const-qualified type or is not |
1094 | /// a reference. |
1095 | bool hasCopyAssignmentWithConstParam() const { |
1096 | return data().HasDeclaredCopyAssignmentWithConstParam || |
1097 | (needsImplicitCopyAssignment() && |
1098 | implicitCopyAssignmentHasConstParam()); |
1099 | } |
1100 | |
1101 | /// \brief Determine whether this class has had a move assignment |
1102 | /// declared by the user. |
1103 | bool hasUserDeclaredMoveAssignment() const { |
1104 | return data().UserDeclaredSpecialMembers & SMF_MoveAssignment; |
1105 | } |
1106 | |
1107 | /// \brief Determine whether this class has a move assignment operator. |
1108 | bool hasMoveAssignment() const { |
1109 | return (data().DeclaredSpecialMembers & SMF_MoveAssignment) || |
1110 | needsImplicitMoveAssignment(); |
1111 | } |
1112 | |
1113 | /// \brief Set that we attempted to declare an implicit move assignment |
1114 | /// operator, but overload resolution failed so we deleted it. |
1115 | void setImplicitMoveAssignmentIsDeleted() { |
1116 | assert((data().DefaultedMoveAssignmentIsDeleted ||(static_cast <bool> ((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && "move assignment should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1118, __extension__ __PRETTY_FUNCTION__)) |
1117 | needsOverloadResolutionForMoveAssignment()) &&(static_cast <bool> ((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && "move assignment should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1118, __extension__ __PRETTY_FUNCTION__)) |
1118 | "move assignment should not be deleted")(static_cast <bool> ((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && "move assignment should not be deleted" ) ? void (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1118, __extension__ __PRETTY_FUNCTION__)); |
1119 | data().DefaultedMoveAssignmentIsDeleted = true; |
1120 | } |
1121 | |
1122 | /// \brief Determine whether this class should get an implicit move |
1123 | /// assignment operator or if any existing special member function inhibits |
1124 | /// this. |
1125 | bool needsImplicitMoveAssignment() const { |
1126 | return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) && |
1127 | !hasUserDeclaredCopyConstructor() && |
1128 | !hasUserDeclaredCopyAssignment() && |
1129 | !hasUserDeclaredMoveConstructor() && |
1130 | !hasUserDeclaredDestructor() && |
1131 | // C++1z [expr.prim.lambda]p21: "the closure type has a deleted copy |
1132 | // assignment operator". The intent is that this counts as a user |
1133 | // declared copy assignment, but we do not model it that way. |
1134 | !isLambda(); |
1135 | } |
1136 | |
1137 | /// \brief Determine whether we need to eagerly declare a move assignment |
1138 | /// operator for this class. |
1139 | bool needsOverloadResolutionForMoveAssignment() const { |
1140 | return data().NeedOverloadResolutionForMoveAssignment; |
1141 | } |
1142 | |
1143 | /// \brief Determine whether this class has a user-declared destructor. |
1144 | /// |
1145 | /// When false, a destructor will be implicitly declared. |
1146 | bool hasUserDeclaredDestructor() const { |
1147 | return data().UserDeclaredSpecialMembers & SMF_Destructor; |
1148 | } |
1149 | |
1150 | /// \brief Determine whether this class needs an implicit destructor to |
1151 | /// be lazily declared. |
1152 | bool needsImplicitDestructor() const { |
1153 | return !(data().DeclaredSpecialMembers & SMF_Destructor); |
1154 | } |
1155 | |
1156 | /// \brief Determine whether we need to eagerly declare a destructor for this |
1157 | /// class. |
1158 | bool needsOverloadResolutionForDestructor() const { |
1159 | return data().NeedOverloadResolutionForDestructor; |
1160 | } |
1161 | |
1162 | /// \brief Determine whether this class describes a lambda function object. |
1163 | bool isLambda() const { |
1164 | // An update record can't turn a non-lambda into a lambda. |
1165 | auto *DD = DefinitionData; |
1166 | return DD && DD->IsLambda; |
1167 | } |
1168 | |
1169 | /// \brief Determine whether this class describes a generic |
1170 | /// lambda function object (i.e. function call operator is |
1171 | /// a template). |
1172 | bool isGenericLambda() const; |
1173 | |
1174 | /// \brief Retrieve the lambda call operator of the closure type |
1175 | /// if this is a closure type. |
1176 | CXXMethodDecl *getLambdaCallOperator() const; |
1177 | |
1178 | /// \brief Retrieve the lambda static invoker, the address of which |
1179 | /// is returned by the conversion operator, and the body of which |
1180 | /// is forwarded to the lambda call operator. |
1181 | CXXMethodDecl *getLambdaStaticInvoker() const; |
1182 | |
1183 | /// \brief Retrieve the generic lambda's template parameter list. |
1184 | /// Returns null if the class does not represent a lambda or a generic |
1185 | /// lambda. |
1186 | TemplateParameterList *getGenericLambdaTemplateParameterList() const; |
1187 | |
1188 | LambdaCaptureDefault getLambdaCaptureDefault() const { |
1189 | assert(isLambda())(static_cast <bool> (isLambda()) ? void (0) : __assert_fail ("isLambda()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1189, __extension__ __PRETTY_FUNCTION__)); |
1190 | return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault); |
1191 | } |
1192 | |
1193 | /// \brief For a closure type, retrieve the mapping from captured |
1194 | /// variables and \c this to the non-static data members that store the |
1195 | /// values or references of the captures. |
1196 | /// |
1197 | /// \param Captures Will be populated with the mapping from captured |
1198 | /// variables to the corresponding fields. |
1199 | /// |
1200 | /// \param ThisCapture Will be set to the field declaration for the |
1201 | /// \c this capture. |
1202 | /// |
1203 | /// \note No entries will be added for init-captures, as they do not capture |
1204 | /// variables. |
1205 | void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures, |
1206 | FieldDecl *&ThisCapture) const; |
1207 | |
1208 | using capture_const_iterator = const LambdaCapture *; |
1209 | using capture_const_range = llvm::iterator_range<capture_const_iterator>; |
1210 | |
1211 | capture_const_range captures() const { |
1212 | return capture_const_range(captures_begin(), captures_end()); |
1213 | } |
1214 | |
1215 | capture_const_iterator captures_begin() const { |
1216 | return isLambda() ? getLambdaData().Captures : nullptr; |
1217 | } |
1218 | |
1219 | capture_const_iterator captures_end() const { |
1220 | return isLambda() ? captures_begin() + getLambdaData().NumCaptures |
1221 | : nullptr; |
1222 | } |
1223 | |
1224 | using conversion_iterator = UnresolvedSetIterator; |
1225 | |
1226 | conversion_iterator conversion_begin() const { |
1227 | return data().Conversions.get(getASTContext()).begin(); |
1228 | } |
1229 | |
1230 | conversion_iterator conversion_end() const { |
1231 | return data().Conversions.get(getASTContext()).end(); |
1232 | } |
1233 | |
1234 | /// Removes a conversion function from this class. The conversion |
1235 | /// function must currently be a member of this class. Furthermore, |
1236 | /// this class must currently be in the process of being defined. |
1237 | void removeConversion(const NamedDecl *Old); |
1238 | |
1239 | /// \brief Get all conversion functions visible in current class, |
1240 | /// including conversion function templates. |
1241 | llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions(); |
1242 | |
1243 | /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]), |
1244 | /// which is a class with no user-declared constructors, no private |
1245 | /// or protected non-static data members, no base classes, and no virtual |
1246 | /// functions (C++ [dcl.init.aggr]p1). |
1247 | bool isAggregate() const { return data().Aggregate; } |
1248 | |
1249 | /// \brief Whether this class has any in-class initializers |
1250 | /// for non-static data members (including those in anonymous unions or |
1251 | /// structs). |
1252 | bool hasInClassInitializer() const { return data().HasInClassInitializer; } |
1253 | |
1254 | /// \brief Whether this class or any of its subobjects has any members of |
1255 | /// reference type which would make value-initialization ill-formed. |
1256 | /// |
1257 | /// Per C++03 [dcl.init]p5: |
1258 | /// - if T is a non-union class type without a user-declared constructor, |
1259 | /// then every non-static data member and base-class component of T is |
1260 | /// value-initialized [...] A program that calls for [...] |
1261 | /// value-initialization of an entity of reference type is ill-formed. |
1262 | bool hasUninitializedReferenceMember() const { |
1263 | return !isUnion() && !hasUserDeclaredConstructor() && |
1264 | data().HasUninitializedReferenceMember; |
1265 | } |
1266 | |
1267 | /// \brief Whether this class is a POD-type (C++ [class]p4) |
1268 | /// |
1269 | /// For purposes of this function a class is POD if it is an aggregate |
1270 | /// that has no non-static non-POD data members, no reference data |
1271 | /// members, no user-defined copy assignment operator and no |
1272 | /// user-defined destructor. |
1273 | /// |
1274 | /// Note that this is the C++ TR1 definition of POD. |
1275 | bool isPOD() const { return data().PlainOldData; } |
1276 | |
1277 | /// \brief True if this class is C-like, without C++-specific features, e.g. |
1278 | /// it contains only public fields, no bases, tag kind is not 'class', etc. |
1279 | bool isCLike() const; |
1280 | |
1281 | /// \brief Determine whether this is an empty class in the sense of |
1282 | /// (C++11 [meta.unary.prop]). |
1283 | /// |
1284 | /// The CXXRecordDecl is a class type, but not a union type, |
1285 | /// with no non-static data members other than bit-fields of length 0, |
1286 | /// no virtual member functions, no virtual base classes, |
1287 | /// and no base class B for which is_empty<B>::value is false. |
1288 | /// |
1289 | /// \note This does NOT include a check for union-ness. |
1290 | bool isEmpty() const { return data().Empty; } |
1291 | |
1292 | /// \brief Determine whether this class has direct non-static data members. |
1293 | bool hasDirectFields() const { |
1294 | auto &D = data(); |
1295 | return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields; |
1296 | } |
1297 | |
1298 | /// Whether this class is polymorphic (C++ [class.virtual]), |
1299 | /// which means that the class contains or inherits a virtual function. |
1300 | bool isPolymorphic() const { return data().Polymorphic; } |
1301 | |
1302 | /// \brief Determine whether this class has a pure virtual function. |
1303 | /// |
1304 | /// The class is is abstract per (C++ [class.abstract]p2) if it declares |
1305 | /// a pure virtual function or inherits a pure virtual function that is |
1306 | /// not overridden. |
1307 | bool isAbstract() const { return data().Abstract; } |
1308 | |
1309 | /// \brief Determine whether this class has standard layout per |
1310 | /// (C++ [class]p7) |
1311 | bool isStandardLayout() const { return data().IsStandardLayout; } |
1312 | |
1313 | /// \brief Determine whether this class, or any of its class subobjects, |
1314 | /// contains a mutable field. |
1315 | bool hasMutableFields() const { return data().HasMutableFields; } |
1316 | |
1317 | /// \brief Determine whether this class has any variant members. |
1318 | bool hasVariantMembers() const { return data().HasVariantMembers; } |
1319 | |
1320 | /// \brief Determine whether this class has a trivial default constructor |
1321 | /// (C++11 [class.ctor]p5). |
1322 | bool hasTrivialDefaultConstructor() const { |
1323 | return hasDefaultConstructor() && |
1324 | (data().HasTrivialSpecialMembers & SMF_DefaultConstructor); |
1325 | } |
1326 | |
1327 | /// \brief Determine whether this class has a non-trivial default constructor |
1328 | /// (C++11 [class.ctor]p5). |
1329 | bool hasNonTrivialDefaultConstructor() const { |
1330 | return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) || |
1331 | (needsImplicitDefaultConstructor() && |
1332 | !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor)); |
1333 | } |
1334 | |
1335 | /// \brief Determine whether this class has at least one constexpr constructor |
1336 | /// other than the copy or move constructors. |
1337 | bool hasConstexprNonCopyMoveConstructor() const { |
1338 | return data().HasConstexprNonCopyMoveConstructor || |
1339 | (needsImplicitDefaultConstructor() && |
1340 | defaultedDefaultConstructorIsConstexpr()); |
1341 | } |
1342 | |
1343 | /// \brief Determine whether a defaulted default constructor for this class |
1344 | /// would be constexpr. |
1345 | bool defaultedDefaultConstructorIsConstexpr() const { |
1346 | return data().DefaultedDefaultConstructorIsConstexpr && |
1347 | (!isUnion() || hasInClassInitializer() || !hasVariantMembers()); |
1348 | } |
1349 | |
1350 | /// \brief Determine whether this class has a constexpr default constructor. |
1351 | bool hasConstexprDefaultConstructor() const { |
1352 | return data().HasConstexprDefaultConstructor || |
1353 | (needsImplicitDefaultConstructor() && |
1354 | defaultedDefaultConstructorIsConstexpr()); |
1355 | } |
1356 | |
1357 | /// \brief Determine whether this class has a trivial copy constructor |
1358 | /// (C++ [class.copy]p6, C++11 [class.copy]p12) |
1359 | bool hasTrivialCopyConstructor() const { |
1360 | return data().HasTrivialSpecialMembers & SMF_CopyConstructor; |
1361 | } |
1362 | |
1363 | bool hasTrivialCopyConstructorForCall() const { |
1364 | return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor; |
1365 | } |
1366 | |
1367 | /// \brief Determine whether this class has a non-trivial copy constructor |
1368 | /// (C++ [class.copy]p6, C++11 [class.copy]p12) |
1369 | bool hasNonTrivialCopyConstructor() const { |
1370 | return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor || |
1371 | !hasTrivialCopyConstructor(); |
1372 | } |
1373 | |
1374 | bool hasNonTrivialCopyConstructorForCall() const { |
1375 | return (data().DeclaredNonTrivialSpecialMembersForCall & |
1376 | SMF_CopyConstructor) || |
1377 | !hasTrivialCopyConstructorForCall(); |
1378 | } |
1379 | |
1380 | /// \brief Determine whether this class has a trivial move constructor |
1381 | /// (C++11 [class.copy]p12) |
1382 | bool hasTrivialMoveConstructor() const { |
1383 | return hasMoveConstructor() && |
1384 | (data().HasTrivialSpecialMembers & SMF_MoveConstructor); |
1385 | } |
1386 | |
1387 | bool hasTrivialMoveConstructorForCall() const { |
1388 | return hasMoveConstructor() && |
1389 | (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor); |
1390 | } |
1391 | |
1392 | /// \brief Determine whether this class has a non-trivial move constructor |
1393 | /// (C++11 [class.copy]p12) |
1394 | bool hasNonTrivialMoveConstructor() const { |
1395 | return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) || |
1396 | (needsImplicitMoveConstructor() && |
1397 | !(data().HasTrivialSpecialMembers & SMF_MoveConstructor)); |
1398 | } |
1399 | |
1400 | bool hasNonTrivialMoveConstructorForCall() const { |
1401 | return (data().DeclaredNonTrivialSpecialMembersForCall & |
1402 | SMF_MoveConstructor) || |
1403 | (needsImplicitMoveConstructor() && |
1404 | !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor)); |
1405 | } |
1406 | |
1407 | /// \brief Determine whether this class has a trivial copy assignment operator |
1408 | /// (C++ [class.copy]p11, C++11 [class.copy]p25) |
1409 | bool hasTrivialCopyAssignment() const { |
1410 | return data().HasTrivialSpecialMembers & SMF_CopyAssignment; |
1411 | } |
1412 | |
1413 | /// \brief Determine whether this class has a non-trivial copy assignment |
1414 | /// operator (C++ [class.copy]p11, C++11 [class.copy]p25) |
1415 | bool hasNonTrivialCopyAssignment() const { |
1416 | return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment || |
1417 | !hasTrivialCopyAssignment(); |
1418 | } |
1419 | |
1420 | /// \brief Determine whether this class has a trivial move assignment operator |
1421 | /// (C++11 [class.copy]p25) |
1422 | bool hasTrivialMoveAssignment() const { |
1423 | return hasMoveAssignment() && |
1424 | (data().HasTrivialSpecialMembers & SMF_MoveAssignment); |
1425 | } |
1426 | |
1427 | /// \brief Determine whether this class has a non-trivial move assignment |
1428 | /// operator (C++11 [class.copy]p25) |
1429 | bool hasNonTrivialMoveAssignment() const { |
1430 | return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) || |
1431 | (needsImplicitMoveAssignment() && |
1432 | !(data().HasTrivialSpecialMembers & SMF_MoveAssignment)); |
1433 | } |
1434 | |
1435 | /// \brief Determine whether this class has a trivial destructor |
1436 | /// (C++ [class.dtor]p3) |
1437 | bool hasTrivialDestructor() const { |
1438 | return data().HasTrivialSpecialMembers & SMF_Destructor; |
1439 | } |
1440 | |
1441 | bool hasTrivialDestructorForCall() const { |
1442 | return data().HasTrivialSpecialMembersForCall & SMF_Destructor; |
1443 | } |
1444 | |
1445 | /// \brief Determine whether this class has a non-trivial destructor |
1446 | /// (C++ [class.dtor]p3) |
1447 | bool hasNonTrivialDestructor() const { |
1448 | return !(data().HasTrivialSpecialMembers & SMF_Destructor); |
1449 | } |
1450 | |
1451 | bool hasNonTrivialDestructorForCall() const { |
1452 | return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor); |
1453 | } |
1454 | |
1455 | void setHasTrivialSpecialMemberForCall() { |
1456 | data().HasTrivialSpecialMembersForCall = |
1457 | (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor); |
1458 | } |
1459 | |
1460 | /// \brief Determine whether declaring a const variable with this type is ok |
1461 | /// per core issue 253. |
1462 | bool allowConstDefaultInit() const { |
1463 | return !data().HasUninitializedFields || |
1464 | !(data().HasDefaultedDefaultConstructor || |
1465 | needsImplicitDefaultConstructor()); |
1466 | } |
1467 | |
1468 | /// \brief Determine whether this class has a destructor which has no |
1469 | /// semantic effect. |
1470 | /// |
1471 | /// Any such destructor will be trivial, public, defaulted and not deleted, |
1472 | /// and will call only irrelevant destructors. |
1473 | bool hasIrrelevantDestructor() const { |
1474 | return data().HasIrrelevantDestructor; |
1475 | } |
1476 | |
1477 | /// \brief Determine whether this class has at least one trivial, non-deleted |
1478 | /// copy or move constructor. |
1479 | bool canPassInRegisters() const { |
1480 | return data().CanPassInRegisters; |
1481 | } |
1482 | |
1483 | /// \brief Set that we can pass this RecordDecl in registers. |
1484 | // FIXME: This should be set as part of completeDefinition. |
1485 | void setCanPassInRegisters(bool CanPass) { |
1486 | data().CanPassInRegisters = CanPass; |
1487 | } |
1488 | |
1489 | /// Determine whether the triviality for the purpose of calls for this class |
1490 | /// is overridden to be trivial because this class or the type of one of its |
1491 | /// subobjects has attribute "trivial_abi". |
1492 | bool hasTrivialABIOverride() const { |
1493 | return canPassInRegisters() && hasNonTrivialDestructor(); |
1494 | } |
1495 | |
1496 | /// \brief Determine whether this class has a non-literal or/ volatile type |
1497 | /// non-static data member or base class. |
1498 | bool hasNonLiteralTypeFieldsOrBases() const { |
1499 | return data().HasNonLiteralTypeFieldsOrBases; |
1500 | } |
1501 | |
1502 | /// \brief Determine whether this class has a using-declaration that names |
1503 | /// a user-declared base class constructor. |
1504 | bool hasInheritedConstructor() const { |
1505 | return data().HasInheritedConstructor; |
1506 | } |
1507 | |
1508 | /// \brief Determine whether this class has a using-declaration that names |
1509 | /// a base class assignment operator. |
1510 | bool hasInheritedAssignment() const { |
1511 | return data().HasInheritedAssignment; |
1512 | } |
1513 | |
1514 | /// \brief Determine whether this class is considered trivially copyable per |
1515 | /// (C++11 [class]p6). |
1516 | bool isTriviallyCopyable() const; |
1517 | |
1518 | /// \brief Determine whether this class is considered trivial. |
1519 | /// |
1520 | /// C++11 [class]p6: |
1521 | /// "A trivial class is a class that has a trivial default constructor and |
1522 | /// is trivially copiable." |
1523 | bool isTrivial() const { |
1524 | return isTriviallyCopyable() && hasTrivialDefaultConstructor(); |
1525 | } |
1526 | |
1527 | /// \brief Determine whether this class is a literal type. |
1528 | /// |
1529 | /// C++11 [basic.types]p10: |
1530 | /// A class type that has all the following properties: |
1531 | /// - it has a trivial destructor |
1532 | /// - every constructor call and full-expression in the |
1533 | /// brace-or-equal-intializers for non-static data members (if any) is |
1534 | /// a constant expression. |
1535 | /// - it is an aggregate type or has at least one constexpr constructor |
1536 | /// or constructor template that is not a copy or move constructor, and |
1537 | /// - all of its non-static data members and base classes are of literal |
1538 | /// types |
1539 | /// |
1540 | /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by |
1541 | /// treating types with trivial default constructors as literal types. |
1542 | /// |
1543 | /// Only in C++17 and beyond, are lambdas literal types. |
1544 | bool isLiteral() const { |
1545 | return hasTrivialDestructor() && |
1546 | (!isLambda() || getASTContext().getLangOpts().CPlusPlus17) && |
1547 | !hasNonLiteralTypeFieldsOrBases() && |
1548 | (isAggregate() || isLambda() || |
1549 | hasConstexprNonCopyMoveConstructor() || |
1550 | hasTrivialDefaultConstructor()); |
1551 | } |
1552 | |
1553 | /// \brief If this record is an instantiation of a member class, |
1554 | /// retrieves the member class from which it was instantiated. |
1555 | /// |
1556 | /// This routine will return non-null for (non-templated) member |
1557 | /// classes of class templates. For example, given: |
1558 | /// |
1559 | /// \code |
1560 | /// template<typename T> |
1561 | /// struct X { |
1562 | /// struct A { }; |
1563 | /// }; |
1564 | /// \endcode |
1565 | /// |
1566 | /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl |
1567 | /// whose parent is the class template specialization X<int>. For |
1568 | /// this declaration, getInstantiatedFromMemberClass() will return |
1569 | /// the CXXRecordDecl X<T>::A. When a complete definition of |
1570 | /// X<int>::A is required, it will be instantiated from the |
1571 | /// declaration returned by getInstantiatedFromMemberClass(). |
1572 | CXXRecordDecl *getInstantiatedFromMemberClass() const; |
1573 | |
1574 | /// \brief If this class is an instantiation of a member class of a |
1575 | /// class template specialization, retrieves the member specialization |
1576 | /// information. |
1577 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1578 | |
1579 | /// \brief Specify that this record is an instantiation of the |
1580 | /// member class \p RD. |
1581 | void setInstantiationOfMemberClass(CXXRecordDecl *RD, |
1582 | TemplateSpecializationKind TSK); |
1583 | |
1584 | /// \brief Retrieves the class template that is described by this |
1585 | /// class declaration. |
1586 | /// |
1587 | /// Every class template is represented as a ClassTemplateDecl and a |
1588 | /// CXXRecordDecl. The former contains template properties (such as |
1589 | /// the template parameter lists) while the latter contains the |
1590 | /// actual description of the template's |
1591 | /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the |
1592 | /// CXXRecordDecl that from a ClassTemplateDecl, while |
1593 | /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from |
1594 | /// a CXXRecordDecl. |
1595 | ClassTemplateDecl *getDescribedClassTemplate() const; |
1596 | |
1597 | void setDescribedClassTemplate(ClassTemplateDecl *Template); |
1598 | |
1599 | /// \brief Determine whether this particular class is a specialization or |
1600 | /// instantiation of a class template or member class of a class template, |
1601 | /// and how it was instantiated or specialized. |
1602 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1603 | |
1604 | /// \brief Set the kind of specialization or template instantiation this is. |
1605 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK); |
1606 | |
1607 | /// \brief Retrieve the record declaration from which this record could be |
1608 | /// instantiated. Returns null if this class is not a template instantiation. |
1609 | const CXXRecordDecl *getTemplateInstantiationPattern() const; |
1610 | |
1611 | CXXRecordDecl *getTemplateInstantiationPattern() { |
1612 | return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this) |
1613 | ->getTemplateInstantiationPattern()); |
1614 | } |
1615 | |
1616 | /// \brief Returns the destructor decl for this class. |
1617 | CXXDestructorDecl *getDestructor() const; |
1618 | |
1619 | /// \brief Returns true if the class destructor, or any implicitly invoked |
1620 | /// destructors are marked noreturn. |
1621 | bool isAnyDestructorNoReturn() const; |
1622 | |
1623 | /// \brief If the class is a local class [class.local], returns |
1624 | /// the enclosing function declaration. |
1625 | const FunctionDecl *isLocalClass() const { |
1626 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(getDeclContext())) |
1627 | return RD->isLocalClass(); |
1628 | |
1629 | return dyn_cast<FunctionDecl>(getDeclContext()); |
1630 | } |
1631 | |
1632 | FunctionDecl *isLocalClass() { |
1633 | return const_cast<FunctionDecl*>( |
1634 | const_cast<const CXXRecordDecl*>(this)->isLocalClass()); |
1635 | } |
1636 | |
1637 | /// \brief Determine whether this dependent class is a current instantiation, |
1638 | /// when viewed from within the given context. |
1639 | bool isCurrentInstantiation(const DeclContext *CurContext) const; |
1640 | |
1641 | /// \brief Determine whether this class is derived from the class \p Base. |
1642 | /// |
1643 | /// This routine only determines whether this class is derived from \p Base, |
1644 | /// but does not account for factors that may make a Derived -> Base class |
1645 | /// ill-formed, such as private/protected inheritance or multiple, ambiguous |
1646 | /// base class subobjects. |
1647 | /// |
1648 | /// \param Base the base class we are searching for. |
1649 | /// |
1650 | /// \returns true if this class is derived from Base, false otherwise. |
1651 | bool isDerivedFrom(const CXXRecordDecl *Base) const; |
1652 | |
1653 | /// \brief Determine whether this class is derived from the type \p Base. |
1654 | /// |
1655 | /// This routine only determines whether this class is derived from \p Base, |
1656 | /// but does not account for factors that may make a Derived -> Base class |
1657 | /// ill-formed, such as private/protected inheritance or multiple, ambiguous |
1658 | /// base class subobjects. |
1659 | /// |
1660 | /// \param Base the base class we are searching for. |
1661 | /// |
1662 | /// \param Paths will contain the paths taken from the current class to the |
1663 | /// given \p Base class. |
1664 | /// |
1665 | /// \returns true if this class is derived from \p Base, false otherwise. |
1666 | /// |
1667 | /// \todo add a separate parameter to configure IsDerivedFrom, rather than |
1668 | /// tangling input and output in \p Paths |
1669 | bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const; |
1670 | |
1671 | /// \brief Determine whether this class is virtually derived from |
1672 | /// the class \p Base. |
1673 | /// |
1674 | /// This routine only determines whether this class is virtually |
1675 | /// derived from \p Base, but does not account for factors that may |
1676 | /// make a Derived -> Base class ill-formed, such as |
1677 | /// private/protected inheritance or multiple, ambiguous base class |
1678 | /// subobjects. |
1679 | /// |
1680 | /// \param Base the base class we are searching for. |
1681 | /// |
1682 | /// \returns true if this class is virtually derived from Base, |
1683 | /// false otherwise. |
1684 | bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const; |
1685 | |
1686 | /// \brief Determine whether this class is provably not derived from |
1687 | /// the type \p Base. |
1688 | bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const; |
1689 | |
1690 | /// \brief Function type used by forallBases() as a callback. |
1691 | /// |
1692 | /// \param BaseDefinition the definition of the base class |
1693 | /// |
1694 | /// \returns true if this base matched the search criteria |
1695 | using ForallBasesCallback = |
1696 | llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>; |
1697 | |
1698 | /// \brief Determines if the given callback holds for all the direct |
1699 | /// or indirect base classes of this type. |
1700 | /// |
1701 | /// The class itself does not count as a base class. This routine |
1702 | /// returns false if the class has non-computable base classes. |
1703 | /// |
1704 | /// \param BaseMatches Callback invoked for each (direct or indirect) base |
1705 | /// class of this type, or if \p AllowShortCircuit is true then until a call |
1706 | /// returns false. |
1707 | /// |
1708 | /// \param AllowShortCircuit if false, forces the callback to be called |
1709 | /// for every base class, even if a dependent or non-matching base was |
1710 | /// found. |
1711 | bool forallBases(ForallBasesCallback BaseMatches, |
1712 | bool AllowShortCircuit = true) const; |
1713 | |
1714 | /// \brief Function type used by lookupInBases() to determine whether a |
1715 | /// specific base class subobject matches the lookup criteria. |
1716 | /// |
1717 | /// \param Specifier the base-class specifier that describes the inheritance |
1718 | /// from the base class we are trying to match. |
1719 | /// |
1720 | /// \param Path the current path, from the most-derived class down to the |
1721 | /// base named by the \p Specifier. |
1722 | /// |
1723 | /// \returns true if this base matched the search criteria, false otherwise. |
1724 | using BaseMatchesCallback = |
1725 | llvm::function_ref<bool(const CXXBaseSpecifier *Specifier, |
1726 | CXXBasePath &Path)>; |
1727 | |
1728 | /// \brief Look for entities within the base classes of this C++ class, |
1729 | /// transitively searching all base class subobjects. |
1730 | /// |
1731 | /// This routine uses the callback function \p BaseMatches to find base |
1732 | /// classes meeting some search criteria, walking all base class subobjects |
1733 | /// and populating the given \p Paths structure with the paths through the |
1734 | /// inheritance hierarchy that resulted in a match. On a successful search, |
1735 | /// the \p Paths structure can be queried to retrieve the matching paths and |
1736 | /// to determine if there were any ambiguities. |
1737 | /// |
1738 | /// \param BaseMatches callback function used to determine whether a given |
1739 | /// base matches the user-defined search criteria. |
1740 | /// |
1741 | /// \param Paths used to record the paths from this class to its base class |
1742 | /// subobjects that match the search criteria. |
1743 | /// |
1744 | /// \param LookupInDependent can be set to true to extend the search to |
1745 | /// dependent base classes. |
1746 | /// |
1747 | /// \returns true if there exists any path from this class to a base class |
1748 | /// subobject that matches the search criteria. |
1749 | bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, |
1750 | bool LookupInDependent = false) const; |
1751 | |
1752 | /// \brief Base-class lookup callback that determines whether the given |
1753 | /// base class specifier refers to a specific class declaration. |
1754 | /// |
1755 | /// This callback can be used with \c lookupInBases() to determine whether |
1756 | /// a given derived class has is a base class subobject of a particular type. |
1757 | /// The base record pointer should refer to the canonical CXXRecordDecl of the |
1758 | /// base class that we are searching for. |
1759 | static bool FindBaseClass(const CXXBaseSpecifier *Specifier, |
1760 | CXXBasePath &Path, const CXXRecordDecl *BaseRecord); |
1761 | |
1762 | /// \brief Base-class lookup callback that determines whether the |
1763 | /// given base class specifier refers to a specific class |
1764 | /// declaration and describes virtual derivation. |
1765 | /// |
1766 | /// This callback can be used with \c lookupInBases() to determine |
1767 | /// whether a given derived class has is a virtual base class |
1768 | /// subobject of a particular type. The base record pointer should |
1769 | /// refer to the canonical CXXRecordDecl of the base class that we |
1770 | /// are searching for. |
1771 | static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, |
1772 | CXXBasePath &Path, |
1773 | const CXXRecordDecl *BaseRecord); |
1774 | |
1775 | /// \brief Base-class lookup callback that determines whether there exists |
1776 | /// a tag with the given name. |
1777 | /// |
1778 | /// This callback can be used with \c lookupInBases() to find tag members |
1779 | /// of the given name within a C++ class hierarchy. |
1780 | static bool FindTagMember(const CXXBaseSpecifier *Specifier, |
1781 | CXXBasePath &Path, DeclarationName Name); |
1782 | |
1783 | /// \brief Base-class lookup callback that determines whether there exists |
1784 | /// a member with the given name. |
1785 | /// |
1786 | /// This callback can be used with \c lookupInBases() to find members |
1787 | /// of the given name within a C++ class hierarchy. |
1788 | static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier, |
1789 | CXXBasePath &Path, DeclarationName Name); |
1790 | |
1791 | /// \brief Base-class lookup callback that determines whether there exists |
1792 | /// a member with the given name. |
1793 | /// |
1794 | /// This callback can be used with \c lookupInBases() to find members |
1795 | /// of the given name within a C++ class hierarchy, including dependent |
1796 | /// classes. |
1797 | static bool |
1798 | FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, |
1799 | CXXBasePath &Path, DeclarationName Name); |
1800 | |
1801 | /// \brief Base-class lookup callback that determines whether there exists |
1802 | /// an OpenMP declare reduction member with the given name. |
1803 | /// |
1804 | /// This callback can be used with \c lookupInBases() to find members |
1805 | /// of the given name within a C++ class hierarchy. |
1806 | static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier, |
1807 | CXXBasePath &Path, DeclarationName Name); |
1808 | |
1809 | /// \brief Base-class lookup callback that determines whether there exists |
1810 | /// a member with the given name that can be used in a nested-name-specifier. |
1811 | /// |
1812 | /// This callback can be used with \c lookupInBases() to find members of |
1813 | /// the given name within a C++ class hierarchy that can occur within |
1814 | /// nested-name-specifiers. |
1815 | static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, |
1816 | CXXBasePath &Path, |
1817 | DeclarationName Name); |
1818 | |
1819 | /// \brief Retrieve the final overriders for each virtual member |
1820 | /// function in the class hierarchy where this class is the |
1821 | /// most-derived class in the class hierarchy. |
1822 | void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const; |
1823 | |
1824 | /// \brief Get the indirect primary bases for this class. |
1825 | void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const; |
1826 | |
1827 | /// Performs an imprecise lookup of a dependent name in this class. |
1828 | /// |
1829 | /// This function does not follow strict semantic rules and should be used |
1830 | /// only when lookup rules can be relaxed, e.g. indexing. |
1831 | std::vector<const NamedDecl *> |
1832 | lookupDependentName(const DeclarationName &Name, |
1833 | llvm::function_ref<bool(const NamedDecl *ND)> Filter); |
1834 | |
1835 | /// Renders and displays an inheritance diagram |
1836 | /// for this C++ class and all of its base classes (transitively) using |
1837 | /// GraphViz. |
1838 | void viewInheritance(ASTContext& Context) const; |
1839 | |
1840 | /// \brief Calculates the access of a decl that is reached |
1841 | /// along a path. |
1842 | static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, |
1843 | AccessSpecifier DeclAccess) { |
1844 | assert(DeclAccess != AS_none)(static_cast <bool> (DeclAccess != AS_none) ? void (0) : __assert_fail ("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1844, __extension__ __PRETTY_FUNCTION__)); |
1845 | if (DeclAccess == AS_private) return AS_none; |
1846 | return (PathAccess > DeclAccess ? PathAccess : DeclAccess); |
1847 | } |
1848 | |
1849 | /// \brief Indicates that the declaration of a defaulted or deleted special |
1850 | /// member function is now complete. |
1851 | void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD); |
1852 | |
1853 | void setTrivialForCallFlags(CXXMethodDecl *MD); |
1854 | |
1855 | /// \brief Indicates that the definition of this class is now complete. |
1856 | void completeDefinition() override; |
1857 | |
1858 | /// \brief Indicates that the definition of this class is now complete, |
1859 | /// and provides a final overrider map to help determine |
1860 | /// |
1861 | /// \param FinalOverriders The final overrider map for this class, which can |
1862 | /// be provided as an optimization for abstract-class checking. If NULL, |
1863 | /// final overriders will be computed if they are needed to complete the |
1864 | /// definition. |
1865 | void completeDefinition(CXXFinalOverriderMap *FinalOverriders); |
1866 | |
1867 | /// \brief Determine whether this class may end up being abstract, even though |
1868 | /// it is not yet known to be abstract. |
1869 | /// |
1870 | /// \returns true if this class is not known to be abstract but has any |
1871 | /// base classes that are abstract. In this case, \c completeDefinition() |
1872 | /// will need to compute final overriders to determine whether the class is |
1873 | /// actually abstract. |
1874 | bool mayBeAbstract() const; |
1875 | |
1876 | /// \brief If this is the closure type of a lambda expression, retrieve the |
1877 | /// number to be used for name mangling in the Itanium C++ ABI. |
1878 | /// |
1879 | /// Zero indicates that this closure type has internal linkage, so the |
1880 | /// mangling number does not matter, while a non-zero value indicates which |
1881 | /// lambda expression this is in this particular context. |
1882 | unsigned getLambdaManglingNumber() const { |
1883 | assert(isLambda() && "Not a lambda closure type!")(static_cast <bool> (isLambda() && "Not a lambda closure type!" ) ? void (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 1883, __extension__ __PRETTY_FUNCTION__)); |
1884 | return getLambdaData().ManglingNumber; |
1885 | } |
1886 | |
1887 | /// \brief Retrieve the declaration that provides additional context for a |
1888 | /// lambda, when the normal declaration context is not specific enough. |
1889 | /// |
1890 | /// Certain contexts (default arguments of in-class function parameters and |
1891 | /// the initializers of data members) have separate name mangling rules for |
1892 | /// lambdas within the Itanium C++ ABI. For these cases, this routine provides |
1893 | /// the declaration in which the lambda occurs, e.g., the function parameter |
1894 | /// or the non-static data member. Otherwise, it returns NULL to imply that |
1895 | /// the declaration context suffices. |
1896 | Decl *getLambdaContextDecl() const; |
1897 | |
1898 | /// \brief Set the mangling number and context declaration for a lambda |
1899 | /// class. |
1900 | void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) { |
1901 | getLambdaData().ManglingNumber = ManglingNumber; |
1902 | getLambdaData().ContextDecl = ContextDecl; |
1903 | } |
1904 | |
1905 | /// \brief Returns the inheritance model used for this record. |
1906 | MSInheritanceAttr::Spelling getMSInheritanceModel() const; |
1907 | |
1908 | /// \brief Calculate what the inheritance model would be for this class. |
1909 | MSInheritanceAttr::Spelling calculateInheritanceModel() const; |
1910 | |
1911 | /// In the Microsoft C++ ABI, use zero for the field offset of a null data |
1912 | /// member pointer if we can guarantee that zero is not a valid field offset, |
1913 | /// or if the member pointer has multiple fields. Polymorphic classes have a |
1914 | /// vfptr at offset zero, so we can use zero for null. If there are multiple |
1915 | /// fields, we can use zero even if it is a valid field offset because |
1916 | /// null-ness testing will check the other fields. |
1917 | bool nullFieldOffsetIsZero() const { |
1918 | return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false, |
1919 | getMSInheritanceModel()) || |
1920 | (hasDefinition() && isPolymorphic()); |
1921 | } |
1922 | |
1923 | /// \brief Controls when vtordisps will be emitted if this record is used as a |
1924 | /// virtual base. |
1925 | MSVtorDispAttr::Mode getMSVtorDispMode() const; |
1926 | |
1927 | /// \brief Determine whether this lambda expression was known to be dependent |
1928 | /// at the time it was created, even if its context does not appear to be |
1929 | /// dependent. |
1930 | /// |
1931 | /// This flag is a workaround for an issue with parsing, where default |
1932 | /// arguments are parsed before their enclosing function declarations have |
1933 | /// been created. This means that any lambda expressions within those |
1934 | /// default arguments will have as their DeclContext the context enclosing |
1935 | /// the function declaration, which may be non-dependent even when the |
1936 | /// function declaration itself is dependent. This flag indicates when we |
1937 | /// know that the lambda is dependent despite that. |
1938 | bool isDependentLambda() const { |
1939 | return isLambda() && getLambdaData().Dependent; |
1940 | } |
1941 | |
1942 | TypeSourceInfo *getLambdaTypeInfo() const { |
1943 | return getLambdaData().MethodTyInfo; |
1944 | } |
1945 | |
1946 | // \brief Determine whether this type is an Interface Like type for |
1947 | // __interface inheritence purposes. |
1948 | bool isInterfaceLike() const; |
1949 | |
1950 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1951 | static bool classofKind(Kind K) { |
1952 | return K >= firstCXXRecord && K <= lastCXXRecord; |
1953 | } |
1954 | }; |
1955 | |
1956 | /// \brief Represents a C++ deduction guide declaration. |
1957 | /// |
1958 | /// \code |
1959 | /// template<typename T> struct A { A(); A(T); }; |
1960 | /// A() -> A<int>; |
1961 | /// \endcode |
1962 | /// |
1963 | /// In this example, there will be an explicit deduction guide from the |
1964 | /// second line, and implicit deduction guide templates synthesized from |
1965 | /// the constructors of \c A. |
1966 | class CXXDeductionGuideDecl : public FunctionDecl { |
1967 | void anchor() override; |
1968 | |
1969 | private: |
1970 | CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1971 | bool IsExplicit, const DeclarationNameInfo &NameInfo, |
1972 | QualType T, TypeSourceInfo *TInfo, |
1973 | SourceLocation EndLocation) |
1974 | : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo, |
1975 | SC_None, false, false) { |
1976 | if (EndLocation.isValid()) |
1977 | setRangeEnd(EndLocation); |
1978 | IsExplicitSpecified = IsExplicit; |
1979 | } |
1980 | |
1981 | public: |
1982 | friend class ASTDeclReader; |
1983 | friend class ASTDeclWriter; |
1984 | |
1985 | static CXXDeductionGuideDecl *Create(ASTContext &C, DeclContext *DC, |
1986 | SourceLocation StartLoc, bool IsExplicit, |
1987 | const DeclarationNameInfo &NameInfo, |
1988 | QualType T, TypeSourceInfo *TInfo, |
1989 | SourceLocation EndLocation); |
1990 | |
1991 | static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1992 | |
1993 | /// Whether this deduction guide is explicit. |
1994 | bool isExplicit() const { return IsExplicitSpecified; } |
1995 | |
1996 | /// Whether this deduction guide was declared with the 'explicit' specifier. |
1997 | bool isExplicitSpecified() const { return IsExplicitSpecified; } |
1998 | |
1999 | /// Get the template for which this guide performs deduction. |
2000 | TemplateDecl *getDeducedTemplate() const { |
2001 | return getDeclName().getCXXDeductionGuideTemplate(); |
2002 | } |
2003 | |
2004 | void setIsCopyDeductionCandidate() { |
2005 | IsCopyDeductionCandidate = true; |
2006 | } |
2007 | |
2008 | bool isCopyDeductionCandidate() const { return IsCopyDeductionCandidate; } |
2009 | |
2010 | // Implement isa/cast/dyncast/etc. |
2011 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2012 | static bool classofKind(Kind K) { return K == CXXDeductionGuide; } |
2013 | }; |
2014 | |
2015 | /// \brief Represents a static or instance method of a struct/union/class. |
2016 | /// |
2017 | /// In the terminology of the C++ Standard, these are the (static and |
2018 | /// non-static) member functions, whether virtual or not. |
2019 | class CXXMethodDecl : public FunctionDecl { |
2020 | void anchor() override; |
2021 | |
2022 | protected: |
2023 | CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD, |
2024 | SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, |
2025 | QualType T, TypeSourceInfo *TInfo, |
2026 | StorageClass SC, bool isInline, |
2027 | bool isConstexpr, SourceLocation EndLocation) |
2028 | : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, |
2029 | SC, isInline, isConstexpr) { |
2030 | if (EndLocation.isValid()) |
2031 | setRangeEnd(EndLocation); |
2032 | } |
2033 | |
2034 | public: |
2035 | static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD, |
2036 | SourceLocation StartLoc, |
2037 | const DeclarationNameInfo &NameInfo, |
2038 | QualType T, TypeSourceInfo *TInfo, |
2039 | StorageClass SC, |
2040 | bool isInline, |
2041 | bool isConstexpr, |
2042 | SourceLocation EndLocation); |
2043 | |
2044 | static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2045 | |
2046 | bool isStatic() const; |
2047 | bool isInstance() const { return !isStatic(); } |
2048 | |
2049 | /// Returns true if the given operator is implicitly static in a record |
2050 | /// context. |
2051 | static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) { |
2052 | // [class.free]p1: |
2053 | // Any allocation function for a class T is a static member |
2054 | // (even if not explicitly declared static). |
2055 | // [class.free]p6 Any deallocation function for a class X is a static member |
2056 | // (even if not explicitly declared static). |
2057 | return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete || |
2058 | OOK == OO_Array_Delete; |
2059 | } |
2060 | |
2061 | bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); } |
2062 | bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); } |
2063 | |
2064 | bool isVirtual() const { |
2065 | CXXMethodDecl *CD = |
2066 | cast<CXXMethodDecl>(const_cast<CXXMethodDecl*>(this)->getCanonicalDecl()); |
2067 | |
2068 | // Member function is virtual if it is marked explicitly so, or if it is |
2069 | // declared in __interface -- then it is automatically pure virtual. |
2070 | if (CD->isVirtualAsWritten() || CD->isPure()) |
2071 | return true; |
2072 | |
2073 | return CD->size_overridden_methods() != 0; |
2074 | } |
2075 | |
2076 | /// If it's possible to devirtualize a call to this method, return the called |
2077 | /// function. Otherwise, return null. |
2078 | |
2079 | /// \param Base The object on which this virtual function is called. |
2080 | /// \param IsAppleKext True if we are compiling for Apple kext. |
2081 | CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext); |
2082 | |
2083 | const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, |
2084 | bool IsAppleKext) const { |
2085 | return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod( |
2086 | Base, IsAppleKext); |
2087 | } |
2088 | |
2089 | /// \brief Determine whether this is a usual deallocation function |
2090 | /// (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded |
2091 | /// delete or delete[] operator with a particular signature. |
2092 | bool isUsualDeallocationFunction() const; |
2093 | |
2094 | /// \brief Determine whether this is a copy-assignment operator, regardless |
2095 | /// of whether it was declared implicitly or explicitly. |
2096 | bool isCopyAssignmentOperator() const; |
2097 | |
2098 | /// \brief Determine whether this is a move assignment operator. |
2099 | bool isMoveAssignmentOperator() const; |
2100 | |
2101 | CXXMethodDecl *getCanonicalDecl() override { |
2102 | return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl()); |
2103 | } |
2104 | const CXXMethodDecl *getCanonicalDecl() const { |
2105 | return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl(); |
2106 | } |
2107 | |
2108 | CXXMethodDecl *getMostRecentDecl() { |
2109 | return cast<CXXMethodDecl>( |
2110 | static_cast<FunctionDecl *>(this)->getMostRecentDecl()); |
2111 | } |
2112 | const CXXMethodDecl *getMostRecentDecl() const { |
2113 | return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl(); |
2114 | } |
2115 | |
2116 | /// True if this method is user-declared and was not |
2117 | /// deleted or defaulted on its first declaration. |
2118 | bool isUserProvided() const { |
2119 | auto *DeclAsWritten = this; |
2120 | if (auto *Pattern = getTemplateInstantiationPattern()) |
2121 | DeclAsWritten = cast<CXXMethodDecl>(Pattern); |
2122 | return !(DeclAsWritten->isDeleted() || |
2123 | DeclAsWritten->getCanonicalDecl()->isDefaulted()); |
2124 | } |
2125 | |
2126 | void addOverriddenMethod(const CXXMethodDecl *MD); |
2127 | |
2128 | using method_iterator = const CXXMethodDecl *const *; |
2129 | |
2130 | method_iterator begin_overridden_methods() const; |
2131 | method_iterator end_overridden_methods() const; |
2132 | unsigned size_overridden_methods() const; |
2133 | |
2134 | using overridden_method_range= ASTContext::overridden_method_range; |
2135 | |
2136 | overridden_method_range overridden_methods() const; |
2137 | |
2138 | /// Returns the parent of this method declaration, which |
2139 | /// is the class in which this method is defined. |
2140 | const CXXRecordDecl *getParent() const { |
2141 | return cast<CXXRecordDecl>(FunctionDecl::getParent()); |
2142 | } |
2143 | |
2144 | /// Returns the parent of this method declaration, which |
2145 | /// is the class in which this method is defined. |
2146 | CXXRecordDecl *getParent() { |
2147 | return const_cast<CXXRecordDecl *>( |
2148 | cast<CXXRecordDecl>(FunctionDecl::getParent())); |
2149 | } |
2150 | |
2151 | /// \brief Returns the type of the \c this pointer. |
2152 | /// |
2153 | /// Should only be called for instance (i.e., non-static) methods. Note |
2154 | /// that for the call operator of a lambda closure type, this returns the |
2155 | /// desugared 'this' type (a pointer to the closure type), not the captured |
2156 | /// 'this' type. |
2157 | QualType getThisType(ASTContext &C) const; |
2158 | |
2159 | unsigned getTypeQualifiers() const { |
2160 | return getType()->getAs<FunctionProtoType>()->getTypeQuals(); |
2161 | } |
2162 | |
2163 | /// \brief Retrieve the ref-qualifier associated with this method. |
2164 | /// |
2165 | /// In the following example, \c f() has an lvalue ref-qualifier, \c g() |
2166 | /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier. |
2167 | /// @code |
2168 | /// struct X { |
2169 | /// void f() &; |
2170 | /// void g() &&; |
2171 | /// void h(); |
2172 | /// }; |
2173 | /// @endcode |
2174 | RefQualifierKind getRefQualifier() const { |
2175 | return getType()->getAs<FunctionProtoType>()->getRefQualifier(); |
2176 | } |
2177 | |
2178 | bool hasInlineBody() const; |
2179 | |
2180 | /// \brief Determine whether this is a lambda closure type's static member |
2181 | /// function that is used for the result of the lambda's conversion to |
2182 | /// function pointer (for a lambda with no captures). |
2183 | /// |
2184 | /// The function itself, if used, will have a placeholder body that will be |
2185 | /// supplied by IR generation to either forward to the function call operator |
2186 | /// or clone the function call operator. |
2187 | bool isLambdaStaticInvoker() const; |
2188 | |
2189 | /// \brief Find the method in \p RD that corresponds to this one. |
2190 | /// |
2191 | /// Find if \p RD or one of the classes it inherits from override this method. |
2192 | /// If so, return it. \p RD is assumed to be a subclass of the class defining |
2193 | /// this method (or be the class itself), unless \p MayBeBase is set to true. |
2194 | CXXMethodDecl * |
2195 | getCorrespondingMethodInClass(const CXXRecordDecl *RD, |
2196 | bool MayBeBase = false); |
2197 | |
2198 | const CXXMethodDecl * |
2199 | getCorrespondingMethodInClass(const CXXRecordDecl *RD, |
2200 | bool MayBeBase = false) const { |
2201 | return const_cast<CXXMethodDecl *>(this) |
2202 | ->getCorrespondingMethodInClass(RD, MayBeBase); |
2203 | } |
2204 | |
2205 | // Implement isa/cast/dyncast/etc. |
2206 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2207 | static bool classofKind(Kind K) { |
2208 | return K >= firstCXXMethod && K <= lastCXXMethod; |
2209 | } |
2210 | }; |
2211 | |
2212 | /// \brief Represents a C++ base or member initializer. |
2213 | /// |
2214 | /// This is part of a constructor initializer that |
2215 | /// initializes one non-static member variable or one base class. For |
2216 | /// example, in the following, both 'A(a)' and 'f(3.14159)' are member |
2217 | /// initializers: |
2218 | /// |
2219 | /// \code |
2220 | /// class A { }; |
2221 | /// class B : public A { |
2222 | /// float f; |
2223 | /// public: |
2224 | /// B(A& a) : A(a), f(3.14159) { } |
2225 | /// }; |
2226 | /// \endcode |
2227 | class CXXCtorInitializer final { |
2228 | /// \brief Either the base class name/delegating constructor type (stored as |
2229 | /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field |
2230 | /// (IndirectFieldDecl*) being initialized. |
2231 | llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *> |
2232 | Initializee; |
2233 | |
2234 | /// \brief The source location for the field name or, for a base initializer |
2235 | /// pack expansion, the location of the ellipsis. |
2236 | /// |
2237 | /// In the case of a delegating |
2238 | /// constructor, it will still include the type's source location as the |
2239 | /// Initializee points to the CXXConstructorDecl (to allow loop detection). |
2240 | SourceLocation MemberOrEllipsisLocation; |
2241 | |
2242 | /// \brief The argument used to initialize the base or member, which may |
2243 | /// end up constructing an object (when multiple arguments are involved). |
2244 | Stmt *Init; |
2245 | |
2246 | /// \brief Location of the left paren of the ctor-initializer. |
2247 | SourceLocation LParenLoc; |
2248 | |
2249 | /// \brief Location of the right paren of the ctor-initializer. |
2250 | SourceLocation RParenLoc; |
2251 | |
2252 | /// \brief If the initializee is a type, whether that type makes this |
2253 | /// a delegating initialization. |
2254 | unsigned IsDelegating : 1; |
2255 | |
2256 | /// \brief If the initializer is a base initializer, this keeps track |
2257 | /// of whether the base is virtual or not. |
2258 | unsigned IsVirtual : 1; |
2259 | |
2260 | /// \brief Whether or not the initializer is explicitly written |
2261 | /// in the sources. |
2262 | unsigned IsWritten : 1; |
2263 | |
2264 | /// If IsWritten is true, then this number keeps track of the textual order |
2265 | /// of this initializer in the original sources, counting from 0. |
2266 | unsigned SourceOrder : 13; |
2267 | |
2268 | public: |
2269 | /// \brief Creates a new base-class initializer. |
2270 | explicit |
2271 | CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual, |
2272 | SourceLocation L, Expr *Init, SourceLocation R, |
2273 | SourceLocation EllipsisLoc); |
2274 | |
2275 | /// \brief Creates a new member initializer. |
2276 | explicit |
2277 | CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, |
2278 | SourceLocation MemberLoc, SourceLocation L, Expr *Init, |
2279 | SourceLocation R); |
2280 | |
2281 | /// \brief Creates a new anonymous field initializer. |
2282 | explicit |
2283 | CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member, |
2284 | SourceLocation MemberLoc, SourceLocation L, Expr *Init, |
2285 | SourceLocation R); |
2286 | |
2287 | /// \brief Creates a new delegating initializer. |
2288 | explicit |
2289 | CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, |
2290 | SourceLocation L, Expr *Init, SourceLocation R); |
2291 | |
2292 | /// \brief Determine whether this initializer is initializing a base class. |
2293 | bool isBaseInitializer() const { |
2294 | return Initializee.is<TypeSourceInfo*>() && !IsDelegating; |
2295 | } |
2296 | |
2297 | /// \brief Determine whether this initializer is initializing a non-static |
2298 | /// data member. |
2299 | bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); } |
2300 | |
2301 | bool isAnyMemberInitializer() const { |
2302 | return isMemberInitializer() || isIndirectMemberInitializer(); |
2303 | } |
2304 | |
2305 | bool isIndirectMemberInitializer() const { |
2306 | return Initializee.is<IndirectFieldDecl*>(); |
2307 | } |
2308 | |
2309 | /// \brief Determine whether this initializer is an implicit initializer |
2310 | /// generated for a field with an initializer defined on the member |
2311 | /// declaration. |
2312 | /// |
2313 | /// In-class member initializers (also known as "non-static data member |
2314 | /// initializations", NSDMIs) were introduced in C++11. |
2315 | bool isInClassMemberInitializer() const { |
2316 | return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass; |
2317 | } |
2318 | |
2319 | /// \brief Determine whether this initializer is creating a delegating |
2320 | /// constructor. |
2321 | bool isDelegatingInitializer() const { |
2322 | return Initializee.is<TypeSourceInfo*>() && IsDelegating; |
2323 | } |
2324 | |
2325 | /// \brief Determine whether this initializer is a pack expansion. |
2326 | bool isPackExpansion() const { |
2327 | return isBaseInitializer() && MemberOrEllipsisLocation.isValid(); |
2328 | } |
2329 | |
2330 | // \brief For a pack expansion, returns the location of the ellipsis. |
2331 | SourceLocation getEllipsisLoc() const { |
2332 | assert(isPackExpansion() && "Initializer is not a pack expansion")(static_cast <bool> (isPackExpansion() && "Initializer is not a pack expansion" ) ? void (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2332, __extension__ __PRETTY_FUNCTION__)); |
2333 | return MemberOrEllipsisLocation; |
2334 | } |
2335 | |
2336 | /// If this is a base class initializer, returns the type of the |
2337 | /// base class with location information. Otherwise, returns an NULL |
2338 | /// type location. |
2339 | TypeLoc getBaseClassLoc() const; |
2340 | |
2341 | /// If this is a base class initializer, returns the type of the base class. |
2342 | /// Otherwise, returns null. |
2343 | const Type *getBaseClass() const; |
2344 | |
2345 | /// Returns whether the base is virtual or not. |
2346 | bool isBaseVirtual() const { |
2347 | assert(isBaseInitializer() && "Must call this on base initializer!")(static_cast <bool> (isBaseInitializer() && "Must call this on base initializer!" ) ? void (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2347, __extension__ __PRETTY_FUNCTION__)); |
2348 | |
2349 | return IsVirtual; |
2350 | } |
2351 | |
2352 | /// \brief Returns the declarator information for a base class or delegating |
2353 | /// initializer. |
2354 | TypeSourceInfo *getTypeSourceInfo() const { |
2355 | return Initializee.dyn_cast<TypeSourceInfo *>(); |
2356 | } |
2357 | |
2358 | /// \brief If this is a member initializer, returns the declaration of the |
2359 | /// non-static data member being initialized. Otherwise, returns null. |
2360 | FieldDecl *getMember() const { |
2361 | if (isMemberInitializer()) |
2362 | return Initializee.get<FieldDecl*>(); |
2363 | return nullptr; |
2364 | } |
2365 | |
2366 | FieldDecl *getAnyMember() const { |
2367 | if (isMemberInitializer()) |
2368 | return Initializee.get<FieldDecl*>(); |
2369 | if (isIndirectMemberInitializer()) |
2370 | return Initializee.get<IndirectFieldDecl*>()->getAnonField(); |
2371 | return nullptr; |
2372 | } |
2373 | |
2374 | IndirectFieldDecl *getIndirectMember() const { |
2375 | if (isIndirectMemberInitializer()) |
2376 | return Initializee.get<IndirectFieldDecl*>(); |
2377 | return nullptr; |
2378 | } |
2379 | |
2380 | SourceLocation getMemberLocation() const { |
2381 | return MemberOrEllipsisLocation; |
2382 | } |
2383 | |
2384 | /// \brief Determine the source location of the initializer. |
2385 | SourceLocation getSourceLocation() const; |
2386 | |
2387 | /// \brief Determine the source range covering the entire initializer. |
2388 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)); |
2389 | |
2390 | /// \brief Determine whether this initializer is explicitly written |
2391 | /// in the source code. |
2392 | bool isWritten() const { return IsWritten; } |
2393 | |
2394 | /// \brief Return the source position of the initializer, counting from 0. |
2395 | /// If the initializer was implicit, -1 is returned. |
2396 | int getSourceOrder() const { |
2397 | return IsWritten ? static_cast<int>(SourceOrder) : -1; |
2398 | } |
2399 | |
2400 | /// \brief Set the source order of this initializer. |
2401 | /// |
2402 | /// This can only be called once for each initializer; it cannot be called |
2403 | /// on an initializer having a positive number of (implicit) array indices. |
2404 | /// |
2405 | /// This assumes that the initializer was written in the source code, and |
2406 | /// ensures that isWritten() returns true. |
2407 | void setSourceOrder(int Pos) { |
2408 | assert(!IsWritten &&(static_cast <bool> (!IsWritten && "setSourceOrder() used on implicit initializer" ) ? void (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2409, __extension__ __PRETTY_FUNCTION__)) |
2409 | "setSourceOrder() used on implicit initializer")(static_cast <bool> (!IsWritten && "setSourceOrder() used on implicit initializer" ) ? void (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2409, __extension__ __PRETTY_FUNCTION__)); |
2410 | assert(SourceOrder == 0 &&(static_cast <bool> (SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer" ) ? void (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2411, __extension__ __PRETTY_FUNCTION__)) |
2411 | "calling twice setSourceOrder() on the same initializer")(static_cast <bool> (SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer" ) ? void (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2411, __extension__ __PRETTY_FUNCTION__)); |
2412 | assert(Pos >= 0 &&(static_cast <bool> (Pos >= 0 && "setSourceOrder() used to make an initializer implicit" ) ? void (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2413, __extension__ __PRETTY_FUNCTION__)) |
2413 | "setSourceOrder() used to make an initializer implicit")(static_cast <bool> (Pos >= 0 && "setSourceOrder() used to make an initializer implicit" ) ? void (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2413, __extension__ __PRETTY_FUNCTION__)); |
2414 | IsWritten = true; |
2415 | SourceOrder = static_cast<unsigned>(Pos); |
2416 | } |
2417 | |
2418 | SourceLocation getLParenLoc() const { return LParenLoc; } |
2419 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2420 | |
2421 | /// \brief Get the initializer. |
2422 | Expr *getInit() const { return static_cast<Expr*>(Init); } |
2423 | }; |
2424 | |
2425 | /// Description of a constructor that was inherited from a base class. |
2426 | class InheritedConstructor { |
2427 | ConstructorUsingShadowDecl *Shadow = nullptr; |
2428 | CXXConstructorDecl *BaseCtor = nullptr; |
2429 | |
2430 | public: |
2431 | InheritedConstructor() = default; |
2432 | InheritedConstructor(ConstructorUsingShadowDecl *Shadow, |
2433 | CXXConstructorDecl *BaseCtor) |
2434 | : Shadow(Shadow), BaseCtor(BaseCtor) {} |
2435 | |
2436 | explicit operator bool() const { return Shadow; } |
2437 | |
2438 | ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; } |
2439 | CXXConstructorDecl *getConstructor() const { return BaseCtor; } |
2440 | }; |
2441 | |
2442 | /// \brief Represents a C++ constructor within a class. |
2443 | /// |
2444 | /// For example: |
2445 | /// |
2446 | /// \code |
2447 | /// class X { |
2448 | /// public: |
2449 | /// explicit X(int); // represented by a CXXConstructorDecl. |
2450 | /// }; |
2451 | /// \endcode |
2452 | class CXXConstructorDecl final |
2453 | : public CXXMethodDecl, |
2454 | private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor> { |
2455 | /// \name Support for base and member initializers. |
2456 | /// \{ |
2457 | /// \brief The arguments used to initialize the base or member. |
2458 | LazyCXXCtorInitializersPtr CtorInitializers; |
2459 | unsigned NumCtorInitializers : 31; |
2460 | /// \} |
2461 | |
2462 | /// \brief Whether this constructor declaration is an implicitly-declared |
2463 | /// inheriting constructor. |
2464 | unsigned IsInheritingConstructor : 1; |
2465 | |
2466 | CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2467 | const DeclarationNameInfo &NameInfo, |
2468 | QualType T, TypeSourceInfo *TInfo, |
2469 | bool isExplicitSpecified, bool isInline, |
2470 | bool isImplicitlyDeclared, bool isConstexpr, |
2471 | InheritedConstructor Inherited) |
2472 | : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo, |
2473 | SC_None, isInline, isConstexpr, SourceLocation()), |
2474 | NumCtorInitializers(0), IsInheritingConstructor((bool)Inherited) { |
2475 | setImplicit(isImplicitlyDeclared); |
2476 | if (Inherited) |
2477 | *getTrailingObjects<InheritedConstructor>() = Inherited; |
2478 | IsExplicitSpecified = isExplicitSpecified; |
2479 | } |
2480 | |
2481 | void anchor() override; |
2482 | |
2483 | public: |
2484 | friend class ASTDeclReader; |
2485 | friend class ASTDeclWriter; |
2486 | friend TrailingObjects; |
2487 | |
2488 | static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
2489 | bool InheritsConstructor); |
2490 | static CXXConstructorDecl * |
2491 | Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2492 | const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, |
2493 | bool isExplicit, bool isInline, bool isImplicitlyDeclared, |
2494 | bool isConstexpr, |
2495 | InheritedConstructor Inherited = InheritedConstructor()); |
2496 | |
2497 | /// \brief Iterates through the member/base initializer list. |
2498 | using init_iterator = CXXCtorInitializer **; |
2499 | |
2500 | /// \brief Iterates through the member/base initializer list. |
2501 | using init_const_iterator = CXXCtorInitializer *const *; |
2502 | |
2503 | using init_range = llvm::iterator_range<init_iterator>; |
2504 | using init_const_range = llvm::iterator_range<init_const_iterator>; |
2505 | |
2506 | init_range inits() { return init_range(init_begin(), init_end()); } |
2507 | init_const_range inits() const { |
2508 | return init_const_range(init_begin(), init_end()); |
2509 | } |
2510 | |
2511 | /// \brief Retrieve an iterator to the first initializer. |
2512 | init_iterator init_begin() { |
2513 | const auto *ConstThis = this; |
2514 | return const_cast<init_iterator>(ConstThis->init_begin()); |
2515 | } |
2516 | |
2517 | /// \brief Retrieve an iterator to the first initializer. |
2518 | init_const_iterator init_begin() const; |
2519 | |
2520 | /// \brief Retrieve an iterator past the last initializer. |
2521 | init_iterator init_end() { |
2522 | return init_begin() + NumCtorInitializers; |
2523 | } |
2524 | |
2525 | /// \brief Retrieve an iterator past the last initializer. |
2526 | init_const_iterator init_end() const { |
2527 | return init_begin() + NumCtorInitializers; |
2528 | } |
2529 | |
2530 | using init_reverse_iterator = std::reverse_iterator<init_iterator>; |
2531 | using init_const_reverse_iterator = |
2532 | std::reverse_iterator<init_const_iterator>; |
2533 | |
2534 | init_reverse_iterator init_rbegin() { |
2535 | return init_reverse_iterator(init_end()); |
2536 | } |
2537 | init_const_reverse_iterator init_rbegin() const { |
2538 | return init_const_reverse_iterator(init_end()); |
2539 | } |
2540 | |
2541 | init_reverse_iterator init_rend() { |
2542 | return init_reverse_iterator(init_begin()); |
2543 | } |
2544 | init_const_reverse_iterator init_rend() const { |
2545 | return init_const_reverse_iterator(init_begin()); |
2546 | } |
2547 | |
2548 | /// \brief Determine the number of arguments used to initialize the member |
2549 | /// or base. |
2550 | unsigned getNumCtorInitializers() const { |
2551 | return NumCtorInitializers; |
2552 | } |
2553 | |
2554 | void setNumCtorInitializers(unsigned numCtorInitializers) { |
2555 | NumCtorInitializers = numCtorInitializers; |
2556 | } |
2557 | |
2558 | void setCtorInitializers(CXXCtorInitializer **Initializers) { |
2559 | CtorInitializers = Initializers; |
2560 | } |
2561 | |
2562 | /// Whether this function is marked as explicit explicitly. |
2563 | bool isExplicitSpecified() const { return IsExplicitSpecified; } |
2564 | |
2565 | /// Whether this function is explicit. |
2566 | bool isExplicit() const { |
2567 | return getCanonicalDecl()->isExplicitSpecified(); |
2568 | } |
2569 | |
2570 | /// \brief Determine whether this constructor is a delegating constructor. |
2571 | bool isDelegatingConstructor() const { |
2572 | return (getNumCtorInitializers() == 1) && |
2573 | init_begin()[0]->isDelegatingInitializer(); |
2574 | } |
2575 | |
2576 | /// \brief When this constructor delegates to another, retrieve the target. |
2577 | CXXConstructorDecl *getTargetConstructor() const; |
2578 | |
2579 | /// Whether this constructor is a default |
2580 | /// constructor (C++ [class.ctor]p5), which can be used to |
2581 | /// default-initialize a class of this type. |
2582 | bool isDefaultConstructor() const; |
2583 | |
2584 | /// \brief Whether this constructor is a copy constructor (C++ [class.copy]p2, |
2585 | /// which can be used to copy the class. |
2586 | /// |
2587 | /// \p TypeQuals will be set to the qualifiers on the |
2588 | /// argument type. For example, \p TypeQuals would be set to \c |
2589 | /// Qualifiers::Const for the following copy constructor: |
2590 | /// |
2591 | /// \code |
2592 | /// class X { |
2593 | /// public: |
2594 | /// X(const X&); |
2595 | /// }; |
2596 | /// \endcode |
2597 | bool isCopyConstructor(unsigned &TypeQuals) const; |
2598 | |
2599 | /// Whether this constructor is a copy |
2600 | /// constructor (C++ [class.copy]p2, which can be used to copy the |
2601 | /// class. |
2602 | bool isCopyConstructor() const { |
2603 | unsigned TypeQuals = 0; |
2604 | return isCopyConstructor(TypeQuals); |
2605 | } |
2606 | |
2607 | /// \brief Determine whether this constructor is a move constructor |
2608 | /// (C++11 [class.copy]p3), which can be used to move values of the class. |
2609 | /// |
2610 | /// \param TypeQuals If this constructor is a move constructor, will be set |
2611 | /// to the type qualifiers on the referent of the first parameter's type. |
2612 | bool isMoveConstructor(unsigned &TypeQuals) const; |
2613 | |
2614 | /// \brief Determine whether this constructor is a move constructor |
2615 | /// (C++11 [class.copy]p3), which can be used to move values of the class. |
2616 | bool isMoveConstructor() const { |
2617 | unsigned TypeQuals = 0; |
2618 | return isMoveConstructor(TypeQuals); |
2619 | } |
2620 | |
2621 | /// \brief Determine whether this is a copy or move constructor. |
2622 | /// |
2623 | /// \param TypeQuals Will be set to the type qualifiers on the reference |
2624 | /// parameter, if in fact this is a copy or move constructor. |
2625 | bool isCopyOrMoveConstructor(unsigned &TypeQuals) const; |
2626 | |
2627 | /// \brief Determine whether this a copy or move constructor. |
2628 | bool isCopyOrMoveConstructor() const { |
2629 | unsigned Quals; |
2630 | return isCopyOrMoveConstructor(Quals); |
2631 | } |
2632 | |
2633 | /// Whether this constructor is a |
2634 | /// converting constructor (C++ [class.conv.ctor]), which can be |
2635 | /// used for user-defined conversions. |
2636 | bool isConvertingConstructor(bool AllowExplicit) const; |
2637 | |
2638 | /// \brief Determine whether this is a member template specialization that |
2639 | /// would copy the object to itself. Such constructors are never used to copy |
2640 | /// an object. |
2641 | bool isSpecializationCopyingObject() const; |
2642 | |
2643 | /// \brief Determine whether this is an implicit constructor synthesized to |
2644 | /// model a call to a constructor inherited from a base class. |
2645 | bool isInheritingConstructor() const { return IsInheritingConstructor; } |
2646 | |
2647 | /// \brief Get the constructor that this inheriting constructor is based on. |
2648 | InheritedConstructor getInheritedConstructor() const { |
2649 | return IsInheritingConstructor ? *getTrailingObjects<InheritedConstructor>() |
2650 | : InheritedConstructor(); |
2651 | } |
2652 | |
2653 | CXXConstructorDecl *getCanonicalDecl() override { |
2654 | return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl()); |
2655 | } |
2656 | const CXXConstructorDecl *getCanonicalDecl() const { |
2657 | return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl(); |
2658 | } |
2659 | |
2660 | // Implement isa/cast/dyncast/etc. |
2661 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2662 | static bool classofKind(Kind K) { return K == CXXConstructor; } |
2663 | }; |
2664 | |
2665 | /// \brief Represents a C++ destructor within a class. |
2666 | /// |
2667 | /// For example: |
2668 | /// |
2669 | /// \code |
2670 | /// class X { |
2671 | /// public: |
2672 | /// ~X(); // represented by a CXXDestructorDecl. |
2673 | /// }; |
2674 | /// \endcode |
2675 | class CXXDestructorDecl : public CXXMethodDecl { |
2676 | friend class ASTDeclReader; |
2677 | friend class ASTDeclWriter; |
2678 | |
2679 | // FIXME: Don't allocate storage for these except in the first declaration |
2680 | // of a virtual destructor. |
2681 | FunctionDecl *OperatorDelete = nullptr; |
2682 | Expr *OperatorDeleteThisArg = nullptr; |
2683 | |
2684 | CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2685 | const DeclarationNameInfo &NameInfo, |
2686 | QualType T, TypeSourceInfo *TInfo, |
2687 | bool isInline, bool isImplicitlyDeclared) |
2688 | : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo, |
2689 | SC_None, isInline, /*isConstexpr=*/false, SourceLocation()) |
2690 | { |
2691 | setImplicit(isImplicitlyDeclared); |
2692 | } |
2693 | |
2694 | void anchor() override; |
2695 | |
2696 | public: |
2697 | static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, |
2698 | SourceLocation StartLoc, |
2699 | const DeclarationNameInfo &NameInfo, |
2700 | QualType T, TypeSourceInfo* TInfo, |
2701 | bool isInline, |
2702 | bool isImplicitlyDeclared); |
2703 | static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID); |
2704 | |
2705 | void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg); |
2706 | |
2707 | const FunctionDecl *getOperatorDelete() const { |
2708 | return getCanonicalDecl()->OperatorDelete; |
2709 | } |
2710 | |
2711 | Expr *getOperatorDeleteThisArg() const { |
2712 | return getCanonicalDecl()->OperatorDeleteThisArg; |
2713 | } |
2714 | |
2715 | CXXDestructorDecl *getCanonicalDecl() override { |
2716 | return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl()); |
2717 | } |
2718 | const CXXDestructorDecl *getCanonicalDecl() const { |
2719 | return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl(); |
2720 | } |
2721 | |
2722 | // Implement isa/cast/dyncast/etc. |
2723 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2724 | static bool classofKind(Kind K) { return K == CXXDestructor; } |
2725 | }; |
2726 | |
2727 | /// \brief Represents a C++ conversion function within a class. |
2728 | /// |
2729 | /// For example: |
2730 | /// |
2731 | /// \code |
2732 | /// class X { |
2733 | /// public: |
2734 | /// operator bool(); |
2735 | /// }; |
2736 | /// \endcode |
2737 | class CXXConversionDecl : public CXXMethodDecl { |
2738 | CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2739 | const DeclarationNameInfo &NameInfo, QualType T, |
2740 | TypeSourceInfo *TInfo, bool isInline, |
2741 | bool isExplicitSpecified, bool isConstexpr, |
2742 | SourceLocation EndLocation) |
2743 | : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo, |
2744 | SC_None, isInline, isConstexpr, EndLocation) { |
2745 | IsExplicitSpecified = isExplicitSpecified; |
2746 | } |
2747 | |
2748 | void anchor() override; |
2749 | |
2750 | public: |
2751 | friend class ASTDeclReader; |
2752 | friend class ASTDeclWriter; |
2753 | |
2754 | static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD, |
2755 | SourceLocation StartLoc, |
2756 | const DeclarationNameInfo &NameInfo, |
2757 | QualType T, TypeSourceInfo *TInfo, |
2758 | bool isInline, bool isExplicit, |
2759 | bool isConstexpr, |
2760 | SourceLocation EndLocation); |
2761 | static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2762 | |
2763 | /// Whether this function is marked as explicit explicitly. |
2764 | bool isExplicitSpecified() const { return IsExplicitSpecified; } |
2765 | |
2766 | /// Whether this function is explicit. |
2767 | bool isExplicit() const { |
2768 | return getCanonicalDecl()->isExplicitSpecified(); |
2769 | } |
2770 | |
2771 | /// \brief Returns the type that this conversion function is converting to. |
2772 | QualType getConversionType() const { |
2773 | return getType()->getAs<FunctionType>()->getReturnType(); |
2774 | } |
2775 | |
2776 | /// \brief Determine whether this conversion function is a conversion from |
2777 | /// a lambda closure type to a block pointer. |
2778 | bool isLambdaToBlockPointerConversion() const; |
2779 | |
2780 | CXXConversionDecl *getCanonicalDecl() override { |
2781 | return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl()); |
2782 | } |
2783 | const CXXConversionDecl *getCanonicalDecl() const { |
2784 | return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl(); |
2785 | } |
2786 | |
2787 | // Implement isa/cast/dyncast/etc. |
2788 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2789 | static bool classofKind(Kind K) { return K == CXXConversion; } |
2790 | }; |
2791 | |
2792 | /// \brief Represents a linkage specification. |
2793 | /// |
2794 | /// For example: |
2795 | /// \code |
2796 | /// extern "C" void foo(); |
2797 | /// \endcode |
2798 | class LinkageSpecDecl : public Decl, public DeclContext { |
2799 | virtual void anchor(); |
2800 | |
2801 | public: |
2802 | /// \brief Represents the language in a linkage specification. |
2803 | /// |
2804 | /// The values are part of the serialization ABI for |
2805 | /// ASTs and cannot be changed without altering that ABI. To help |
2806 | /// ensure a stable ABI for this, we choose the DW_LANG_ encodings |
2807 | /// from the dwarf standard. |
2808 | enum LanguageIDs { |
2809 | lang_c = /* DW_LANG_C */ 0x0002, |
2810 | lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004 |
2811 | }; |
2812 | |
2813 | private: |
2814 | /// \brief The language for this linkage specification. |
2815 | unsigned Language : 3; |
2816 | |
2817 | /// \brief True if this linkage spec has braces. |
2818 | /// |
2819 | /// This is needed so that hasBraces() returns the correct result while the |
2820 | /// linkage spec body is being parsed. Once RBraceLoc has been set this is |
2821 | /// not used, so it doesn't need to be serialized. |
2822 | unsigned HasBraces : 1; |
2823 | |
2824 | /// \brief The source location for the extern keyword. |
2825 | SourceLocation ExternLoc; |
2826 | |
2827 | /// \brief The source location for the right brace (if valid). |
2828 | SourceLocation RBraceLoc; |
2829 | |
2830 | LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc, |
2831 | SourceLocation LangLoc, LanguageIDs lang, bool HasBraces) |
2832 | : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec), |
2833 | Language(lang), HasBraces(HasBraces), ExternLoc(ExternLoc), |
2834 | RBraceLoc(SourceLocation()) {} |
2835 | |
2836 | public: |
2837 | static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC, |
2838 | SourceLocation ExternLoc, |
2839 | SourceLocation LangLoc, LanguageIDs Lang, |
2840 | bool HasBraces); |
2841 | static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2842 | |
2843 | /// \brief Return the language specified by this linkage specification. |
2844 | LanguageIDs getLanguage() const { return LanguageIDs(Language); } |
2845 | |
2846 | /// \brief Set the language specified by this linkage specification. |
2847 | void setLanguage(LanguageIDs L) { Language = L; } |
2848 | |
2849 | /// \brief Determines whether this linkage specification had braces in |
2850 | /// its syntactic form. |
2851 | bool hasBraces() const { |
2852 | assert(!RBraceLoc.isValid() || HasBraces)(static_cast <bool> (!RBraceLoc.isValid() || HasBraces) ? void (0) : __assert_fail ("!RBraceLoc.isValid() || HasBraces" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 2852, __extension__ __PRETTY_FUNCTION__)); |
2853 | return HasBraces; |
2854 | } |
2855 | |
2856 | SourceLocation getExternLoc() const { return ExternLoc; } |
2857 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
2858 | void setExternLoc(SourceLocation L) { ExternLoc = L; } |
2859 | void setRBraceLoc(SourceLocation L) { |
2860 | RBraceLoc = L; |
2861 | HasBraces = RBraceLoc.isValid(); |
2862 | } |
2863 | |
2864 | SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { |
2865 | if (hasBraces()) |
2866 | return getRBraceLoc(); |
2867 | // No braces: get the end location of the (only) declaration in context |
2868 | // (if present). |
2869 | return decls_empty() ? getLocation() : decls_begin()->getLocEnd(); |
2870 | } |
2871 | |
2872 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
2873 | return SourceRange(ExternLoc, getLocEnd()); |
2874 | } |
2875 | |
2876 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2877 | static bool classofKind(Kind K) { return K == LinkageSpec; } |
2878 | |
2879 | static DeclContext *castToDeclContext(const LinkageSpecDecl *D) { |
2880 | return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D)); |
2881 | } |
2882 | |
2883 | static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) { |
2884 | return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC)); |
2885 | } |
2886 | }; |
2887 | |
2888 | /// \brief Represents C++ using-directive. |
2889 | /// |
2890 | /// For example: |
2891 | /// \code |
2892 | /// using namespace std; |
2893 | /// \endcode |
2894 | /// |
2895 | /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide |
2896 | /// artificial names for all using-directives in order to store |
2897 | /// them in DeclContext effectively. |
2898 | class UsingDirectiveDecl : public NamedDecl { |
2899 | /// \brief The location of the \c using keyword. |
2900 | SourceLocation UsingLoc; |
2901 | |
2902 | /// \brief The location of the \c namespace keyword. |
2903 | SourceLocation NamespaceLoc; |
2904 | |
2905 | /// \brief The nested-name-specifier that precedes the namespace. |
2906 | NestedNameSpecifierLoc QualifierLoc; |
2907 | |
2908 | /// \brief The namespace nominated by this using-directive. |
2909 | NamedDecl *NominatedNamespace; |
2910 | |
2911 | /// Enclosing context containing both using-directive and nominated |
2912 | /// namespace. |
2913 | DeclContext *CommonAncestor; |
2914 | |
2915 | UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc, |
2916 | SourceLocation NamespcLoc, |
2917 | NestedNameSpecifierLoc QualifierLoc, |
2918 | SourceLocation IdentLoc, |
2919 | NamedDecl *Nominated, |
2920 | DeclContext *CommonAncestor) |
2921 | : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc), |
2922 | NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc), |
2923 | NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {} |
2924 | |
2925 | /// \brief Returns special DeclarationName used by using-directives. |
2926 | /// |
2927 | /// This is only used by DeclContext for storing UsingDirectiveDecls in |
2928 | /// its lookup structure. |
2929 | static DeclarationName getName() { |
2930 | return DeclarationName::getUsingDirectiveName(); |
2931 | } |
2932 | |
2933 | void anchor() override; |
2934 | |
2935 | public: |
2936 | friend class ASTDeclReader; |
2937 | |
2938 | // Friend for getUsingDirectiveName. |
2939 | friend class DeclContext; |
2940 | |
2941 | /// \brief Retrieve the nested-name-specifier that qualifies the |
2942 | /// name of the namespace, with source-location information. |
2943 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
2944 | |
2945 | /// \brief Retrieve the nested-name-specifier that qualifies the |
2946 | /// name of the namespace. |
2947 | NestedNameSpecifier *getQualifier() const { |
2948 | return QualifierLoc.getNestedNameSpecifier(); |
2949 | } |
2950 | |
2951 | NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; } |
2952 | const NamedDecl *getNominatedNamespaceAsWritten() const { |
2953 | return NominatedNamespace; |
2954 | } |
2955 | |
2956 | /// \brief Returns the namespace nominated by this using-directive. |
2957 | NamespaceDecl *getNominatedNamespace(); |
2958 | |
2959 | const NamespaceDecl *getNominatedNamespace() const { |
2960 | return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace(); |
2961 | } |
2962 | |
2963 | /// \brief Returns the common ancestor context of this using-directive and |
2964 | /// its nominated namespace. |
2965 | DeclContext *getCommonAncestor() { return CommonAncestor; } |
2966 | const DeclContext *getCommonAncestor() const { return CommonAncestor; } |
2967 | |
2968 | /// \brief Return the location of the \c using keyword. |
2969 | SourceLocation getUsingLoc() const { return UsingLoc; } |
2970 | |
2971 | // FIXME: Could omit 'Key' in name. |
2972 | /// \brief Returns the location of the \c namespace keyword. |
2973 | SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; } |
2974 | |
2975 | /// \brief Returns the location of this using declaration's identifier. |
2976 | SourceLocation getIdentLocation() const { return getLocation(); } |
2977 | |
2978 | static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC, |
2979 | SourceLocation UsingLoc, |
2980 | SourceLocation NamespaceLoc, |
2981 | NestedNameSpecifierLoc QualifierLoc, |
2982 | SourceLocation IdentLoc, |
2983 | NamedDecl *Nominated, |
2984 | DeclContext *CommonAncestor); |
2985 | static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2986 | |
2987 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
2988 | return SourceRange(UsingLoc, getLocation()); |
2989 | } |
2990 | |
2991 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2992 | static bool classofKind(Kind K) { return K == UsingDirective; } |
2993 | }; |
2994 | |
2995 | /// \brief Represents a C++ namespace alias. |
2996 | /// |
2997 | /// For example: |
2998 | /// |
2999 | /// \code |
3000 | /// namespace Foo = Bar; |
3001 | /// \endcode |
3002 | class NamespaceAliasDecl : public NamedDecl, |
3003 | public Redeclarable<NamespaceAliasDecl> { |
3004 | friend class ASTDeclReader; |
3005 | |
3006 | /// \brief The location of the \c namespace keyword. |
3007 | SourceLocation NamespaceLoc; |
3008 | |
3009 | /// \brief The location of the namespace's identifier. |
3010 | /// |
3011 | /// This is accessed by TargetNameLoc. |
3012 | SourceLocation IdentLoc; |
3013 | |
3014 | /// \brief The nested-name-specifier that precedes the namespace. |
3015 | NestedNameSpecifierLoc QualifierLoc; |
3016 | |
3017 | /// \brief The Decl that this alias points to, either a NamespaceDecl or |
3018 | /// a NamespaceAliasDecl. |
3019 | NamedDecl *Namespace; |
3020 | |
3021 | NamespaceAliasDecl(ASTContext &C, DeclContext *DC, |
3022 | SourceLocation NamespaceLoc, SourceLocation AliasLoc, |
3023 | IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, |
3024 | SourceLocation IdentLoc, NamedDecl *Namespace) |
3025 | : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C), |
3026 | NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc), |
3027 | QualifierLoc(QualifierLoc), Namespace(Namespace) {} |
3028 | |
3029 | void anchor() override; |
3030 | |
3031 | using redeclarable_base = Redeclarable<NamespaceAliasDecl>; |
3032 | |
3033 | NamespaceAliasDecl *getNextRedeclarationImpl() override; |
3034 | NamespaceAliasDecl *getPreviousDeclImpl() override; |
3035 | NamespaceAliasDecl *getMostRecentDeclImpl() override; |
3036 | |
3037 | public: |
3038 | static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, |
3039 | SourceLocation NamespaceLoc, |
3040 | SourceLocation AliasLoc, |
3041 | IdentifierInfo *Alias, |
3042 | NestedNameSpecifierLoc QualifierLoc, |
3043 | SourceLocation IdentLoc, |
3044 | NamedDecl *Namespace); |
3045 | |
3046 | static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3047 | |
3048 | using redecl_range = redeclarable_base::redecl_range; |
3049 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3050 | |
3051 | using redeclarable_base::redecls_begin; |
3052 | using redeclarable_base::redecls_end; |
3053 | using redeclarable_base::redecls; |
3054 | using redeclarable_base::getPreviousDecl; |
3055 | using redeclarable_base::getMostRecentDecl; |
3056 | |
3057 | NamespaceAliasDecl *getCanonicalDecl() override { |
3058 | return getFirstDecl(); |
3059 | } |
3060 | const NamespaceAliasDecl *getCanonicalDecl() const { |
3061 | return getFirstDecl(); |
3062 | } |
3063 | |
3064 | /// \brief Retrieve the nested-name-specifier that qualifies the |
3065 | /// name of the namespace, with source-location information. |
3066 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3067 | |
3068 | /// \brief Retrieve the nested-name-specifier that qualifies the |
3069 | /// name of the namespace. |
3070 | NestedNameSpecifier *getQualifier() const { |
3071 | return QualifierLoc.getNestedNameSpecifier(); |
3072 | } |
3073 | |
3074 | /// \brief Retrieve the namespace declaration aliased by this directive. |
3075 | NamespaceDecl *getNamespace() { |
3076 | if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Namespace)) |
3077 | return AD->getNamespace(); |
3078 | |
3079 | return cast<NamespaceDecl>(Namespace); |
3080 | } |
3081 | |
3082 | const NamespaceDecl *getNamespace() const { |
3083 | return const_cast<NamespaceAliasDecl*>(this)->getNamespace(); |
3084 | } |
3085 | |
3086 | /// Returns the location of the alias name, i.e. 'foo' in |
3087 | /// "namespace foo = ns::bar;". |
3088 | SourceLocation getAliasLoc() const { return getLocation(); } |
3089 | |
3090 | /// Returns the location of the \c namespace keyword. |
3091 | SourceLocation getNamespaceLoc() const { return NamespaceLoc; } |
3092 | |
3093 | /// Returns the location of the identifier in the named namespace. |
3094 | SourceLocation getTargetNameLoc() const { return IdentLoc; } |
3095 | |
3096 | /// \brief Retrieve the namespace that this alias refers to, which |
3097 | /// may either be a NamespaceDecl or a NamespaceAliasDecl. |
3098 | NamedDecl *getAliasedNamespace() const { return Namespace; } |
3099 | |
3100 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3101 | return SourceRange(NamespaceLoc, IdentLoc); |
3102 | } |
3103 | |
3104 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3105 | static bool classofKind(Kind K) { return K == NamespaceAlias; } |
3106 | }; |
3107 | |
3108 | /// \brief Represents a shadow declaration introduced into a scope by a |
3109 | /// (resolved) using declaration. |
3110 | /// |
3111 | /// For example, |
3112 | /// \code |
3113 | /// namespace A { |
3114 | /// void foo(); |
3115 | /// } |
3116 | /// namespace B { |
3117 | /// using A::foo; // <- a UsingDecl |
3118 | /// // Also creates a UsingShadowDecl for A::foo() in B |
3119 | /// } |
3120 | /// \endcode |
3121 | class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> { |
3122 | friend class UsingDecl; |
3123 | |
3124 | /// The referenced declaration. |
3125 | NamedDecl *Underlying = nullptr; |
3126 | |
3127 | /// \brief The using declaration which introduced this decl or the next using |
3128 | /// shadow declaration contained in the aforementioned using declaration. |
3129 | NamedDecl *UsingOrNextShadow = nullptr; |
3130 | |
3131 | void anchor() override; |
3132 | |
3133 | using redeclarable_base = Redeclarable<UsingShadowDecl>; |
3134 | |
3135 | UsingShadowDecl *getNextRedeclarationImpl() override { |
3136 | return getNextRedeclaration(); |
3137 | } |
3138 | |
3139 | UsingShadowDecl *getPreviousDeclImpl() override { |
3140 | return getPreviousDecl(); |
3141 | } |
3142 | |
3143 | UsingShadowDecl *getMostRecentDeclImpl() override { |
3144 | return getMostRecentDecl(); |
3145 | } |
3146 | |
3147 | protected: |
3148 | UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc, |
3149 | UsingDecl *Using, NamedDecl *Target); |
3150 | UsingShadowDecl(Kind K, ASTContext &C, EmptyShell); |
3151 | |
3152 | public: |
3153 | friend class ASTDeclReader; |
3154 | friend class ASTDeclWriter; |
3155 | |
3156 | static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC, |
3157 | SourceLocation Loc, UsingDecl *Using, |
3158 | NamedDecl *Target) { |
3159 | return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target); |
3160 | } |
3161 | |
3162 | static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3163 | |
3164 | using redecl_range = redeclarable_base::redecl_range; |
3165 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3166 | |
3167 | using redeclarable_base::redecls_begin; |
3168 | using redeclarable_base::redecls_end; |
3169 | using redeclarable_base::redecls; |
3170 | using redeclarable_base::getPreviousDecl; |
3171 | using redeclarable_base::getMostRecentDecl; |
3172 | using redeclarable_base::isFirstDecl; |
3173 | |
3174 | UsingShadowDecl *getCanonicalDecl() override { |
3175 | return getFirstDecl(); |
3176 | } |
3177 | const UsingShadowDecl *getCanonicalDecl() const { |
3178 | return getFirstDecl(); |
3179 | } |
3180 | |
3181 | /// \brief Gets the underlying declaration which has been brought into the |
3182 | /// local scope. |
3183 | NamedDecl *getTargetDecl() const { return Underlying; } |
3184 | |
3185 | /// \brief Sets the underlying declaration which has been brought into the |
3186 | /// local scope. |
3187 | void setTargetDecl(NamedDecl *ND) { |
3188 | assert(ND && "Target decl is null!")(static_cast <bool> (ND && "Target decl is null!" ) ? void (0) : __assert_fail ("ND && \"Target decl is null!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/DeclCXX.h" , 3188, __extension__ __PRETTY_FUNCTION__)); |
3189 | Underlying = ND; |
3190 | // A UsingShadowDecl is never a friend or local extern declaration, even |
3191 | // if it is a shadow declaration for one. |
3192 | IdentifierNamespace = |
3193 | ND->getIdentifierNamespace() & |
3194 | ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern); |
3195 | } |
3196 | |
3197 | /// \brief Gets the using declaration to which this declaration is tied. |
3198 | UsingDecl *getUsingDecl() const; |
3199 | |
3200 | /// \brief The next using shadow declaration contained in the shadow decl |
3201 | /// chain of the using declaration which introduced this decl. |
3202 | UsingShadowDecl *getNextUsingShadowDecl() const { |
3203 | return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow); |
3204 | } |
3205 | |
3206 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3207 | static bool classofKind(Kind K) { |
3208 | return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow; |
3209 | } |
3210 | }; |
3211 | |
3212 | /// \brief Represents a shadow constructor declaration introduced into a |
3213 | /// class by a C++11 using-declaration that names a constructor. |
3214 | /// |
3215 | /// For example: |
3216 | /// \code |
3217 | /// struct Base { Base(int); }; |
3218 | /// struct Derived { |
3219 | /// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl |
3220 | /// }; |
3221 | /// \endcode |
3222 | class ConstructorUsingShadowDecl final : public UsingShadowDecl { |
3223 | /// \brief If this constructor using declaration inherted the constructor |
3224 | /// from an indirect base class, this is the ConstructorUsingShadowDecl |
3225 | /// in the named direct base class from which the declaration was inherited. |
3226 | ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr; |
3227 | |
3228 | /// \brief If this constructor using declaration inherted the constructor |
3229 | /// from an indirect base class, this is the ConstructorUsingShadowDecl |
3230 | /// that will be used to construct the unique direct or virtual base class |
3231 | /// that receives the constructor arguments. |
3232 | ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr; |
3233 | |
3234 | /// \brief \c true if the constructor ultimately named by this using shadow |
3235 | /// declaration is within a virtual base class subobject of the class that |
3236 | /// contains this declaration. |
3237 | unsigned IsVirtual : 1; |
3238 | |
3239 | ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc, |
3240 | UsingDecl *Using, NamedDecl *Target, |
3241 | bool TargetInVirtualBase) |
3242 | : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using, |
3243 | Target->getUnderlyingDecl()), |
3244 | NominatedBaseClassShadowDecl( |
3245 | dyn_cast<ConstructorUsingShadowDecl>(Target)), |
3246 | ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl), |
3247 | IsVirtual(TargetInVirtualBase) { |
3248 | // If we found a constructor that chains to a constructor for a virtual |
3249 | // base, we should directly call that virtual base constructor instead. |
3250 | // FIXME: This logic belongs in Sema. |
3251 | if (NominatedBaseClassShadowDecl && |
3252 | NominatedBaseClassShadowDecl->constructsVirtualBase()) { |
3253 | ConstructedBaseClassShadowDecl = |
3254 | NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl; |
3255 | IsVirtual = true; |
3256 | } |
3257 | } |
3258 | |
3259 | ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty) |
3260 | : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {} |
3261 | |
3262 | void anchor() override; |
3263 | |
3264 | public: |
3265 | friend class ASTDeclReader; |
3266 | friend class ASTDeclWriter; |
3267 | |
3268 | static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC, |
3269 | SourceLocation Loc, |
3270 | UsingDecl *Using, NamedDecl *Target, |
3271 | bool IsVirtual); |
3272 | static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C, |
3273 | unsigned ID); |
3274 | |
3275 | /// Returns the parent of this using shadow declaration, which |
3276 | /// is the class in which this is declared. |
3277 | //@{ |
3278 | const CXXRecordDecl *getParent() const { |
3279 | return cast<CXXRecordDecl>(getDeclContext()); |
3280 | } |
3281 | CXXRecordDecl *getParent() { |
3282 | return cast<CXXRecordDecl>(getDeclContext()); |
3283 | } |
3284 | //@} |
3285 | |
3286 | /// \brief Get the inheriting constructor declaration for the direct base |
3287 | /// class from which this using shadow declaration was inherited, if there is |
3288 | /// one. This can be different for each redeclaration of the same shadow decl. |
3289 | ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const { |
3290 | return NominatedBaseClassShadowDecl; |
3291 | } |
3292 | |
3293 | /// \brief Get the inheriting constructor declaration for the base class |
3294 | /// for which we don't have an explicit initializer, if there is one. |
3295 | ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const { |
3296 | return ConstructedBaseClassShadowDecl; |
3297 | } |
3298 | |
3299 | /// \brief Get the base class that was named in the using declaration. This |
3300 | /// can be different for each redeclaration of this same shadow decl. |
3301 | CXXRecordDecl *getNominatedBaseClass() const; |
3302 | |
3303 | /// \brief Get the base class whose constructor or constructor shadow |
3304 | /// declaration is passed the constructor arguments. |
3305 | CXXRecordDecl *getConstructedBaseClass() const { |
3306 | return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl |
3307 | ? ConstructedBaseClassShadowDecl |
3308 | : getTargetDecl()) |
3309 | ->getDeclContext()); |
3310 | } |
3311 | |
3312 | /// \brief Returns \c true if the constructed base class is a virtual base |
3313 | /// class subobject of this declaration's class. |
3314 | bool constructsVirtualBase() const { |
3315 | return IsVirtual; |
3316 | } |
3317 | |
3318 | /// \brief Get the constructor or constructor template in the derived class |
3319 | /// correspnding to this using shadow declaration, if it has been implicitly |
3320 | /// declared already. |
3321 | CXXConstructorDecl *getConstructor() const; |
3322 | void setConstructor(NamedDecl *Ctor); |
3323 | |
3324 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3325 | static bool classofKind(Kind K) { return K == ConstructorUsingShadow; } |
3326 | }; |
3327 | |
3328 | /// \brief Represents a C++ using-declaration. |
3329 | /// |
3330 | /// For example: |
3331 | /// \code |
3332 | /// using someNameSpace::someIdentifier; |
3333 | /// \endcode |
3334 | class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> { |
3335 | /// \brief The source location of the 'using' keyword itself. |
3336 | SourceLocation UsingLocation; |
3337 | |
3338 | /// \brief The nested-name-specifier that precedes the name. |
3339 | NestedNameSpecifierLoc QualifierLoc; |
3340 | |
3341 | /// \brief Provides source/type location info for the declaration name |
3342 | /// embedded in the ValueDecl base class. |
3343 | DeclarationNameLoc DNLoc; |
3344 | |
3345 | /// \brief The first shadow declaration of the shadow decl chain associated |
3346 | /// with this using declaration. |
3347 | /// |
3348 | /// The bool member of the pair store whether this decl has the \c typename |
3349 | /// keyword. |
3350 | llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow; |
3351 | |
3352 | UsingDecl(DeclContext *DC, SourceLocation UL, |
3353 | NestedNameSpecifierLoc QualifierLoc, |
3354 | const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword) |
3355 | : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()), |
3356 | UsingLocation(UL), QualifierLoc(QualifierLoc), |
3357 | DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) { |
3358 | } |
3359 | |
3360 | void anchor() override; |
3361 | |
3362 | public: |
3363 | friend class ASTDeclReader; |
3364 | friend class ASTDeclWriter; |
3365 | |
3366 | /// \brief Return the source location of the 'using' keyword. |
3367 | SourceLocation getUsingLoc() const { return UsingLocation; } |
3368 | |
3369 | /// \brief Set the source location of the 'using' keyword. |
3370 | void setUsingLoc(SourceLocation L) { UsingLocation = L; } |
3371 | |
3372 | /// \brief Retrieve the nested-name-specifier that qualifies the name, |
3373 | /// with source-location information. |
3374 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3375 | |
3376 | /// \brief Retrieve the nested-name-specifier that qualifies the name. |
3377 | NestedNameSpecifier *getQualifier() const { |
3378 | return QualifierLoc.getNestedNameSpecifier(); |
3379 | } |
3380 | |
3381 | DeclarationNameInfo getNameInfo() const { |
3382 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
3383 | } |
3384 | |
3385 | /// \brief Return true if it is a C++03 access declaration (no 'using'). |
3386 | bool isAccessDeclaration() const { return UsingLocation.isInvalid(); } |
3387 | |
3388 | /// \brief Return true if the using declaration has 'typename'. |
3389 | bool hasTypename() const { return FirstUsingShadow.getInt(); } |
3390 | |
3391 | /// \brief Sets whether the using declaration has 'typename'. |
3392 | void setTypename(bool TN) { FirstUsingShadow.setInt(TN); } |
3393 | |
3394 | /// \brief Iterates through the using shadow declarations associated with |
3395 | /// this using declaration. |
3396 | class shadow_iterator { |
3397 | /// \brief The current using shadow declaration. |
3398 | UsingShadowDecl *Current = nullptr; |
3399 | |
3400 | public: |
3401 | using value_type = UsingShadowDecl *; |
3402 | using reference = UsingShadowDecl *; |
3403 | using pointer = UsingShadowDecl *; |
3404 | using iterator_category = std::forward_iterator_tag; |
3405 | using difference_type = std::ptrdiff_t; |
3406 | |
3407 | shadow_iterator() = default; |
3408 | explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {} |
3409 | |
3410 | reference operator*() const { return Current; } |
3411 | pointer operator->() const { return Current; } |
3412 | |
3413 | shadow_iterator& operator++() { |
3414 | Current = Current->getNextUsingShadowDecl(); |
3415 | return *this; |
3416 | } |
3417 | |
3418 | shadow_iterator operator++(int) { |
3419 | shadow_iterator tmp(*this); |
3420 | ++(*this); |
3421 | return tmp; |
3422 | } |
3423 | |
3424 | friend bool operator==(shadow_iterator x, shadow_iterator y) { |
3425 | return x.Current == y.Current; |
3426 | } |
3427 | friend bool operator!=(shadow_iterator x, shadow_iterator y) { |
3428 | return x.Current != y.Current; |
3429 | } |
3430 | }; |
3431 | |
3432 | using shadow_range = llvm::iterator_range<shadow_iterator>; |
3433 | |
3434 | shadow_range shadows() const { |
3435 | return shadow_range(shadow_begin(), shadow_end()); |
3436 | } |
3437 | |
3438 | shadow_iterator shadow_begin() const { |
3439 | return shadow_iterator(FirstUsingShadow.getPointer()); |
3440 | } |
3441 | |
3442 | shadow_iterator shadow_end() const { return shadow_iterator(); } |
3443 | |
3444 | /// \brief Return the number of shadowed declarations associated with this |
3445 | /// using declaration. |
3446 | unsigned shadow_size() const { |
3447 | return std::distance(shadow_begin(), shadow_end()); |
3448 | } |
3449 | |
3450 | void addShadowDecl(UsingShadowDecl *S); |
3451 | void removeShadowDecl(UsingShadowDecl *S); |
3452 | |
3453 | static UsingDecl *Create(ASTContext &C, DeclContext *DC, |
3454 | SourceLocation UsingL, |
3455 | NestedNameSpecifierLoc QualifierLoc, |
3456 | const DeclarationNameInfo &NameInfo, |
3457 | bool HasTypenameKeyword); |
3458 | |
3459 | static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3460 | |
3461 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3462 | |
3463 | /// Retrieves the canonical declaration of this declaration. |
3464 | UsingDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3465 | const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3466 | |
3467 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3468 | static bool classofKind(Kind K) { return K == Using; } |
3469 | }; |
3470 | |
3471 | /// Represents a pack of using declarations that a single |
3472 | /// using-declarator pack-expanded into. |
3473 | /// |
3474 | /// \code |
3475 | /// template<typename ...T> struct X : T... { |
3476 | /// using T::operator()...; |
3477 | /// using T::operator T...; |
3478 | /// }; |
3479 | /// \endcode |
3480 | /// |
3481 | /// In the second case above, the UsingPackDecl will have the name |
3482 | /// 'operator T' (which contains an unexpanded pack), but the individual |
3483 | /// UsingDecls and UsingShadowDecls will have more reasonable names. |
3484 | class UsingPackDecl final |
3485 | : public NamedDecl, public Mergeable<UsingPackDecl>, |
3486 | private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> { |
3487 | /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from |
3488 | /// which this waas instantiated. |
3489 | NamedDecl *InstantiatedFrom; |
3490 | |
3491 | /// The number of using-declarations created by this pack expansion. |
3492 | unsigned NumExpansions; |
3493 | |
3494 | UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom, |
3495 | ArrayRef<NamedDecl *> UsingDecls) |
3496 | : NamedDecl(UsingPack, DC, |
3497 | InstantiatedFrom ? InstantiatedFrom->getLocation() |
3498 | : SourceLocation(), |
3499 | InstantiatedFrom ? InstantiatedFrom->getDeclName() |
3500 | : DeclarationName()), |
3501 | InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) { |
3502 | std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(), |
3503 | getTrailingObjects<NamedDecl *>()); |
3504 | } |
3505 | |
3506 | void anchor() override; |
3507 | |
3508 | public: |
3509 | friend class ASTDeclReader; |
3510 | friend class ASTDeclWriter; |
3511 | friend TrailingObjects; |
3512 | |
3513 | /// Get the using declaration from which this was instantiated. This will |
3514 | /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl |
3515 | /// that is a pack expansion. |
3516 | NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; } |
3517 | |
3518 | /// Get the set of using declarations that this pack expanded into. Note that |
3519 | /// some of these may still be unresolved. |
3520 | ArrayRef<NamedDecl *> expansions() const { |
3521 | return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions); |
3522 | } |
3523 | |
3524 | static UsingPackDecl *Create(ASTContext &C, DeclContext *DC, |
3525 | NamedDecl *InstantiatedFrom, |
3526 | ArrayRef<NamedDecl *> UsingDecls); |
3527 | |
3528 | static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
3529 | unsigned NumExpansions); |
3530 | |
3531 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3532 | return InstantiatedFrom->getSourceRange(); |
3533 | } |
3534 | |
3535 | UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3536 | const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3537 | |
3538 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3539 | static bool classofKind(Kind K) { return K == UsingPack; } |
3540 | }; |
3541 | |
3542 | /// \brief Represents a dependent using declaration which was not marked with |
3543 | /// \c typename. |
3544 | /// |
3545 | /// Unlike non-dependent using declarations, these *only* bring through |
3546 | /// non-types; otherwise they would break two-phase lookup. |
3547 | /// |
3548 | /// \code |
3549 | /// template \<class T> class A : public Base<T> { |
3550 | /// using Base<T>::foo; |
3551 | /// }; |
3552 | /// \endcode |
3553 | class UnresolvedUsingValueDecl : public ValueDecl, |
3554 | public Mergeable<UnresolvedUsingValueDecl> { |
3555 | /// \brief The source location of the 'using' keyword |
3556 | SourceLocation UsingLocation; |
3557 | |
3558 | /// \brief If this is a pack expansion, the location of the '...'. |
3559 | SourceLocation EllipsisLoc; |
3560 | |
3561 | /// \brief The nested-name-specifier that precedes the name. |
3562 | NestedNameSpecifierLoc QualifierLoc; |
3563 | |
3564 | /// \brief Provides source/type location info for the declaration name |
3565 | /// embedded in the ValueDecl base class. |
3566 | DeclarationNameLoc DNLoc; |
3567 | |
3568 | UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty, |
3569 | SourceLocation UsingLoc, |
3570 | NestedNameSpecifierLoc QualifierLoc, |
3571 | const DeclarationNameInfo &NameInfo, |
3572 | SourceLocation EllipsisLoc) |
3573 | : ValueDecl(UnresolvedUsingValue, DC, |
3574 | NameInfo.getLoc(), NameInfo.getName(), Ty), |
3575 | UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc), |
3576 | QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {} |
3577 | |
3578 | void anchor() override; |
3579 | |
3580 | public: |
3581 | friend class ASTDeclReader; |
3582 | friend class ASTDeclWriter; |
3583 | |
3584 | /// \brief Returns the source location of the 'using' keyword. |
3585 | SourceLocation getUsingLoc() const { return UsingLocation; } |
3586 | |
3587 | /// \brief Set the source location of the 'using' keyword. |
3588 | void setUsingLoc(SourceLocation L) { UsingLocation = L; } |
3589 | |
3590 | /// \brief Return true if it is a C++03 access declaration (no 'using'). |
3591 | bool isAccessDeclaration() const { return UsingLocation.isInvalid(); } |
3592 | |
3593 | /// \brief Retrieve the nested-name-specifier that qualifies the name, |
3594 | /// with source-location information. |
3595 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3596 | |
3597 | /// \brief Retrieve the nested-name-specifier that qualifies the name. |
3598 | NestedNameSpecifier *getQualifier() const { |
3599 | return QualifierLoc.getNestedNameSpecifier(); |
3600 | } |
3601 | |
3602 | DeclarationNameInfo getNameInfo() const { |
3603 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
3604 | } |
3605 | |
3606 | /// \brief Determine whether this is a pack expansion. |
3607 | bool isPackExpansion() const { |
3608 | return EllipsisLoc.isValid(); |
3609 | } |
3610 | |
3611 | /// \brief Get the location of the ellipsis if this is a pack expansion. |
3612 | SourceLocation getEllipsisLoc() const { |
3613 | return EllipsisLoc; |
3614 | } |
3615 | |
3616 | static UnresolvedUsingValueDecl * |
3617 | Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, |
3618 | NestedNameSpecifierLoc QualifierLoc, |
3619 | const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc); |
3620 | |
3621 | static UnresolvedUsingValueDecl * |
3622 | CreateDeserialized(ASTContext &C, unsigned ID); |
3623 | |
3624 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3625 | |
3626 | /// Retrieves the canonical declaration of this declaration. |
3627 | UnresolvedUsingValueDecl *getCanonicalDecl() override { |
3628 | return getFirstDecl(); |
3629 | } |
3630 | const UnresolvedUsingValueDecl *getCanonicalDecl() const { |
3631 | return getFirstDecl(); |
3632 | } |
3633 | |
3634 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3635 | static bool classofKind(Kind K) { return K == UnresolvedUsingValue; } |
3636 | }; |
3637 | |
3638 | /// \brief Represents a dependent using declaration which was marked with |
3639 | /// \c typename. |
3640 | /// |
3641 | /// \code |
3642 | /// template \<class T> class A : public Base<T> { |
3643 | /// using typename Base<T>::foo; |
3644 | /// }; |
3645 | /// \endcode |
3646 | /// |
3647 | /// The type associated with an unresolved using typename decl is |
3648 | /// currently always a typename type. |
3649 | class UnresolvedUsingTypenameDecl |
3650 | : public TypeDecl, |
3651 | public Mergeable<UnresolvedUsingTypenameDecl> { |
3652 | friend class ASTDeclReader; |
3653 | |
3654 | /// \brief The source location of the 'typename' keyword |
3655 | SourceLocation TypenameLocation; |
3656 | |
3657 | /// \brief If this is a pack expansion, the location of the '...'. |
3658 | SourceLocation EllipsisLoc; |
3659 | |
3660 | /// \brief The nested-name-specifier that precedes the name. |
3661 | NestedNameSpecifierLoc QualifierLoc; |
3662 | |
3663 | UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc, |
3664 | SourceLocation TypenameLoc, |
3665 | NestedNameSpecifierLoc QualifierLoc, |
3666 | SourceLocation TargetNameLoc, |
3667 | IdentifierInfo *TargetName, |
3668 | SourceLocation EllipsisLoc) |
3669 | : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName, |
3670 | UsingLoc), |
3671 | TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc), |
3672 | QualifierLoc(QualifierLoc) {} |
3673 | |
3674 | void anchor() override; |
3675 | |
3676 | public: |
3677 | /// \brief Returns the source location of the 'using' keyword. |
3678 | SourceLocation getUsingLoc() const { return getLocStart(); } |
3679 | |
3680 | /// \brief Returns the source location of the 'typename' keyword. |
3681 | SourceLocation getTypenameLoc() const { return TypenameLocation; } |
3682 | |
3683 | /// \brief Retrieve the nested-name-specifier that qualifies the name, |
3684 | /// with source-location information. |
3685 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3686 | |
3687 | /// \brief Retrieve the nested-name-specifier that qualifies the name. |
3688 | NestedNameSpecifier *getQualifier() const { |
3689 | return QualifierLoc.getNestedNameSpecifier(); |
3690 | } |
3691 | |
3692 | DeclarationNameInfo getNameInfo() const { |
3693 | return DeclarationNameInfo(getDeclName(), getLocation()); |
3694 | } |
3695 | |
3696 | /// \brief Determine whether this is a pack expansion. |
3697 | bool isPackExpansion() const { |
3698 | return EllipsisLoc.isValid(); |
3699 | } |
3700 | |
3701 | /// \brief Get the location of the ellipsis if this is a pack expansion. |
3702 | SourceLocation getEllipsisLoc() const { |
3703 | return EllipsisLoc; |
3704 | } |
3705 | |
3706 | static UnresolvedUsingTypenameDecl * |
3707 | Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, |
3708 | SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, |
3709 | SourceLocation TargetNameLoc, DeclarationName TargetName, |
3710 | SourceLocation EllipsisLoc); |
3711 | |
3712 | static UnresolvedUsingTypenameDecl * |
3713 | CreateDeserialized(ASTContext &C, unsigned ID); |
3714 | |
3715 | /// Retrieves the canonical declaration of this declaration. |
3716 | UnresolvedUsingTypenameDecl *getCanonicalDecl() override { |
3717 | return getFirstDecl(); |
3718 | } |
3719 | const UnresolvedUsingTypenameDecl *getCanonicalDecl() const { |
3720 | return getFirstDecl(); |
3721 | } |
3722 | |
3723 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3724 | static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; } |
3725 | }; |
3726 | |
3727 | /// \brief Represents a C++11 static_assert declaration. |
3728 | class StaticAssertDecl : public Decl { |
3729 | llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed; |
3730 | StringLiteral *Message; |
3731 | SourceLocation RParenLoc; |
3732 | |
3733 | StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc, |
3734 | Expr *AssertExpr, StringLiteral *Message, |
3735 | SourceLocation RParenLoc, bool Failed) |
3736 | : Decl(StaticAssert, DC, StaticAssertLoc), |
3737 | AssertExprAndFailed(AssertExpr, Failed), Message(Message), |
3738 | RParenLoc(RParenLoc) {} |
3739 | |
3740 | virtual void anchor(); |
3741 | |
3742 | public: |
3743 | friend class ASTDeclReader; |
3744 | |
3745 | static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC, |
3746 | SourceLocation StaticAssertLoc, |
3747 | Expr *AssertExpr, StringLiteral *Message, |
3748 | SourceLocation RParenLoc, bool Failed); |
3749 | static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3750 | |
3751 | Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); } |
3752 | const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); } |
3753 | |
3754 | StringLiteral *getMessage() { return Message; } |
3755 | const StringLiteral *getMessage() const { return Message; } |
3756 | |
3757 | bool isFailed() const { return AssertExprAndFailed.getInt(); } |
3758 | |
3759 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3760 | |
3761 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3762 | return SourceRange(getLocation(), getRParenLoc()); |
3763 | } |
3764 | |
3765 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3766 | static bool classofKind(Kind K) { return K == StaticAssert; } |
3767 | }; |
3768 | |
3769 | /// A binding in a decomposition declaration. For instance, given: |
3770 | /// |
3771 | /// int n[3]; |
3772 | /// auto &[a, b, c] = n; |
3773 | /// |
3774 | /// a, b, and c are BindingDecls, whose bindings are the expressions |
3775 | /// x[0], x[1], and x[2] respectively, where x is the implicit |
3776 | /// DecompositionDecl of type 'int (&)[3]'. |
3777 | class BindingDecl : public ValueDecl { |
3778 | /// The binding represented by this declaration. References to this |
3779 | /// declaration are effectively equivalent to this expression (except |
3780 | /// that it is only evaluated once at the point of declaration of the |
3781 | /// binding). |
3782 | Expr *Binding = nullptr; |
3783 | |
3784 | BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id) |
3785 | : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {} |
3786 | |
3787 | void anchor() override; |
3788 | |
3789 | public: |
3790 | friend class ASTDeclReader; |
3791 | |
3792 | static BindingDecl *Create(ASTContext &C, DeclContext *DC, |
3793 | SourceLocation IdLoc, IdentifierInfo *Id); |
3794 | static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3795 | |
3796 | /// Get the expression to which this declaration is bound. This may be null |
3797 | /// in two different cases: while parsing the initializer for the |
3798 | /// decomposition declaration, and when the initializer is type-dependent. |
3799 | Expr *getBinding() const { return Binding; } |
3800 | |
3801 | /// Get the variable (if any) that holds the value of evaluating the binding. |
3802 | /// Only present for user-defined bindings for tuple-like types. |
3803 | VarDecl *getHoldingVar() const; |
3804 | |
3805 | /// Set the binding for this BindingDecl, along with its declared type (which |
3806 | /// should be a possibly-cv-qualified form of the type of the binding, or a |
3807 | /// reference to such a type). |
3808 | void setBinding(QualType DeclaredType, Expr *Binding) { |
3809 | setType(DeclaredType); |
3810 | this->Binding = Binding; |
3811 | } |
3812 | |
3813 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3814 | static bool classofKind(Kind K) { return K == Decl::Binding; } |
3815 | }; |
3816 | |
3817 | /// A decomposition declaration. For instance, given: |
3818 | /// |
3819 | /// int n[3]; |
3820 | /// auto &[a, b, c] = n; |
3821 | /// |
3822 | /// the second line declares a DecompositionDecl of type 'int (&)[3]', and |
3823 | /// three BindingDecls (named a, b, and c). An instance of this class is always |
3824 | /// unnamed, but behaves in almost all other respects like a VarDecl. |
3825 | class DecompositionDecl final |
3826 | : public VarDecl, |
3827 | private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> { |
3828 | /// The number of BindingDecl*s following this object. |
3829 | unsigned NumBindings; |
3830 | |
3831 | DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3832 | SourceLocation LSquareLoc, QualType T, |
3833 | TypeSourceInfo *TInfo, StorageClass SC, |
3834 | ArrayRef<BindingDecl *> Bindings) |
3835 | : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo, |
3836 | SC), |
3837 | NumBindings(Bindings.size()) { |
3838 | std::uninitialized_copy(Bindings.begin(), Bindings.end(), |
3839 | getTrailingObjects<BindingDecl *>()); |
3840 | } |
3841 | |
3842 | void anchor() override; |
3843 | |
3844 | public: |
3845 | friend class ASTDeclReader; |
3846 | friend TrailingObjects; |
3847 | |
3848 | static DecompositionDecl *Create(ASTContext &C, DeclContext *DC, |
3849 | SourceLocation StartLoc, |
3850 | SourceLocation LSquareLoc, |
3851 | QualType T, TypeSourceInfo *TInfo, |
3852 | StorageClass S, |
3853 | ArrayRef<BindingDecl *> Bindings); |
3854 | static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
3855 | unsigned NumBindings); |
3856 | |
3857 | ArrayRef<BindingDecl *> bindings() const { |
3858 | return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings); |
3859 | } |
3860 | |
3861 | void printName(raw_ostream &os) const override; |
3862 | |
3863 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3864 | static bool classofKind(Kind K) { return K == Decomposition; } |
3865 | }; |
3866 | |
3867 | /// An instance of this class represents the declaration of a property |
3868 | /// member. This is a Microsoft extension to C++, first introduced in |
3869 | /// Visual Studio .NET 2003 as a parallel to similar features in C# |
3870 | /// and Managed C++. |
3871 | /// |
3872 | /// A property must always be a non-static class member. |
3873 | /// |
3874 | /// A property member superficially resembles a non-static data |
3875 | /// member, except preceded by a property attribute: |
3876 | /// __declspec(property(get=GetX, put=PutX)) int x; |
3877 | /// Either (but not both) of the 'get' and 'put' names may be omitted. |
3878 | /// |
3879 | /// A reference to a property is always an lvalue. If the lvalue |
3880 | /// undergoes lvalue-to-rvalue conversion, then a getter name is |
3881 | /// required, and that member is called with no arguments. |
3882 | /// If the lvalue is assigned into, then a setter name is required, |
3883 | /// and that member is called with one argument, the value assigned. |
3884 | /// Both operations are potentially overloaded. Compound assignments |
3885 | /// are permitted, as are the increment and decrement operators. |
3886 | /// |
3887 | /// The getter and putter methods are permitted to be overloaded, |
3888 | /// although their return and parameter types are subject to certain |
3889 | /// restrictions according to the type of the property. |
3890 | /// |
3891 | /// A property declared using an incomplete array type may |
3892 | /// additionally be subscripted, adding extra parameters to the getter |
3893 | /// and putter methods. |
3894 | class MSPropertyDecl : public DeclaratorDecl { |
3895 | IdentifierInfo *GetterId, *SetterId; |
3896 | |
3897 | MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N, |
3898 | QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, |
3899 | IdentifierInfo *Getter, IdentifierInfo *Setter) |
3900 | : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL), |
3901 | GetterId(Getter), SetterId(Setter) {} |
3902 | |
3903 | public: |
3904 | friend class ASTDeclReader; |
3905 | |
3906 | static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC, |
3907 | SourceLocation L, DeclarationName N, QualType T, |
3908 | TypeSourceInfo *TInfo, SourceLocation StartL, |
3909 | IdentifierInfo *Getter, IdentifierInfo *Setter); |
3910 | static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3911 | |
3912 | static bool classof(const Decl *D) { return D->getKind() == MSProperty; } |
3913 | |
3914 | bool hasGetter() const { return GetterId != nullptr; } |
3915 | IdentifierInfo* getGetterId() const { return GetterId; } |
3916 | bool hasSetter() const { return SetterId != nullptr; } |
3917 | IdentifierInfo* getSetterId() const { return SetterId; } |
3918 | }; |
3919 | |
3920 | /// Insertion operator for diagnostics. This allows sending an AccessSpecifier |
3921 | /// into a diagnostic with <<. |
3922 | const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
3923 | AccessSpecifier AS); |
3924 | |
3925 | const PartialDiagnostic &operator<<(const PartialDiagnostic &DB, |
3926 | AccessSpecifier AS); |
3927 | |
3928 | } // namespace clang |
3929 | |
3930 | #endif // LLVM_CLANG_AST_DECLCXX_H |
1 | //===- Decl.h - Classes for representing declarations -----------*- 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 defines the Decl subclasses. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_AST_DECL_H |
15 | #define LLVM_CLANG_AST_DECL_H |
16 | |
17 | #include "clang/AST/APValue.h" |
18 | #include "clang/AST/DeclBase.h" |
19 | #include "clang/AST/DeclarationName.h" |
20 | #include "clang/AST/ExternalASTSource.h" |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/Redeclarable.h" |
23 | #include "clang/AST/Type.h" |
24 | #include "clang/Basic/AddressSpaces.h" |
25 | #include "clang/Basic/Diagnostic.h" |
26 | #include "clang/Basic/IdentifierTable.h" |
27 | #include "clang/Basic/LLVM.h" |
28 | #include "clang/Basic/Linkage.h" |
29 | #include "clang/Basic/OperatorKinds.h" |
30 | #include "clang/Basic/PartialDiagnostic.h" |
31 | #include "clang/Basic/PragmaKinds.h" |
32 | #include "clang/Basic/SourceLocation.h" |
33 | #include "clang/Basic/Specifiers.h" |
34 | #include "clang/Basic/Visibility.h" |
35 | #include "llvm/ADT/APSInt.h" |
36 | #include "llvm/ADT/ArrayRef.h" |
37 | #include "llvm/ADT/Optional.h" |
38 | #include "llvm/ADT/PointerIntPair.h" |
39 | #include "llvm/ADT/PointerUnion.h" |
40 | #include "llvm/ADT/StringRef.h" |
41 | #include "llvm/ADT/iterator_range.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include "llvm/Support/Compiler.h" |
44 | #include "llvm/Support/TrailingObjects.h" |
45 | #include <cassert> |
46 | #include <cstddef> |
47 | #include <cstdint> |
48 | #include <string> |
49 | #include <utility> |
50 | |
51 | namespace clang { |
52 | |
53 | class ASTContext; |
54 | struct ASTTemplateArgumentListInfo; |
55 | class Attr; |
56 | class CompoundStmt; |
57 | class DependentFunctionTemplateSpecializationInfo; |
58 | class EnumDecl; |
59 | class Expr; |
60 | class FunctionTemplateDecl; |
61 | class FunctionTemplateSpecializationInfo; |
62 | class LabelStmt; |
63 | class MemberSpecializationInfo; |
64 | class Module; |
65 | class NamespaceDecl; |
66 | class ParmVarDecl; |
67 | class RecordDecl; |
68 | class Stmt; |
69 | class StringLiteral; |
70 | class TagDecl; |
71 | class TemplateArgumentList; |
72 | class TemplateArgumentListInfo; |
73 | class TemplateParameterList; |
74 | class TypeAliasTemplateDecl; |
75 | class TypeLoc; |
76 | class UnresolvedSetImpl; |
77 | class VarTemplateDecl; |
78 | |
79 | /// A container of type source information. |
80 | /// |
81 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
82 | /// @code |
83 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
84 | /// TL.getStartLoc().print(OS, SrcMgr); |
85 | /// @endcode |
86 | class LLVM_ALIGNAS(8)alignas(8) TypeSourceInfo { |
87 | // Contains a memory block after the class, used for type source information, |
88 | // allocated by ASTContext. |
89 | friend class ASTContext; |
90 | |
91 | QualType Ty; |
92 | |
93 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
94 | |
95 | public: |
96 | /// Return the type wrapped by this type source info. |
97 | QualType getType() const { return Ty; } |
98 | |
99 | /// Return the TypeLoc wrapper for the type source info. |
100 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
101 | |
102 | /// Override the type stored in this TypeSourceInfo. Use with caution! |
103 | void overrideType(QualType T) { Ty = T; } |
104 | }; |
105 | |
106 | /// The top declaration context. |
107 | class TranslationUnitDecl : public Decl, public DeclContext { |
108 | ASTContext &Ctx; |
109 | |
110 | /// The (most recently entered) anonymous namespace for this |
111 | /// translation unit, if one has been created. |
112 | NamespaceDecl *AnonymousNamespace = nullptr; |
113 | |
114 | explicit TranslationUnitDecl(ASTContext &ctx); |
115 | |
116 | virtual void anchor(); |
117 | |
118 | public: |
119 | ASTContext &getASTContext() const { return Ctx; } |
120 | |
121 | NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } |
122 | void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } |
123 | |
124 | static TranslationUnitDecl *Create(ASTContext &C); |
125 | |
126 | // Implement isa/cast/dyncast/etc. |
127 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
128 | static bool classofKind(Kind K) { return K == TranslationUnit; } |
129 | static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { |
130 | return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); |
131 | } |
132 | static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { |
133 | return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); |
134 | } |
135 | }; |
136 | |
137 | /// Represents a `#pragma comment` line. Always a child of |
138 | /// TranslationUnitDecl. |
139 | class PragmaCommentDecl final |
140 | : public Decl, |
141 | private llvm::TrailingObjects<PragmaCommentDecl, char> { |
142 | friend class ASTDeclReader; |
143 | friend class ASTDeclWriter; |
144 | friend TrailingObjects; |
145 | |
146 | PragmaMSCommentKind CommentKind; |
147 | |
148 | PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc, |
149 | PragmaMSCommentKind CommentKind) |
150 | : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {} |
151 | |
152 | virtual void anchor(); |
153 | |
154 | public: |
155 | static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC, |
156 | SourceLocation CommentLoc, |
157 | PragmaMSCommentKind CommentKind, |
158 | StringRef Arg); |
159 | static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
160 | unsigned ArgSize); |
161 | |
162 | PragmaMSCommentKind getCommentKind() const { return CommentKind; } |
163 | |
164 | StringRef getArg() const { return getTrailingObjects<char>(); } |
165 | |
166 | // Implement isa/cast/dyncast/etc. |
167 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
168 | static bool classofKind(Kind K) { return K == PragmaComment; } |
169 | }; |
170 | |
171 | /// Represents a `#pragma detect_mismatch` line. Always a child of |
172 | /// TranslationUnitDecl. |
173 | class PragmaDetectMismatchDecl final |
174 | : public Decl, |
175 | private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> { |
176 | friend class ASTDeclReader; |
177 | friend class ASTDeclWriter; |
178 | friend TrailingObjects; |
179 | |
180 | size_t ValueStart; |
181 | |
182 | PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc, |
183 | size_t ValueStart) |
184 | : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {} |
185 | |
186 | virtual void anchor(); |
187 | |
188 | public: |
189 | static PragmaDetectMismatchDecl *Create(const ASTContext &C, |
190 | TranslationUnitDecl *DC, |
191 | SourceLocation Loc, StringRef Name, |
192 | StringRef Value); |
193 | static PragmaDetectMismatchDecl * |
194 | CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); |
195 | |
196 | StringRef getName() const { return getTrailingObjects<char>(); } |
197 | StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; } |
198 | |
199 | // Implement isa/cast/dyncast/etc. |
200 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
201 | static bool classofKind(Kind K) { return K == PragmaDetectMismatch; } |
202 | }; |
203 | |
204 | /// Declaration context for names declared as extern "C" in C++. This |
205 | /// is neither the semantic nor lexical context for such declarations, but is |
206 | /// used to check for conflicts with other extern "C" declarations. Example: |
207 | /// |
208 | /// \code |
209 | /// namespace N { extern "C" void f(); } // #1 |
210 | /// void N::f() {} // #2 |
211 | /// namespace M { extern "C" void f(); } // #3 |
212 | /// \endcode |
213 | /// |
214 | /// The semantic context of #1 is namespace N and its lexical context is the |
215 | /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical |
216 | /// context is the TU. However, both declarations are also visible in the |
217 | /// extern "C" context. |
218 | /// |
219 | /// The declaration at #3 finds it is a redeclaration of \c N::f through |
220 | /// lookup in the extern "C" context. |
221 | class ExternCContextDecl : public Decl, public DeclContext { |
222 | explicit ExternCContextDecl(TranslationUnitDecl *TU) |
223 | : Decl(ExternCContext, TU, SourceLocation()), |
224 | DeclContext(ExternCContext) {} |
225 | |
226 | virtual void anchor(); |
227 | |
228 | public: |
229 | static ExternCContextDecl *Create(const ASTContext &C, |
230 | TranslationUnitDecl *TU); |
231 | |
232 | // Implement isa/cast/dyncast/etc. |
233 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
234 | static bool classofKind(Kind K) { return K == ExternCContext; } |
235 | static DeclContext *castToDeclContext(const ExternCContextDecl *D) { |
236 | return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D)); |
237 | } |
238 | static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) { |
239 | return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC)); |
240 | } |
241 | }; |
242 | |
243 | /// This represents a decl that may have a name. Many decls have names such |
244 | /// as ObjCMethodDecl, but not \@class, etc. |
245 | /// |
246 | /// Note that not every NamedDecl is actually named (e.g., a struct might |
247 | /// be anonymous), and not every name is an identifier. |
248 | class NamedDecl : public Decl { |
249 | /// The name of this declaration, which is typically a normal |
250 | /// identifier but may also be a special kind of name (C++ |
251 | /// constructor, Objective-C selector, etc.) |
252 | DeclarationName Name; |
253 | |
254 | virtual void anchor(); |
255 | |
256 | private: |
257 | NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__)); |
258 | |
259 | protected: |
260 | NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) |
261 | : Decl(DK, DC, L), Name(N) {} |
262 | |
263 | public: |
264 | /// Get the identifier that names this declaration, if there is one. |
265 | /// |
266 | /// This will return NULL if this declaration has no name (e.g., for |
267 | /// an unnamed class) or if the name is a special name (C++ constructor, |
268 | /// Objective-C selector, etc.). |
269 | IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } |
270 | |
271 | /// Get the name of identifier for this declaration as a StringRef. |
272 | /// |
273 | /// This requires that the declaration have a name and that it be a simple |
274 | /// identifier. |
275 | StringRef getName() const { |
276 | assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier" ) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 276, __extension__ __PRETTY_FUNCTION__)); |
277 | return getIdentifier() ? getIdentifier()->getName() : ""; |
278 | } |
279 | |
280 | /// Get a human-readable name for the declaration, even if it is one of the |
281 | /// special kinds of names (C++ constructor, Objective-C selector, etc). |
282 | /// |
283 | /// Creating this name requires expensive string manipulation, so it should |
284 | /// be called only when performance doesn't matter. For simple declarations, |
285 | /// getNameAsCString() should suffice. |
286 | // |
287 | // FIXME: This function should be renamed to indicate that it is not just an |
288 | // alternate form of getName(), and clients should move as appropriate. |
289 | // |
290 | // FIXME: Deprecated, move clients to getName(). |
291 | std::string getNameAsString() const { return Name.getAsString(); } |
292 | |
293 | virtual void printName(raw_ostream &os) const; |
294 | |
295 | /// Get the actual, stored name of the declaration, which may be a special |
296 | /// name. |
297 | DeclarationName getDeclName() const { return Name; } |
298 | |
299 | /// Set the name of this declaration. |
300 | void setDeclName(DeclarationName N) { Name = N; } |
301 | |
302 | /// Returns a human-readable qualified name for this declaration, like |
303 | /// A::B::i, for i being member of namespace A::B. |
304 | /// |
305 | /// If the declaration is not a member of context which can be named (record, |
306 | /// namespace), it will return the same result as printName(). |
307 | /// |
308 | /// Creating this name is expensive, so it should be called only when |
309 | /// performance doesn't matter. |
310 | void printQualifiedName(raw_ostream &OS) const; |
311 | void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
312 | |
313 | // FIXME: Remove string version. |
314 | std::string getQualifiedNameAsString() const; |
315 | |
316 | /// Appends a human-readable name for this declaration into the given stream. |
317 | /// |
318 | /// This is the method invoked by Sema when displaying a NamedDecl |
319 | /// in a diagnostic. It does not necessarily produce the same |
320 | /// result as printName(); for example, class template |
321 | /// specializations are printed with their template arguments. |
322 | virtual void getNameForDiagnostic(raw_ostream &OS, |
323 | const PrintingPolicy &Policy, |
324 | bool Qualified) const; |
325 | |
326 | /// Determine whether this declaration, if known to be well-formed within |
327 | /// its context, will replace the declaration OldD if introduced into scope. |
328 | /// |
329 | /// A declaration will replace another declaration if, for example, it is |
330 | /// a redeclaration of the same variable or function, but not if it is a |
331 | /// declaration of a different kind (function vs. class) or an overloaded |
332 | /// function. |
333 | /// |
334 | /// \param IsKnownNewer \c true if this declaration is known to be newer |
335 | /// than \p OldD (for instance, if this declaration is newly-created). |
336 | bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const; |
337 | |
338 | /// Determine whether this declaration has linkage. |
339 | bool hasLinkage() const; |
340 | |
341 | using Decl::isModulePrivate; |
342 | using Decl::setModulePrivate; |
343 | |
344 | /// Determine whether this declaration is a C++ class member. |
345 | bool isCXXClassMember() const { |
346 | const DeclContext *DC = getDeclContext(); |
347 | |
348 | // C++0x [class.mem]p1: |
349 | // The enumerators of an unscoped enumeration defined in |
350 | // the class are members of the class. |
351 | if (isa<EnumDecl>(DC)) |
352 | DC = DC->getRedeclContext(); |
353 | |
354 | return DC->isRecord(); |
355 | } |
356 | |
357 | /// Determine whether the given declaration is an instance member of |
358 | /// a C++ class. |
359 | bool isCXXInstanceMember() const; |
360 | |
361 | /// Determine what kind of linkage this entity has. |
362 | /// |
363 | /// This is not the linkage as defined by the standard or the codegen notion |
364 | /// of linkage. It is just an implementation detail that is used to compute |
365 | /// those. |
366 | Linkage getLinkageInternal() const; |
367 | |
368 | /// Get the linkage from a semantic point of view. Entities in |
369 | /// anonymous namespaces are external (in c++98). |
370 | Linkage getFormalLinkage() const { |
371 | return clang::getFormalLinkage(getLinkageInternal()); |
372 | } |
373 | |
374 | /// True if this decl has external linkage. |
375 | bool hasExternalFormalLinkage() const { |
376 | return isExternalFormalLinkage(getLinkageInternal()); |
377 | } |
378 | |
379 | bool isExternallyVisible() const { |
380 | return clang::isExternallyVisible(getLinkageInternal()); |
381 | } |
382 | |
383 | /// Determine whether this declaration can be redeclared in a |
384 | /// different translation unit. |
385 | bool isExternallyDeclarable() const { |
386 | return isExternallyVisible() && !getOwningModuleForLinkage(); |
387 | } |
388 | |
389 | /// Determines the visibility of this entity. |
390 | Visibility getVisibility() const { |
391 | return getLinkageAndVisibility().getVisibility(); |
392 | } |
393 | |
394 | /// Determines the linkage and visibility of this entity. |
395 | LinkageInfo getLinkageAndVisibility() const; |
396 | |
397 | /// Kinds of explicit visibility. |
398 | enum ExplicitVisibilityKind { |
399 | /// Do an LV computation for, ultimately, a type. |
400 | /// Visibility may be restricted by type visibility settings and |
401 | /// the visibility of template arguments. |
402 | VisibilityForType, |
403 | |
404 | /// Do an LV computation for, ultimately, a non-type declaration. |
405 | /// Visibility may be restricted by value visibility settings and |
406 | /// the visibility of template arguments. |
407 | VisibilityForValue |
408 | }; |
409 | |
410 | /// If visibility was explicitly specified for this |
411 | /// declaration, return that visibility. |
412 | Optional<Visibility> |
413 | getExplicitVisibility(ExplicitVisibilityKind kind) const; |
414 | |
415 | /// True if the computed linkage is valid. Used for consistency |
416 | /// checking. Should always return true. |
417 | bool isLinkageValid() const; |
418 | |
419 | /// True if something has required us to compute the linkage |
420 | /// of this declaration. |
421 | /// |
422 | /// Language features which can retroactively change linkage (like a |
423 | /// typedef name for linkage purposes) may need to consider this, |
424 | /// but hopefully only in transitory ways during parsing. |
425 | bool hasLinkageBeenComputed() const { |
426 | return hasCachedLinkage(); |
427 | } |
428 | |
429 | /// Looks through UsingDecls and ObjCCompatibleAliasDecls for |
430 | /// the underlying named decl. |
431 | NamedDecl *getUnderlyingDecl() { |
432 | // Fast-path the common case. |
433 | if (this->getKind() != UsingShadow && |
434 | this->getKind() != ConstructorUsingShadow && |
435 | this->getKind() != ObjCCompatibleAlias && |
436 | this->getKind() != NamespaceAlias) |
437 | return this; |
438 | |
439 | return getUnderlyingDeclImpl(); |
440 | } |
441 | const NamedDecl *getUnderlyingDecl() const { |
442 | return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); |
443 | } |
444 | |
445 | NamedDecl *getMostRecentDecl() { |
446 | return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl()); |
447 | } |
448 | const NamedDecl *getMostRecentDecl() const { |
449 | return const_cast<NamedDecl*>(this)->getMostRecentDecl(); |
450 | } |
451 | |
452 | ObjCStringFormatFamily getObjCFStringFormattingFamily() const; |
453 | |
454 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
455 | static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } |
456 | }; |
457 | |
458 | inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { |
459 | ND.printName(OS); |
460 | return OS; |
461 | } |
462 | |
463 | /// Represents the declaration of a label. Labels also have a |
464 | /// corresponding LabelStmt, which indicates the position that the label was |
465 | /// defined at. For normal labels, the location of the decl is the same as the |
466 | /// location of the statement. For GNU local labels (__label__), the decl |
467 | /// location is where the __label__ is. |
468 | class LabelDecl : public NamedDecl { |
469 | LabelStmt *TheStmt; |
470 | StringRef MSAsmName; |
471 | bool MSAsmNameResolved = false; |
472 | |
473 | /// For normal labels, this is the same as the main declaration |
474 | /// label, i.e., the location of the identifier; for GNU local labels, |
475 | /// this is the location of the __label__ keyword. |
476 | SourceLocation LocStart; |
477 | |
478 | LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, |
479 | LabelStmt *S, SourceLocation StartL) |
480 | : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} |
481 | |
482 | void anchor() override; |
483 | |
484 | public: |
485 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
486 | SourceLocation IdentL, IdentifierInfo *II); |
487 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
488 | SourceLocation IdentL, IdentifierInfo *II, |
489 | SourceLocation GnuLabelL); |
490 | static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
491 | |
492 | LabelStmt *getStmt() const { return TheStmt; } |
493 | void setStmt(LabelStmt *T) { TheStmt = T; } |
494 | |
495 | bool isGnuLocal() const { return LocStart != getLocation(); } |
496 | void setLocStart(SourceLocation L) { LocStart = L; } |
497 | |
498 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
499 | return SourceRange(LocStart, getLocation()); |
500 | } |
501 | |
502 | bool isMSAsmLabel() const { return !MSAsmName.empty(); } |
503 | bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; } |
504 | void setMSAsmLabel(StringRef Name); |
505 | StringRef getMSAsmLabel() const { return MSAsmName; } |
506 | void setMSAsmLabelResolved() { MSAsmNameResolved = true; } |
507 | |
508 | // Implement isa/cast/dyncast/etc. |
509 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
510 | static bool classofKind(Kind K) { return K == Label; } |
511 | }; |
512 | |
513 | /// Represent a C++ namespace. |
514 | class NamespaceDecl : public NamedDecl, public DeclContext, |
515 | public Redeclarable<NamespaceDecl> |
516 | { |
517 | /// The starting location of the source range, pointing |
518 | /// to either the namespace or the inline keyword. |
519 | SourceLocation LocStart; |
520 | |
521 | /// The ending location of the source range. |
522 | SourceLocation RBraceLoc; |
523 | |
524 | /// A pointer to either the anonymous namespace that lives just inside |
525 | /// this namespace or to the first namespace in the chain (the latter case |
526 | /// only when this is not the first in the chain), along with a |
527 | /// boolean value indicating whether this is an inline namespace. |
528 | llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; |
529 | |
530 | NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, |
531 | SourceLocation StartLoc, SourceLocation IdLoc, |
532 | IdentifierInfo *Id, NamespaceDecl *PrevDecl); |
533 | |
534 | using redeclarable_base = Redeclarable<NamespaceDecl>; |
535 | |
536 | NamespaceDecl *getNextRedeclarationImpl() override; |
537 | NamespaceDecl *getPreviousDeclImpl() override; |
538 | NamespaceDecl *getMostRecentDeclImpl() override; |
539 | |
540 | public: |
541 | friend class ASTDeclReader; |
542 | friend class ASTDeclWriter; |
543 | |
544 | static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, |
545 | bool Inline, SourceLocation StartLoc, |
546 | SourceLocation IdLoc, IdentifierInfo *Id, |
547 | NamespaceDecl *PrevDecl); |
548 | |
549 | static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
550 | |
551 | using redecl_range = redeclarable_base::redecl_range; |
552 | using redecl_iterator = redeclarable_base::redecl_iterator; |
553 | |
554 | using redeclarable_base::redecls_begin; |
555 | using redeclarable_base::redecls_end; |
556 | using redeclarable_base::redecls; |
557 | using redeclarable_base::getPreviousDecl; |
558 | using redeclarable_base::getMostRecentDecl; |
559 | using redeclarable_base::isFirstDecl; |
560 | |
561 | /// Returns true if this is an anonymous namespace declaration. |
562 | /// |
563 | /// For example: |
564 | /// \code |
565 | /// namespace { |
566 | /// ... |
567 | /// }; |
568 | /// \endcode |
569 | /// q.v. C++ [namespace.unnamed] |
570 | bool isAnonymousNamespace() const { |
571 | return !getIdentifier(); |
572 | } |
573 | |
574 | /// Returns true if this is an inline namespace declaration. |
575 | bool isInline() const { |
576 | return AnonOrFirstNamespaceAndInline.getInt(); |
577 | } |
578 | |
579 | /// Set whether this is an inline namespace declaration. |
580 | void setInline(bool Inline) { |
581 | AnonOrFirstNamespaceAndInline.setInt(Inline); |
582 | } |
583 | |
584 | /// Get the original (first) namespace declaration. |
585 | NamespaceDecl *getOriginalNamespace(); |
586 | |
587 | /// Get the original (first) namespace declaration. |
588 | const NamespaceDecl *getOriginalNamespace() const; |
589 | |
590 | /// Return true if this declaration is an original (first) declaration |
591 | /// of the namespace. This is false for non-original (subsequent) namespace |
592 | /// declarations and anonymous namespaces. |
593 | bool isOriginalNamespace() const; |
594 | |
595 | /// Retrieve the anonymous namespace nested inside this namespace, |
596 | /// if any. |
597 | NamespaceDecl *getAnonymousNamespace() const { |
598 | return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); |
599 | } |
600 | |
601 | void setAnonymousNamespace(NamespaceDecl *D) { |
602 | getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); |
603 | } |
604 | |
605 | /// Retrieves the canonical declaration of this namespace. |
606 | NamespaceDecl *getCanonicalDecl() override { |
607 | return getOriginalNamespace(); |
608 | } |
609 | const NamespaceDecl *getCanonicalDecl() const { |
610 | return getOriginalNamespace(); |
611 | } |
612 | |
613 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
614 | return SourceRange(LocStart, RBraceLoc); |
615 | } |
616 | |
617 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
618 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
619 | void setLocStart(SourceLocation L) { LocStart = L; } |
620 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
621 | |
622 | // Implement isa/cast/dyncast/etc. |
623 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
624 | static bool classofKind(Kind K) { return K == Namespace; } |
625 | static DeclContext *castToDeclContext(const NamespaceDecl *D) { |
626 | return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); |
627 | } |
628 | static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { |
629 | return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); |
630 | } |
631 | }; |
632 | |
633 | /// Represent the declaration of a variable (in which case it is |
634 | /// an lvalue) a function (in which case it is a function designator) or |
635 | /// an enum constant. |
636 | class ValueDecl : public NamedDecl { |
637 | QualType DeclType; |
638 | |
639 | void anchor() override; |
640 | |
641 | protected: |
642 | ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, |
643 | DeclarationName N, QualType T) |
644 | : NamedDecl(DK, DC, L, N), DeclType(T) {} |
645 | |
646 | public: |
647 | QualType getType() const { return DeclType; } |
648 | void setType(QualType newType) { DeclType = newType; } |
649 | |
650 | /// Determine whether this symbol is weakly-imported, |
651 | /// or declared with the weak or weak-ref attr. |
652 | bool isWeak() const; |
653 | |
654 | // Implement isa/cast/dyncast/etc. |
655 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
656 | static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } |
657 | }; |
658 | |
659 | /// A struct with extended info about a syntactic |
660 | /// name qualifier, to be used for the case of out-of-line declarations. |
661 | struct QualifierInfo { |
662 | NestedNameSpecifierLoc QualifierLoc; |
663 | |
664 | /// The number of "outer" template parameter lists. |
665 | /// The count includes all of the template parameter lists that were matched |
666 | /// against the template-ids occurring into the NNS and possibly (in the |
667 | /// case of an explicit specialization) a final "template <>". |
668 | unsigned NumTemplParamLists = 0; |
669 | |
670 | /// A new-allocated array of size NumTemplParamLists, |
671 | /// containing pointers to the "outer" template parameter lists. |
672 | /// It includes all of the template parameter lists that were matched |
673 | /// against the template-ids occurring into the NNS and possibly (in the |
674 | /// case of an explicit specialization) a final "template <>". |
675 | TemplateParameterList** TemplParamLists = nullptr; |
676 | |
677 | QualifierInfo() = default; |
678 | QualifierInfo(const QualifierInfo &) = delete; |
679 | QualifierInfo& operator=(const QualifierInfo &) = delete; |
680 | |
681 | /// Sets info about "outer" template parameter lists. |
682 | void setTemplateParameterListsInfo(ASTContext &Context, |
683 | ArrayRef<TemplateParameterList *> TPLists); |
684 | }; |
685 | |
686 | /// Represents a ValueDecl that came out of a declarator. |
687 | /// Contains type source information through TypeSourceInfo. |
688 | class DeclaratorDecl : public ValueDecl { |
689 | // A struct representing both a TInfo and a syntactic qualifier, |
690 | // to be used for the (uncommon) case of out-of-line declarations. |
691 | struct ExtInfo : public QualifierInfo { |
692 | TypeSourceInfo *TInfo; |
693 | }; |
694 | |
695 | llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo; |
696 | |
697 | /// The start of the source range for this declaration, |
698 | /// ignoring outer template declarations. |
699 | SourceLocation InnerLocStart; |
700 | |
701 | bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } |
702 | ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } |
703 | const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } |
704 | |
705 | protected: |
706 | DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, |
707 | DeclarationName N, QualType T, TypeSourceInfo *TInfo, |
708 | SourceLocation StartL) |
709 | : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {} |
710 | |
711 | public: |
712 | friend class ASTDeclReader; |
713 | friend class ASTDeclWriter; |
714 | |
715 | TypeSourceInfo *getTypeSourceInfo() const { |
716 | return hasExtInfo() |
717 | ? getExtInfo()->TInfo |
718 | : DeclInfo.get<TypeSourceInfo*>(); |
719 | } |
720 | |
721 | void setTypeSourceInfo(TypeSourceInfo *TI) { |
722 | if (hasExtInfo()) |
723 | getExtInfo()->TInfo = TI; |
724 | else |
725 | DeclInfo = TI; |
726 | } |
727 | |
728 | /// Return start of source range ignoring outer template declarations. |
729 | SourceLocation getInnerLocStart() const { return InnerLocStart; } |
730 | void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } |
731 | |
732 | /// Return start of source range taking into account any outer template |
733 | /// declarations. |
734 | SourceLocation getOuterLocStart() const; |
735 | |
736 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
737 | |
738 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { |
739 | return getOuterLocStart(); |
740 | } |
741 | |
742 | /// Retrieve the nested-name-specifier that qualifies the name of this |
743 | /// declaration, if it was present in the source. |
744 | NestedNameSpecifier *getQualifier() const { |
745 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
746 | : nullptr; |
747 | } |
748 | |
749 | /// Retrieve the nested-name-specifier (with source-location |
750 | /// information) that qualifies the name of this declaration, if it was |
751 | /// present in the source. |
752 | NestedNameSpecifierLoc getQualifierLoc() const { |
753 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
754 | : NestedNameSpecifierLoc(); |
755 | } |
756 | |
757 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
758 | |
759 | unsigned getNumTemplateParameterLists() const { |
760 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
761 | } |
762 | |
763 | TemplateParameterList *getTemplateParameterList(unsigned index) const { |
764 | assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 764, __extension__ __PRETTY_FUNCTION__)); |
765 | return getExtInfo()->TemplParamLists[index]; |
766 | } |
767 | |
768 | void setTemplateParameterListsInfo(ASTContext &Context, |
769 | ArrayRef<TemplateParameterList *> TPLists); |
770 | |
771 | SourceLocation getTypeSpecStartLoc() const; |
772 | |
773 | // Implement isa/cast/dyncast/etc. |
774 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
775 | static bool classofKind(Kind K) { |
776 | return K >= firstDeclarator && K <= lastDeclarator; |
777 | } |
778 | }; |
779 | |
780 | /// Structure used to store a statement, the constant value to |
781 | /// which it was evaluated (if any), and whether or not the statement |
782 | /// is an integral constant expression (if known). |
783 | struct EvaluatedStmt { |
784 | /// Whether this statement was already evaluated. |
785 | bool WasEvaluated : 1; |
786 | |
787 | /// Whether this statement is being evaluated. |
788 | bool IsEvaluating : 1; |
789 | |
790 | /// Whether we already checked whether this statement was an |
791 | /// integral constant expression. |
792 | bool CheckedICE : 1; |
793 | |
794 | /// Whether we are checking whether this statement is an |
795 | /// integral constant expression. |
796 | bool CheckingICE : 1; |
797 | |
798 | /// Whether this statement is an integral constant expression, |
799 | /// or in C++11, whether the statement is a constant expression. Only |
800 | /// valid if CheckedICE is true. |
801 | bool IsICE : 1; |
802 | |
803 | Stmt *Value; |
804 | APValue Evaluated; |
805 | |
806 | EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), |
807 | CheckingICE(false), IsICE(false) {} |
808 | |
809 | }; |
810 | |
811 | /// Represents a variable declaration or definition. |
812 | class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { |
813 | public: |
814 | /// Initialization styles. |
815 | enum InitializationStyle { |
816 | /// C-style initialization with assignment |
817 | CInit, |
818 | |
819 | /// Call-style initialization (C++98) |
820 | CallInit, |
821 | |
822 | /// Direct list-initialization (C++11) |
823 | ListInit |
824 | }; |
825 | |
826 | /// Kinds of thread-local storage. |
827 | enum TLSKind { |
828 | /// Not a TLS variable. |
829 | TLS_None, |
830 | |
831 | /// TLS with a known-constant initializer. |
832 | TLS_Static, |
833 | |
834 | /// TLS with a dynamic initializer. |
835 | TLS_Dynamic |
836 | }; |
837 | |
838 | /// Return the string used to specify the storage class \p SC. |
839 | /// |
840 | /// It is illegal to call this function with SC == None. |
841 | static const char *getStorageClassSpecifierString(StorageClass SC); |
842 | |
843 | protected: |
844 | // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we |
845 | // have allocated the auxiliary struct of information there. |
846 | // |
847 | // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for |
848 | // this as *many* VarDecls are ParmVarDecls that don't have default |
849 | // arguments. We could save some space by moving this pointer union to be |
850 | // allocated in trailing space when necessary. |
851 | using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>; |
852 | |
853 | /// The initializer for this variable or, for a ParmVarDecl, the |
854 | /// C++ default argument. |
855 | mutable InitType Init; |
856 | |
857 | private: |
858 | friend class ASTDeclReader; |
859 | friend class ASTNodeImporter; |
860 | friend class StmtIteratorBase; |
861 | |
862 | class VarDeclBitfields { |
863 | friend class ASTDeclReader; |
864 | friend class VarDecl; |
865 | |
866 | unsigned SClass : 3; |
867 | unsigned TSCSpec : 2; |
868 | unsigned InitStyle : 2; |
869 | }; |
870 | enum { NumVarDeclBits = 7 }; |
871 | |
872 | protected: |
873 | enum { NumParameterIndexBits = 8 }; |
874 | |
875 | enum DefaultArgKind { |
876 | DAK_None, |
877 | DAK_Unparsed, |
878 | DAK_Uninstantiated, |
879 | DAK_Normal |
880 | }; |
881 | |
882 | class ParmVarDeclBitfields { |
883 | friend class ASTDeclReader; |
884 | friend class ParmVarDecl; |
885 | |
886 | unsigned : NumVarDeclBits; |
887 | |
888 | /// Whether this parameter inherits a default argument from a |
889 | /// prior declaration. |
890 | unsigned HasInheritedDefaultArg : 1; |
891 | |
892 | /// Describes the kind of default argument for this parameter. By default |
893 | /// this is none. If this is normal, then the default argument is stored in |
894 | /// the \c VarDecl initializer expression unless we were unable to parse |
895 | /// (even an invalid) expression for the default argument. |
896 | unsigned DefaultArgKind : 2; |
897 | |
898 | /// Whether this parameter undergoes K&R argument promotion. |
899 | unsigned IsKNRPromoted : 1; |
900 | |
901 | /// Whether this parameter is an ObjC method parameter or not. |
902 | unsigned IsObjCMethodParam : 1; |
903 | |
904 | /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. |
905 | /// Otherwise, the number of function parameter scopes enclosing |
906 | /// the function parameter scope in which this parameter was |
907 | /// declared. |
908 | unsigned ScopeDepthOrObjCQuals : 7; |
909 | |
910 | /// The number of parameters preceding this parameter in the |
911 | /// function parameter scope in which it was declared. |
912 | unsigned ParameterIndex : NumParameterIndexBits; |
913 | }; |
914 | |
915 | class NonParmVarDeclBitfields { |
916 | friend class ASTDeclReader; |
917 | friend class ImplicitParamDecl; |
918 | friend class VarDecl; |
919 | |
920 | unsigned : NumVarDeclBits; |
921 | |
922 | // FIXME: We need something similar to CXXRecordDecl::DefinitionData. |
923 | /// Whether this variable is a definition which was demoted due to |
924 | /// module merge. |
925 | unsigned IsThisDeclarationADemotedDefinition : 1; |
926 | |
927 | /// Whether this variable is the exception variable in a C++ catch |
928 | /// or an Objective-C @catch statement. |
929 | unsigned ExceptionVar : 1; |
930 | |
931 | /// Whether this local variable could be allocated in the return |
932 | /// slot of its function, enabling the named return value optimization |
933 | /// (NRVO). |
934 | unsigned NRVOVariable : 1; |
935 | |
936 | /// Whether this variable is the for-range-declaration in a C++0x |
937 | /// for-range statement. |
938 | unsigned CXXForRangeDecl : 1; |
939 | |
940 | /// Whether this variable is an ARC pseudo-__strong |
941 | /// variable; see isARCPseudoStrong() for details. |
942 | unsigned ARCPseudoStrong : 1; |
943 | |
944 | /// Whether this variable is (C++1z) inline. |
945 | unsigned IsInline : 1; |
946 | |
947 | /// Whether this variable has (C++1z) inline explicitly specified. |
948 | unsigned IsInlineSpecified : 1; |
949 | |
950 | /// Whether this variable is (C++0x) constexpr. |
951 | unsigned IsConstexpr : 1; |
952 | |
953 | /// Whether this variable is the implicit variable for a lambda |
954 | /// init-capture. |
955 | unsigned IsInitCapture : 1; |
956 | |
957 | /// Whether this local extern variable's previous declaration was |
958 | /// declared in the same block scope. This controls whether we should merge |
959 | /// the type of this declaration with its previous declaration. |
960 | unsigned PreviousDeclInSameBlockScope : 1; |
961 | |
962 | /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or |
963 | /// something else. |
964 | unsigned ImplicitParamKind : 3; |
965 | }; |
966 | |
967 | union { |
968 | unsigned AllBits; |
969 | VarDeclBitfields VarDeclBits; |
970 | ParmVarDeclBitfields ParmVarDeclBits; |
971 | NonParmVarDeclBitfields NonParmVarDeclBits; |
972 | }; |
973 | |
974 | VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
975 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
976 | TypeSourceInfo *TInfo, StorageClass SC); |
977 | |
978 | using redeclarable_base = Redeclarable<VarDecl>; |
979 | |
980 | VarDecl *getNextRedeclarationImpl() override { |
981 | return getNextRedeclaration(); |
982 | } |
983 | |
984 | VarDecl *getPreviousDeclImpl() override { |
985 | return getPreviousDecl(); |
986 | } |
987 | |
988 | VarDecl *getMostRecentDeclImpl() override { |
989 | return getMostRecentDecl(); |
990 | } |
991 | |
992 | public: |
993 | using redecl_range = redeclarable_base::redecl_range; |
994 | using redecl_iterator = redeclarable_base::redecl_iterator; |
995 | |
996 | using redeclarable_base::redecls_begin; |
997 | using redeclarable_base::redecls_end; |
998 | using redeclarable_base::redecls; |
999 | using redeclarable_base::getPreviousDecl; |
1000 | using redeclarable_base::getMostRecentDecl; |
1001 | using redeclarable_base::isFirstDecl; |
1002 | |
1003 | static VarDecl *Create(ASTContext &C, DeclContext *DC, |
1004 | SourceLocation StartLoc, SourceLocation IdLoc, |
1005 | IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, |
1006 | StorageClass S); |
1007 | |
1008 | static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1009 | |
1010 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1011 | |
1012 | /// Returns the storage class as written in the source. For the |
1013 | /// computed linkage of symbol, see getLinkage. |
1014 | StorageClass getStorageClass() const { |
1015 | return (StorageClass) VarDeclBits.SClass; |
1016 | } |
1017 | void setStorageClass(StorageClass SC); |
1018 | |
1019 | void setTSCSpec(ThreadStorageClassSpecifier TSC) { |
1020 | VarDeclBits.TSCSpec = TSC; |
1021 | assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC && "truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1021, __extension__ __PRETTY_FUNCTION__)); |
1022 | } |
1023 | ThreadStorageClassSpecifier getTSCSpec() const { |
1024 | return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); |
1025 | } |
1026 | TLSKind getTLSKind() const; |
1027 | |
1028 | /// Returns true if a variable with function scope is a non-static local |
1029 | /// variable. |
1030 | bool hasLocalStorage() const { |
1031 | if (getStorageClass() == SC_None) { |
1032 | // OpenCL v1.2 s6.5.3: The __constant or constant address space name is |
1033 | // used to describe variables allocated in global memory and which are |
1034 | // accessed inside a kernel(s) as read-only variables. As such, variables |
1035 | // in constant address space cannot have local storage. |
1036 | if (getType().getAddressSpace() == LangAS::opencl_constant) |
1037 | return false; |
1038 | // Second check is for C++11 [dcl.stc]p4. |
1039 | return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; |
1040 | } |
1041 | |
1042 | // Global Named Register (GNU extension) |
1043 | if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) |
1044 | return false; |
1045 | |
1046 | // Return true for: Auto, Register. |
1047 | // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. |
1048 | |
1049 | return getStorageClass() >= SC_Auto; |
1050 | } |
1051 | |
1052 | /// Returns true if a variable with function scope is a static local |
1053 | /// variable. |
1054 | bool isStaticLocal() const { |
1055 | return (getStorageClass() == SC_Static || |
1056 | // C++11 [dcl.stc]p4 |
1057 | (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local)) |
1058 | && !isFileVarDecl(); |
1059 | } |
1060 | |
1061 | /// Returns true if a variable has extern or __private_extern__ |
1062 | /// storage. |
1063 | bool hasExternalStorage() const { |
1064 | return getStorageClass() == SC_Extern || |
1065 | getStorageClass() == SC_PrivateExtern; |
1066 | } |
1067 | |
1068 | /// Returns true for all variables that do not have local storage. |
1069 | /// |
1070 | /// This includes all global variables as well as static variables declared |
1071 | /// within a function. |
1072 | bool hasGlobalStorage() const { return !hasLocalStorage(); } |
1073 | |
1074 | /// Get the storage duration of this variable, per C++ [basic.stc]. |
1075 | StorageDuration getStorageDuration() const { |
1076 | return hasLocalStorage() ? SD_Automatic : |
1077 | getTSCSpec() ? SD_Thread : SD_Static; |
1078 | } |
1079 | |
1080 | /// Compute the language linkage. |
1081 | LanguageLinkage getLanguageLinkage() const; |
1082 | |
1083 | /// Determines whether this variable is a variable with external, C linkage. |
1084 | bool isExternC() const; |
1085 | |
1086 | /// Determines whether this variable's context is, or is nested within, |
1087 | /// a C++ extern "C" linkage spec. |
1088 | bool isInExternCContext() const; |
1089 | |
1090 | /// Determines whether this variable's context is, or is nested within, |
1091 | /// a C++ extern "C++" linkage spec. |
1092 | bool isInExternCXXContext() const; |
1093 | |
1094 | /// Returns true for local variable declarations other than parameters. |
1095 | /// Note that this includes static variables inside of functions. It also |
1096 | /// includes variables inside blocks. |
1097 | /// |
1098 | /// void foo() { int x; static int y; extern int z; } |
1099 | bool isLocalVarDecl() const { |
1100 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1101 | return false; |
1102 | if (const DeclContext *DC = getLexicalDeclContext()) |
1103 | return DC->getRedeclContext()->isFunctionOrMethod(); |
1104 | return false; |
1105 | } |
1106 | |
1107 | /// Similar to isLocalVarDecl but also includes parameters. |
1108 | bool isLocalVarDeclOrParm() const { |
1109 | return isLocalVarDecl() || getKind() == Decl::ParmVar; |
1110 | } |
1111 | |
1112 | /// Similar to isLocalVarDecl, but excludes variables declared in blocks. |
1113 | bool isFunctionOrMethodVarDecl() const { |
1114 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1115 | return false; |
1116 | const DeclContext *DC = getLexicalDeclContext()->getRedeclContext(); |
1117 | return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; |
1118 | } |
1119 | |
1120 | /// Determines whether this is a static data member. |
1121 | /// |
1122 | /// This will only be true in C++, and applies to, e.g., the |
1123 | /// variable 'x' in: |
1124 | /// \code |
1125 | /// struct S { |
1126 | /// static int x; |
1127 | /// }; |
1128 | /// \endcode |
1129 | bool isStaticDataMember() const { |
1130 | // If it wasn't static, it would be a FieldDecl. |
1131 | return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); |
1132 | } |
1133 | |
1134 | VarDecl *getCanonicalDecl() override; |
1135 | const VarDecl *getCanonicalDecl() const { |
1136 | return const_cast<VarDecl*>(this)->getCanonicalDecl(); |
1137 | } |
1138 | |
1139 | enum DefinitionKind { |
1140 | /// This declaration is only a declaration. |
1141 | DeclarationOnly, |
1142 | |
1143 | /// This declaration is a tentative definition. |
1144 | TentativeDefinition, |
1145 | |
1146 | /// This declaration is definitely a definition. |
1147 | Definition |
1148 | }; |
1149 | |
1150 | /// Check whether this declaration is a definition. If this could be |
1151 | /// a tentative definition (in C), don't check whether there's an overriding |
1152 | /// definition. |
1153 | DefinitionKind isThisDeclarationADefinition(ASTContext &) const; |
1154 | DefinitionKind isThisDeclarationADefinition() const { |
1155 | return isThisDeclarationADefinition(getASTContext()); |
1156 | } |
1157 | |
1158 | /// Check whether this variable is defined in this translation unit. |
1159 | DefinitionKind hasDefinition(ASTContext &) const; |
1160 | DefinitionKind hasDefinition() const { |
1161 | return hasDefinition(getASTContext()); |
1162 | } |
1163 | |
1164 | /// Get the tentative definition that acts as the real definition in a TU. |
1165 | /// Returns null if there is a proper definition available. |
1166 | VarDecl *getActingDefinition(); |
1167 | const VarDecl *getActingDefinition() const { |
1168 | return const_cast<VarDecl*>(this)->getActingDefinition(); |
1169 | } |
1170 | |
1171 | /// Get the real (not just tentative) definition for this declaration. |
1172 | VarDecl *getDefinition(ASTContext &); |
1173 | const VarDecl *getDefinition(ASTContext &C) const { |
1174 | return const_cast<VarDecl*>(this)->getDefinition(C); |
1175 | } |
1176 | VarDecl *getDefinition() { |
1177 | return getDefinition(getASTContext()); |
1178 | } |
1179 | const VarDecl *getDefinition() const { |
1180 | return const_cast<VarDecl*>(this)->getDefinition(); |
1181 | } |
1182 | |
1183 | /// Determine whether this is or was instantiated from an out-of-line |
1184 | /// definition of a static data member. |
1185 | bool isOutOfLine() const override; |
1186 | |
1187 | /// Returns true for file scoped variable declaration. |
1188 | bool isFileVarDecl() const { |
1189 | Kind K = getKind(); |
1190 | if (K == ParmVar || K == ImplicitParam) |
1191 | return false; |
1192 | |
1193 | if (getLexicalDeclContext()->getRedeclContext()->isFileContext()) |
1194 | return true; |
1195 | |
1196 | if (isStaticDataMember()) |
1197 | return true; |
1198 | |
1199 | return false; |
1200 | } |
1201 | |
1202 | /// Get the initializer for this variable, no matter which |
1203 | /// declaration it is attached to. |
1204 | const Expr *getAnyInitializer() const { |
1205 | const VarDecl *D; |
1206 | return getAnyInitializer(D); |
1207 | } |
1208 | |
1209 | /// Get the initializer for this variable, no matter which |
1210 | /// declaration it is attached to. Also get that declaration. |
1211 | const Expr *getAnyInitializer(const VarDecl *&D) const; |
1212 | |
1213 | bool hasInit() const; |
1214 | const Expr *getInit() const { |
1215 | return const_cast<VarDecl *>(this)->getInit(); |
1216 | } |
1217 | Expr *getInit(); |
1218 | |
1219 | /// Retrieve the address of the initializer expression. |
1220 | Stmt **getInitAddress(); |
1221 | |
1222 | void setInit(Expr *I); |
1223 | |
1224 | /// Determine whether this variable's value can be used in a |
1225 | /// constant expression, according to the relevant language standard. |
1226 | /// This only checks properties of the declaration, and does not check |
1227 | /// whether the initializer is in fact a constant expression. |
1228 | bool isUsableInConstantExpressions(ASTContext &C) const; |
1229 | |
1230 | EvaluatedStmt *ensureEvaluatedStmt() const; |
1231 | |
1232 | /// \brief Attempt to evaluate the value of the initializer attached to this |
1233 | /// declaration, and produce notes explaining why it cannot be evaluated or is |
1234 | /// not a constant expression. Returns a pointer to the value if evaluation |
1235 | /// succeeded, 0 otherwise. |
1236 | APValue *evaluateValue() const; |
1237 | APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1238 | |
1239 | /// \brief Return the already-evaluated value of this variable's |
1240 | /// initializer, or NULL if the value is not yet known. Returns pointer |
1241 | /// to untyped APValue if the value could not be evaluated. |
1242 | APValue *getEvaluatedValue() const; |
1243 | |
1244 | /// \brief Determines whether it is already known whether the |
1245 | /// initializer is an integral constant expression or not. |
1246 | bool isInitKnownICE() const; |
1247 | |
1248 | /// \brief Determines whether the initializer is an integral constant |
1249 | /// expression, or in C++11, whether the initializer is a constant |
1250 | /// expression. |
1251 | /// |
1252 | /// \pre isInitKnownICE() |
1253 | bool isInitICE() const; |
1254 | |
1255 | /// \brief Determine whether the value of the initializer attached to this |
1256 | /// declaration is an integral constant expression. |
1257 | bool checkInitIsICE() const; |
1258 | |
1259 | void setInitStyle(InitializationStyle Style) { |
1260 | VarDeclBits.InitStyle = Style; |
1261 | } |
1262 | |
1263 | /// \brief The style of initialization for this declaration. |
1264 | /// |
1265 | /// C-style initialization is "int x = 1;". Call-style initialization is |
1266 | /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be |
1267 | /// the expression inside the parens or a "ClassType(a,b,c)" class constructor |
1268 | /// expression for class types. List-style initialization is C++11 syntax, |
1269 | /// e.g. "int x{1};". Clients can distinguish between different forms of |
1270 | /// initialization by checking this value. In particular, "int x = {1};" is |
1271 | /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the |
1272 | /// Init expression in all three cases is an InitListExpr. |
1273 | InitializationStyle getInitStyle() const { |
1274 | return static_cast<InitializationStyle>(VarDeclBits.InitStyle); |
1275 | } |
1276 | |
1277 | /// \brief Whether the initializer is a direct-initializer (list or call). |
1278 | bool isDirectInit() const { |
1279 | return getInitStyle() != CInit; |
1280 | } |
1281 | |
1282 | /// \brief If this definition should pretend to be a declaration. |
1283 | bool isThisDeclarationADemotedDefinition() const { |
1284 | return isa<ParmVarDecl>(this) ? false : |
1285 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition; |
1286 | } |
1287 | |
1288 | /// \brief This is a definition which should be demoted to a declaration. |
1289 | /// |
1290 | /// In some cases (mostly module merging) we can end up with two visible |
1291 | /// definitions one of which needs to be demoted to a declaration to keep |
1292 | /// the AST invariants. |
1293 | void demoteThisDefinitionToDeclaration() { |
1294 | assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() && "Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1294, __extension__ __PRETTY_FUNCTION__)); |
1295 | assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1295, __extension__ __PRETTY_FUNCTION__)); |
1296 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1; |
1297 | } |
1298 | |
1299 | /// \brief Determine whether this variable is the exception variable in a |
1300 | /// C++ catch statememt or an Objective-C \@catch statement. |
1301 | bool isExceptionVariable() const { |
1302 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar; |
1303 | } |
1304 | void setExceptionVariable(bool EV) { |
1305 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1305, __extension__ __PRETTY_FUNCTION__)); |
1306 | NonParmVarDeclBits.ExceptionVar = EV; |
1307 | } |
1308 | |
1309 | /// \brief Determine whether this local variable can be used with the named |
1310 | /// return value optimization (NRVO). |
1311 | /// |
1312 | /// The named return value optimization (NRVO) works by marking certain |
1313 | /// non-volatile local variables of class type as NRVO objects. These |
1314 | /// locals can be allocated within the return slot of their containing |
1315 | /// function, in which case there is no need to copy the object to the |
1316 | /// return slot when returning from the function. Within the function body, |
1317 | /// each return that returns the NRVO object will have this variable as its |
1318 | /// NRVO candidate. |
1319 | bool isNRVOVariable() const { |
1320 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable; |
1321 | } |
1322 | void setNRVOVariable(bool NRVO) { |
1323 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1323, __extension__ __PRETTY_FUNCTION__)); |
1324 | NonParmVarDeclBits.NRVOVariable = NRVO; |
1325 | } |
1326 | |
1327 | /// \brief Determine whether this variable is the for-range-declaration in |
1328 | /// a C++0x for-range statement. |
1329 | bool isCXXForRangeDecl() const { |
1330 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl; |
1331 | } |
1332 | void setCXXForRangeDecl(bool FRD) { |
1333 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1333, __extension__ __PRETTY_FUNCTION__)); |
1334 | NonParmVarDeclBits.CXXForRangeDecl = FRD; |
1335 | } |
1336 | |
1337 | /// \brief Determine whether this variable is an ARC pseudo-__strong |
1338 | /// variable. A pseudo-__strong variable has a __strong-qualified |
1339 | /// type but does not actually retain the object written into it. |
1340 | /// Generally such variables are also 'const' for safety. |
1341 | bool isARCPseudoStrong() const { |
1342 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong; |
1343 | } |
1344 | void setARCPseudoStrong(bool ps) { |
1345 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1345, __extension__ __PRETTY_FUNCTION__)); |
1346 | NonParmVarDeclBits.ARCPseudoStrong = ps; |
1347 | } |
1348 | |
1349 | /// Whether this variable is (C++1z) inline. |
1350 | bool isInline() const { |
1351 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline; |
1352 | } |
1353 | bool isInlineSpecified() const { |
1354 | return isa<ParmVarDecl>(this) ? false |
1355 | : NonParmVarDeclBits.IsInlineSpecified; |
1356 | } |
1357 | void setInlineSpecified() { |
1358 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1358, __extension__ __PRETTY_FUNCTION__)); |
1359 | NonParmVarDeclBits.IsInline = true; |
1360 | NonParmVarDeclBits.IsInlineSpecified = true; |
1361 | } |
1362 | void setImplicitlyInline() { |
1363 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1363, __extension__ __PRETTY_FUNCTION__)); |
1364 | NonParmVarDeclBits.IsInline = true; |
1365 | } |
1366 | |
1367 | /// Whether this variable is (C++11) constexpr. |
1368 | bool isConstexpr() const { |
1369 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr; |
1370 | } |
1371 | void setConstexpr(bool IC) { |
1372 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1372, __extension__ __PRETTY_FUNCTION__)); |
1373 | NonParmVarDeclBits.IsConstexpr = IC; |
1374 | } |
1375 | |
1376 | /// Whether this variable is the implicit variable for a lambda init-capture. |
1377 | bool isInitCapture() const { |
1378 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture; |
1379 | } |
1380 | void setInitCapture(bool IC) { |
1381 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1381, __extension__ __PRETTY_FUNCTION__)); |
1382 | NonParmVarDeclBits.IsInitCapture = IC; |
1383 | } |
1384 | |
1385 | /// Whether this local extern variable declaration's previous declaration |
1386 | /// was declared in the same block scope. Only correct in C++. |
1387 | bool isPreviousDeclInSameBlockScope() const { |
1388 | return isa<ParmVarDecl>(this) |
1389 | ? false |
1390 | : NonParmVarDeclBits.PreviousDeclInSameBlockScope; |
1391 | } |
1392 | void setPreviousDeclInSameBlockScope(bool Same) { |
1393 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1393, __extension__ __PRETTY_FUNCTION__)); |
1394 | NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same; |
1395 | } |
1396 | |
1397 | /// \brief Retrieve the variable declaration from which this variable could |
1398 | /// be instantiated, if it is an instantiation (rather than a non-template). |
1399 | VarDecl *getTemplateInstantiationPattern() const; |
1400 | |
1401 | /// \brief If this variable is an instantiated static data member of a |
1402 | /// class template specialization, returns the templated static data member |
1403 | /// from which it was instantiated. |
1404 | VarDecl *getInstantiatedFromStaticDataMember() const; |
1405 | |
1406 | /// \brief If this variable is an instantiation of a variable template or a |
1407 | /// static data member of a class template, determine what kind of |
1408 | /// template specialization or instantiation this is. |
1409 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1410 | |
1411 | /// \brief If this variable is an instantiation of a variable template or a |
1412 | /// static data member of a class template, determine its point of |
1413 | /// instantiation. |
1414 | SourceLocation getPointOfInstantiation() const; |
1415 | |
1416 | /// \brief If this variable is an instantiation of a static data member of a |
1417 | /// class template specialization, retrieves the member specialization |
1418 | /// information. |
1419 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1420 | |
1421 | /// \brief For a static data member that was instantiated from a static |
1422 | /// data member of a class template, set the template specialiation kind. |
1423 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
1424 | SourceLocation PointOfInstantiation = SourceLocation()); |
1425 | |
1426 | /// \brief Specify that this variable is an instantiation of the |
1427 | /// static data member VD. |
1428 | void setInstantiationOfStaticDataMember(VarDecl *VD, |
1429 | TemplateSpecializationKind TSK); |
1430 | |
1431 | /// \brief Retrieves the variable template that is described by this |
1432 | /// variable declaration. |
1433 | /// |
1434 | /// Every variable template is represented as a VarTemplateDecl and a |
1435 | /// VarDecl. The former contains template properties (such as |
1436 | /// the template parameter lists) while the latter contains the |
1437 | /// actual description of the template's |
1438 | /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the |
1439 | /// VarDecl that from a VarTemplateDecl, while |
1440 | /// getDescribedVarTemplate() retrieves the VarTemplateDecl from |
1441 | /// a VarDecl. |
1442 | VarTemplateDecl *getDescribedVarTemplate() const; |
1443 | |
1444 | void setDescribedVarTemplate(VarTemplateDecl *Template); |
1445 | |
1446 | // Implement isa/cast/dyncast/etc. |
1447 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1448 | static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } |
1449 | }; |
1450 | |
1451 | class ImplicitParamDecl : public VarDecl { |
1452 | void anchor() override; |
1453 | |
1454 | public: |
1455 | /// Defines the kind of the implicit parameter: is this an implicit parameter |
1456 | /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured |
1457 | /// context or something else. |
1458 | enum ImplicitParamKind : unsigned { |
1459 | /// Parameter for Objective-C 'self' argument |
1460 | ObjCSelf, |
1461 | |
1462 | /// Parameter for Objective-C '_cmd' argument |
1463 | ObjCCmd, |
1464 | |
1465 | /// Parameter for C++ 'this' argument |
1466 | CXXThis, |
1467 | |
1468 | /// Parameter for C++ virtual table pointers |
1469 | CXXVTT, |
1470 | |
1471 | /// Parameter for captured context |
1472 | CapturedContext, |
1473 | |
1474 | /// Other implicit parameter |
1475 | Other, |
1476 | }; |
1477 | |
1478 | /// Create implicit parameter. |
1479 | static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, |
1480 | SourceLocation IdLoc, IdentifierInfo *Id, |
1481 | QualType T, ImplicitParamKind ParamKind); |
1482 | static ImplicitParamDecl *Create(ASTContext &C, QualType T, |
1483 | ImplicitParamKind ParamKind); |
1484 | |
1485 | static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1486 | |
1487 | ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, |
1488 | IdentifierInfo *Id, QualType Type, |
1489 | ImplicitParamKind ParamKind) |
1490 | : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type, |
1491 | /*TInfo=*/nullptr, SC_None) { |
1492 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1493 | setImplicit(); |
1494 | } |
1495 | |
1496 | ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind) |
1497 | : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(), |
1498 | SourceLocation(), /*Id=*/nullptr, Type, |
1499 | /*TInfo=*/nullptr, SC_None) { |
1500 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1501 | setImplicit(); |
1502 | } |
1503 | |
1504 | /// Returns the implicit parameter kind. |
1505 | ImplicitParamKind getParameterKind() const { |
1506 | return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind); |
1507 | } |
1508 | |
1509 | // Implement isa/cast/dyncast/etc. |
1510 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1511 | static bool classofKind(Kind K) { return K == ImplicitParam; } |
1512 | }; |
1513 | |
1514 | /// Represents a parameter to a function. |
1515 | class ParmVarDecl : public VarDecl { |
1516 | public: |
1517 | enum { MaxFunctionScopeDepth = 255 }; |
1518 | enum { MaxFunctionScopeIndex = 255 }; |
1519 | |
1520 | protected: |
1521 | ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1522 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1523 | TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg) |
1524 | : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) { |
1525 | assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg == false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1525, __extension__ __PRETTY_FUNCTION__)); |
1526 | assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None ) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1526, __extension__ __PRETTY_FUNCTION__)); |
1527 | assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false ) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1527, __extension__ __PRETTY_FUNCTION__)); |
1528 | assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam == false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1528, __extension__ __PRETTY_FUNCTION__)); |
1529 | setDefaultArg(DefArg); |
1530 | } |
1531 | |
1532 | public: |
1533 | static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, |
1534 | SourceLocation StartLoc, |
1535 | SourceLocation IdLoc, IdentifierInfo *Id, |
1536 | QualType T, TypeSourceInfo *TInfo, |
1537 | StorageClass S, Expr *DefArg); |
1538 | |
1539 | static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1540 | |
1541 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1542 | |
1543 | void setObjCMethodScopeInfo(unsigned parameterIndex) { |
1544 | ParmVarDeclBits.IsObjCMethodParam = true; |
1545 | setParameterIndex(parameterIndex); |
1546 | } |
1547 | |
1548 | void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { |
1549 | assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam ) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1549, __extension__ __PRETTY_FUNCTION__)); |
1550 | |
1551 | ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; |
1552 | assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1553, __extension__ __PRETTY_FUNCTION__)) |
1553 | && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1553, __extension__ __PRETTY_FUNCTION__)); |
1554 | |
1555 | setParameterIndex(parameterIndex); |
1556 | } |
1557 | |
1558 | bool isObjCMethodParameter() const { |
1559 | return ParmVarDeclBits.IsObjCMethodParam; |
1560 | } |
1561 | |
1562 | unsigned getFunctionScopeDepth() const { |
1563 | if (ParmVarDeclBits.IsObjCMethodParam) return 0; |
1564 | return ParmVarDeclBits.ScopeDepthOrObjCQuals; |
1565 | } |
1566 | |
1567 | /// Returns the index of this parameter in its prototype or method scope. |
1568 | unsigned getFunctionScopeIndex() const { |
1569 | return getParameterIndex(); |
1570 | } |
1571 | |
1572 | ObjCDeclQualifier getObjCDeclQualifier() const { |
1573 | if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; |
1574 | return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); |
1575 | } |
1576 | void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { |
1577 | assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1577, __extension__ __PRETTY_FUNCTION__)); |
1578 | ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; |
1579 | } |
1580 | |
1581 | /// True if the value passed to this parameter must undergo |
1582 | /// K&R-style default argument promotion: |
1583 | /// |
1584 | /// C99 6.5.2.2. |
1585 | /// If the expression that denotes the called function has a type |
1586 | /// that does not include a prototype, the integer promotions are |
1587 | /// performed on each argument, and arguments that have type float |
1588 | /// are promoted to double. |
1589 | bool isKNRPromoted() const { |
1590 | return ParmVarDeclBits.IsKNRPromoted; |
1591 | } |
1592 | void setKNRPromoted(bool promoted) { |
1593 | ParmVarDeclBits.IsKNRPromoted = promoted; |
1594 | } |
1595 | |
1596 | Expr *getDefaultArg(); |
1597 | const Expr *getDefaultArg() const { |
1598 | return const_cast<ParmVarDecl *>(this)->getDefaultArg(); |
1599 | } |
1600 | |
1601 | void setDefaultArg(Expr *defarg); |
1602 | |
1603 | /// \brief Retrieve the source range that covers the entire default |
1604 | /// argument. |
1605 | SourceRange getDefaultArgRange() const; |
1606 | void setUninstantiatedDefaultArg(Expr *arg); |
1607 | Expr *getUninstantiatedDefaultArg(); |
1608 | const Expr *getUninstantiatedDefaultArg() const { |
1609 | return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg(); |
1610 | } |
1611 | |
1612 | /// Determines whether this parameter has a default argument, |
1613 | /// either parsed or not. |
1614 | bool hasDefaultArg() const; |
1615 | |
1616 | /// Determines whether this parameter has a default argument that has not |
1617 | /// yet been parsed. This will occur during the processing of a C++ class |
1618 | /// whose member functions have default arguments, e.g., |
1619 | /// @code |
1620 | /// class X { |
1621 | /// public: |
1622 | /// void f(int x = 17); // x has an unparsed default argument now |
1623 | /// }; // x has a regular default argument now |
1624 | /// @endcode |
1625 | bool hasUnparsedDefaultArg() const { |
1626 | return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed; |
1627 | } |
1628 | |
1629 | bool hasUninstantiatedDefaultArg() const { |
1630 | return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated; |
1631 | } |
1632 | |
1633 | /// Specify that this parameter has an unparsed default argument. |
1634 | /// The argument will be replaced with a real default argument via |
1635 | /// setDefaultArg when the class definition enclosing the function |
1636 | /// declaration that owns this default argument is completed. |
1637 | void setUnparsedDefaultArg() { |
1638 | ParmVarDeclBits.DefaultArgKind = DAK_Unparsed; |
1639 | } |
1640 | |
1641 | bool hasInheritedDefaultArg() const { |
1642 | return ParmVarDeclBits.HasInheritedDefaultArg; |
1643 | } |
1644 | |
1645 | void setHasInheritedDefaultArg(bool I = true) { |
1646 | ParmVarDeclBits.HasInheritedDefaultArg = I; |
1647 | } |
1648 | |
1649 | QualType getOriginalType() const; |
1650 | |
1651 | /// \brief Determine whether this parameter is actually a function |
1652 | /// parameter pack. |
1653 | bool isParameterPack() const; |
1654 | |
1655 | /// Sets the function declaration that owns this |
1656 | /// ParmVarDecl. Since ParmVarDecls are often created before the |
1657 | /// FunctionDecls that own them, this routine is required to update |
1658 | /// the DeclContext appropriately. |
1659 | void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } |
1660 | |
1661 | // Implement isa/cast/dyncast/etc. |
1662 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1663 | static bool classofKind(Kind K) { return K == ParmVar; } |
1664 | |
1665 | private: |
1666 | enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; |
1667 | |
1668 | void setParameterIndex(unsigned parameterIndex) { |
1669 | if (parameterIndex >= ParameterIndexSentinel) { |
1670 | setParameterIndexLarge(parameterIndex); |
1671 | return; |
1672 | } |
1673 | |
1674 | ParmVarDeclBits.ParameterIndex = parameterIndex; |
1675 | assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 1675, __extension__ __PRETTY_FUNCTION__)); |
1676 | } |
1677 | unsigned getParameterIndex() const { |
1678 | unsigned d = ParmVarDeclBits.ParameterIndex; |
1679 | return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; |
1680 | } |
1681 | |
1682 | void setParameterIndexLarge(unsigned parameterIndex); |
1683 | unsigned getParameterIndexLarge() const; |
1684 | }; |
1685 | |
1686 | /// Represents a function declaration or definition. |
1687 | /// |
1688 | /// Since a given function can be declared several times in a program, |
1689 | /// there may be several FunctionDecls that correspond to that |
1690 | /// function. Only one of those FunctionDecls will be found when |
1691 | /// traversing the list of declarations in the context of the |
1692 | /// FunctionDecl (e.g., the translation unit); this FunctionDecl |
1693 | /// contains all of the information known about the function. Other, |
1694 | /// previous declarations of the function are available via the |
1695 | /// getPreviousDecl() chain. |
1696 | class FunctionDecl : public DeclaratorDecl, public DeclContext, |
1697 | public Redeclarable<FunctionDecl> { |
1698 | public: |
1699 | /// \brief The kind of templated function a FunctionDecl can be. |
1700 | enum TemplatedKind { |
1701 | TK_NonTemplate, |
1702 | TK_FunctionTemplate, |
1703 | TK_MemberSpecialization, |
1704 | TK_FunctionTemplateSpecialization, |
1705 | TK_DependentFunctionTemplateSpecialization |
1706 | }; |
1707 | |
1708 | private: |
1709 | /// A new[]'d array of pointers to VarDecls for the formal |
1710 | /// parameters of this function. This is null if a prototype or if there are |
1711 | /// no formals. |
1712 | ParmVarDecl **ParamInfo = nullptr; |
1713 | |
1714 | LazyDeclStmtPtr Body; |
1715 | |
1716 | // FIXME: This can be packed into the bitfields in DeclContext. |
1717 | // NOTE: VC++ packs bitfields poorly if the types differ. |
1718 | unsigned SClass : 3; |
1719 | unsigned IsInline : 1; |
1720 | unsigned IsInlineSpecified : 1; |
1721 | |
1722 | protected: |
1723 | // This is shared by CXXConstructorDecl, CXXConversionDecl, and |
1724 | // CXXDeductionGuideDecl. |
1725 | unsigned IsExplicitSpecified : 1; |
1726 | |
1727 | private: |
1728 | unsigned IsVirtualAsWritten : 1; |
1729 | unsigned IsPure : 1; |
1730 | unsigned HasInheritedPrototype : 1; |
1731 | unsigned HasWrittenPrototype : 1; |
1732 | unsigned IsDeleted : 1; |
1733 | unsigned IsTrivial : 1; // sunk from CXXMethodDecl |
1734 | |
1735 | /// This flag indicates whether this function is trivial for the purpose of |
1736 | /// calls. This is meaningful only when this function is a copy/move |
1737 | /// constructor or a destructor. |
1738 | unsigned IsTrivialForCall : 1; |
1739 | |
1740 | unsigned IsDefaulted : 1; // sunk from CXXMethoDecl |
1741 | unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl |
1742 | unsigned HasImplicitReturnZero : 1; |
1743 | unsigned IsLateTemplateParsed : 1; |
1744 | unsigned IsConstexpr : 1; |
1745 | unsigned InstantiationIsPending : 1; |
1746 | |
1747 | /// \brief Indicates if the function uses __try. |
1748 | unsigned UsesSEHTry : 1; |
1749 | |
1750 | /// \brief Indicates if the function was a definition but its body was |
1751 | /// skipped. |
1752 | unsigned HasSkippedBody : 1; |
1753 | |
1754 | /// Indicates if the function declaration will have a body, once we're done |
1755 | /// parsing it. |
1756 | unsigned WillHaveBody : 1; |
1757 | |
1758 | /// Indicates that this function is a multiversioned function using attribute |
1759 | /// 'target'. |
1760 | unsigned IsMultiVersion : 1; |
1761 | |
1762 | protected: |
1763 | /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid |
1764 | /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned |
1765 | /// int as opposed to adding a single bit to FunctionDecl. |
1766 | /// Indicates that the Deduction Guide is the implicitly generated 'copy |
1767 | /// deduction candidate' (is used during overload resolution). |
1768 | unsigned IsCopyDeductionCandidate : 1; |
1769 | |
1770 | private: |
1771 | |
1772 | /// Store the ODRHash after first calculation. |
1773 | unsigned HasODRHash : 1; |
1774 | unsigned ODRHash; |
1775 | |
1776 | /// \brief End part of this FunctionDecl's source range. |
1777 | /// |
1778 | /// We could compute the full range in getSourceRange(). However, when we're |
1779 | /// dealing with a function definition deserialized from a PCH/AST file, |
1780 | /// we can only compute the full range once the function body has been |
1781 | /// de-serialized, so it's far better to have the (sometimes-redundant) |
1782 | /// EndRangeLoc. |
1783 | SourceLocation EndRangeLoc; |
1784 | |
1785 | /// \brief The template or declaration that this declaration |
1786 | /// describes or was instantiated from, respectively. |
1787 | /// |
1788 | /// For non-templates, this value will be NULL. For function |
1789 | /// declarations that describe a function template, this will be a |
1790 | /// pointer to a FunctionTemplateDecl. For member functions |
1791 | /// of class template specializations, this will be a MemberSpecializationInfo |
1792 | /// pointer containing information about the specialization. |
1793 | /// For function template specializations, this will be a |
1794 | /// FunctionTemplateSpecializationInfo, which contains information about |
1795 | /// the template being specialized and the template arguments involved in |
1796 | /// that specialization. |
1797 | llvm::PointerUnion4<FunctionTemplateDecl *, |
1798 | MemberSpecializationInfo *, |
1799 | FunctionTemplateSpecializationInfo *, |
1800 | DependentFunctionTemplateSpecializationInfo *> |
1801 | TemplateOrSpecialization; |
1802 | |
1803 | /// Provides source/type location info for the declaration name embedded in |
1804 | /// the DeclaratorDecl base class. |
1805 | DeclarationNameLoc DNLoc; |
1806 | |
1807 | /// \brief Specify that this function declaration is actually a function |
1808 | /// template specialization. |
1809 | /// |
1810 | /// \param C the ASTContext. |
1811 | /// |
1812 | /// \param Template the function template that this function template |
1813 | /// specialization specializes. |
1814 | /// |
1815 | /// \param TemplateArgs the template arguments that produced this |
1816 | /// function template specialization from the template. |
1817 | /// |
1818 | /// \param InsertPos If non-NULL, the position in the function template |
1819 | /// specialization set where the function template specialization data will |
1820 | /// be inserted. |
1821 | /// |
1822 | /// \param TSK the kind of template specialization this is. |
1823 | /// |
1824 | /// \param TemplateArgsAsWritten location info of template arguments. |
1825 | /// |
1826 | /// \param PointOfInstantiation point at which the function template |
1827 | /// specialization was first instantiated. |
1828 | void setFunctionTemplateSpecialization(ASTContext &C, |
1829 | FunctionTemplateDecl *Template, |
1830 | const TemplateArgumentList *TemplateArgs, |
1831 | void *InsertPos, |
1832 | TemplateSpecializationKind TSK, |
1833 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
1834 | SourceLocation PointOfInstantiation); |
1835 | |
1836 | /// \brief Specify that this record is an instantiation of the |
1837 | /// member function FD. |
1838 | void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, |
1839 | TemplateSpecializationKind TSK); |
1840 | |
1841 | void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); |
1842 | |
1843 | protected: |
1844 | FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1845 | const DeclarationNameInfo &NameInfo, QualType T, |
1846 | TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified, |
1847 | bool isConstexprSpecified) |
1848 | : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, |
1849 | StartLoc), |
1850 | DeclContext(DK), redeclarable_base(C), SClass(S), |
1851 | IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified), |
1852 | IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false), |
1853 | HasInheritedPrototype(false), HasWrittenPrototype(true), |
1854 | IsDeleted(false), IsTrivial(false), IsTrivialForCall(false), |
1855 | IsDefaulted(false), |
1856 | IsExplicitlyDefaulted(false), HasImplicitReturnZero(false), |
1857 | IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified), |
1858 | InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false), |
1859 | WillHaveBody(false), IsMultiVersion(false), |
1860 | IsCopyDeductionCandidate(false), HasODRHash(false), ODRHash(0), |
1861 | EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {} |
1862 | |
1863 | using redeclarable_base = Redeclarable<FunctionDecl>; |
1864 | |
1865 | FunctionDecl *getNextRedeclarationImpl() override { |
1866 | return getNextRedeclaration(); |
1867 | } |
1868 | |
1869 | FunctionDecl *getPreviousDeclImpl() override { |
1870 | return getPreviousDecl(); |
1871 | } |
1872 | |
1873 | FunctionDecl *getMostRecentDeclImpl() override { |
1874 | return getMostRecentDecl(); |
1875 | } |
1876 | |
1877 | public: |
1878 | friend class ASTDeclReader; |
1879 | friend class ASTDeclWriter; |
1880 | |
1881 | using redecl_range = redeclarable_base::redecl_range; |
1882 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1883 | |
1884 | using redeclarable_base::redecls_begin; |
1885 | using redeclarable_base::redecls_end; |
1886 | using redeclarable_base::redecls; |
1887 | using redeclarable_base::getPreviousDecl; |
1888 | using redeclarable_base::getMostRecentDecl; |
1889 | using redeclarable_base::isFirstDecl; |
1890 | |
1891 | static FunctionDecl *Create(ASTContext &C, DeclContext *DC, |
1892 | SourceLocation StartLoc, SourceLocation NLoc, |
1893 | DeclarationName N, QualType T, |
1894 | TypeSourceInfo *TInfo, |
1895 | StorageClass SC, |
1896 | bool isInlineSpecified = false, |
1897 | bool hasWrittenPrototype = true, |
1898 | bool isConstexprSpecified = false) { |
1899 | DeclarationNameInfo NameInfo(N, NLoc); |
1900 | return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, |
1901 | SC, |
1902 | isInlineSpecified, hasWrittenPrototype, |
1903 | isConstexprSpecified); |
1904 | } |
1905 | |
1906 | static FunctionDecl *Create(ASTContext &C, DeclContext *DC, |
1907 | SourceLocation StartLoc, |
1908 | const DeclarationNameInfo &NameInfo, |
1909 | QualType T, TypeSourceInfo *TInfo, |
1910 | StorageClass SC, |
1911 | bool isInlineSpecified, |
1912 | bool hasWrittenPrototype, |
1913 | bool isConstexprSpecified = false); |
1914 | |
1915 | static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1916 | |
1917 | DeclarationNameInfo getNameInfo() const { |
1918 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
1919 | } |
1920 | |
1921 | void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, |
1922 | bool Qualified) const override; |
1923 | |
1924 | void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } |
1925 | |
1926 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1927 | |
1928 | /// \brief Returns true if the function has a body (definition). The |
1929 | /// function body might be in any of the (re-)declarations of this |
1930 | /// function. The variant that accepts a FunctionDecl pointer will |
1931 | /// set that function declaration to the actual declaration |
1932 | /// containing the body (if there is one). |
1933 | bool hasBody(const FunctionDecl *&Definition) const; |
1934 | |
1935 | bool hasBody() const override { |
1936 | const FunctionDecl* Definition; |
1937 | return hasBody(Definition); |
1938 | } |
1939 | |
1940 | /// Returns whether the function has a trivial body that does not require any |
1941 | /// specific codegen. |
1942 | bool hasTrivialBody() const; |
1943 | |
1944 | /// Returns true if the function is defined at all, including a deleted |
1945 | /// definition. Except for the behavior when the function is deleted, behaves |
1946 | /// like hasBody. |
1947 | bool isDefined(const FunctionDecl *&Definition) const; |
1948 | |
1949 | virtual bool isDefined() const { |
1950 | const FunctionDecl* Definition; |
1951 | return isDefined(Definition); |
1952 | } |
1953 | |
1954 | /// \brief Get the definition for this declaration. |
1955 | FunctionDecl *getDefinition() { |
1956 | const FunctionDecl *Definition; |
1957 | if (isDefined(Definition)) |
1958 | return const_cast<FunctionDecl *>(Definition); |
1959 | return nullptr; |
1960 | } |
1961 | const FunctionDecl *getDefinition() const { |
1962 | return const_cast<FunctionDecl *>(this)->getDefinition(); |
1963 | } |
1964 | |
1965 | /// Retrieve the body (definition) of the function. The function body might be |
1966 | /// in any of the (re-)declarations of this function. The variant that accepts |
1967 | /// a FunctionDecl pointer will set that function declaration to the actual |
1968 | /// declaration containing the body (if there is one). |
1969 | /// NOTE: For checking if there is a body, use hasBody() instead, to avoid |
1970 | /// unnecessary AST de-serialization of the body. |
1971 | Stmt *getBody(const FunctionDecl *&Definition) const; |
1972 | |
1973 | Stmt *getBody() const override { |
1974 | const FunctionDecl* Definition; |
1975 | return getBody(Definition); |
1976 | } |
1977 | |
1978 | /// Returns whether this specific declaration of the function is also a |
1979 | /// definition that does not contain uninstantiated body. |
1980 | /// |
1981 | /// This does not determine whether the function has been defined (e.g., in a |
1982 | /// previous definition); for that information, use isDefined. |
1983 | bool isThisDeclarationADefinition() const { |
1984 | return IsDeleted || IsDefaulted || Body || HasSkippedBody || |
1985 | IsLateTemplateParsed || WillHaveBody || hasDefiningAttr(); |
1986 | } |
1987 | |
1988 | /// Returns whether this specific declaration of the function has a body - |
1989 | /// that is, if it is a non-deleted definition. |
1990 | bool doesThisDeclarationHaveABody() const { |
1991 | return Body || IsLateTemplateParsed; |
1992 | } |
1993 | |
1994 | void setBody(Stmt *B); |
1995 | void setLazyBody(uint64_t Offset) { Body = Offset; } |
1996 | |
1997 | /// Whether this function is variadic. |
1998 | bool isVariadic() const; |
1999 | |
2000 | /// Whether this function is marked as virtual explicitly. |
2001 | bool isVirtualAsWritten() const { return IsVirtualAsWritten; } |
2002 | void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; } |
2003 | |
2004 | /// Whether this virtual function is pure, i.e. makes the containing class |
2005 | /// abstract. |
2006 | bool isPure() const { return IsPure; } |
2007 | void setPure(bool P = true); |
2008 | |
2009 | /// Whether this templated function will be late parsed. |
2010 | bool isLateTemplateParsed() const { return IsLateTemplateParsed; } |
2011 | void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; } |
2012 | |
2013 | /// Whether this function is "trivial" in some specialized C++ senses. |
2014 | /// Can only be true for default constructors, copy constructors, |
2015 | /// copy assignment operators, and destructors. Not meaningful until |
2016 | /// the class has been fully built by Sema. |
2017 | bool isTrivial() const { return IsTrivial; } |
2018 | void setTrivial(bool IT) { IsTrivial = IT; } |
2019 | |
2020 | bool isTrivialForCall() const { return IsTrivialForCall; } |
2021 | void setTrivialForCall(bool IT) { IsTrivialForCall = IT; } |
2022 | |
2023 | /// Whether this function is defaulted per C++0x. Only valid for |
2024 | /// special member functions. |
2025 | bool isDefaulted() const { return IsDefaulted; } |
2026 | void setDefaulted(bool D = true) { IsDefaulted = D; } |
2027 | |
2028 | /// Whether this function is explicitly defaulted per C++0x. Only valid |
2029 | /// for special member functions. |
2030 | bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; } |
2031 | void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; } |
2032 | |
2033 | /// Whether falling off this function implicitly returns null/zero. |
2034 | /// If a more specific implicit return value is required, front-ends |
2035 | /// should synthesize the appropriate return statements. |
2036 | bool hasImplicitReturnZero() const { return HasImplicitReturnZero; } |
2037 | void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; } |
2038 | |
2039 | /// \brief Whether this function has a prototype, either because one |
2040 | /// was explicitly written or because it was "inherited" by merging |
2041 | /// a declaration without a prototype with a declaration that has a |
2042 | /// prototype. |
2043 | bool hasPrototype() const { |
2044 | return HasWrittenPrototype || HasInheritedPrototype; |
2045 | } |
2046 | |
2047 | bool hasWrittenPrototype() const { return HasWrittenPrototype; } |
2048 | |
2049 | /// \brief Whether this function inherited its prototype from a |
2050 | /// previous declaration. |
2051 | bool hasInheritedPrototype() const { return HasInheritedPrototype; } |
2052 | void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; } |
2053 | |
2054 | /// Whether this is a (C++11) constexpr function or constexpr constructor. |
2055 | bool isConstexpr() const { return IsConstexpr; } |
2056 | void setConstexpr(bool IC) { IsConstexpr = IC; } |
2057 | |
2058 | /// \brief Whether the instantiation of this function is pending. |
2059 | /// This bit is set when the decision to instantiate this function is made |
2060 | /// and unset if and when the function body is created. That leaves out |
2061 | /// cases where instantiation did not happen because the template definition |
2062 | /// was not seen in this TU. This bit remains set in those cases, under the |
2063 | /// assumption that the instantiation will happen in some other TU. |
2064 | bool instantiationIsPending() const { return InstantiationIsPending; } |
2065 | void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; } |
2066 | |
2067 | /// \brief Indicates the function uses __try. |
2068 | bool usesSEHTry() const { return UsesSEHTry; } |
2069 | void setUsesSEHTry(bool UST) { UsesSEHTry = UST; } |
2070 | |
2071 | /// \brief Whether this function has been deleted. |
2072 | /// |
2073 | /// A function that is "deleted" (via the C++0x "= delete" syntax) |
2074 | /// acts like a normal function, except that it cannot actually be |
2075 | /// called or have its address taken. Deleted functions are |
2076 | /// typically used in C++ overload resolution to attract arguments |
2077 | /// whose type or lvalue/rvalue-ness would permit the use of a |
2078 | /// different overload that would behave incorrectly. For example, |
2079 | /// one might use deleted functions to ban implicit conversion from |
2080 | /// a floating-point number to an Integer type: |
2081 | /// |
2082 | /// @code |
2083 | /// struct Integer { |
2084 | /// Integer(long); // construct from a long |
2085 | /// Integer(double) = delete; // no construction from float or double |
2086 | /// Integer(long double) = delete; // no construction from long double |
2087 | /// }; |
2088 | /// @endcode |
2089 | // If a function is deleted, its first declaration must be. |
2090 | bool isDeleted() const { return getCanonicalDecl()->IsDeleted; } |
2091 | bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; } |
2092 | void setDeletedAsWritten(bool D = true) { IsDeleted = D; } |
2093 | |
2094 | /// \brief Determines whether this function is "main", which is the |
2095 | /// entry point into an executable program. |
2096 | bool isMain() const; |
2097 | |
2098 | /// \brief Determines whether this function is a MSVCRT user defined entry |
2099 | /// point. |
2100 | bool isMSVCRTEntryPoint() const; |
2101 | |
2102 | /// \brief Determines whether this operator new or delete is one |
2103 | /// of the reserved global placement operators: |
2104 | /// void *operator new(size_t, void *); |
2105 | /// void *operator new[](size_t, void *); |
2106 | /// void operator delete(void *, void *); |
2107 | /// void operator delete[](void *, void *); |
2108 | /// These functions have special behavior under [new.delete.placement]: |
2109 | /// These functions are reserved, a C++ program may not define |
2110 | /// functions that displace the versions in the Standard C++ library. |
2111 | /// The provisions of [basic.stc.dynamic] do not apply to these |
2112 | /// reserved placement forms of operator new and operator delete. |
2113 | /// |
2114 | /// This function must be an allocation or deallocation function. |
2115 | bool isReservedGlobalPlacementOperator() const; |
2116 | |
2117 | /// \brief Determines whether this function is one of the replaceable |
2118 | /// global allocation functions: |
2119 | /// void *operator new(size_t); |
2120 | /// void *operator new(size_t, const std::nothrow_t &) noexcept; |
2121 | /// void *operator new[](size_t); |
2122 | /// void *operator new[](size_t, const std::nothrow_t &) noexcept; |
2123 | /// void operator delete(void *) noexcept; |
2124 | /// void operator delete(void *, std::size_t) noexcept; [C++1y] |
2125 | /// void operator delete(void *, const std::nothrow_t &) noexcept; |
2126 | /// void operator delete[](void *) noexcept; |
2127 | /// void operator delete[](void *, std::size_t) noexcept; [C++1y] |
2128 | /// void operator delete[](void *, const std::nothrow_t &) noexcept; |
2129 | /// These functions have special behavior under C++1y [expr.new]: |
2130 | /// An implementation is allowed to omit a call to a replaceable global |
2131 | /// allocation function. [...] |
2132 | /// |
2133 | /// If this function is an aligned allocation/deallocation function, return |
2134 | /// true through IsAligned. |
2135 | bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const; |
2136 | |
2137 | /// \brief Determine whether this is a destroying operator delete. |
2138 | bool isDestroyingOperatorDelete() const; |
2139 | |
2140 | /// Compute the language linkage. |
2141 | LanguageLinkage getLanguageLinkage() const; |
2142 | |
2143 | /// \brief Determines whether this function is a function with |
2144 | /// external, C linkage. |
2145 | bool isExternC() const; |
2146 | |
2147 | /// \brief Determines whether this function's context is, or is nested within, |
2148 | /// a C++ extern "C" linkage spec. |
2149 | bool isInExternCContext() const; |
2150 | |
2151 | /// \brief Determines whether this function's context is, or is nested within, |
2152 | /// a C++ extern "C++" linkage spec. |
2153 | bool isInExternCXXContext() const; |
2154 | |
2155 | /// \brief Determines whether this is a global function. |
2156 | bool isGlobal() const; |
2157 | |
2158 | /// \brief Determines whether this function is known to be 'noreturn', through |
2159 | /// an attribute on its declaration or its type. |
2160 | bool isNoReturn() const; |
2161 | |
2162 | /// \brief True if the function was a definition but its body was skipped. |
2163 | bool hasSkippedBody() const { return HasSkippedBody; } |
2164 | void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; } |
2165 | |
2166 | /// True if this function will eventually have a body, once it's fully parsed. |
2167 | bool willHaveBody() const { return WillHaveBody; } |
2168 | void setWillHaveBody(bool V = true) { WillHaveBody = V; } |
2169 | |
2170 | /// True if this function is considered a multiversioned function. |
2171 | bool isMultiVersion() const { return getCanonicalDecl()->IsMultiVersion; } |
2172 | |
2173 | /// Sets the multiversion state for this declaration and all of its |
2174 | /// redeclarations. |
2175 | void setIsMultiVersion(bool V = true) { |
2176 | getCanonicalDecl()->IsMultiVersion = V; |
2177 | } |
2178 | |
2179 | void setPreviousDeclaration(FunctionDecl * PrevDecl); |
2180 | |
2181 | FunctionDecl *getCanonicalDecl() override; |
2182 | const FunctionDecl *getCanonicalDecl() const { |
2183 | return const_cast<FunctionDecl*>(this)->getCanonicalDecl(); |
2184 | } |
2185 | |
2186 | unsigned getBuiltinID() const; |
2187 | |
2188 | // ArrayRef interface to parameters. |
2189 | ArrayRef<ParmVarDecl *> parameters() const { |
2190 | return {ParamInfo, getNumParams()}; |
2191 | } |
2192 | MutableArrayRef<ParmVarDecl *> parameters() { |
2193 | return {ParamInfo, getNumParams()}; |
2194 | } |
2195 | |
2196 | // Iterator access to formal parameters. |
2197 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
2198 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
2199 | |
2200 | bool param_empty() const { return parameters().empty(); } |
2201 | param_iterator param_begin() { return parameters().begin(); } |
2202 | param_iterator param_end() { return parameters().end(); } |
2203 | param_const_iterator param_begin() const { return parameters().begin(); } |
2204 | param_const_iterator param_end() const { return parameters().end(); } |
2205 | size_t param_size() const { return parameters().size(); } |
2206 | |
2207 | /// Return the number of parameters this function must have based on its |
2208 | /// FunctionType. This is the length of the ParamInfo array after it has been |
2209 | /// created. |
2210 | unsigned getNumParams() const; |
2211 | |
2212 | const ParmVarDecl *getParamDecl(unsigned i) const { |
2213 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2213, __extension__ __PRETTY_FUNCTION__)); |
2214 | return ParamInfo[i]; |
2215 | } |
2216 | ParmVarDecl *getParamDecl(unsigned i) { |
2217 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2217, __extension__ __PRETTY_FUNCTION__)); |
2218 | return ParamInfo[i]; |
2219 | } |
2220 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
2221 | setParams(getASTContext(), NewParamInfo); |
2222 | } |
2223 | |
2224 | /// Returns the minimum number of arguments needed to call this function. This |
2225 | /// may be fewer than the number of function parameters, if some of the |
2226 | /// parameters have default arguments (in C++). |
2227 | unsigned getMinRequiredArguments() const; |
2228 | |
2229 | QualType getReturnType() const { |
2230 | assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType >() && "Expected a FunctionType!") ? void (0) : __assert_fail ("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2230, __extension__ __PRETTY_FUNCTION__)); |
2231 | return getType()->getAs<FunctionType>()->getReturnType(); |
2232 | } |
2233 | |
2234 | /// \brief Attempt to compute an informative source range covering the |
2235 | /// function return type. This may omit qualifiers and other information with |
2236 | /// limited representation in the AST. |
2237 | SourceRange getReturnTypeSourceRange() const; |
2238 | |
2239 | /// \brief Attempt to compute an informative source range covering the |
2240 | /// function exception specification, if any. |
2241 | SourceRange getExceptionSpecSourceRange() const; |
2242 | |
2243 | /// \brief Determine the type of an expression that calls this function. |
2244 | QualType getCallResultType() const { |
2245 | assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType >() && "Expected a FunctionType!") ? void (0) : __assert_fail ("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2245, __extension__ __PRETTY_FUNCTION__)); |
2246 | return getType()->getAs<FunctionType>()->getCallResultType(getASTContext()); |
2247 | } |
2248 | |
2249 | /// \brief Returns the WarnUnusedResultAttr that is either declared on this |
2250 | /// function, or its return type declaration. |
2251 | const Attr *getUnusedResultAttr() const; |
2252 | |
2253 | /// \brief Returns true if this function or its return type has the |
2254 | /// warn_unused_result attribute. |
2255 | bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; } |
2256 | |
2257 | /// \brief Returns the storage class as written in the source. For the |
2258 | /// computed linkage of symbol, see getLinkage. |
2259 | StorageClass getStorageClass() const { return StorageClass(SClass); } |
2260 | |
2261 | /// \brief Determine whether the "inline" keyword was specified for this |
2262 | /// function. |
2263 | bool isInlineSpecified() const { return IsInlineSpecified; } |
2264 | |
2265 | /// Set whether the "inline" keyword was specified for this function. |
2266 | void setInlineSpecified(bool I) { |
2267 | IsInlineSpecified = I; |
2268 | IsInline = I; |
2269 | } |
2270 | |
2271 | /// Flag that this function is implicitly inline. |
2272 | void setImplicitlyInline() { |
2273 | IsInline = true; |
2274 | } |
2275 | |
2276 | /// \brief Determine whether this function should be inlined, because it is |
2277 | /// either marked "inline" or "constexpr" or is a member function of a class |
2278 | /// that was defined in the class body. |
2279 | bool isInlined() const { return IsInline; } |
2280 | |
2281 | bool isInlineDefinitionExternallyVisible() const; |
2282 | |
2283 | bool isMSExternInline() const; |
2284 | |
2285 | bool doesDeclarationForceExternallyVisibleDefinition() const; |
2286 | |
2287 | /// Whether this function declaration represents an C++ overloaded |
2288 | /// operator, e.g., "operator+". |
2289 | bool isOverloadedOperator() const { |
2290 | return getOverloadedOperator() != OO_None; |
2291 | } |
2292 | |
2293 | OverloadedOperatorKind getOverloadedOperator() const; |
2294 | |
2295 | const IdentifierInfo *getLiteralIdentifier() const; |
2296 | |
2297 | /// \brief If this function is an instantiation of a member function |
2298 | /// of a class template specialization, retrieves the function from |
2299 | /// which it was instantiated. |
2300 | /// |
2301 | /// This routine will return non-NULL for (non-templated) member |
2302 | /// functions of class templates and for instantiations of function |
2303 | /// templates. For example, given: |
2304 | /// |
2305 | /// \code |
2306 | /// template<typename T> |
2307 | /// struct X { |
2308 | /// void f(T); |
2309 | /// }; |
2310 | /// \endcode |
2311 | /// |
2312 | /// The declaration for X<int>::f is a (non-templated) FunctionDecl |
2313 | /// whose parent is the class template specialization X<int>. For |
2314 | /// this declaration, getInstantiatedFromFunction() will return |
2315 | /// the FunctionDecl X<T>::A. When a complete definition of |
2316 | /// X<int>::A is required, it will be instantiated from the |
2317 | /// declaration returned by getInstantiatedFromMemberFunction(). |
2318 | FunctionDecl *getInstantiatedFromMemberFunction() const; |
2319 | |
2320 | /// \brief What kind of templated function this is. |
2321 | TemplatedKind getTemplatedKind() const; |
2322 | |
2323 | /// \brief If this function is an instantiation of a member function of a |
2324 | /// class template specialization, retrieves the member specialization |
2325 | /// information. |
2326 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
2327 | |
2328 | /// \brief Specify that this record is an instantiation of the |
2329 | /// member function FD. |
2330 | void setInstantiationOfMemberFunction(FunctionDecl *FD, |
2331 | TemplateSpecializationKind TSK) { |
2332 | setInstantiationOfMemberFunction(getASTContext(), FD, TSK); |
2333 | } |
2334 | |
2335 | /// \brief Retrieves the function template that is described by this |
2336 | /// function declaration. |
2337 | /// |
2338 | /// Every function template is represented as a FunctionTemplateDecl |
2339 | /// and a FunctionDecl (or something derived from FunctionDecl). The |
2340 | /// former contains template properties (such as the template |
2341 | /// parameter lists) while the latter contains the actual |
2342 | /// description of the template's |
2343 | /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the |
2344 | /// FunctionDecl that describes the function template, |
2345 | /// getDescribedFunctionTemplate() retrieves the |
2346 | /// FunctionTemplateDecl from a FunctionDecl. |
2347 | FunctionTemplateDecl *getDescribedFunctionTemplate() const; |
2348 | |
2349 | void setDescribedFunctionTemplate(FunctionTemplateDecl *Template); |
2350 | |
2351 | /// \brief Determine whether this function is a function template |
2352 | /// specialization. |
2353 | bool isFunctionTemplateSpecialization() const { |
2354 | return getPrimaryTemplate() != nullptr; |
2355 | } |
2356 | |
2357 | /// \brief Retrieve the class scope template pattern that this function |
2358 | /// template specialization is instantiated from. |
2359 | FunctionDecl *getClassScopeSpecializationPattern() const; |
2360 | |
2361 | /// \brief If this function is actually a function template specialization, |
2362 | /// retrieve information about this function template specialization. |
2363 | /// Otherwise, returns NULL. |
2364 | FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const; |
2365 | |
2366 | /// \brief Determines whether this function is a function template |
2367 | /// specialization or a member of a class template specialization that can |
2368 | /// be implicitly instantiated. |
2369 | bool isImplicitlyInstantiable() const; |
2370 | |
2371 | /// \brief Determines if the given function was instantiated from a |
2372 | /// function template. |
2373 | bool isTemplateInstantiation() const; |
2374 | |
2375 | /// \brief Retrieve the function declaration from which this function could |
2376 | /// be instantiated, if it is an instantiation (rather than a non-template |
2377 | /// or a specialization, for example). |
2378 | FunctionDecl *getTemplateInstantiationPattern() const; |
2379 | |
2380 | /// \brief Retrieve the primary template that this function template |
2381 | /// specialization either specializes or was instantiated from. |
2382 | /// |
2383 | /// If this function declaration is not a function template specialization, |
2384 | /// returns NULL. |
2385 | FunctionTemplateDecl *getPrimaryTemplate() const; |
2386 | |
2387 | /// \brief Retrieve the template arguments used to produce this function |
2388 | /// template specialization from the primary template. |
2389 | /// |
2390 | /// If this function declaration is not a function template specialization, |
2391 | /// returns NULL. |
2392 | const TemplateArgumentList *getTemplateSpecializationArgs() const; |
2393 | |
2394 | /// \brief Retrieve the template argument list as written in the sources, |
2395 | /// if any. |
2396 | /// |
2397 | /// If this function declaration is not a function template specialization |
2398 | /// or if it had no explicit template argument list, returns NULL. |
2399 | /// Note that it an explicit template argument list may be written empty, |
2400 | /// e.g., template<> void foo<>(char* s); |
2401 | const ASTTemplateArgumentListInfo* |
2402 | getTemplateSpecializationArgsAsWritten() const; |
2403 | |
2404 | /// \brief Specify that this function declaration is actually a function |
2405 | /// template specialization. |
2406 | /// |
2407 | /// \param Template the function template that this function template |
2408 | /// specialization specializes. |
2409 | /// |
2410 | /// \param TemplateArgs the template arguments that produced this |
2411 | /// function template specialization from the template. |
2412 | /// |
2413 | /// \param InsertPos If non-NULL, the position in the function template |
2414 | /// specialization set where the function template specialization data will |
2415 | /// be inserted. |
2416 | /// |
2417 | /// \param TSK the kind of template specialization this is. |
2418 | /// |
2419 | /// \param TemplateArgsAsWritten location info of template arguments. |
2420 | /// |
2421 | /// \param PointOfInstantiation point at which the function template |
2422 | /// specialization was first instantiated. |
2423 | void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, |
2424 | const TemplateArgumentList *TemplateArgs, |
2425 | void *InsertPos, |
2426 | TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, |
2427 | const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr, |
2428 | SourceLocation PointOfInstantiation = SourceLocation()) { |
2429 | setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, |
2430 | InsertPos, TSK, TemplateArgsAsWritten, |
2431 | PointOfInstantiation); |
2432 | } |
2433 | |
2434 | /// \brief Specifies that this function declaration is actually a |
2435 | /// dependent function template specialization. |
2436 | void setDependentTemplateSpecialization(ASTContext &Context, |
2437 | const UnresolvedSetImpl &Templates, |
2438 | const TemplateArgumentListInfo &TemplateArgs); |
2439 | |
2440 | DependentFunctionTemplateSpecializationInfo * |
2441 | getDependentSpecializationInfo() const; |
2442 | |
2443 | /// \brief Determine what kind of template instantiation this function |
2444 | /// represents. |
2445 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
2446 | |
2447 | /// \brief Determine what kind of template instantiation this function |
2448 | /// represents. |
2449 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
2450 | SourceLocation PointOfInstantiation = SourceLocation()); |
2451 | |
2452 | /// \brief Retrieve the (first) point of instantiation of a function template |
2453 | /// specialization or a member of a class template specialization. |
2454 | /// |
2455 | /// \returns the first point of instantiation, if this function was |
2456 | /// instantiated from a template; otherwise, returns an invalid source |
2457 | /// location. |
2458 | SourceLocation getPointOfInstantiation() const; |
2459 | |
2460 | /// \brief Determine whether this is or was instantiated from an out-of-line |
2461 | /// definition of a member function. |
2462 | bool isOutOfLine() const override; |
2463 | |
2464 | /// \brief Identify a memory copying or setting function. |
2465 | /// If the given function is a memory copy or setting function, returns |
2466 | /// the corresponding Builtin ID. If the function is not a memory function, |
2467 | /// returns 0. |
2468 | unsigned getMemoryFunctionKind() const; |
2469 | |
2470 | /// \brief Returns ODRHash of the function. This value is calculated and |
2471 | /// stored on first call, then the stored value returned on the other calls. |
2472 | unsigned getODRHash(); |
2473 | |
2474 | // Implement isa/cast/dyncast/etc. |
2475 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2476 | static bool classofKind(Kind K) { |
2477 | return K >= firstFunction && K <= lastFunction; |
2478 | } |
2479 | static DeclContext *castToDeclContext(const FunctionDecl *D) { |
2480 | return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); |
2481 | } |
2482 | static FunctionDecl *castFromDeclContext(const DeclContext *DC) { |
2483 | return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); |
2484 | } |
2485 | }; |
2486 | |
2487 | /// Represents a member of a struct/union/class. |
2488 | class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> { |
2489 | unsigned BitField : 1; |
2490 | unsigned Mutable : 1; |
2491 | mutable unsigned CachedFieldIndex : 30; |
2492 | |
2493 | /// The kinds of value we can store in InitializerOrBitWidth. |
2494 | /// |
2495 | /// Note that this is compatible with InClassInitStyle except for |
2496 | /// ISK_CapturedVLAType. |
2497 | enum InitStorageKind { |
2498 | /// If the pointer is null, there's nothing special. Otherwise, |
2499 | /// this is a bitfield and the pointer is the Expr* storing the |
2500 | /// bit-width. |
2501 | ISK_NoInit = (unsigned) ICIS_NoInit, |
2502 | |
2503 | /// The pointer is an (optional due to delayed parsing) Expr* |
2504 | /// holding the copy-initializer. |
2505 | ISK_InClassCopyInit = (unsigned) ICIS_CopyInit, |
2506 | |
2507 | /// The pointer is an (optional due to delayed parsing) Expr* |
2508 | /// holding the list-initializer. |
2509 | ISK_InClassListInit = (unsigned) ICIS_ListInit, |
2510 | |
2511 | /// The pointer is a VariableArrayType* that's been captured; |
2512 | /// the enclosing context is a lambda or captured statement. |
2513 | ISK_CapturedVLAType, |
2514 | }; |
2515 | |
2516 | /// If this is a bitfield with a default member initializer, this |
2517 | /// structure is used to represent the two expressions. |
2518 | struct InitAndBitWidth { |
2519 | Expr *Init; |
2520 | Expr *BitWidth; |
2521 | }; |
2522 | |
2523 | /// \brief Storage for either the bit-width, the in-class initializer, or |
2524 | /// both (via InitAndBitWidth), or the captured variable length array bound. |
2525 | /// |
2526 | /// If the storage kind is ISK_InClassCopyInit or |
2527 | /// ISK_InClassListInit, but the initializer is null, then this |
2528 | /// field has an in-class initializer that has not yet been parsed |
2529 | /// and attached. |
2530 | // FIXME: Tail-allocate this to reduce the size of FieldDecl in the |
2531 | // overwhelmingly common case that we have none of these things. |
2532 | llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage; |
2533 | |
2534 | protected: |
2535 | FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, |
2536 | SourceLocation IdLoc, IdentifierInfo *Id, |
2537 | QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2538 | InClassInitStyle InitStyle) |
2539 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), |
2540 | BitField(false), Mutable(Mutable), CachedFieldIndex(0), |
2541 | InitStorage(nullptr, (InitStorageKind) InitStyle) { |
2542 | if (BW) |
2543 | setBitWidth(BW); |
2544 | } |
2545 | |
2546 | public: |
2547 | friend class ASTDeclReader; |
2548 | friend class ASTDeclWriter; |
2549 | |
2550 | static FieldDecl *Create(const ASTContext &C, DeclContext *DC, |
2551 | SourceLocation StartLoc, SourceLocation IdLoc, |
2552 | IdentifierInfo *Id, QualType T, |
2553 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2554 | InClassInitStyle InitStyle); |
2555 | |
2556 | static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2557 | |
2558 | /// Returns the index of this field within its record, |
2559 | /// as appropriate for passing to ASTRecordLayout::getFieldOffset. |
2560 | unsigned getFieldIndex() const; |
2561 | |
2562 | /// Determines whether this field is mutable (C++ only). |
2563 | bool isMutable() const { return Mutable; } |
2564 | |
2565 | /// Determines whether this field is a bitfield. |
2566 | bool isBitField() const { return BitField; } |
2567 | |
2568 | /// Determines whether this is an unnamed bitfield. |
2569 | bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } |
2570 | |
2571 | /// Determines whether this field is a |
2572 | /// representative for an anonymous struct or union. Such fields are |
2573 | /// unnamed and are implicitly generated by the implementation to |
2574 | /// store the data for the anonymous union or struct. |
2575 | bool isAnonymousStructOrUnion() const; |
2576 | |
2577 | Expr *getBitWidth() const { |
2578 | if (!BitField) |
2579 | return nullptr; |
2580 | void *Ptr = InitStorage.getPointer(); |
2581 | if (getInClassInitStyle()) |
2582 | return static_cast<InitAndBitWidth*>(Ptr)->BitWidth; |
2583 | return static_cast<Expr*>(Ptr); |
2584 | } |
2585 | |
2586 | unsigned getBitWidthValue(const ASTContext &Ctx) const; |
2587 | |
2588 | /// Set the bit-field width for this member. |
2589 | // Note: used by some clients (i.e., do not remove it). |
2590 | void setBitWidth(Expr *Width) { |
2591 | assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2592, __extension__ __PRETTY_FUNCTION__)) |
2592 | "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2592, __extension__ __PRETTY_FUNCTION__)); |
2593 | assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified" ) ? void (0) : __assert_fail ("Width && \"no bit width specified\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2593, __extension__ __PRETTY_FUNCTION__)); |
2594 | InitStorage.setPointer( |
2595 | InitStorage.getInt() |
2596 | ? new (getASTContext()) |
2597 | InitAndBitWidth{getInClassInitializer(), Width} |
2598 | : static_cast<void*>(Width)); |
2599 | BitField = true; |
2600 | } |
2601 | |
2602 | /// Remove the bit-field width from this member. |
2603 | // Note: used by some clients (i.e., do not remove it). |
2604 | void removeBitWidth() { |
2605 | assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove" ) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2605, __extension__ __PRETTY_FUNCTION__)); |
2606 | InitStorage.setPointer(getInClassInitializer()); |
2607 | BitField = false; |
2608 | } |
2609 | |
2610 | /// Get the kind of (C++11) default member initializer that this field has. |
2611 | InClassInitStyle getInClassInitStyle() const { |
2612 | InitStorageKind storageKind = InitStorage.getInt(); |
2613 | return (storageKind == ISK_CapturedVLAType |
2614 | ? ICIS_NoInit : (InClassInitStyle) storageKind); |
2615 | } |
2616 | |
2617 | /// Determine whether this member has a C++11 default member initializer. |
2618 | bool hasInClassInitializer() const { |
2619 | return getInClassInitStyle() != ICIS_NoInit; |
2620 | } |
2621 | |
2622 | /// Get the C++11 default member initializer for this member, or null if one |
2623 | /// has not been set. If a valid declaration has a default member initializer, |
2624 | /// but this returns null, then we have not parsed and attached it yet. |
2625 | Expr *getInClassInitializer() const { |
2626 | if (!hasInClassInitializer()) |
2627 | return nullptr; |
2628 | void *Ptr = InitStorage.getPointer(); |
2629 | if (BitField) |
2630 | return static_cast<InitAndBitWidth*>(Ptr)->Init; |
2631 | return static_cast<Expr*>(Ptr); |
2632 | } |
2633 | |
2634 | /// Set the C++11 in-class initializer for this member. |
2635 | void setInClassInitializer(Expr *Init) { |
2636 | assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() && !getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2636, __extension__ __PRETTY_FUNCTION__)); |
2637 | if (BitField) |
2638 | static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init; |
2639 | else |
2640 | InitStorage.setPointer(Init); |
2641 | } |
2642 | |
2643 | /// Remove the C++11 in-class initializer from this member. |
2644 | void removeInClassInitializer() { |
2645 | assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() && "no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2645, __extension__ __PRETTY_FUNCTION__)); |
2646 | InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit); |
2647 | } |
2648 | |
2649 | /// \brief Determine whether this member captures the variable length array |
2650 | /// type. |
2651 | bool hasCapturedVLAType() const { |
2652 | return InitStorage.getInt() == ISK_CapturedVLAType; |
2653 | } |
2654 | |
2655 | /// \brief Get the captured variable length array type. |
2656 | const VariableArrayType *getCapturedVLAType() const { |
2657 | return hasCapturedVLAType() ? static_cast<const VariableArrayType *>( |
2658 | InitStorage.getPointer()) |
2659 | : nullptr; |
2660 | } |
2661 | |
2662 | /// \brief Set the captured variable length array type for this field. |
2663 | void setCapturedVLAType(const VariableArrayType *VLAType); |
2664 | |
2665 | /// Returns the parent of this field declaration, which |
2666 | /// is the struct in which this field is defined. |
2667 | const RecordDecl *getParent() const { |
2668 | return cast<RecordDecl>(getDeclContext()); |
2669 | } |
2670 | |
2671 | RecordDecl *getParent() { |
2672 | return cast<RecordDecl>(getDeclContext()); |
2673 | } |
2674 | |
2675 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2676 | |
2677 | /// Retrieves the canonical declaration of this field. |
2678 | FieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2679 | const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2680 | |
2681 | // Implement isa/cast/dyncast/etc. |
2682 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2683 | static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } |
2684 | }; |
2685 | |
2686 | /// An instance of this object exists for each enum constant |
2687 | /// that is defined. For example, in "enum X {a,b}", each of a/b are |
2688 | /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a |
2689 | /// TagType for the X EnumDecl. |
2690 | class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> { |
2691 | Stmt *Init; // an integer constant expression |
2692 | llvm::APSInt Val; // The value. |
2693 | |
2694 | protected: |
2695 | EnumConstantDecl(DeclContext *DC, SourceLocation L, |
2696 | IdentifierInfo *Id, QualType T, Expr *E, |
2697 | const llvm::APSInt &V) |
2698 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} |
2699 | |
2700 | public: |
2701 | friend class StmtIteratorBase; |
2702 | |
2703 | static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, |
2704 | SourceLocation L, IdentifierInfo *Id, |
2705 | QualType T, Expr *E, |
2706 | const llvm::APSInt &V); |
2707 | static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2708 | |
2709 | const Expr *getInitExpr() const { return (const Expr*) Init; } |
2710 | Expr *getInitExpr() { return (Expr*) Init; } |
2711 | const llvm::APSInt &getInitVal() const { return Val; } |
2712 | |
2713 | void setInitExpr(Expr *E) { Init = (Stmt*) E; } |
2714 | void setInitVal(const llvm::APSInt &V) { Val = V; } |
2715 | |
2716 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2717 | |
2718 | /// Retrieves the canonical declaration of this enumerator. |
2719 | EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2720 | const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2721 | |
2722 | // Implement isa/cast/dyncast/etc. |
2723 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2724 | static bool classofKind(Kind K) { return K == EnumConstant; } |
2725 | }; |
2726 | |
2727 | /// Represents a field injected from an anonymous union/struct into the parent |
2728 | /// scope. These are always implicit. |
2729 | class IndirectFieldDecl : public ValueDecl, |
2730 | public Mergeable<IndirectFieldDecl> { |
2731 | NamedDecl **Chaining; |
2732 | unsigned ChainingSize; |
2733 | |
2734 | IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L, |
2735 | DeclarationName N, QualType T, |
2736 | MutableArrayRef<NamedDecl *> CH); |
2737 | |
2738 | void anchor() override; |
2739 | |
2740 | public: |
2741 | friend class ASTDeclReader; |
2742 | |
2743 | static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, |
2744 | SourceLocation L, IdentifierInfo *Id, |
2745 | QualType T, llvm::MutableArrayRef<NamedDecl *> CH); |
2746 | |
2747 | static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2748 | |
2749 | using chain_iterator = ArrayRef<NamedDecl *>::const_iterator; |
2750 | |
2751 | ArrayRef<NamedDecl *> chain() const { |
2752 | return llvm::makeArrayRef(Chaining, ChainingSize); |
2753 | } |
2754 | chain_iterator chain_begin() const { return chain().begin(); } |
2755 | chain_iterator chain_end() const { return chain().end(); } |
2756 | |
2757 | unsigned getChainingSize() const { return ChainingSize; } |
2758 | |
2759 | FieldDecl *getAnonField() const { |
2760 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2760, __extension__ __PRETTY_FUNCTION__)); |
2761 | return cast<FieldDecl>(chain().back()); |
2762 | } |
2763 | |
2764 | VarDecl *getVarDecl() const { |
2765 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 2765, __extension__ __PRETTY_FUNCTION__)); |
2766 | return dyn_cast<VarDecl>(chain().front()); |
2767 | } |
2768 | |
2769 | IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2770 | const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2771 | |
2772 | // Implement isa/cast/dyncast/etc. |
2773 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2774 | static bool classofKind(Kind K) { return K == IndirectField; } |
2775 | }; |
2776 | |
2777 | /// Represents a declaration of a type. |
2778 | class TypeDecl : public NamedDecl { |
2779 | friend class ASTContext; |
2780 | |
2781 | /// This indicates the Type object that represents |
2782 | /// this TypeDecl. It is a cache maintained by |
2783 | /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and |
2784 | /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. |
2785 | mutable const Type *TypeForDecl = nullptr; |
2786 | |
2787 | /// The start of the source range for this declaration. |
2788 | SourceLocation LocStart; |
2789 | |
2790 | void anchor() override; |
2791 | |
2792 | protected: |
2793 | TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, |
2794 | SourceLocation StartL = SourceLocation()) |
2795 | : NamedDecl(DK, DC, L, Id), LocStart(StartL) {} |
2796 | |
2797 | public: |
2798 | // Low-level accessor. If you just want the type defined by this node, |
2799 | // check out ASTContext::getTypeDeclType or one of |
2800 | // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you |
2801 | // already know the specific kind of node this is. |
2802 | const Type *getTypeForDecl() const { return TypeForDecl; } |
2803 | void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } |
2804 | |
2805 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
2806 | void setLocStart(SourceLocation L) { LocStart = L; } |
2807 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
2808 | if (LocStart.isValid()) |
2809 | return SourceRange(LocStart, getLocation()); |
2810 | else |
2811 | return SourceRange(getLocation()); |
2812 | } |
2813 | |
2814 | // Implement isa/cast/dyncast/etc. |
2815 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2816 | static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } |
2817 | }; |
2818 | |
2819 | /// Base class for declarations which introduce a typedef-name. |
2820 | class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { |
2821 | struct LLVM_ALIGNAS(8)alignas(8) ModedTInfo { |
2822 | TypeSourceInfo *first; |
2823 | QualType second; |
2824 | }; |
2825 | |
2826 | /// If int part is 0, we have not computed IsTransparentTag. |
2827 | /// Otherwise, IsTransparentTag is (getInt() >> 1). |
2828 | mutable llvm::PointerIntPair< |
2829 | llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2> |
2830 | MaybeModedTInfo; |
2831 | |
2832 | void anchor() override; |
2833 | |
2834 | protected: |
2835 | TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC, |
2836 | SourceLocation StartLoc, SourceLocation IdLoc, |
2837 | IdentifierInfo *Id, TypeSourceInfo *TInfo) |
2838 | : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C), |
2839 | MaybeModedTInfo(TInfo, 0) {} |
2840 | |
2841 | using redeclarable_base = Redeclarable<TypedefNameDecl>; |
2842 | |
2843 | TypedefNameDecl *getNextRedeclarationImpl() override { |
2844 | return getNextRedeclaration(); |
2845 | } |
2846 | |
2847 | TypedefNameDecl *getPreviousDeclImpl() override { |
2848 | return getPreviousDecl(); |
2849 | } |
2850 | |
2851 | TypedefNameDecl *getMostRecentDeclImpl() override { |
2852 | return getMostRecentDecl(); |
2853 | } |
2854 | |
2855 | public: |
2856 | using redecl_range = redeclarable_base::redecl_range; |
2857 | using redecl_iterator = redeclarable_base::redecl_iterator; |
2858 | |
2859 | using redeclarable_base::redecls_begin; |
2860 | using redeclarable_base::redecls_end; |
2861 | using redeclarable_base::redecls; |
2862 | using redeclarable_base::getPreviousDecl; |
2863 | using redeclarable_base::getMostRecentDecl; |
2864 | using redeclarable_base::isFirstDecl; |
2865 | |
2866 | bool isModed() const { |
2867 | return MaybeModedTInfo.getPointer().is<ModedTInfo *>(); |
2868 | } |
2869 | |
2870 | TypeSourceInfo *getTypeSourceInfo() const { |
2871 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first |
2872 | : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>(); |
2873 | } |
2874 | |
2875 | QualType getUnderlyingType() const { |
2876 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second |
2877 | : MaybeModedTInfo.getPointer() |
2878 | .get<TypeSourceInfo *>() |
2879 | ->getType(); |
2880 | } |
2881 | |
2882 | void setTypeSourceInfo(TypeSourceInfo *newType) { |
2883 | MaybeModedTInfo.setPointer(newType); |
2884 | } |
2885 | |
2886 | void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) { |
2887 | MaybeModedTInfo.setPointer(new (getASTContext(), 8) |
2888 | ModedTInfo({unmodedTSI, modedTy})); |
2889 | } |
2890 | |
2891 | /// Retrieves the canonical declaration of this typedef-name. |
2892 | TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2893 | const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2894 | |
2895 | /// Retrieves the tag declaration for which this is the typedef name for |
2896 | /// linkage purposes, if any. |
2897 | /// |
2898 | /// \param AnyRedecl Look for the tag declaration in any redeclaration of |
2899 | /// this typedef declaration. |
2900 | TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const; |
2901 | |
2902 | /// Determines if this typedef shares a name and spelling location with its |
2903 | /// underlying tag type, as is the case with the NS_ENUM macro. |
2904 | bool isTransparentTag() const { |
2905 | if (MaybeModedTInfo.getInt()) |
2906 | return MaybeModedTInfo.getInt() & 0x2; |
2907 | return isTransparentTagSlow(); |
2908 | } |
2909 | |
2910 | // Implement isa/cast/dyncast/etc. |
2911 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2912 | static bool classofKind(Kind K) { |
2913 | return K >= firstTypedefName && K <= lastTypedefName; |
2914 | } |
2915 | |
2916 | private: |
2917 | bool isTransparentTagSlow() const; |
2918 | }; |
2919 | |
2920 | /// Represents the declaration of a typedef-name via the 'typedef' |
2921 | /// type specifier. |
2922 | class TypedefDecl : public TypedefNameDecl { |
2923 | TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
2924 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
2925 | : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {} |
2926 | |
2927 | public: |
2928 | static TypedefDecl *Create(ASTContext &C, DeclContext *DC, |
2929 | SourceLocation StartLoc, SourceLocation IdLoc, |
2930 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
2931 | static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2932 | |
2933 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2934 | |
2935 | // Implement isa/cast/dyncast/etc. |
2936 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2937 | static bool classofKind(Kind K) { return K == Typedef; } |
2938 | }; |
2939 | |
2940 | /// Represents the declaration of a typedef-name via a C++11 |
2941 | /// alias-declaration. |
2942 | class TypeAliasDecl : public TypedefNameDecl { |
2943 | /// The template for which this is the pattern, if any. |
2944 | TypeAliasTemplateDecl *Template; |
2945 | |
2946 | TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
2947 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
2948 | : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo), |
2949 | Template(nullptr) {} |
2950 | |
2951 | public: |
2952 | static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, |
2953 | SourceLocation StartLoc, SourceLocation IdLoc, |
2954 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
2955 | static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2956 | |
2957 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2958 | |
2959 | TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; } |
2960 | void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; } |
2961 | |
2962 | // Implement isa/cast/dyncast/etc. |
2963 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2964 | static bool classofKind(Kind K) { return K == TypeAlias; } |
2965 | }; |
2966 | |
2967 | /// Represents the declaration of a struct/union/class/enum. |
2968 | class TagDecl |
2969 | : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> { |
2970 | public: |
2971 | // This is really ugly. |
2972 | using TagKind = TagTypeKind; |
2973 | |
2974 | private: |
2975 | // FIXME: This can be packed into the bitfields in Decl. |
2976 | /// The TagKind enum. |
2977 | unsigned TagDeclKind : 3; |
2978 | |
2979 | /// True if this is a definition ("struct foo {};"), false if it is a |
2980 | /// declaration ("struct foo;"). It is not considered a definition |
2981 | /// until the definition has been fully processed. |
2982 | unsigned IsCompleteDefinition : 1; |
2983 | |
2984 | protected: |
2985 | /// True if this is currently being defined. |
2986 | unsigned IsBeingDefined : 1; |
2987 | |
2988 | private: |
2989 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
2990 | /// for the very first time) in the syntax of a declarator. |
2991 | unsigned IsEmbeddedInDeclarator : 1; |
2992 | |
2993 | /// True if this tag is free standing, e.g. "struct foo;". |
2994 | unsigned IsFreeStanding : 1; |
2995 | |
2996 | protected: |
2997 | // These are used by (and only defined for) EnumDecl. |
2998 | unsigned NumPositiveBits : 8; |
2999 | unsigned NumNegativeBits : 8; |
3000 | |
3001 | /// True if this tag declaration is a scoped enumeration. Only |
3002 | /// possible in C++11 mode. |
3003 | unsigned IsScoped : 1; |
3004 | |
3005 | /// If this tag declaration is a scoped enum, |
3006 | /// then this is true if the scoped enum was declared using the class |
3007 | /// tag, false if it was declared with the struct tag. No meaning is |
3008 | /// associated if this tag declaration is not a scoped enum. |
3009 | unsigned IsScopedUsingClassTag : 1; |
3010 | |
3011 | /// True if this is an enumeration with fixed underlying type. Only |
3012 | /// possible in C++11, Microsoft extensions, or Objective C mode. |
3013 | unsigned IsFixed : 1; |
3014 | |
3015 | /// Indicates whether it is possible for declarations of this kind |
3016 | /// to have an out-of-date definition. |
3017 | /// |
3018 | /// This option is only enabled when modules are enabled. |
3019 | unsigned MayHaveOutOfDateDef : 1; |
3020 | |
3021 | /// Has the full definition of this type been required by a use somewhere in |
3022 | /// the TU. |
3023 | unsigned IsCompleteDefinitionRequired : 1; |
3024 | |
3025 | private: |
3026 | SourceRange BraceRange; |
3027 | |
3028 | // A struct representing syntactic qualifier info, |
3029 | // to be used for the (uncommon) case of out-of-line declarations. |
3030 | using ExtInfo = QualifierInfo; |
3031 | |
3032 | /// \brief If the (out-of-line) tag declaration name |
3033 | /// is qualified, it points to the qualifier info (nns and range); |
3034 | /// otherwise, if the tag declaration is anonymous and it is part of |
3035 | /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); |
3036 | /// otherwise, if the tag declaration is anonymous and it is used as a |
3037 | /// declaration specifier for variables, it points to the first VarDecl (used |
3038 | /// for mangling); |
3039 | /// otherwise, it is a null (TypedefNameDecl) pointer. |
3040 | llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier; |
3041 | |
3042 | bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); } |
3043 | ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); } |
3044 | const ExtInfo *getExtInfo() const { |
3045 | return TypedefNameDeclOrQualifier.get<ExtInfo *>(); |
3046 | } |
3047 | |
3048 | protected: |
3049 | TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3050 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
3051 | SourceLocation StartL) |
3052 | : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), |
3053 | TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false), |
3054 | IsEmbeddedInDeclarator(false), IsFreeStanding(false), |
3055 | IsCompleteDefinitionRequired(false), |
3056 | TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { |
3057 | assert((DK != Enum || TK == TTK_Enum) &&(static_cast <bool> ((DK != Enum || TK == TTK_Enum) && "EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3058, __extension__ __PRETTY_FUNCTION__)) |
3058 | "EnumDecl not matched with TTK_Enum")(static_cast <bool> ((DK != Enum || TK == TTK_Enum) && "EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3058, __extension__ __PRETTY_FUNCTION__)); |
3059 | setPreviousDecl(PrevDecl); |
3060 | } |
3061 | |
3062 | using redeclarable_base = Redeclarable<TagDecl>; |
3063 | |
3064 | TagDecl *getNextRedeclarationImpl() override { |
3065 | return getNextRedeclaration(); |
3066 | } |
3067 | |
3068 | TagDecl *getPreviousDeclImpl() override { |
3069 | return getPreviousDecl(); |
3070 | } |
3071 | |
3072 | TagDecl *getMostRecentDeclImpl() override { |
3073 | return getMostRecentDecl(); |
3074 | } |
3075 | |
3076 | /// @brief Completes the definition of this tag declaration. |
3077 | /// |
3078 | /// This is a helper function for derived classes. |
3079 | void completeDefinition(); |
3080 | |
3081 | public: |
3082 | friend class ASTDeclReader; |
3083 | friend class ASTDeclWriter; |
3084 | |
3085 | using redecl_range = redeclarable_base::redecl_range; |
3086 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3087 | |
3088 | using redeclarable_base::redecls_begin; |
3089 | using redeclarable_base::redecls_end; |
3090 | using redeclarable_base::redecls; |
3091 | using redeclarable_base::getPreviousDecl; |
3092 | using redeclarable_base::getMostRecentDecl; |
3093 | using redeclarable_base::isFirstDecl; |
3094 | |
3095 | SourceRange getBraceRange() const { return BraceRange; } |
3096 | void setBraceRange(SourceRange R) { BraceRange = R; } |
3097 | |
3098 | /// Return SourceLocation representing start of source |
3099 | /// range ignoring outer template declarations. |
3100 | SourceLocation getInnerLocStart() const { return getLocStart(); } |
3101 | |
3102 | /// Return SourceLocation representing start of source |
3103 | /// range taking into account any outer template declarations. |
3104 | SourceLocation getOuterLocStart() const; |
3105 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3106 | |
3107 | TagDecl *getCanonicalDecl() override; |
3108 | const TagDecl *getCanonicalDecl() const { |
3109 | return const_cast<TagDecl*>(this)->getCanonicalDecl(); |
3110 | } |
3111 | |
3112 | /// Return true if this declaration is a completion definition of the type. |
3113 | /// Provided for consistency. |
3114 | bool isThisDeclarationADefinition() const { |
3115 | return isCompleteDefinition(); |
3116 | } |
3117 | |
3118 | /// Return true if this decl has its body fully specified. |
3119 | bool isCompleteDefinition() const { |
3120 | return IsCompleteDefinition; |
3121 | } |
3122 | |
3123 | /// \brief Return true if this complete decl is |
3124 | /// required to be complete for some existing use. |
3125 | bool isCompleteDefinitionRequired() const { |
3126 | return IsCompleteDefinitionRequired; |
3127 | } |
3128 | |
3129 | /// Return true if this decl is currently being defined. |
3130 | bool isBeingDefined() const { |
3131 | return IsBeingDefined; |
3132 | } |
3133 | |
3134 | bool isEmbeddedInDeclarator() const { |
3135 | return IsEmbeddedInDeclarator; |
3136 | } |
3137 | void setEmbeddedInDeclarator(bool isInDeclarator) { |
3138 | IsEmbeddedInDeclarator = isInDeclarator; |
3139 | } |
3140 | |
3141 | bool isFreeStanding() const { return IsFreeStanding; } |
3142 | void setFreeStanding(bool isFreeStanding = true) { |
3143 | IsFreeStanding = isFreeStanding; |
3144 | } |
3145 | |
3146 | /// \brief Whether this declaration declares a type that is |
3147 | /// dependent, i.e., a type that somehow depends on template |
3148 | /// parameters. |
3149 | bool isDependentType() const { return isDependentContext(); } |
3150 | |
3151 | /// Starts the definition of this tag declaration. |
3152 | /// |
3153 | /// This method should be invoked at the beginning of the definition |
3154 | /// of this tag declaration. It will set the tag type into a state |
3155 | /// where it is in the process of being defined. |
3156 | void startDefinition(); |
3157 | |
3158 | /// Returns the TagDecl that actually defines this |
3159 | /// struct/union/class/enum. When determining whether or not a |
3160 | /// struct/union/class/enum has a definition, one should use this |
3161 | /// method as opposed to 'isDefinition'. 'isDefinition' indicates |
3162 | /// whether or not a specific TagDecl is defining declaration, not |
3163 | /// whether or not the struct/union/class/enum type is defined. |
3164 | /// This method returns NULL if there is no TagDecl that defines |
3165 | /// the struct/union/class/enum. |
3166 | TagDecl *getDefinition() const; |
3167 | |
3168 | void setCompleteDefinition(bool V) { IsCompleteDefinition = V; } |
3169 | |
3170 | void setCompleteDefinitionRequired(bool V = true) { |
3171 | IsCompleteDefinitionRequired = V; |
3172 | } |
3173 | |
3174 | StringRef getKindName() const { |
3175 | return TypeWithKeyword::getTagTypeKindName(getTagKind()); |
3176 | } |
3177 | |
3178 | TagKind getTagKind() const { |
3179 | return TagKind(TagDeclKind); |
3180 | } |
3181 | |
3182 | void setTagKind(TagKind TK) { TagDeclKind = TK; } |
3183 | |
3184 | bool isStruct() const { return getTagKind() == TTK_Struct; } |
3185 | bool isInterface() const { return getTagKind() == TTK_Interface; } |
3186 | bool isClass() const { return getTagKind() == TTK_Class; } |
3187 | bool isUnion() const { return getTagKind() == TTK_Union; } |
3188 | bool isEnum() const { return getTagKind() == TTK_Enum; } |
3189 | |
3190 | /// Is this tag type named, either directly or via being defined in |
3191 | /// a typedef of this type? |
3192 | /// |
3193 | /// C++11 [basic.link]p8: |
3194 | /// A type is said to have linkage if and only if: |
3195 | /// - it is a class or enumeration type that is named (or has a |
3196 | /// name for linkage purposes) and the name has linkage; ... |
3197 | /// C++11 [dcl.typedef]p9: |
3198 | /// If the typedef declaration defines an unnamed class (or enum), |
3199 | /// the first typedef-name declared by the declaration to be that |
3200 | /// class type (or enum type) is used to denote the class type (or |
3201 | /// enum type) for linkage purposes only. |
3202 | /// |
3203 | /// C does not have an analogous rule, but the same concept is |
3204 | /// nonetheless useful in some places. |
3205 | bool hasNameForLinkage() const { |
3206 | return (getDeclName() || getTypedefNameForAnonDecl()); |
3207 | } |
3208 | |
3209 | TypedefNameDecl *getTypedefNameForAnonDecl() const { |
3210 | return hasExtInfo() ? nullptr |
3211 | : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>(); |
3212 | } |
3213 | |
3214 | void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); |
3215 | |
3216 | /// \brief Retrieve the nested-name-specifier that qualifies the name of this |
3217 | /// declaration, if it was present in the source. |
3218 | NestedNameSpecifier *getQualifier() const { |
3219 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
3220 | : nullptr; |
3221 | } |
3222 | |
3223 | /// \brief Retrieve the nested-name-specifier (with source-location |
3224 | /// information) that qualifies the name of this declaration, if it was |
3225 | /// present in the source. |
3226 | NestedNameSpecifierLoc getQualifierLoc() const { |
3227 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
3228 | : NestedNameSpecifierLoc(); |
3229 | } |
3230 | |
3231 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
3232 | |
3233 | unsigned getNumTemplateParameterLists() const { |
3234 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
3235 | } |
3236 | |
3237 | TemplateParameterList *getTemplateParameterList(unsigned i) const { |
3238 | assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3238, __extension__ __PRETTY_FUNCTION__)); |
3239 | return getExtInfo()->TemplParamLists[i]; |
3240 | } |
3241 | |
3242 | void setTemplateParameterListsInfo(ASTContext &Context, |
3243 | ArrayRef<TemplateParameterList *> TPLists); |
3244 | |
3245 | // Implement isa/cast/dyncast/etc. |
3246 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3247 | static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } |
3248 | |
3249 | static DeclContext *castToDeclContext(const TagDecl *D) { |
3250 | return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); |
3251 | } |
3252 | |
3253 | static TagDecl *castFromDeclContext(const DeclContext *DC) { |
3254 | return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); |
3255 | } |
3256 | }; |
3257 | |
3258 | /// Represents an enum. In C++11, enums can be forward-declared |
3259 | /// with a fixed underlying type, and in C we allow them to be forward-declared |
3260 | /// with no underlying type as an extension. |
3261 | class EnumDecl : public TagDecl { |
3262 | /// This represent the integer type that the enum corresponds |
3263 | /// to for code generation purposes. Note that the enumerator constants may |
3264 | /// have a different type than this does. |
3265 | /// |
3266 | /// If the underlying integer type was explicitly stated in the source |
3267 | /// code, this is a TypeSourceInfo* for that type. Otherwise this type |
3268 | /// was automatically deduced somehow, and this is a Type*. |
3269 | /// |
3270 | /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in |
3271 | /// some cases it won't. |
3272 | /// |
3273 | /// The underlying type of an enumeration never has any qualifiers, so |
3274 | /// we can get away with just storing a raw Type*, and thus save an |
3275 | /// extra pointer when TypeSourceInfo is needed. |
3276 | llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType; |
3277 | |
3278 | /// The integer type that values of this type should |
3279 | /// promote to. In C, enumerators are generally of an integer type |
3280 | /// directly, but gcc-style large enumerators (and all enumerators |
3281 | /// in C++) are of the enum type instead. |
3282 | QualType PromotionType; |
3283 | |
3284 | /// \brief If this enumeration is an instantiation of a member enumeration |
3285 | /// of a class template specialization, this is the member specialization |
3286 | /// information. |
3287 | MemberSpecializationInfo *SpecializationInfo = nullptr; |
3288 | |
3289 | EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3290 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
3291 | bool Scoped, bool ScopedUsingClassTag, bool Fixed) |
3292 | : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { |
3293 | assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void (0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3293, __extension__ __PRETTY_FUNCTION__)); |
3294 | IntegerType = (const Type *)nullptr; |
3295 | NumNegativeBits = 0; |
3296 | NumPositiveBits = 0; |
3297 | IsScoped = Scoped; |
3298 | IsScopedUsingClassTag = ScopedUsingClassTag; |
3299 | IsFixed = Fixed; |
3300 | } |
3301 | |
3302 | void anchor() override; |
3303 | |
3304 | void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
3305 | TemplateSpecializationKind TSK); |
3306 | public: |
3307 | friend class ASTDeclReader; |
3308 | |
3309 | EnumDecl *getCanonicalDecl() override { |
3310 | return cast<EnumDecl>(TagDecl::getCanonicalDecl()); |
3311 | } |
3312 | const EnumDecl *getCanonicalDecl() const { |
3313 | return const_cast<EnumDecl*>(this)->getCanonicalDecl(); |
3314 | } |
3315 | |
3316 | EnumDecl *getPreviousDecl() { |
3317 | return cast_or_null<EnumDecl>( |
3318 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3319 | } |
3320 | const EnumDecl *getPreviousDecl() const { |
3321 | return const_cast<EnumDecl*>(this)->getPreviousDecl(); |
3322 | } |
3323 | |
3324 | EnumDecl *getMostRecentDecl() { |
3325 | return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3326 | } |
3327 | const EnumDecl *getMostRecentDecl() const { |
3328 | return const_cast<EnumDecl*>(this)->getMostRecentDecl(); |
3329 | } |
3330 | |
3331 | EnumDecl *getDefinition() const { |
3332 | return cast_or_null<EnumDecl>(TagDecl::getDefinition()); |
3333 | } |
3334 | |
3335 | static EnumDecl *Create(ASTContext &C, DeclContext *DC, |
3336 | SourceLocation StartLoc, SourceLocation IdLoc, |
3337 | IdentifierInfo *Id, EnumDecl *PrevDecl, |
3338 | bool IsScoped, bool IsScopedUsingClassTag, |
3339 | bool IsFixed); |
3340 | static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3341 | |
3342 | /// When created, the EnumDecl corresponds to a |
3343 | /// forward-declared enum. This method is used to mark the |
3344 | /// declaration as being defined; its enumerators have already been |
3345 | /// added (via DeclContext::addDecl). NewType is the new underlying |
3346 | /// type of the enumeration type. |
3347 | void completeDefinition(QualType NewType, |
3348 | QualType PromotionType, |
3349 | unsigned NumPositiveBits, |
3350 | unsigned NumNegativeBits); |
3351 | |
3352 | // Iterates through the enumerators of this enumeration. |
3353 | using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>; |
3354 | using enumerator_range = |
3355 | llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>; |
3356 | |
3357 | enumerator_range enumerators() const { |
3358 | return enumerator_range(enumerator_begin(), enumerator_end()); |
3359 | } |
3360 | |
3361 | enumerator_iterator enumerator_begin() const { |
3362 | const EnumDecl *E = getDefinition(); |
3363 | if (!E) |
3364 | E = this; |
3365 | return enumerator_iterator(E->decls_begin()); |
3366 | } |
3367 | |
3368 | enumerator_iterator enumerator_end() const { |
3369 | const EnumDecl *E = getDefinition(); |
3370 | if (!E) |
3371 | E = this; |
3372 | return enumerator_iterator(E->decls_end()); |
3373 | } |
3374 | |
3375 | /// Return the integer type that enumerators should promote to. |
3376 | QualType getPromotionType() const { return PromotionType; } |
3377 | |
3378 | /// Set the promotion type. |
3379 | void setPromotionType(QualType T) { PromotionType = T; } |
3380 | |
3381 | /// Return the integer type this enum decl corresponds to. |
3382 | /// This returns a null QualType for an enum forward definition with no fixed |
3383 | /// underlying type. |
3384 | QualType getIntegerType() const { |
3385 | if (!IntegerType) |
3386 | return QualType(); |
3387 | if (const Type *T = IntegerType.dyn_cast<const Type*>()) |
3388 | return QualType(T, 0); |
3389 | return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType(); |
3390 | } |
3391 | |
3392 | /// \brief Set the underlying integer type. |
3393 | void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } |
3394 | |
3395 | /// \brief Set the underlying integer type source info. |
3396 | void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; } |
3397 | |
3398 | /// \brief Return the type source info for the underlying integer type, |
3399 | /// if no type source info exists, return 0. |
3400 | TypeSourceInfo *getIntegerTypeSourceInfo() const { |
3401 | return IntegerType.dyn_cast<TypeSourceInfo*>(); |
3402 | } |
3403 | |
3404 | /// \brief Retrieve the source range that covers the underlying type if |
3405 | /// specified. |
3406 | SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__)); |
3407 | |
3408 | /// \brief Returns the width in bits required to store all the |
3409 | /// non-negative enumerators of this enum. |
3410 | unsigned getNumPositiveBits() const { |
3411 | return NumPositiveBits; |
3412 | } |
3413 | void setNumPositiveBits(unsigned Num) { |
3414 | NumPositiveBits = Num; |
3415 | assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount" ) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3415, __extension__ __PRETTY_FUNCTION__)); |
3416 | } |
3417 | |
3418 | /// \brief Returns the width in bits required to store all the |
3419 | /// negative enumerators of this enum. These widths include |
3420 | /// the rightmost leading 1; that is: |
3421 | /// |
3422 | /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS |
3423 | /// ------------------------ ------- ----------------- |
3424 | /// -1 1111111 1 |
3425 | /// -10 1110110 5 |
3426 | /// -101 1001011 8 |
3427 | unsigned getNumNegativeBits() const { |
3428 | return NumNegativeBits; |
3429 | } |
3430 | void setNumNegativeBits(unsigned Num) { |
3431 | NumNegativeBits = Num; |
3432 | } |
3433 | |
3434 | /// \brief Returns true if this is a C++11 scoped enumeration. |
3435 | bool isScoped() const { |
3436 | return IsScoped; |
3437 | } |
3438 | |
3439 | /// \brief Returns true if this is a C++11 scoped enumeration. |
3440 | bool isScopedUsingClassTag() const { |
3441 | return IsScopedUsingClassTag; |
3442 | } |
3443 | |
3444 | /// \brief Returns true if this is an Objective-C, C++11, or |
3445 | /// Microsoft-style enumeration with a fixed underlying type. |
3446 | bool isFixed() const { |
3447 | return IsFixed; |
3448 | } |
3449 | |
3450 | /// \brief Returns true if this can be considered a complete type. |
3451 | bool isComplete() const { |
3452 | // IntegerType is set for fixed type enums and non-fixed but implicitly |
3453 | // int-sized Microsoft enums. |
3454 | return isCompleteDefinition() || IntegerType; |
3455 | } |
3456 | |
3457 | /// Returns true if this enum is either annotated with |
3458 | /// enum_extensibility(closed) or isn't annotated with enum_extensibility. |
3459 | bool isClosed() const; |
3460 | |
3461 | /// Returns true if this enum is annotated with flag_enum and isn't annotated |
3462 | /// with enum_extensibility(open). |
3463 | bool isClosedFlag() const; |
3464 | |
3465 | /// Returns true if this enum is annotated with neither flag_enum nor |
3466 | /// enum_extensibility(open). |
3467 | bool isClosedNonFlag() const; |
3468 | |
3469 | /// \brief Retrieve the enum definition from which this enumeration could |
3470 | /// be instantiated, if it is an instantiation (rather than a non-template). |
3471 | EnumDecl *getTemplateInstantiationPattern() const; |
3472 | |
3473 | /// \brief Returns the enumeration (declared within the template) |
3474 | /// from which this enumeration type was instantiated, or NULL if |
3475 | /// this enumeration was not instantiated from any template. |
3476 | EnumDecl *getInstantiatedFromMemberEnum() const; |
3477 | |
3478 | /// \brief If this enumeration is a member of a specialization of a |
3479 | /// templated class, determine what kind of template specialization |
3480 | /// or instantiation this is. |
3481 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
3482 | |
3483 | /// \brief For an enumeration member that was instantiated from a member |
3484 | /// enumeration of a templated class, set the template specialiation kind. |
3485 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
3486 | SourceLocation PointOfInstantiation = SourceLocation()); |
3487 | |
3488 | /// \brief If this enumeration is an instantiation of a member enumeration of |
3489 | /// a class template specialization, retrieves the member specialization |
3490 | /// information. |
3491 | MemberSpecializationInfo *getMemberSpecializationInfo() const { |
3492 | return SpecializationInfo; |
3493 | } |
3494 | |
3495 | /// \brief Specify that this enumeration is an instantiation of the |
3496 | /// member enumeration ED. |
3497 | void setInstantiationOfMemberEnum(EnumDecl *ED, |
3498 | TemplateSpecializationKind TSK) { |
3499 | setInstantiationOfMemberEnum(getASTContext(), ED, TSK); |
3500 | } |
3501 | |
3502 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3503 | static bool classofKind(Kind K) { return K == Enum; } |
3504 | }; |
3505 | |
3506 | /// Represents a struct/union/class. For example: |
3507 | /// struct X; // Forward declaration, no "body". |
3508 | /// union Y { int A, B; }; // Has body with members A and B (FieldDecls). |
3509 | /// This decl will be marked invalid if *any* members are invalid. |
3510 | class RecordDecl : public TagDecl { |
3511 | friend class DeclContext; |
3512 | |
3513 | // FIXME: This can be packed into the bitfields in Decl. |
3514 | /// This is true if this struct ends with a flexible |
3515 | /// array member (e.g. int X[]) or if this union contains a struct that does. |
3516 | /// If so, this cannot be contained in arrays or other structs as a member. |
3517 | bool HasFlexibleArrayMember : 1; |
3518 | |
3519 | /// Whether this is the type of an anonymous struct or union. |
3520 | bool AnonymousStructOrUnion : 1; |
3521 | |
3522 | /// This is true if this struct has at least one member |
3523 | /// containing an Objective-C object pointer type. |
3524 | bool HasObjectMember : 1; |
3525 | |
3526 | /// This is true if struct has at least one member of |
3527 | /// 'volatile' type. |
3528 | bool HasVolatileMember : 1; |
3529 | |
3530 | /// Whether the field declarations of this record have been loaded |
3531 | /// from external storage. To avoid unnecessary deserialization of |
3532 | /// methods/nested types we allow deserialization of just the fields |
3533 | /// when needed. |
3534 | mutable bool LoadedFieldsFromExternalStorage : 1; |
3535 | |
3536 | protected: |
3537 | RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3538 | SourceLocation StartLoc, SourceLocation IdLoc, |
3539 | IdentifierInfo *Id, RecordDecl *PrevDecl); |
3540 | |
3541 | public: |
3542 | static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
3543 | SourceLocation StartLoc, SourceLocation IdLoc, |
3544 | IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr); |
3545 | static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
3546 | |
3547 | RecordDecl *getPreviousDecl() { |
3548 | return cast_or_null<RecordDecl>( |
3549 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3550 | } |
3551 | const RecordDecl *getPreviousDecl() const { |
3552 | return const_cast<RecordDecl*>(this)->getPreviousDecl(); |
3553 | } |
3554 | |
3555 | RecordDecl *getMostRecentDecl() { |
3556 | return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3557 | } |
3558 | const RecordDecl *getMostRecentDecl() const { |
3559 | return const_cast<RecordDecl*>(this)->getMostRecentDecl(); |
3560 | } |
3561 | |
3562 | bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } |
3563 | void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } |
3564 | |
3565 | /// Whether this is an anonymous struct or union. To be an anonymous |
3566 | /// struct or union, it must have been declared without a name and |
3567 | /// there must be no objects of this type declared, e.g., |
3568 | /// @code |
3569 | /// union { int i; float f; }; |
3570 | /// @endcode |
3571 | /// is an anonymous union but neither of the following are: |
3572 | /// @code |
3573 | /// union X { int i; float f; }; |
3574 | /// union { int i; float f; } obj; |
3575 | /// @endcode |
3576 | bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; } |
3577 | void setAnonymousStructOrUnion(bool Anon) { |
3578 | AnonymousStructOrUnion = Anon; |
3579 | } |
3580 | |
3581 | bool hasObjectMember() const { return HasObjectMember; } |
3582 | void setHasObjectMember (bool val) { HasObjectMember = val; } |
3583 | |
3584 | bool hasVolatileMember() const { return HasVolatileMember; } |
3585 | void setHasVolatileMember (bool val) { HasVolatileMember = val; } |
3586 | |
3587 | bool hasLoadedFieldsFromExternalStorage() const { |
3588 | return LoadedFieldsFromExternalStorage; |
3589 | } |
3590 | void setHasLoadedFieldsFromExternalStorage(bool val) { |
3591 | LoadedFieldsFromExternalStorage = val; |
3592 | } |
3593 | |
3594 | /// \brief Determines whether this declaration represents the |
3595 | /// injected class name. |
3596 | /// |
3597 | /// The injected class name in C++ is the name of the class that |
3598 | /// appears inside the class itself. For example: |
3599 | /// |
3600 | /// \code |
3601 | /// struct C { |
3602 | /// // C is implicitly declared here as a synonym for the class name. |
3603 | /// }; |
3604 | /// |
3605 | /// C::C c; // same as "C c;" |
3606 | /// \endcode |
3607 | bool isInjectedClassName() const; |
3608 | |
3609 | /// \brief Determine whether this record is a class describing a lambda |
3610 | /// function object. |
3611 | bool isLambda() const; |
3612 | |
3613 | /// \brief Determine whether this record is a record for captured variables in |
3614 | /// CapturedStmt construct. |
3615 | bool isCapturedRecord() const; |
3616 | |
3617 | /// \brief Mark the record as a record for captured variables in CapturedStmt |
3618 | /// construct. |
3619 | void setCapturedRecord(); |
3620 | |
3621 | /// Returns the RecordDecl that actually defines |
3622 | /// this struct/union/class. When determining whether or not a |
3623 | /// struct/union/class is completely defined, one should use this |
3624 | /// method as opposed to 'isCompleteDefinition'. |
3625 | /// 'isCompleteDefinition' indicates whether or not a specific |
3626 | /// RecordDecl is a completed definition, not whether or not the |
3627 | /// record type is defined. This method returns NULL if there is |
3628 | /// no RecordDecl that defines the struct/union/tag. |
3629 | RecordDecl *getDefinition() const { |
3630 | return cast_or_null<RecordDecl>(TagDecl::getDefinition()); |
3631 | } |
3632 | |
3633 | // Iterator access to field members. The field iterator only visits |
3634 | // the non-static data members of this class, ignoring any static |
3635 | // data members, functions, constructors, destructors, etc. |
3636 | using field_iterator = specific_decl_iterator<FieldDecl>; |
3637 | using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>; |
3638 | |
3639 | field_range fields() const { return field_range(field_begin(), field_end()); } |
3640 | field_iterator field_begin() const; |
3641 | |
3642 | field_iterator field_end() const { |
3643 | return field_iterator(decl_iterator()); |
3644 | } |
3645 | |
3646 | // Whether there are any fields (non-static data members) in this record. |
3647 | bool field_empty() const { |
3648 | return field_begin() == field_end(); |
3649 | } |
3650 | |
3651 | /// Note that the definition of this type is now complete. |
3652 | virtual void completeDefinition(); |
3653 | |
3654 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3655 | static bool classofKind(Kind K) { |
3656 | return K >= firstRecord && K <= lastRecord; |
3657 | } |
3658 | |
3659 | /// \brief Get whether or not this is an ms_struct which can |
3660 | /// be turned on with an attribute, pragma, or -mms-bitfields |
3661 | /// commandline option. |
3662 | bool isMsStruct(const ASTContext &C) const; |
3663 | |
3664 | /// \brief Whether we are allowed to insert extra padding between fields. |
3665 | /// These padding are added to help AddressSanitizer detect |
3666 | /// intra-object-overflow bugs. |
3667 | bool mayInsertExtraPadding(bool EmitRemark = false) const; |
3668 | |
3669 | /// Finds the first data member which has a name. |
3670 | /// nullptr is returned if no named data member exists. |
3671 | const FieldDecl *findFirstNamedDataMember() const; |
3672 | |
3673 | private: |
3674 | /// \brief Deserialize just the fields. |
3675 | void LoadFieldsFromExternalStorage() const; |
3676 | }; |
3677 | |
3678 | class FileScopeAsmDecl : public Decl { |
3679 | StringLiteral *AsmString; |
3680 | SourceLocation RParenLoc; |
3681 | |
3682 | FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, |
3683 | SourceLocation StartL, SourceLocation EndL) |
3684 | : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} |
3685 | |
3686 | virtual void anchor(); |
3687 | |
3688 | public: |
3689 | static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, |
3690 | StringLiteral *Str, SourceLocation AsmLoc, |
3691 | SourceLocation RParenLoc); |
3692 | |
3693 | static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3694 | |
3695 | SourceLocation getAsmLoc() const { return getLocation(); } |
3696 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3697 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
3698 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3699 | return SourceRange(getAsmLoc(), getRParenLoc()); |
3700 | } |
3701 | |
3702 | const StringLiteral *getAsmString() const { return AsmString; } |
3703 | StringLiteral *getAsmString() { return AsmString; } |
3704 | void setAsmString(StringLiteral *Asm) { AsmString = Asm; } |
3705 | |
3706 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3707 | static bool classofKind(Kind K) { return K == FileScopeAsm; } |
3708 | }; |
3709 | |
3710 | /// Pepresents a block literal declaration, which is like an |
3711 | /// unnamed FunctionDecl. For example: |
3712 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
3713 | class BlockDecl : public Decl, public DeclContext { |
3714 | public: |
3715 | /// A class which contains all the information about a particular |
3716 | /// captured value. |
3717 | class Capture { |
3718 | enum { |
3719 | flag_isByRef = 0x1, |
3720 | flag_isNested = 0x2 |
3721 | }; |
3722 | |
3723 | /// The variable being captured. |
3724 | llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; |
3725 | |
3726 | /// The copy expression, expressed in terms of a DeclRef (or |
3727 | /// BlockDeclRef) to the captured variable. Only required if the |
3728 | /// variable has a C++ class type. |
3729 | Expr *CopyExpr; |
3730 | |
3731 | public: |
3732 | Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) |
3733 | : VariableAndFlags(variable, |
3734 | (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), |
3735 | CopyExpr(copy) {} |
3736 | |
3737 | /// The variable being captured. |
3738 | VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } |
3739 | |
3740 | /// Whether this is a "by ref" capture, i.e. a capture of a __block |
3741 | /// variable. |
3742 | bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } |
3743 | |
3744 | /// Whether this is a nested capture, i.e. the variable captured |
3745 | /// is not from outside the immediately enclosing function/block. |
3746 | bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } |
3747 | |
3748 | bool hasCopyExpr() const { return CopyExpr != nullptr; } |
3749 | Expr *getCopyExpr() const { return CopyExpr; } |
3750 | void setCopyExpr(Expr *e) { CopyExpr = e; } |
3751 | }; |
3752 | |
3753 | private: |
3754 | // FIXME: This can be packed into the bitfields in Decl. |
3755 | bool IsVariadic : 1; |
3756 | bool CapturesCXXThis : 1; |
3757 | bool BlockMissingReturnType : 1; |
3758 | bool IsConversionFromLambda : 1; |
3759 | |
3760 | /// A new[]'d array of pointers to ParmVarDecls for the formal |
3761 | /// parameters of this function. This is null if a prototype or if there are |
3762 | /// no formals. |
3763 | ParmVarDecl **ParamInfo = nullptr; |
3764 | unsigned NumParams = 0; |
3765 | |
3766 | Stmt *Body = nullptr; |
3767 | TypeSourceInfo *SignatureAsWritten = nullptr; |
3768 | |
3769 | const Capture *Captures = nullptr; |
3770 | unsigned NumCaptures = 0; |
3771 | |
3772 | unsigned ManglingNumber = 0; |
3773 | Decl *ManglingContextDecl = nullptr; |
3774 | |
3775 | protected: |
3776 | BlockDecl(DeclContext *DC, SourceLocation CaretLoc) |
3777 | : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false), |
3778 | CapturesCXXThis(false), BlockMissingReturnType(true), |
3779 | IsConversionFromLambda(false) {} |
3780 | |
3781 | public: |
3782 | static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); |
3783 | static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3784 | |
3785 | SourceLocation getCaretLocation() const { return getLocation(); } |
3786 | |
3787 | bool isVariadic() const { return IsVariadic; } |
3788 | void setIsVariadic(bool value) { IsVariadic = value; } |
3789 | |
3790 | CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } |
3791 | Stmt *getBody() const override { return (Stmt*) Body; } |
3792 | void setBody(CompoundStmt *B) { Body = (Stmt*) B; } |
3793 | |
3794 | void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } |
3795 | TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } |
3796 | |
3797 | // ArrayRef access to formal parameters. |
3798 | ArrayRef<ParmVarDecl *> parameters() const { |
3799 | return {ParamInfo, getNumParams()}; |
3800 | } |
3801 | MutableArrayRef<ParmVarDecl *> parameters() { |
3802 | return {ParamInfo, getNumParams()}; |
3803 | } |
3804 | |
3805 | // Iterator access to formal parameters. |
3806 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
3807 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
3808 | |
3809 | bool param_empty() const { return parameters().empty(); } |
3810 | param_iterator param_begin() { return parameters().begin(); } |
3811 | param_iterator param_end() { return parameters().end(); } |
3812 | param_const_iterator param_begin() const { return parameters().begin(); } |
3813 | param_const_iterator param_end() const { return parameters().end(); } |
3814 | size_t param_size() const { return parameters().size(); } |
3815 | |
3816 | unsigned getNumParams() const { return NumParams; } |
3817 | |
3818 | const ParmVarDecl *getParamDecl(unsigned i) const { |
3819 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3819, __extension__ __PRETTY_FUNCTION__)); |
3820 | return ParamInfo[i]; |
3821 | } |
3822 | ParmVarDecl *getParamDecl(unsigned i) { |
3823 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3823, __extension__ __PRETTY_FUNCTION__)); |
3824 | return ParamInfo[i]; |
3825 | } |
3826 | |
3827 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); |
3828 | |
3829 | /// True if this block (or its nested blocks) captures |
3830 | /// anything of local storage from its enclosing scopes. |
3831 | bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; } |
3832 | |
3833 | /// Returns the number of captured variables. |
3834 | /// Does not include an entry for 'this'. |
3835 | unsigned getNumCaptures() const { return NumCaptures; } |
3836 | |
3837 | using capture_const_iterator = ArrayRef<Capture>::const_iterator; |
3838 | |
3839 | ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; } |
3840 | |
3841 | capture_const_iterator capture_begin() const { return captures().begin(); } |
3842 | capture_const_iterator capture_end() const { return captures().end(); } |
3843 | |
3844 | bool capturesCXXThis() const { return CapturesCXXThis; } |
3845 | bool blockMissingReturnType() const { return BlockMissingReturnType; } |
3846 | void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; } |
3847 | |
3848 | bool isConversionFromLambda() const { return IsConversionFromLambda; } |
3849 | void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; } |
3850 | |
3851 | bool capturesVariable(const VarDecl *var) const; |
3852 | |
3853 | void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
3854 | bool CapturesCXXThis); |
3855 | |
3856 | unsigned getBlockManglingNumber() const { |
3857 | return ManglingNumber; |
3858 | } |
3859 | |
3860 | Decl *getBlockManglingContextDecl() const { |
3861 | return ManglingContextDecl; |
3862 | } |
3863 | |
3864 | void setBlockMangling(unsigned Number, Decl *Ctx) { |
3865 | ManglingNumber = Number; |
3866 | ManglingContextDecl = Ctx; |
3867 | } |
3868 | |
3869 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3870 | |
3871 | // Implement isa/cast/dyncast/etc. |
3872 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3873 | static bool classofKind(Kind K) { return K == Block; } |
3874 | static DeclContext *castToDeclContext(const BlockDecl *D) { |
3875 | return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); |
3876 | } |
3877 | static BlockDecl *castFromDeclContext(const DeclContext *DC) { |
3878 | return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); |
3879 | } |
3880 | }; |
3881 | |
3882 | /// Represents the body of a CapturedStmt, and serves as its DeclContext. |
3883 | class CapturedDecl final |
3884 | : public Decl, |
3885 | public DeclContext, |
3886 | private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> { |
3887 | protected: |
3888 | size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) { |
3889 | return NumParams; |
3890 | } |
3891 | |
3892 | private: |
3893 | /// \brief The number of parameters to the outlined function. |
3894 | unsigned NumParams; |
3895 | |
3896 | /// \brief The position of context parameter in list of parameters. |
3897 | unsigned ContextParam; |
3898 | |
3899 | /// \brief The body of the outlined function. |
3900 | llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow; |
3901 | |
3902 | explicit CapturedDecl(DeclContext *DC, unsigned NumParams); |
3903 | |
3904 | ImplicitParamDecl *const *getParams() const { |
3905 | return getTrailingObjects<ImplicitParamDecl *>(); |
3906 | } |
3907 | |
3908 | ImplicitParamDecl **getParams() { |
3909 | return getTrailingObjects<ImplicitParamDecl *>(); |
3910 | } |
3911 | |
3912 | public: |
3913 | friend class ASTDeclReader; |
3914 | friend class ASTDeclWriter; |
3915 | friend TrailingObjects; |
3916 | |
3917 | static CapturedDecl *Create(ASTContext &C, DeclContext *DC, |
3918 | unsigned NumParams); |
3919 | static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
3920 | unsigned NumParams); |
3921 | |
3922 | Stmt *getBody() const override; |
3923 | void setBody(Stmt *B); |
3924 | |
3925 | bool isNothrow() const; |
3926 | void setNothrow(bool Nothrow = true); |
3927 | |
3928 | unsigned getNumParams() const { return NumParams; } |
3929 | |
3930 | ImplicitParamDecl *getParam(unsigned i) const { |
3931 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3931, __extension__ __PRETTY_FUNCTION__)); |
3932 | return getParams()[i]; |
3933 | } |
3934 | void setParam(unsigned i, ImplicitParamDecl *P) { |
3935 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3935, __extension__ __PRETTY_FUNCTION__)); |
3936 | getParams()[i] = P; |
3937 | } |
3938 | |
3939 | // ArrayRef interface to parameters. |
3940 | ArrayRef<ImplicitParamDecl *> parameters() const { |
3941 | return {getParams(), getNumParams()}; |
3942 | } |
3943 | MutableArrayRef<ImplicitParamDecl *> parameters() { |
3944 | return {getParams(), getNumParams()}; |
3945 | } |
3946 | |
3947 | /// \brief Retrieve the parameter containing captured variables. |
3948 | ImplicitParamDecl *getContextParam() const { |
3949 | assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void (0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3949, __extension__ __PRETTY_FUNCTION__)); |
3950 | return getParam(ContextParam); |
3951 | } |
3952 | void setContextParam(unsigned i, ImplicitParamDecl *P) { |
3953 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 3953, __extension__ __PRETTY_FUNCTION__)); |
3954 | ContextParam = i; |
3955 | setParam(i, P); |
3956 | } |
3957 | unsigned getContextParamPosition() const { return ContextParam; } |
3958 | |
3959 | using param_iterator = ImplicitParamDecl *const *; |
3960 | using param_range = llvm::iterator_range<param_iterator>; |
3961 | |
3962 | /// \brief Retrieve an iterator pointing to the first parameter decl. |
3963 | param_iterator param_begin() const { return getParams(); } |
3964 | /// \brief Retrieve an iterator one past the last parameter decl. |
3965 | param_iterator param_end() const { return getParams() + NumParams; } |
3966 | |
3967 | // Implement isa/cast/dyncast/etc. |
3968 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3969 | static bool classofKind(Kind K) { return K == Captured; } |
3970 | static DeclContext *castToDeclContext(const CapturedDecl *D) { |
3971 | return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); |
3972 | } |
3973 | static CapturedDecl *castFromDeclContext(const DeclContext *DC) { |
3974 | return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); |
3975 | } |
3976 | }; |
3977 | |
3978 | /// \brief Describes a module import declaration, which makes the contents |
3979 | /// of the named module visible in the current translation unit. |
3980 | /// |
3981 | /// An import declaration imports the named module (or submodule). For example: |
3982 | /// \code |
3983 | /// @import std.vector; |
3984 | /// \endcode |
3985 | /// |
3986 | /// Import declarations can also be implicitly generated from |
3987 | /// \#include/\#import directives. |
3988 | class ImportDecl final : public Decl, |
3989 | llvm::TrailingObjects<ImportDecl, SourceLocation> { |
3990 | friend class ASTContext; |
3991 | friend class ASTDeclReader; |
3992 | friend class ASTReader; |
3993 | friend TrailingObjects; |
3994 | |
3995 | /// \brief The imported module, along with a bit that indicates whether |
3996 | /// we have source-location information for each identifier in the module |
3997 | /// name. |
3998 | /// |
3999 | /// When the bit is false, we only have a single source location for the |
4000 | /// end of the import declaration. |
4001 | llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete; |
4002 | |
4003 | /// \brief The next import in the list of imports local to the translation |
4004 | /// unit being parsed (not loaded from an AST file). |
4005 | ImportDecl *NextLocalImport = nullptr; |
4006 | |
4007 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4008 | ArrayRef<SourceLocation> IdentifierLocs); |
4009 | |
4010 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4011 | SourceLocation EndLoc); |
4012 | |
4013 | ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} |
4014 | |
4015 | public: |
4016 | /// \brief Create a new module import declaration. |
4017 | static ImportDecl *Create(ASTContext &C, DeclContext *DC, |
4018 | SourceLocation StartLoc, Module *Imported, |
4019 | ArrayRef<SourceLocation> IdentifierLocs); |
4020 | |
4021 | /// \brief Create a new module import declaration for an implicitly-generated |
4022 | /// import. |
4023 | static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, |
4024 | SourceLocation StartLoc, Module *Imported, |
4025 | SourceLocation EndLoc); |
4026 | |
4027 | /// \brief Create a new, deserialized module import declaration. |
4028 | static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4029 | unsigned NumLocations); |
4030 | |
4031 | /// \brief Retrieve the module that was imported by the import declaration. |
4032 | Module *getImportedModule() const { return ImportedAndComplete.getPointer(); } |
4033 | |
4034 | /// \brief Retrieves the locations of each of the identifiers that make up |
4035 | /// the complete module name in the import declaration. |
4036 | /// |
4037 | /// This will return an empty array if the locations of the individual |
4038 | /// identifiers aren't available. |
4039 | ArrayRef<SourceLocation> getIdentifierLocs() const; |
4040 | |
4041 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4042 | |
4043 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4044 | static bool classofKind(Kind K) { return K == Import; } |
4045 | }; |
4046 | |
4047 | /// \brief Represents a C++ Modules TS module export declaration. |
4048 | /// |
4049 | /// For example: |
4050 | /// \code |
4051 | /// export void foo(); |
4052 | /// \endcode |
4053 | class ExportDecl final : public Decl, public DeclContext { |
4054 | virtual void anchor(); |
4055 | |
4056 | private: |
4057 | friend class ASTDeclReader; |
4058 | |
4059 | /// \brief The source location for the right brace (if valid). |
4060 | SourceLocation RBraceLoc; |
4061 | |
4062 | ExportDecl(DeclContext *DC, SourceLocation ExportLoc) |
4063 | : Decl(Export, DC, ExportLoc), DeclContext(Export), |
4064 | RBraceLoc(SourceLocation()) {} |
4065 | |
4066 | public: |
4067 | static ExportDecl *Create(ASTContext &C, DeclContext *DC, |
4068 | SourceLocation ExportLoc); |
4069 | static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4070 | |
4071 | SourceLocation getExportLoc() const { return getLocation(); } |
4072 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4073 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
4074 | |
4075 | SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { |
4076 | if (RBraceLoc.isValid()) |
4077 | return RBraceLoc; |
4078 | // No braces: get the end location of the (only) declaration in context |
4079 | // (if present). |
4080 | return decls_empty() ? getLocation() : decls_begin()->getLocEnd(); |
4081 | } |
4082 | |
4083 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4084 | return SourceRange(getLocation(), getLocEnd()); |
4085 | } |
4086 | |
4087 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4088 | static bool classofKind(Kind K) { return K == Export; } |
4089 | static DeclContext *castToDeclContext(const ExportDecl *D) { |
4090 | return static_cast<DeclContext *>(const_cast<ExportDecl*>(D)); |
4091 | } |
4092 | static ExportDecl *castFromDeclContext(const DeclContext *DC) { |
4093 | return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC)); |
4094 | } |
4095 | }; |
4096 | |
4097 | /// Represents an empty-declaration. |
4098 | class EmptyDecl : public Decl { |
4099 | EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {} |
4100 | |
4101 | virtual void anchor(); |
4102 | |
4103 | public: |
4104 | static EmptyDecl *Create(ASTContext &C, DeclContext *DC, |
4105 | SourceLocation L); |
4106 | static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4107 | |
4108 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4109 | static bool classofKind(Kind K) { return K == Empty; } |
4110 | }; |
4111 | |
4112 | /// Insertion operator for diagnostics. This allows sending NamedDecl's |
4113 | /// into a diagnostic with <<. |
4114 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
4115 | const NamedDecl* ND) { |
4116 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4117 | DiagnosticsEngine::ak_nameddecl); |
4118 | return DB; |
4119 | } |
4120 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
4121 | const NamedDecl* ND) { |
4122 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4123 | DiagnosticsEngine::ak_nameddecl); |
4124 | return PD; |
4125 | } |
4126 | |
4127 | template<typename decl_type> |
4128 | void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) { |
4129 | // Note: This routine is implemented here because we need both NamedDecl |
4130 | // and Redeclarable to be defined. |
4131 | assert(RedeclLink.NextIsLatest() &&(static_cast <bool> (RedeclLink.NextIsLatest() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 4132, __extension__ __PRETTY_FUNCTION__)) |
4132 | "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.NextIsLatest() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 4132, __extension__ __PRETTY_FUNCTION__)); |
4133 | |
4134 | if (PrevDecl) { |
4135 | // Point to previous. Make sure that this is actually the most recent |
4136 | // redeclaration, or we can build invalid chains. If the most recent |
4137 | // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. |
4138 | First = PrevDecl->getFirstDecl(); |
4139 | assert(First->RedeclLink.NextIsLatest() && "Expected first")(static_cast <bool> (First->RedeclLink.NextIsLatest( ) && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.NextIsLatest() && \"Expected first\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 4139, __extension__ __PRETTY_FUNCTION__)); |
4140 | decl_type *MostRecent = First->getNextRedeclaration(); |
4141 | RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); |
4142 | |
4143 | // If the declaration was previously visible, a redeclaration of it remains |
4144 | // visible even if it wouldn't be visible by itself. |
4145 | static_cast<decl_type*>(this)->IdentifierNamespace |= |
4146 | MostRecent->getIdentifierNamespace() & |
4147 | (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); |
4148 | } else { |
4149 | // Make this first. |
4150 | First = static_cast<decl_type*>(this); |
4151 | } |
4152 | |
4153 | // First one will point to this one as latest. |
4154 | First->RedeclLink.setLatest(static_cast<decl_type*>(this)); |
4155 | |
4156 | assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 4157, __extension__ __PRETTY_FUNCTION__)) |
4157 | cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Decl.h" , 4157, __extension__ __PRETTY_FUNCTION__)); |
4158 | } |
4159 | |
4160 | // Inline function definitions. |
4161 | |
4162 | /// Check if the given decl is complete. |
4163 | /// |
4164 | /// We use this function to break a cycle between the inline definitions in |
4165 | /// Type.h and Decl.h. |
4166 | inline bool IsEnumDeclComplete(EnumDecl *ED) { |
4167 | return ED->isComplete(); |
4168 | } |
4169 | |
4170 | /// Check if the given decl is scoped. |
4171 | /// |
4172 | /// We use this function to break a cycle between the inline definitions in |
4173 | /// Type.h and Decl.h. |
4174 | inline bool IsEnumDeclScoped(EnumDecl *ED) { |
4175 | return ED->isScoped(); |
4176 | } |
4177 | |
4178 | } // namespace clang |
4179 | |
4180 | #endif // LLVM_CLANG_AST_DECL_H |
1 | //===- Redeclarable.h - Base for Decls that can be redeclared --*- 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 defines the Redeclarable interface. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_AST_REDECLARABLE_H |
15 | #define LLVM_CLANG_AST_REDECLARABLE_H |
16 | |
17 | #include "clang/AST/ExternalASTSource.h" |
18 | #include "llvm/ADT/DenseMapInfo.h" |
19 | #include "llvm/ADT/PointerUnion.h" |
20 | #include "llvm/ADT/iterator_range.h" |
21 | #include "llvm/Support/Casting.h" |
22 | #include <cassert> |
23 | #include <cstddef> |
24 | #include <iterator> |
25 | |
26 | namespace clang { |
27 | |
28 | class ASTContext; |
29 | class Decl; |
30 | |
31 | // Some notes on redeclarables: |
32 | // |
33 | // - Every redeclarable is on a circular linked list. |
34 | // |
35 | // - Every decl has a pointer to the first element of the chain _and_ a |
36 | // DeclLink that may point to one of 3 possible states: |
37 | // - the "previous" (temporal) element in the chain |
38 | // - the "latest" (temporal) element in the chain |
39 | // - the an "uninitialized-latest" value (when newly-constructed) |
40 | // |
41 | // - The first element is also often called the canonical element. Every |
42 | // element has a pointer to it so that "getCanonical" can be fast. |
43 | // |
44 | // - Most links in the chain point to previous, except the link out of |
45 | // the first; it points to latest. |
46 | // |
47 | // - Elements are called "first", "previous", "latest" or |
48 | // "most-recent" when referring to temporal order: order of addition |
49 | // to the chain. |
50 | // |
51 | // - To make matters confusing, the DeclLink type uses the term "next" |
52 | // for its pointer-storage internally (thus functions like |
53 | // NextIsPrevious). It's easiest to just ignore the implementation of |
54 | // DeclLink when making sense of the redeclaration chain. |
55 | // |
56 | // - There's also a "definition" link for several types of |
57 | // redeclarable, where only one definition should exist at any given |
58 | // time (and the defn pointer is stored in the decl's "data" which |
59 | // is copied to every element on the chain when it's changed). |
60 | // |
61 | // Here is some ASCII art: |
62 | // |
63 | // "first" "latest" |
64 | // "canonical" "most recent" |
65 | // +------------+ first +--------------+ |
66 | // | | <--------------------------- | | |
67 | // | | | | |
68 | // | | | | |
69 | // | | +--------------+ | | |
70 | // | | first | | | | |
71 | // | | <---- | | | | |
72 | // | | | | | | |
73 | // | @class A | link | @interface A | link | @class A | |
74 | // | seen first | <---- | seen second | <---- | seen third | |
75 | // | | | | | | |
76 | // +------------+ +--------------+ +--------------+ |
77 | // | data | defn | data | defn | data | |
78 | // | | ----> | | <---- | | |
79 | // +------------+ +--------------+ +--------------+ |
80 | // | | ^ ^ |
81 | // | |defn | | |
82 | // | link +-----+ | |
83 | // +-->-------------------------------------------+ |
84 | |
85 | /// \brief Provides common interface for the Decls that can be redeclared. |
86 | template<typename decl_type> |
87 | class Redeclarable { |
88 | protected: |
89 | class DeclLink { |
90 | /// A pointer to a known latest declaration, either statically known or |
91 | /// generationally updated as decls are added by an external source. |
92 | using KnownLatest = |
93 | LazyGenerationalUpdatePtr<const Decl *, Decl *, |
94 | &ExternalASTSource::CompleteRedeclChain>; |
95 | |
96 | /// We store a pointer to the ASTContext in the UninitializedLatest |
97 | /// pointer, but to avoid circular type dependencies when we steal the low |
98 | /// bits of this pointer, we use a raw void* here. |
99 | using UninitializedLatest = const void *; |
100 | |
101 | using Previous = Decl *; |
102 | |
103 | /// A pointer to either an uninitialized latest declaration (where either |
104 | /// we've not yet set the previous decl or there isn't one), or to a known |
105 | /// previous declaration. |
106 | using NotKnownLatest = llvm::PointerUnion<Previous, UninitializedLatest>; |
107 | |
108 | mutable llvm::PointerUnion<NotKnownLatest, KnownLatest> Next; |
109 | |
110 | public: |
111 | enum PreviousTag { PreviousLink }; |
112 | enum LatestTag { LatestLink }; |
113 | |
114 | DeclLink(LatestTag, const ASTContext &Ctx) |
115 | : Next(NotKnownLatest(reinterpret_cast<UninitializedLatest>(&Ctx))) {} |
116 | DeclLink(PreviousTag, decl_type *D) : Next(NotKnownLatest(Previous(D))) {} |
117 | |
118 | bool NextIsPrevious() const { |
119 | return Next.is<NotKnownLatest>() && |
120 | // FIXME: 'template' is required on the next line due to an |
121 | // apparent clang bug. |
122 | Next.get<NotKnownLatest>().template is<Previous>(); |
123 | } |
124 | |
125 | bool NextIsLatest() const { return !NextIsPrevious(); } |
126 | |
127 | decl_type *getNext(const decl_type *D) const { |
128 | if (Next.is<NotKnownLatest>()) { |
129 | NotKnownLatest NKL = Next.get<NotKnownLatest>(); |
130 | if (NKL.is<Previous>()) |
131 | return static_cast<decl_type*>(NKL.get<Previous>()); |
132 | |
133 | // Allocate the generational 'most recent' cache now, if needed. |
134 | Next = KnownLatest(*reinterpret_cast<const ASTContext *>( |
135 | NKL.get<UninitializedLatest>()), |
136 | const_cast<decl_type *>(D)); |
137 | } |
138 | |
139 | return static_cast<decl_type*>(Next.get<KnownLatest>().get(D)); |
140 | } |
141 | |
142 | void setPrevious(decl_type *D) { |
143 | assert(NextIsPrevious() && "decl became non-canonical unexpectedly")(static_cast <bool> (NextIsPrevious() && "decl became non-canonical unexpectedly" ) ? void (0) : __assert_fail ("NextIsPrevious() && \"decl became non-canonical unexpectedly\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Redeclarable.h" , 143, __extension__ __PRETTY_FUNCTION__)); |
144 | Next = Previous(D); |
145 | } |
146 | |
147 | void setLatest(decl_type *D) { |
148 | assert(NextIsLatest() && "decl became canonical unexpectedly")(static_cast <bool> (NextIsLatest() && "decl became canonical unexpectedly" ) ? void (0) : __assert_fail ("NextIsLatest() && \"decl became canonical unexpectedly\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Redeclarable.h" , 148, __extension__ __PRETTY_FUNCTION__)); |
149 | if (Next.is<NotKnownLatest>()) { |
150 | NotKnownLatest NKL = Next.get<NotKnownLatest>(); |
151 | Next = KnownLatest(*reinterpret_cast<const ASTContext *>( |
152 | NKL.get<UninitializedLatest>()), |
153 | D); |
154 | } else { |
155 | auto Latest = Next.get<KnownLatest>(); |
156 | Latest.set(D); |
157 | Next = Latest; |
158 | } |
159 | } |
160 | |
161 | void markIncomplete() { Next.get<KnownLatest>().markIncomplete(); } |
162 | |
163 | Decl *getLatestNotUpdated() const { |
164 | assert(NextIsLatest() && "expected a canonical decl")(static_cast <bool> (NextIsLatest() && "expected a canonical decl" ) ? void (0) : __assert_fail ("NextIsLatest() && \"expected a canonical decl\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Redeclarable.h" , 164, __extension__ __PRETTY_FUNCTION__)); |
165 | if (Next.is<NotKnownLatest>()) |
166 | return nullptr; |
167 | return Next.get<KnownLatest>().getNotUpdated(); |
168 | } |
169 | }; |
170 | |
171 | static DeclLink PreviousDeclLink(decl_type *D) { |
172 | return DeclLink(DeclLink::PreviousLink, D); |
173 | } |
174 | |
175 | static DeclLink LatestDeclLink(const ASTContext &Ctx) { |
176 | return DeclLink(DeclLink::LatestLink, Ctx); |
177 | } |
178 | |
179 | /// \brief Points to the next redeclaration in the chain. |
180 | /// |
181 | /// If NextIsPrevious() is true, this is a link to the previous declaration |
182 | /// of this same Decl. If NextIsLatest() is true, this is the first |
183 | /// declaration and Link points to the latest declaration. For example: |
184 | /// |
185 | /// #1 int f(int x, int y = 1); // <pointer to #3, true> |
186 | /// #2 int f(int x = 0, int y); // <pointer to #1, false> |
187 | /// #3 int f(int x, int y) { return x + y; } // <pointer to #2, false> |
188 | /// |
189 | /// If there is only one declaration, it is <pointer to self, true> |
190 | DeclLink RedeclLink; |
191 | |
192 | decl_type *First; |
193 | |
194 | decl_type *getNextRedeclaration() const { |
195 | return RedeclLink.getNext(static_cast<const decl_type *>(this)); |
196 | } |
197 | |
198 | public: |
199 | friend class ASTDeclReader; |
200 | friend class ASTDeclWriter; |
201 | |
202 | Redeclarable(const ASTContext &Ctx) |
203 | : RedeclLink(LatestDeclLink(Ctx)), |
204 | First(static_cast<decl_type *>(this)) {} |
205 | |
206 | /// \brief Return the previous declaration of this declaration or NULL if this |
207 | /// is the first declaration. |
208 | decl_type *getPreviousDecl() { |
209 | if (RedeclLink.NextIsPrevious()) |
210 | return getNextRedeclaration(); |
211 | return nullptr; |
212 | } |
213 | const decl_type *getPreviousDecl() const { |
214 | return const_cast<decl_type *>( |
215 | static_cast<const decl_type*>(this))->getPreviousDecl(); |
216 | } |
217 | |
218 | /// \brief Return the first declaration of this declaration or itself if this |
219 | /// is the only declaration. |
220 | decl_type *getFirstDecl() { return First; } |
221 | |
222 | /// \brief Return the first declaration of this declaration or itself if this |
223 | /// is the only declaration. |
224 | const decl_type *getFirstDecl() const { return First; } |
225 | |
226 | /// \brief True if this is the first declaration in its redeclaration chain. |
227 | bool isFirstDecl() const { return RedeclLink.NextIsLatest(); } |
228 | |
229 | /// \brief Returns the most recent (re)declaration of this declaration. |
230 | decl_type *getMostRecentDecl() { |
231 | return getFirstDecl()->getNextRedeclaration(); |
232 | } |
233 | |
234 | /// \brief Returns the most recent (re)declaration of this declaration. |
235 | const decl_type *getMostRecentDecl() const { |
236 | return getFirstDecl()->getNextRedeclaration(); |
237 | } |
238 | |
239 | /// \brief Set the previous declaration. If PrevDecl is NULL, set this as the |
240 | /// first and only declaration. |
241 | void setPreviousDecl(decl_type *PrevDecl); |
242 | |
243 | /// \brief Iterates through all the redeclarations of the same decl. |
244 | class redecl_iterator { |
245 | /// Current - The current declaration. |
246 | decl_type *Current = nullptr; |
247 | decl_type *Starter; |
248 | bool PassedFirst = false; |
249 | |
250 | public: |
251 | using value_type = decl_type *; |
252 | using reference = decl_type *; |
253 | using pointer = decl_type *; |
254 | using iterator_category = std::forward_iterator_tag; |
255 | using difference_type = std::ptrdiff_t; |
256 | |
257 | redecl_iterator() = default; |
258 | explicit redecl_iterator(decl_type *C) : Current(C), Starter(C) {} |
259 | |
260 | reference operator*() const { return Current; } |
261 | pointer operator->() const { return Current; } |
262 | |
263 | redecl_iterator& operator++() { |
264 | assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end" ) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Redeclarable.h" , 264, __extension__ __PRETTY_FUNCTION__)); |
265 | // Sanity check to avoid infinite loop on invalid redecl chain. |
266 | if (Current->isFirstDecl()) { |
267 | if (PassedFirst) { |
268 | assert(0 && "Passed first decl twice, invalid redecl chain!")(static_cast <bool> (0 && "Passed first decl twice, invalid redecl chain!" ) ? void (0) : __assert_fail ("0 && \"Passed first decl twice, invalid redecl chain!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Redeclarable.h" , 268, __extension__ __PRETTY_FUNCTION__)); |
269 | Current = nullptr; |
270 | return *this; |
271 | } |
272 | PassedFirst = true; |
273 | } |
274 | |
275 | // Get either previous decl or latest decl. |
276 | decl_type *Next = Current->getNextRedeclaration(); |
277 | Current = (Next != Starter) ? Next : nullptr; |
278 | return *this; |
279 | } |
280 | |
281 | redecl_iterator operator++(int) { |
282 | redecl_iterator tmp(*this); |
283 | ++(*this); |
284 | return tmp; |
285 | } |
286 | |
287 | friend bool operator==(redecl_iterator x, redecl_iterator y) { |
288 | return x.Current == y.Current; |
289 | } |
290 | friend bool operator!=(redecl_iterator x, redecl_iterator y) { |
291 | return x.Current != y.Current; |
292 | } |
293 | }; |
294 | |
295 | using redecl_range = llvm::iterator_range<redecl_iterator>; |
296 | |
297 | /// \brief Returns an iterator range for all the redeclarations of the same |
298 | /// decl. It will iterate at least once (when this decl is the only one). |
299 | redecl_range redecls() const { |
300 | return redecl_range(redecl_iterator(const_cast<decl_type *>( |
301 | static_cast<const decl_type *>(this))), |
302 | redecl_iterator()); |
303 | } |
304 | |
305 | redecl_iterator redecls_begin() const { return redecls().begin(); } |
306 | redecl_iterator redecls_end() const { return redecls().end(); } |
307 | }; |
308 | |
309 | /// \brief Get the primary declaration for a declaration from an AST file. That |
310 | /// will be the first-loaded declaration. |
311 | Decl *getPrimaryMergedDecl(Decl *D); |
312 | |
313 | /// \brief Provides common interface for the Decls that cannot be redeclared, |
314 | /// but can be merged if the same declaration is brought in from multiple |
315 | /// modules. |
316 | template<typename decl_type> |
317 | class Mergeable { |
318 | public: |
319 | Mergeable() = default; |
320 | |
321 | /// \brief Return the first declaration of this declaration or itself if this |
322 | /// is the only declaration. |
323 | decl_type *getFirstDecl() { |
324 | decl_type *D = static_cast<decl_type*>(this); |
325 | if (!D->isFromASTFile()) |
326 | return D; |
327 | return cast<decl_type>(getPrimaryMergedDecl(const_cast<decl_type*>(D))); |
328 | } |
329 | |
330 | /// \brief Return the first declaration of this declaration or itself if this |
331 | /// is the only declaration. |
332 | const decl_type *getFirstDecl() const { |
333 | const decl_type *D = static_cast<const decl_type*>(this); |
334 | if (!D->isFromASTFile()) |
335 | return D; |
336 | return cast<decl_type>(getPrimaryMergedDecl(const_cast<decl_type*>(D))); |
337 | } |
338 | |
339 | /// \brief Returns true if this is the first declaration. |
340 | bool isFirstDecl() const { return getFirstDecl() == this; } |
341 | }; |
342 | |
343 | /// A wrapper class around a pointer that always points to its canonical |
344 | /// declaration. |
345 | /// |
346 | /// CanonicalDeclPtr<decl_type> behaves just like decl_type*, except we call |
347 | /// decl_type::getCanonicalDecl() on construction. |
348 | /// |
349 | /// This is useful for hashtables that you want to be keyed on a declaration's |
350 | /// canonical decl -- if you use CanonicalDeclPtr as the key, you don't need to |
351 | /// remember to call getCanonicalDecl() everywhere. |
352 | template <typename decl_type> class CanonicalDeclPtr { |
353 | public: |
354 | CanonicalDeclPtr() = default; |
355 | CanonicalDeclPtr(decl_type *Ptr) |
356 | : Ptr(Ptr ? Ptr->getCanonicalDecl() : nullptr) {} |
357 | CanonicalDeclPtr(const CanonicalDeclPtr &) = default; |
358 | CanonicalDeclPtr &operator=(const CanonicalDeclPtr &) = default; |
359 | |
360 | operator decl_type *() { return Ptr; } |
361 | operator const decl_type *() const { return Ptr; } |
362 | |
363 | decl_type *operator->() { return Ptr; } |
364 | const decl_type *operator->() const { return Ptr; } |
365 | |
366 | decl_type &operator*() { return *Ptr; } |
367 | const decl_type &operator*() const { return *Ptr; } |
368 | |
369 | private: |
370 | friend struct llvm::DenseMapInfo<CanonicalDeclPtr<decl_type>>; |
371 | |
372 | decl_type *Ptr = nullptr; |
373 | }; |
374 | |
375 | } // namespace clang |
376 | |
377 | namespace llvm { |
378 | |
379 | template <typename decl_type> |
380 | struct DenseMapInfo<clang::CanonicalDeclPtr<decl_type>> { |
381 | using CanonicalDeclPtr = clang::CanonicalDeclPtr<decl_type>; |
382 | using BaseInfo = DenseMapInfo<decl_type *>; |
383 | |
384 | static CanonicalDeclPtr getEmptyKey() { |
385 | // Construct our CanonicalDeclPtr this way because the regular constructor |
386 | // would dereference P.Ptr, which is not allowed. |
387 | CanonicalDeclPtr P; |
388 | P.Ptr = BaseInfo::getEmptyKey(); |
389 | return P; |
390 | } |
391 | |
392 | static CanonicalDeclPtr getTombstoneKey() { |
393 | CanonicalDeclPtr P; |
394 | P.Ptr = BaseInfo::getTombstoneKey(); |
395 | return P; |
396 | } |
397 | |
398 | static unsigned getHashValue(const CanonicalDeclPtr &P) { |
399 | return BaseInfo::getHashValue(P); |
400 | } |
401 | |
402 | static bool isEqual(const CanonicalDeclPtr &LHS, |
403 | const CanonicalDeclPtr &RHS) { |
404 | return BaseInfo::isEqual(LHS, RHS); |
405 | } |
406 | }; |
407 | |
408 | } // namespace llvm |
409 | |
410 | #endif // LLVM_CLANG_AST_REDECLARABLE_H |
1 | //===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- 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 defines the PointerUnion class, which is a discriminated union of |
11 | // pointer types. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_ADT_POINTERUNION_H |
16 | #define LLVM_ADT_POINTERUNION_H |
17 | |
18 | #include "llvm/ADT/DenseMapInfo.h" |
19 | #include "llvm/ADT/PointerIntPair.h" |
20 | #include "llvm/Support/PointerLikeTypeTraits.h" |
21 | #include <cassert> |
22 | #include <cstddef> |
23 | #include <cstdint> |
24 | |
25 | namespace llvm { |
26 | |
27 | template <typename T> struct PointerUnionTypeSelectorReturn { |
28 | using Return = T; |
29 | }; |
30 | |
31 | /// Get a type based on whether two types are the same or not. |
32 | /// |
33 | /// For: |
34 | /// |
35 | /// \code |
36 | /// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return; |
37 | /// \endcode |
38 | /// |
39 | /// Ret will be EQ type if T1 is same as T2 or NE type otherwise. |
40 | template <typename T1, typename T2, typename RET_EQ, typename RET_NE> |
41 | struct PointerUnionTypeSelector { |
42 | using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return; |
43 | }; |
44 | |
45 | template <typename T, typename RET_EQ, typename RET_NE> |
46 | struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> { |
47 | using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return; |
48 | }; |
49 | |
50 | template <typename T1, typename T2, typename RET_EQ, typename RET_NE> |
51 | struct PointerUnionTypeSelectorReturn< |
52 | PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> { |
53 | using Return = |
54 | typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return; |
55 | }; |
56 | |
57 | /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion |
58 | /// for the two template arguments. |
59 | template <typename PT1, typename PT2> class PointerUnionUIntTraits { |
60 | public: |
61 | static inline void *getAsVoidPointer(void *P) { return P; } |
62 | static inline void *getFromVoidPointer(void *P) { return P; } |
63 | |
64 | enum { |
65 | PT1BitsAv = (int)(PointerLikeTypeTraits<PT1>::NumLowBitsAvailable), |
66 | PT2BitsAv = (int)(PointerLikeTypeTraits<PT2>::NumLowBitsAvailable), |
67 | NumLowBitsAvailable = PT1BitsAv < PT2BitsAv ? PT1BitsAv : PT2BitsAv |
68 | }; |
69 | }; |
70 | |
71 | /// A discriminated union of two pointer types, with the discriminator in the |
72 | /// low bit of the pointer. |
73 | /// |
74 | /// This implementation is extremely efficient in space due to leveraging the |
75 | /// low bits of the pointer, while exposing a natural and type-safe API. |
76 | /// |
77 | /// Common use patterns would be something like this: |
78 | /// PointerUnion<int*, float*> P; |
79 | /// P = (int*)0; |
80 | /// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0" |
81 | /// X = P.get<int*>(); // ok. |
82 | /// Y = P.get<float*>(); // runtime assertion failure. |
83 | /// Z = P.get<double*>(); // compile time failure. |
84 | /// P = (float*)0; |
85 | /// Y = P.get<float*>(); // ok. |
86 | /// X = P.get<int*>(); // runtime assertion failure. |
87 | template <typename PT1, typename PT2> class PointerUnion { |
88 | public: |
89 | using ValTy = |
90 | PointerIntPair<void *, 1, bool, PointerUnionUIntTraits<PT1, PT2>>; |
91 | |
92 | private: |
93 | ValTy Val; |
94 | |
95 | struct IsPT1 { |
96 | static const int Num = 0; |
97 | }; |
98 | struct IsPT2 { |
99 | static const int Num = 1; |
100 | }; |
101 | template <typename T> struct UNION_DOESNT_CONTAIN_TYPE {}; |
102 | |
103 | public: |
104 | PointerUnion() = default; |
105 | PointerUnion(PT1 V) |
106 | : Val(const_cast<void *>( |
107 | PointerLikeTypeTraits<PT1>::getAsVoidPointer(V))) {} |
108 | PointerUnion(PT2 V) |
109 | : Val(const_cast<void *>(PointerLikeTypeTraits<PT2>::getAsVoidPointer(V)), |
110 | 1) {} |
111 | |
112 | /// Test if the pointer held in the union is null, regardless of |
113 | /// which type it is. |
114 | bool isNull() const { |
115 | // Convert from the void* to one of the pointer types, to make sure that |
116 | // we recursively strip off low bits if we have a nested PointerUnion. |
117 | return !PointerLikeTypeTraits<PT1>::getFromVoidPointer(Val.getPointer()); |
118 | } |
119 | |
120 | explicit operator bool() const { return !isNull(); } |
121 | |
122 | /// Test if the Union currently holds the type matching T. |
123 | template <typename T> int is() const { |
124 | using Ty = typename ::llvm::PointerUnionTypeSelector< |
125 | PT1, T, IsPT1, |
126 | ::llvm::PointerUnionTypeSelector<PT2, T, IsPT2, |
127 | UNION_DOESNT_CONTAIN_TYPE<T>>>::Return; |
128 | int TyNo = Ty::Num; |
129 | return static_cast<int>(Val.getInt()) == TyNo; |
130 | } |
131 | |
132 | /// Returns the value of the specified pointer type. |
133 | /// |
134 | /// If the specified pointer type is incorrect, assert. |
135 | template <typename T> T get() const { |
136 | assert(is<T>() && "Invalid accessor called")(static_cast <bool> (is<T>() && "Invalid accessor called" ) ? void (0) : __assert_fail ("is<T>() && \"Invalid accessor called\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 136, __extension__ __PRETTY_FUNCTION__)); |
137 | return PointerLikeTypeTraits<T>::getFromVoidPointer(Val.getPointer()); |
138 | } |
139 | |
140 | /// Returns the current pointer if it is of the specified pointer type, |
141 | /// otherwises returns null. |
142 | template <typename T> T dyn_cast() const { |
143 | if (is<T>()) |
144 | return get<T>(); |
145 | return T(); |
146 | } |
147 | |
148 | /// If the union is set to the first pointer type get an address pointing to |
149 | /// it. |
150 | PT1 const *getAddrOfPtr1() const { |
151 | return const_cast<PointerUnion *>(this)->getAddrOfPtr1(); |
152 | } |
153 | |
154 | /// If the union is set to the first pointer type get an address pointing to |
155 | /// it. |
156 | PT1 *getAddrOfPtr1() { |
157 | assert(is<PT1>() && "Val is not the first pointer")(static_cast <bool> (is<PT1>() && "Val is not the first pointer" ) ? void (0) : __assert_fail ("is<PT1>() && \"Val is not the first pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 157, __extension__ __PRETTY_FUNCTION__)); |
158 | assert((static_cast <bool> (get<PT1>() == Val.getPointer () && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? void (0) : __assert_fail ("get<PT1>() == Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 160, __extension__ __PRETTY_FUNCTION__)) |
159 | get<PT1>() == Val.getPointer() &&(static_cast <bool> (get<PT1>() == Val.getPointer () && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? void (0) : __assert_fail ("get<PT1>() == Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 160, __extension__ __PRETTY_FUNCTION__)) |
160 | "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast <bool> (get<PT1>() == Val.getPointer () && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? void (0) : __assert_fail ("get<PT1>() == Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 160, __extension__ __PRETTY_FUNCTION__)); |
161 | return const_cast<PT1 *>( |
162 | reinterpret_cast<const PT1 *>(Val.getAddrOfPointer())); |
163 | } |
164 | |
165 | /// Assignment from nullptr which just clears the union. |
166 | const PointerUnion &operator=(std::nullptr_t) { |
167 | Val.initWithPointer(nullptr); |
168 | return *this; |
169 | } |
170 | |
171 | /// Assignment operators - Allow assigning into this union from either |
172 | /// pointer type, setting the discriminator to remember what it came from. |
173 | const PointerUnion &operator=(const PT1 &RHS) { |
174 | Val.initWithPointer( |
175 | const_cast<void *>(PointerLikeTypeTraits<PT1>::getAsVoidPointer(RHS))); |
176 | return *this; |
177 | } |
178 | const PointerUnion &operator=(const PT2 &RHS) { |
179 | Val.setPointerAndInt( |
180 | const_cast<void *>(PointerLikeTypeTraits<PT2>::getAsVoidPointer(RHS)), |
181 | 1); |
182 | return *this; |
183 | } |
184 | |
185 | void *getOpaqueValue() const { return Val.getOpaqueValue(); } |
186 | static inline PointerUnion getFromOpaqueValue(void *VP) { |
187 | PointerUnion V; |
188 | V.Val = ValTy::getFromOpaqueValue(VP); |
189 | return V; |
190 | } |
191 | }; |
192 | |
193 | template <typename PT1, typename PT2> |
194 | bool operator==(PointerUnion<PT1, PT2> lhs, PointerUnion<PT1, PT2> rhs) { |
195 | return lhs.getOpaqueValue() == rhs.getOpaqueValue(); |
196 | } |
197 | |
198 | template <typename PT1, typename PT2> |
199 | bool operator!=(PointerUnion<PT1, PT2> lhs, PointerUnion<PT1, PT2> rhs) { |
200 | return lhs.getOpaqueValue() != rhs.getOpaqueValue(); |
201 | } |
202 | |
203 | template <typename PT1, typename PT2> |
204 | bool operator<(PointerUnion<PT1, PT2> lhs, PointerUnion<PT1, PT2> rhs) { |
205 | return lhs.getOpaqueValue() < rhs.getOpaqueValue(); |
206 | } |
207 | |
208 | // Teach SmallPtrSet that PointerUnion is "basically a pointer", that has |
209 | // # low bits available = min(PT1bits,PT2bits)-1. |
210 | template <typename PT1, typename PT2> |
211 | struct PointerLikeTypeTraits<PointerUnion<PT1, PT2>> { |
212 | static inline void *getAsVoidPointer(const PointerUnion<PT1, PT2> &P) { |
213 | return P.getOpaqueValue(); |
214 | } |
215 | |
216 | static inline PointerUnion<PT1, PT2> getFromVoidPointer(void *P) { |
217 | return PointerUnion<PT1, PT2>::getFromOpaqueValue(P); |
218 | } |
219 | |
220 | // The number of bits available are the min of the two pointer types. |
221 | enum { |
222 | NumLowBitsAvailable = PointerLikeTypeTraits< |
223 | typename PointerUnion<PT1, PT2>::ValTy>::NumLowBitsAvailable |
224 | }; |
225 | }; |
226 | |
227 | /// A pointer union of three pointer types. See documentation for PointerUnion |
228 | /// for usage. |
229 | template <typename PT1, typename PT2, typename PT3> class PointerUnion3 { |
230 | public: |
231 | using InnerUnion = PointerUnion<PT1, PT2>; |
232 | using ValTy = PointerUnion<InnerUnion, PT3>; |
233 | |
234 | private: |
235 | ValTy Val; |
236 | |
237 | struct IsInnerUnion { |
238 | ValTy Val; |
239 | |
240 | IsInnerUnion(ValTy val) : Val(val) {} |
241 | |
242 | template <typename T> int is() const { |
243 | return Val.template is<InnerUnion>() && |
244 | Val.template get<InnerUnion>().template is<T>(); |
245 | } |
246 | |
247 | template <typename T> T get() const { |
248 | return Val.template get<InnerUnion>().template get<T>(); |
249 | } |
250 | }; |
251 | |
252 | struct IsPT3 { |
253 | ValTy Val; |
254 | |
255 | IsPT3(ValTy val) : Val(val) {} |
256 | |
257 | template <typename T> int is() const { return Val.template is<T>(); } |
258 | template <typename T> T get() const { return Val.template get<T>(); } |
259 | }; |
260 | |
261 | public: |
262 | PointerUnion3() = default; |
263 | PointerUnion3(PT1 V) { Val = InnerUnion(V); } |
264 | PointerUnion3(PT2 V) { Val = InnerUnion(V); } |
265 | PointerUnion3(PT3 V) { Val = V; } |
266 | |
267 | /// Test if the pointer held in the union is null, regardless of |
268 | /// which type it is. |
269 | bool isNull() const { return Val.isNull(); } |
270 | explicit operator bool() const { return !isNull(); } |
271 | |
272 | /// Test if the Union currently holds the type matching T. |
273 | template <typename T> int is() const { |
274 | // If T is PT1/PT2 choose IsInnerUnion otherwise choose IsPT3. |
275 | using Ty = typename ::llvm::PointerUnionTypeSelector< |
276 | PT1, T, IsInnerUnion, |
277 | ::llvm::PointerUnionTypeSelector<PT2, T, IsInnerUnion, IsPT3>>::Return; |
278 | return Ty(Val).template is<T>(); |
279 | } |
280 | |
281 | /// Returns the value of the specified pointer type. |
282 | /// |
283 | /// If the specified pointer type is incorrect, assert. |
284 | template <typename T> T get() const { |
285 | assert(is<T>() && "Invalid accessor called")(static_cast <bool> (is<T>() && "Invalid accessor called" ) ? void (0) : __assert_fail ("is<T>() && \"Invalid accessor called\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 285, __extension__ __PRETTY_FUNCTION__)); |
286 | // If T is PT1/PT2 choose IsInnerUnion otherwise choose IsPT3. |
287 | using Ty = typename ::llvm::PointerUnionTypeSelector< |
288 | PT1, T, IsInnerUnion, |
289 | ::llvm::PointerUnionTypeSelector<PT2, T, IsInnerUnion, IsPT3>>::Return; |
290 | return Ty(Val).template get<T>(); |
291 | } |
292 | |
293 | /// Returns the current pointer if it is of the specified pointer type, |
294 | /// otherwises returns null. |
295 | template <typename T> T dyn_cast() const { |
296 | if (is<T>()) |
297 | return get<T>(); |
298 | return T(); |
299 | } |
300 | |
301 | /// Assignment from nullptr which just clears the union. |
302 | const PointerUnion3 &operator=(std::nullptr_t) { |
303 | Val = nullptr; |
304 | return *this; |
305 | } |
306 | |
307 | /// Assignment operators - Allow assigning into this union from either |
308 | /// pointer type, setting the discriminator to remember what it came from. |
309 | const PointerUnion3 &operator=(const PT1 &RHS) { |
310 | Val = InnerUnion(RHS); |
311 | return *this; |
312 | } |
313 | const PointerUnion3 &operator=(const PT2 &RHS) { |
314 | Val = InnerUnion(RHS); |
315 | return *this; |
316 | } |
317 | const PointerUnion3 &operator=(const PT3 &RHS) { |
318 | Val = RHS; |
319 | return *this; |
320 | } |
321 | |
322 | void *getOpaqueValue() const { return Val.getOpaqueValue(); } |
323 | static inline PointerUnion3 getFromOpaqueValue(void *VP) { |
324 | PointerUnion3 V; |
325 | V.Val = ValTy::getFromOpaqueValue(VP); |
326 | return V; |
327 | } |
328 | }; |
329 | |
330 | // Teach SmallPtrSet that PointerUnion3 is "basically a pointer", that has |
331 | // # low bits available = min(PT1bits,PT2bits,PT2bits)-2. |
332 | template <typename PT1, typename PT2, typename PT3> |
333 | struct PointerLikeTypeTraits<PointerUnion3<PT1, PT2, PT3>> { |
334 | static inline void *getAsVoidPointer(const PointerUnion3<PT1, PT2, PT3> &P) { |
335 | return P.getOpaqueValue(); |
336 | } |
337 | |
338 | static inline PointerUnion3<PT1, PT2, PT3> getFromVoidPointer(void *P) { |
339 | return PointerUnion3<PT1, PT2, PT3>::getFromOpaqueValue(P); |
340 | } |
341 | |
342 | // The number of bits available are the min of the two pointer types. |
343 | enum { |
344 | NumLowBitsAvailable = PointerLikeTypeTraits< |
345 | typename PointerUnion3<PT1, PT2, PT3>::ValTy>::NumLowBitsAvailable |
346 | }; |
347 | }; |
348 | |
349 | /// A pointer union of four pointer types. See documentation for PointerUnion |
350 | /// for usage. |
351 | template <typename PT1, typename PT2, typename PT3, typename PT4> |
352 | class PointerUnion4 { |
353 | public: |
354 | using InnerUnion1 = PointerUnion<PT1, PT2>; |
355 | using InnerUnion2 = PointerUnion<PT3, PT4>; |
356 | using ValTy = PointerUnion<InnerUnion1, InnerUnion2>; |
357 | |
358 | private: |
359 | ValTy Val; |
360 | |
361 | public: |
362 | PointerUnion4() = default; |
363 | PointerUnion4(PT1 V) { Val = InnerUnion1(V); } |
364 | PointerUnion4(PT2 V) { Val = InnerUnion1(V); } |
365 | PointerUnion4(PT3 V) { Val = InnerUnion2(V); } |
366 | PointerUnion4(PT4 V) { Val = InnerUnion2(V); } |
367 | |
368 | /// Test if the pointer held in the union is null, regardless of |
369 | /// which type it is. |
370 | bool isNull() const { return Val.isNull(); } |
371 | explicit operator bool() const { return !isNull(); } |
372 | |
373 | /// Test if the Union currently holds the type matching T. |
374 | template <typename T> int is() const { |
375 | // If T is PT1/PT2 choose InnerUnion1 otherwise choose InnerUnion2. |
376 | using Ty = typename ::llvm::PointerUnionTypeSelector< |
377 | PT1, T, InnerUnion1, |
378 | ::llvm::PointerUnionTypeSelector<PT2, T, InnerUnion1, |
379 | InnerUnion2>>::Return; |
380 | return Val.template is<Ty>() && Val.template get<Ty>().template is<T>(); |
381 | } |
382 | |
383 | /// Returns the value of the specified pointer type. |
384 | /// |
385 | /// If the specified pointer type is incorrect, assert. |
386 | template <typename T> T get() const { |
387 | assert(is<T>() && "Invalid accessor called")(static_cast <bool> (is<T>() && "Invalid accessor called" ) ? void (0) : __assert_fail ("is<T>() && \"Invalid accessor called\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerUnion.h" , 387, __extension__ __PRETTY_FUNCTION__)); |
388 | // If T is PT1/PT2 choose InnerUnion1 otherwise choose InnerUnion2. |
389 | using Ty = typename ::llvm::PointerUnionTypeSelector< |
390 | PT1, T, InnerUnion1, |
391 | ::llvm::PointerUnionTypeSelector<PT2, T, InnerUnion1, |
392 | InnerUnion2>>::Return; |
393 | return Val.template get<Ty>().template get<T>(); |
394 | } |
395 | |
396 | /// Returns the current pointer if it is of the specified pointer type, |
397 | /// otherwises returns null. |
398 | template <typename T> T dyn_cast() const { |
399 | if (is<T>()) |
400 | return get<T>(); |
401 | return T(); |
402 | } |
403 | |
404 | /// Assignment from nullptr which just clears the union. |
405 | const PointerUnion4 &operator=(std::nullptr_t) { |
406 | Val = nullptr; |
407 | return *this; |
408 | } |
409 | |
410 | /// Assignment operators - Allow assigning into this union from either |
411 | /// pointer type, setting the discriminator to remember what it came from. |
412 | const PointerUnion4 &operator=(const PT1 &RHS) { |
413 | Val = InnerUnion1(RHS); |
414 | return *this; |
415 | } |
416 | const PointerUnion4 &operator=(const PT2 &RHS) { |
417 | Val = InnerUnion1(RHS); |
418 | return *this; |
419 | } |
420 | const PointerUnion4 &operator=(const PT3 &RHS) { |
421 | Val = InnerUnion2(RHS); |
422 | return *this; |
423 | } |
424 | const PointerUnion4 &operator=(const PT4 &RHS) { |
425 | Val = InnerUnion2(RHS); |
426 | return *this; |
427 | } |
428 | |
429 | void *getOpaqueValue() const { return Val.getOpaqueValue(); } |
430 | static inline PointerUnion4 getFromOpaqueValue(void *VP) { |
431 | PointerUnion4 V; |
432 | V.Val = ValTy::getFromOpaqueValue(VP); |
433 | return V; |
434 | } |
435 | }; |
436 | |
437 | // Teach SmallPtrSet that PointerUnion4 is "basically a pointer", that has |
438 | // # low bits available = min(PT1bits,PT2bits,PT2bits)-2. |
439 | template <typename PT1, typename PT2, typename PT3, typename PT4> |
440 | struct PointerLikeTypeTraits<PointerUnion4<PT1, PT2, PT3, PT4>> { |
441 | static inline void * |
442 | getAsVoidPointer(const PointerUnion4<PT1, PT2, PT3, PT4> &P) { |
443 | return P.getOpaqueValue(); |
444 | } |
445 | |
446 | static inline PointerUnion4<PT1, PT2, PT3, PT4> getFromVoidPointer(void *P) { |
447 | return PointerUnion4<PT1, PT2, PT3, PT4>::getFromOpaqueValue(P); |
448 | } |
449 | |
450 | // The number of bits available are the min of the two pointer types. |
451 | enum { |
452 | NumLowBitsAvailable = PointerLikeTypeTraits< |
453 | typename PointerUnion4<PT1, PT2, PT3, PT4>::ValTy>::NumLowBitsAvailable |
454 | }; |
455 | }; |
456 | |
457 | // Teach DenseMap how to use PointerUnions as keys. |
458 | template <typename T, typename U> struct DenseMapInfo<PointerUnion<T, U>> { |
459 | using Pair = PointerUnion<T, U>; |
460 | using FirstInfo = DenseMapInfo<T>; |
461 | using SecondInfo = DenseMapInfo<U>; |
462 | |
463 | static inline Pair getEmptyKey() { return Pair(FirstInfo::getEmptyKey()); } |
464 | |
465 | static inline Pair getTombstoneKey() { |
466 | return Pair(FirstInfo::getTombstoneKey()); |
467 | } |
468 | |
469 | static unsigned getHashValue(const Pair &PairVal) { |
470 | intptr_t key = (intptr_t)PairVal.getOpaqueValue(); |
471 | return DenseMapInfo<intptr_t>::getHashValue(key); |
472 | } |
473 | |
474 | static bool isEqual(const Pair &LHS, const Pair &RHS) { |
475 | return LHS.template is<T>() == RHS.template is<T>() && |
476 | (LHS.template is<T>() ? FirstInfo::isEqual(LHS.template get<T>(), |
477 | RHS.template get<T>()) |
478 | : SecondInfo::isEqual(LHS.template get<U>(), |
479 | RHS.template get<U>())); |
480 | } |
481 | }; |
482 | |
483 | } // end namespace llvm |
484 | |
485 | #endif // LLVM_ADT_POINTERUNION_H |
1 | //===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- 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 defines the PointerIntPair class. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_ADT_POINTERINTPAIR_H |
15 | #define LLVM_ADT_POINTERINTPAIR_H |
16 | |
17 | #include "llvm/Support/PointerLikeTypeTraits.h" |
18 | #include <cassert> |
19 | #include <cstdint> |
20 | #include <limits> |
21 | |
22 | namespace llvm { |
23 | |
24 | template <typename T> struct DenseMapInfo; |
25 | template <typename PointerT, unsigned IntBits, typename PtrTraits> |
26 | struct PointerIntPairInfo; |
27 | |
28 | /// PointerIntPair - This class implements a pair of a pointer and small |
29 | /// integer. It is designed to represent this in the space required by one |
30 | /// pointer by bitmangling the integer into the low part of the pointer. This |
31 | /// can only be done for small integers: typically up to 3 bits, but it depends |
32 | /// on the number of bits available according to PointerLikeTypeTraits for the |
33 | /// type. |
34 | /// |
35 | /// Note that PointerIntPair always puts the IntVal part in the highest bits |
36 | /// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for |
37 | /// the bool into bit #2, not bit #0, which allows the low two bits to be used |
38 | /// for something else. For example, this allows: |
39 | /// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool> |
40 | /// ... and the two bools will land in different bits. |
41 | template <typename PointerTy, unsigned IntBits, typename IntType = unsigned, |
42 | typename PtrTraits = PointerLikeTypeTraits<PointerTy>, |
43 | typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>> |
44 | class PointerIntPair { |
45 | intptr_t Value = 0; |
46 | |
47 | public: |
48 | constexpr PointerIntPair() = default; |
49 | |
50 | PointerIntPair(PointerTy PtrVal, IntType IntVal) { |
51 | setPointerAndInt(PtrVal, IntVal); |
52 | } |
53 | |
54 | explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); } |
55 | |
56 | PointerTy getPointer() const { return Info::getPointer(Value); } |
57 | |
58 | IntType getInt() const { return (IntType)Info::getInt(Value); } |
59 | |
60 | void setPointer(PointerTy PtrVal) { |
61 | Value = Info::updatePointer(Value, PtrVal); |
62 | } |
63 | |
64 | void setInt(IntType IntVal) { |
65 | Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal)); |
66 | } |
67 | |
68 | void initWithPointer(PointerTy PtrVal) { |
69 | Value = Info::updatePointer(0, PtrVal); |
70 | } |
71 | |
72 | void setPointerAndInt(PointerTy PtrVal, IntType IntVal) { |
73 | Value = Info::updateInt(Info::updatePointer(0, PtrVal), |
74 | static_cast<intptr_t>(IntVal)); |
75 | } |
76 | |
77 | PointerTy const *getAddrOfPointer() const { |
78 | return const_cast<PointerIntPair *>(this)->getAddrOfPointer(); |
79 | } |
80 | |
81 | PointerTy *getAddrOfPointer() { |
82 | assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&(static_cast <bool> (Value == reinterpret_cast<intptr_t >(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer") ? void (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerIntPair.h" , 84, __extension__ __PRETTY_FUNCTION__)) |
83 | "Can only return the address if IntBits is cleared and "(static_cast <bool> (Value == reinterpret_cast<intptr_t >(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer") ? void (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerIntPair.h" , 84, __extension__ __PRETTY_FUNCTION__)) |
84 | "PtrTraits doesn't change the pointer")(static_cast <bool> (Value == reinterpret_cast<intptr_t >(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer") ? void (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerIntPair.h" , 84, __extension__ __PRETTY_FUNCTION__)); |
85 | return reinterpret_cast<PointerTy *>(&Value); |
86 | } |
87 | |
88 | void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); } |
89 | |
90 | void setFromOpaqueValue(void *Val) { |
91 | Value = reinterpret_cast<intptr_t>(Val); |
92 | } |
93 | |
94 | static PointerIntPair getFromOpaqueValue(void *V) { |
95 | PointerIntPair P; |
96 | P.setFromOpaqueValue(V); |
97 | return P; |
98 | } |
99 | |
100 | // Allow PointerIntPairs to be created from const void * if and only if the |
101 | // pointer type could be created from a const void *. |
102 | static PointerIntPair getFromOpaqueValue(const void *V) { |
103 | (void)PtrTraits::getFromVoidPointer(V); |
104 | return getFromOpaqueValue(const_cast<void *>(V)); |
105 | } |
106 | |
107 | bool operator==(const PointerIntPair &RHS) const { |
108 | return Value == RHS.Value; |
109 | } |
110 | |
111 | bool operator!=(const PointerIntPair &RHS) const { |
112 | return Value != RHS.Value; |
113 | } |
114 | |
115 | bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; } |
116 | bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; } |
117 | |
118 | bool operator<=(const PointerIntPair &RHS) const { |
119 | return Value <= RHS.Value; |
120 | } |
121 | |
122 | bool operator>=(const PointerIntPair &RHS) const { |
123 | return Value >= RHS.Value; |
124 | } |
125 | }; |
126 | |
127 | template <typename PointerT, unsigned IntBits, typename PtrTraits> |
128 | struct PointerIntPairInfo { |
129 | static_assert(PtrTraits::NumLowBitsAvailable < |
130 | std::numeric_limits<uintptr_t>::digits, |
131 | "cannot use a pointer type that has all bits free"); |
132 | static_assert(IntBits <= PtrTraits::NumLowBitsAvailable, |
133 | "PointerIntPair with integer size too large for pointer"); |
134 | enum : uintptr_t { |
135 | /// PointerBitMask - The bits that come from the pointer. |
136 | PointerBitMask = |
137 | ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1), |
138 | |
139 | /// IntShift - The number of low bits that we reserve for other uses, and |
140 | /// keep zero. |
141 | IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits, |
142 | |
143 | /// IntMask - This is the unshifted mask for valid bits of the int type. |
144 | IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1), |
145 | |
146 | // ShiftedIntMask - This is the bits for the integer shifted in place. |
147 | ShiftedIntMask = (uintptr_t)(IntMask << IntShift) |
148 | }; |
149 | |
150 | static PointerT getPointer(intptr_t Value) { |
151 | return PtrTraits::getFromVoidPointer( |
152 | reinterpret_cast<void *>(Value & PointerBitMask)); |
153 | } |
154 | |
155 | static intptr_t getInt(intptr_t Value) { |
156 | return (Value >> IntShift) & IntMask; |
157 | } |
158 | |
159 | static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) { |
160 | intptr_t PtrWord = |
161 | reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr)); |
162 | assert((PtrWord & ~PointerBitMask) == 0 &&(static_cast <bool> ((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned") ? void ( 0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerIntPair.h" , 163, __extension__ __PRETTY_FUNCTION__)) |
163 | "Pointer is not sufficiently aligned")(static_cast <bool> ((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned") ? void ( 0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerIntPair.h" , 163, __extension__ __PRETTY_FUNCTION__)); |
164 | // Preserve all low bits, just update the pointer. |
165 | return PtrWord | (OrigValue & ~PointerBitMask); |
166 | } |
167 | |
168 | static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) { |
169 | intptr_t IntWord = static_cast<intptr_t>(Int); |
170 | assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(static_cast <bool> ((IntWord & ~IntMask) == 0 && "Integer too large for field") ? void (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/ADT/PointerIntPair.h" , 170, __extension__ __PRETTY_FUNCTION__)); |
171 | |
172 | // Preserve all bits other than the ones we are updating. |
173 | return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift; |
174 | } |
175 | }; |
176 | |
177 | template <typename T> struct isPodLike; |
178 | template <typename PointerTy, unsigned IntBits, typename IntType> |
179 | struct isPodLike<PointerIntPair<PointerTy, IntBits, IntType>> { |
180 | static const bool value = true; |
181 | }; |
182 | |
183 | // Provide specialization of DenseMapInfo for PointerIntPair. |
184 | template <typename PointerTy, unsigned IntBits, typename IntType> |
185 | struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> { |
186 | using Ty = PointerIntPair<PointerTy, IntBits, IntType>; |
187 | |
188 | static Ty getEmptyKey() { |
189 | uintptr_t Val = static_cast<uintptr_t>(-1); |
190 | Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable; |
191 | return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val)); |
192 | } |
193 | |
194 | static Ty getTombstoneKey() { |
195 | uintptr_t Val = static_cast<uintptr_t>(-2); |
196 | Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable; |
197 | return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val)); |
198 | } |
199 | |
200 | static unsigned getHashValue(Ty V) { |
201 | uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue()); |
202 | return unsigned(IV) ^ unsigned(IV >> 9); |
203 | } |
204 | |
205 | static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; } |
206 | }; |
207 | |
208 | // Teach SmallPtrSet that PointerIntPair is "basically a pointer". |
209 | template <typename PointerTy, unsigned IntBits, typename IntType, |
210 | typename PtrTraits> |
211 | struct PointerLikeTypeTraits< |
212 | PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> { |
213 | static inline void * |
214 | getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) { |
215 | return P.getOpaqueValue(); |
216 | } |
217 | |
218 | static inline PointerIntPair<PointerTy, IntBits, IntType> |
219 | getFromVoidPointer(void *P) { |
220 | return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P); |
221 | } |
222 | |
223 | static inline PointerIntPair<PointerTy, IntBits, IntType> |
224 | getFromVoidPointer(const void *P) { |
225 | return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P); |
226 | } |
227 | |
228 | enum { NumLowBitsAvailable = PtrTraits::NumLowBitsAvailable - IntBits }; |
229 | }; |
230 | |
231 | } // end namespace llvm |
232 | |
233 | #endif // LLVM_ADT_POINTERINTPAIR_H |
1 | //===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(), |
11 | // and dyn_cast_or_null<X>() templates. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_SUPPORT_CASTING_H |
16 | #define LLVM_SUPPORT_CASTING_H |
17 | |
18 | #include "llvm/Support/Compiler.h" |
19 | #include "llvm/Support/type_traits.h" |
20 | #include <cassert> |
21 | #include <memory> |
22 | #include <type_traits> |
23 | |
24 | namespace llvm { |
25 | |
26 | //===----------------------------------------------------------------------===// |
27 | // isa<x> Support Templates |
28 | //===----------------------------------------------------------------------===// |
29 | |
30 | // Define a template that can be specialized by smart pointers to reflect the |
31 | // fact that they are automatically dereferenced, and are not involved with the |
32 | // template selection process... the default implementation is a noop. |
33 | // |
34 | template<typename From> struct simplify_type { |
35 | using SimpleType = From; // The real type this represents... |
36 | |
37 | // An accessor to get the real value... |
38 | static SimpleType &getSimplifiedValue(From &Val) { return Val; } |
39 | }; |
40 | |
41 | template<typename From> struct simplify_type<const From> { |
42 | using NonConstSimpleType = typename simplify_type<From>::SimpleType; |
43 | using SimpleType = |
44 | typename add_const_past_pointer<NonConstSimpleType>::type; |
45 | using RetType = |
46 | typename add_lvalue_reference_if_not_pointer<SimpleType>::type; |
47 | |
48 | static RetType getSimplifiedValue(const From& Val) { |
49 | return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val)); |
50 | } |
51 | }; |
52 | |
53 | // The core of the implementation of isa<X> is here; To and From should be |
54 | // the names of classes. This template can be specialized to customize the |
55 | // implementation of isa<> without rewriting it from scratch. |
56 | template <typename To, typename From, typename Enabler = void> |
57 | struct isa_impl { |
58 | static inline bool doit(const From &Val) { |
59 | return To::classof(&Val); |
60 | } |
61 | }; |
62 | |
63 | /// \brief Always allow upcasts, and perform no dynamic check for them. |
64 | template <typename To, typename From> |
65 | struct isa_impl< |
66 | To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> { |
67 | static inline bool doit(const From &) { return true; } |
68 | }; |
69 | |
70 | template <typename To, typename From> struct isa_impl_cl { |
71 | static inline bool doit(const From &Val) { |
72 | return isa_impl<To, From>::doit(Val); |
73 | } |
74 | }; |
75 | |
76 | template <typename To, typename From> struct isa_impl_cl<To, const From> { |
77 | static inline bool doit(const From &Val) { |
78 | return isa_impl<To, From>::doit(Val); |
79 | } |
80 | }; |
81 | |
82 | template <typename To, typename From> |
83 | struct isa_impl_cl<To, const std::unique_ptr<From>> { |
84 | static inline bool doit(const std::unique_ptr<From> &Val) { |
85 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 85, __extension__ __PRETTY_FUNCTION__)); |
86 | return isa_impl_cl<To, From>::doit(*Val); |
87 | } |
88 | }; |
89 | |
90 | template <typename To, typename From> struct isa_impl_cl<To, From*> { |
91 | static inline bool doit(const From *Val) { |
92 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 92, __extension__ __PRETTY_FUNCTION__)); |
93 | return isa_impl<To, From>::doit(*Val); |
94 | } |
95 | }; |
96 | |
97 | template <typename To, typename From> struct isa_impl_cl<To, From*const> { |
98 | static inline bool doit(const From *Val) { |
99 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 99, __extension__ __PRETTY_FUNCTION__)); |
100 | return isa_impl<To, From>::doit(*Val); |
101 | } |
102 | }; |
103 | |
104 | template <typename To, typename From> struct isa_impl_cl<To, const From*> { |
105 | static inline bool doit(const From *Val) { |
106 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 106, __extension__ __PRETTY_FUNCTION__)); |
107 | return isa_impl<To, From>::doit(*Val); |
108 | } |
109 | }; |
110 | |
111 | template <typename To, typename From> struct isa_impl_cl<To, const From*const> { |
112 | static inline bool doit(const From *Val) { |
113 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 113, __extension__ __PRETTY_FUNCTION__)); |
114 | return isa_impl<To, From>::doit(*Val); |
115 | } |
116 | }; |
117 | |
118 | template<typename To, typename From, typename SimpleFrom> |
119 | struct isa_impl_wrap { |
120 | // When From != SimplifiedType, we can simplify the type some more by using |
121 | // the simplify_type template. |
122 | static bool doit(const From &Val) { |
123 | return isa_impl_wrap<To, SimpleFrom, |
124 | typename simplify_type<SimpleFrom>::SimpleType>::doit( |
125 | simplify_type<const From>::getSimplifiedValue(Val)); |
126 | } |
127 | }; |
128 | |
129 | template<typename To, typename FromTy> |
130 | struct isa_impl_wrap<To, FromTy, FromTy> { |
131 | // When From == SimpleType, we are as simple as we are going to get. |
132 | static bool doit(const FromTy &Val) { |
133 | return isa_impl_cl<To,FromTy>::doit(Val); |
134 | } |
135 | }; |
136 | |
137 | // isa<X> - Return true if the parameter to the template is an instance of the |
138 | // template type argument. Used like this: |
139 | // |
140 | // if (isa<Type>(myVal)) { ... } |
141 | // |
142 | template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) { |
143 | return isa_impl_wrap<X, const Y, |
144 | typename simplify_type<const Y>::SimpleType>::doit(Val); |
145 | } |
146 | |
147 | //===----------------------------------------------------------------------===// |
148 | // cast<x> Support Templates |
149 | //===----------------------------------------------------------------------===// |
150 | |
151 | template<class To, class From> struct cast_retty; |
152 | |
153 | // Calculate what type the 'cast' function should return, based on a requested |
154 | // type of To and a source type of From. |
155 | template<class To, class From> struct cast_retty_impl { |
156 | using ret_type = To &; // Normal case, return Ty& |
157 | }; |
158 | template<class To, class From> struct cast_retty_impl<To, const From> { |
159 | using ret_type = const To &; // Normal case, return Ty& |
160 | }; |
161 | |
162 | template<class To, class From> struct cast_retty_impl<To, From*> { |
163 | using ret_type = To *; // Pointer arg case, return Ty* |
164 | }; |
165 | |
166 | template<class To, class From> struct cast_retty_impl<To, const From*> { |
167 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
168 | }; |
169 | |
170 | template<class To, class From> struct cast_retty_impl<To, const From*const> { |
171 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
172 | }; |
173 | |
174 | template <class To, class From> |
175 | struct cast_retty_impl<To, std::unique_ptr<From>> { |
176 | private: |
177 | using PointerType = typename cast_retty_impl<To, From *>::ret_type; |
178 | using ResultType = typename std::remove_pointer<PointerType>::type; |
179 | |
180 | public: |
181 | using ret_type = std::unique_ptr<ResultType>; |
182 | }; |
183 | |
184 | template<class To, class From, class SimpleFrom> |
185 | struct cast_retty_wrap { |
186 | // When the simplified type and the from type are not the same, use the type |
187 | // simplifier to reduce the type, then reuse cast_retty_impl to get the |
188 | // resultant type. |
189 | using ret_type = typename cast_retty<To, SimpleFrom>::ret_type; |
190 | }; |
191 | |
192 | template<class To, class FromTy> |
193 | struct cast_retty_wrap<To, FromTy, FromTy> { |
194 | // When the simplified type is equal to the from type, use it directly. |
195 | using ret_type = typename cast_retty_impl<To,FromTy>::ret_type; |
196 | }; |
197 | |
198 | template<class To, class From> |
199 | struct cast_retty { |
200 | using ret_type = typename cast_retty_wrap< |
201 | To, From, typename simplify_type<From>::SimpleType>::ret_type; |
202 | }; |
203 | |
204 | // Ensure the non-simple values are converted using the simplify_type template |
205 | // that may be specialized by smart pointers... |
206 | // |
207 | template<class To, class From, class SimpleFrom> struct cast_convert_val { |
208 | // This is not a simple type, use the template to simplify it... |
209 | static typename cast_retty<To, From>::ret_type doit(From &Val) { |
210 | return cast_convert_val<To, SimpleFrom, |
211 | typename simplify_type<SimpleFrom>::SimpleType>::doit( |
212 | simplify_type<From>::getSimplifiedValue(Val)); |
213 | } |
214 | }; |
215 | |
216 | template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> { |
217 | // This _is_ a simple type, just cast it. |
218 | static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) { |
219 | typename cast_retty<To, FromTy>::ret_type Res2 |
220 | = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val); |
221 | return Res2; |
222 | } |
223 | }; |
224 | |
225 | template <class X> struct is_simple_type { |
226 | static const bool value = |
227 | std::is_same<X, typename simplify_type<X>::SimpleType>::value; |
228 | }; |
229 | |
230 | // cast<X> - Return the argument parameter cast to the specified type. This |
231 | // casting operator asserts that the type is correct, so it does not return null |
232 | // on failure. It does not allow a null argument (use cast_or_null for that). |
233 | // It is typically used like this: |
234 | // |
235 | // cast<Instruction>(myVal)->getParent() |
236 | // |
237 | template <class X, class Y> |
238 | inline typename std::enable_if<!is_simple_type<Y>::value, |
239 | typename cast_retty<X, const Y>::ret_type>::type |
240 | cast(const Y &Val) { |
241 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 241, __extension__ __PRETTY_FUNCTION__)); |
242 | return cast_convert_val< |
243 | X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val); |
244 | } |
245 | |
246 | template <class X, class Y> |
247 | inline typename cast_retty<X, Y>::ret_type cast(Y &Val) { |
248 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 248, __extension__ __PRETTY_FUNCTION__)); |
249 | return cast_convert_val<X, Y, |
250 | typename simplify_type<Y>::SimpleType>::doit(Val); |
251 | } |
252 | |
253 | template <class X, class Y> |
254 | inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) { |
255 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 255, __extension__ __PRETTY_FUNCTION__)); |
256 | return cast_convert_val<X, Y*, |
257 | typename simplify_type<Y*>::SimpleType>::doit(Val); |
258 | } |
259 | |
260 | template <class X, class Y> |
261 | inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type |
262 | cast(std::unique_ptr<Y> &&Val) { |
263 | assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!") ? void (0 ) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 263, __extension__ __PRETTY_FUNCTION__)); |
264 | using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type; |
265 | return ret_type( |
266 | cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit( |
267 | Val.release())); |
268 | } |
269 | |
270 | // cast_or_null<X> - Functionally identical to cast, except that a null value is |
271 | // accepted. |
272 | // |
273 | template <class X, class Y> |
274 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
275 | typename std::enable_if<!is_simple_type<Y>::value, |
276 | typename cast_retty<X, const Y>::ret_type>::type |
277 | cast_or_null(const Y &Val) { |
278 | if (!Val) |
279 | return nullptr; |
280 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 280, __extension__ __PRETTY_FUNCTION__)); |
281 | return cast<X>(Val); |
282 | } |
283 | |
284 | template <class X, class Y> |
285 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
286 | typename std::enable_if<!is_simple_type<Y>::value, |
287 | typename cast_retty<X, Y>::ret_type>::type |
288 | cast_or_null(Y &Val) { |
289 | if (!Val) |
290 | return nullptr; |
291 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 291, __extension__ __PRETTY_FUNCTION__)); |
292 | return cast<X>(Val); |
293 | } |
294 | |
295 | template <class X, class Y> |
296 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type |
297 | cast_or_null(Y *Val) { |
298 | if (!Val) return nullptr; |
299 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Casting.h" , 299, __extension__ __PRETTY_FUNCTION__)); |
300 | return cast<X>(Val); |
301 | } |
302 | |
303 | template <class X, class Y> |
304 | inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type |
305 | cast_or_null(std::unique_ptr<Y> &&Val) { |
306 | if (!Val) |
307 | return nullptr; |
308 | return cast<X>(std::move(Val)); |
309 | } |
310 | |
311 | // dyn_cast<X> - Return the argument parameter cast to the specified type. This |
312 | // casting operator returns null if the argument is of the wrong type, so it can |
313 | // be used to test for a type as well as cast if successful. This should be |
314 | // used in the context of an if statement like this: |
315 | // |
316 | // if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... } |
317 | // |
318 | |
319 | template <class X, class Y> |
320 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
321 | typename std::enable_if<!is_simple_type<Y>::value, |
322 | typename cast_retty<X, const Y>::ret_type>::type |
323 | dyn_cast(const Y &Val) { |
324 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
325 | } |
326 | |
327 | template <class X, class Y> |
328 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) { |
329 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
330 | } |
331 | |
332 | template <class X, class Y> |
333 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) { |
334 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
335 | } |
336 | |
337 | // dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null |
338 | // value is accepted. |
339 | // |
340 | template <class X, class Y> |
341 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
342 | typename std::enable_if<!is_simple_type<Y>::value, |
343 | typename cast_retty<X, const Y>::ret_type>::type |
344 | dyn_cast_or_null(const Y &Val) { |
345 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
346 | } |
347 | |
348 | template <class X, class Y> |
349 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
350 | typename std::enable_if<!is_simple_type<Y>::value, |
351 | typename cast_retty<X, Y>::ret_type>::type |
352 | dyn_cast_or_null(Y &Val) { |
353 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
354 | } |
355 | |
356 | template <class X, class Y> |
357 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type |
358 | dyn_cast_or_null(Y *Val) { |
359 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
360 | } |
361 | |
362 | // unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>, |
363 | // taking ownership of the input pointer iff isa<X>(Val) is true. If the |
364 | // cast is successful, From refers to nullptr on exit and the casted value |
365 | // is returned. If the cast is unsuccessful, the function returns nullptr |
366 | // and From is unchanged. |
367 | template <class X, class Y> |
368 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val) |
369 | -> decltype(cast<X>(Val)) { |
370 | if (!isa<X>(Val)) |
371 | return nullptr; |
372 | return cast<X>(std::move(Val)); |
373 | } |
374 | |
375 | template <class X, class Y> |
376 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) |
377 | -> decltype(cast<X>(Val)) { |
378 | return unique_dyn_cast<X, Y>(Val); |
379 | } |
380 | |
381 | // dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that |
382 | // a null value is accepted. |
383 | template <class X, class Y> |
384 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) |
385 | -> decltype(cast<X>(Val)) { |
386 | if (!Val) |
387 | return nullptr; |
388 | return unique_dyn_cast<X, Y>(Val); |
389 | } |
390 | |
391 | template <class X, class Y> |
392 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) |
393 | -> decltype(cast<X>(Val)) { |
394 | return unique_dyn_cast_or_null<X, Y>(Val); |
395 | } |
396 | |
397 | } // end namespace llvm |
398 | |
399 | #endif // LLVM_SUPPORT_CASTING_H |
1 | //===- Type.h - C Language Family Type Representation -----------*- 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 C Language Family Type Representation |
12 | /// |
13 | /// This file defines the clang::Type interface and subclasses, used to |
14 | /// represent types for languages in the C family. |
15 | // |
16 | //===----------------------------------------------------------------------===// |
17 | |
18 | #ifndef LLVM_CLANG_AST_TYPE_H |
19 | #define LLVM_CLANG_AST_TYPE_H |
20 | |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/TemplateName.h" |
23 | #include "clang/Basic/AddressSpaces.h" |
24 | #include "clang/Basic/Diagnostic.h" |
25 | #include "clang/Basic/ExceptionSpecificationType.h" |
26 | #include "clang/Basic/LLVM.h" |
27 | #include "clang/Basic/Linkage.h" |
28 | #include "clang/Basic/PartialDiagnostic.h" |
29 | #include "clang/Basic/SourceLocation.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Basic/Visibility.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/ADT/ArrayRef.h" |
34 | #include "llvm/ADT/FoldingSet.h" |
35 | #include "llvm/ADT/None.h" |
36 | #include "llvm/ADT/Optional.h" |
37 | #include "llvm/ADT/PointerIntPair.h" |
38 | #include "llvm/ADT/PointerUnion.h" |
39 | #include "llvm/ADT/StringRef.h" |
40 | #include "llvm/ADT/Twine.h" |
41 | #include "llvm/ADT/iterator_range.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include "llvm/Support/Compiler.h" |
44 | #include "llvm/Support/ErrorHandling.h" |
45 | #include "llvm/Support/PointerLikeTypeTraits.h" |
46 | #include "llvm/Support/type_traits.h" |
47 | #include <cassert> |
48 | #include <cstddef> |
49 | #include <cstdint> |
50 | #include <cstring> |
51 | #include <string> |
52 | #include <type_traits> |
53 | #include <utility> |
54 | |
55 | namespace clang { |
56 | |
57 | class ExtQuals; |
58 | class QualType; |
59 | class Type; |
60 | |
61 | enum { |
62 | TypeAlignmentInBits = 4, |
63 | TypeAlignment = 1 << TypeAlignmentInBits |
64 | }; |
65 | |
66 | } // namespace clang |
67 | |
68 | namespace llvm { |
69 | |
70 | template <typename T> |
71 | struct PointerLikeTypeTraits; |
72 | template<> |
73 | struct PointerLikeTypeTraits< ::clang::Type*> { |
74 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
75 | |
76 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
77 | return static_cast< ::clang::Type*>(P); |
78 | } |
79 | |
80 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
81 | }; |
82 | |
83 | template<> |
84 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
85 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
86 | |
87 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
88 | return static_cast< ::clang::ExtQuals*>(P); |
89 | } |
90 | |
91 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
92 | }; |
93 | |
94 | template <> |
95 | struct isPodLike<clang::QualType> { static const bool value = true; }; |
96 | |
97 | } // namespace llvm |
98 | |
99 | namespace clang { |
100 | |
101 | class ArrayType; |
102 | class ASTContext; |
103 | class AttributedType; |
104 | class AutoType; |
105 | class BuiltinType; |
106 | template <typename> class CanQual; |
107 | class ComplexType; |
108 | class CXXRecordDecl; |
109 | class DeclContext; |
110 | class DeducedType; |
111 | class EnumDecl; |
112 | class Expr; |
113 | class ExtQualsTypeCommonBase; |
114 | class FunctionDecl; |
115 | class FunctionNoProtoType; |
116 | class FunctionProtoType; |
117 | class IdentifierInfo; |
118 | class InjectedClassNameType; |
119 | class NamedDecl; |
120 | class ObjCInterfaceDecl; |
121 | class ObjCObjectPointerType; |
122 | class ObjCObjectType; |
123 | class ObjCProtocolDecl; |
124 | class ObjCTypeParamDecl; |
125 | class ParenType; |
126 | struct PrintingPolicy; |
127 | class RecordDecl; |
128 | class RecordType; |
129 | class Stmt; |
130 | class TagDecl; |
131 | class TemplateArgument; |
132 | class TemplateArgumentListInfo; |
133 | class TemplateArgumentLoc; |
134 | class TemplateSpecializationType; |
135 | class TemplateTypeParmDecl; |
136 | class TypedefNameDecl; |
137 | class TypedefType; |
138 | class UnresolvedUsingTypenameDecl; |
139 | |
140 | using CanQualType = CanQual<Type>; |
141 | |
142 | // Provide forward declarations for all of the *Type classes |
143 | #define TYPE(Class, Base) class Class##Type; |
144 | #include "clang/AST/TypeNodes.def" |
145 | |
146 | /// The collection of all-type qualifiers we support. |
147 | /// Clang supports five independent qualifiers: |
148 | /// * C99: const, volatile, and restrict |
149 | /// * MS: __unaligned |
150 | /// * Embedded C (TR18037): address spaces |
151 | /// * Objective C: the GC attributes (none, weak, or strong) |
152 | class Qualifiers { |
153 | public: |
154 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
155 | Const = 0x1, |
156 | Restrict = 0x2, |
157 | Volatile = 0x4, |
158 | CVRMask = Const | Volatile | Restrict |
159 | }; |
160 | |
161 | enum GC { |
162 | GCNone = 0, |
163 | Weak, |
164 | Strong |
165 | }; |
166 | |
167 | enum ObjCLifetime { |
168 | /// There is no lifetime qualification on this type. |
169 | OCL_None, |
170 | |
171 | /// This object can be modified without requiring retains or |
172 | /// releases. |
173 | OCL_ExplicitNone, |
174 | |
175 | /// Assigning into this object requires the old value to be |
176 | /// released and the new value to be retained. The timing of the |
177 | /// release of the old value is inexact: it may be moved to |
178 | /// immediately after the last known point where the value is |
179 | /// live. |
180 | OCL_Strong, |
181 | |
182 | /// Reading or writing from this object requires a barrier call. |
183 | OCL_Weak, |
184 | |
185 | /// Assigning into this object requires a lifetime extension. |
186 | OCL_Autoreleasing |
187 | }; |
188 | |
189 | enum { |
190 | /// The maximum supported address space number. |
191 | /// 23 bits should be enough for anyone. |
192 | MaxAddressSpace = 0x7fffffu, |
193 | |
194 | /// The width of the "fast" qualifier mask. |
195 | FastWidth = 3, |
196 | |
197 | /// The fast qualifier mask. |
198 | FastMask = (1 << FastWidth) - 1 |
199 | }; |
200 | |
201 | /// Returns the common set of qualifiers while removing them from |
202 | /// the given sets. |
203 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
204 | // If both are only CVR-qualified, bit operations are sufficient. |
205 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
206 | Qualifiers Q; |
207 | Q.Mask = L.Mask & R.Mask; |
208 | L.Mask &= ~Q.Mask; |
209 | R.Mask &= ~Q.Mask; |
210 | return Q; |
211 | } |
212 | |
213 | Qualifiers Q; |
214 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
215 | Q.addCVRQualifiers(CommonCRV); |
216 | L.removeCVRQualifiers(CommonCRV); |
217 | R.removeCVRQualifiers(CommonCRV); |
218 | |
219 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
220 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
221 | L.removeObjCGCAttr(); |
222 | R.removeObjCGCAttr(); |
223 | } |
224 | |
225 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
226 | Q.setObjCLifetime(L.getObjCLifetime()); |
227 | L.removeObjCLifetime(); |
228 | R.removeObjCLifetime(); |
229 | } |
230 | |
231 | if (L.getAddressSpace() == R.getAddressSpace()) { |
232 | Q.setAddressSpace(L.getAddressSpace()); |
233 | L.removeAddressSpace(); |
234 | R.removeAddressSpace(); |
235 | } |
236 | return Q; |
237 | } |
238 | |
239 | static Qualifiers fromFastMask(unsigned Mask) { |
240 | Qualifiers Qs; |
241 | Qs.addFastQualifiers(Mask); |
242 | return Qs; |
243 | } |
244 | |
245 | static Qualifiers fromCVRMask(unsigned CVR) { |
246 | Qualifiers Qs; |
247 | Qs.addCVRQualifiers(CVR); |
248 | return Qs; |
249 | } |
250 | |
251 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
252 | Qualifiers Qs; |
253 | Qs.addCVRUQualifiers(CVRU); |
254 | return Qs; |
255 | } |
256 | |
257 | // Deserialize qualifiers from an opaque representation. |
258 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
259 | Qualifiers Qs; |
260 | Qs.Mask = opaque; |
261 | return Qs; |
262 | } |
263 | |
264 | // Serialize these qualifiers into an opaque representation. |
265 | unsigned getAsOpaqueValue() const { |
266 | return Mask; |
267 | } |
268 | |
269 | bool hasConst() const { return Mask & Const; } |
270 | void setConst(bool flag) { |
271 | Mask = (Mask & ~Const) | (flag ? Const : 0); |
272 | } |
273 | void removeConst() { Mask &= ~Const; } |
274 | void addConst() { Mask |= Const; } |
275 | |
276 | bool hasVolatile() const { return Mask & Volatile; } |
277 | void setVolatile(bool flag) { |
278 | Mask = (Mask & ~Volatile) | (flag ? Volatile : 0); |
279 | } |
280 | void removeVolatile() { Mask &= ~Volatile; } |
281 | void addVolatile() { Mask |= Volatile; } |
282 | |
283 | bool hasRestrict() const { return Mask & Restrict; } |
284 | void setRestrict(bool flag) { |
285 | Mask = (Mask & ~Restrict) | (flag ? Restrict : 0); |
286 | } |
287 | void removeRestrict() { Mask &= ~Restrict; } |
288 | void addRestrict() { Mask |= Restrict; } |
289 | |
290 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
291 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
292 | void setCVRQualifiers(unsigned mask) { |
293 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 293, __extension__ __PRETTY_FUNCTION__)); |
294 | Mask = (Mask & ~CVRMask) | mask; |
295 | } |
296 | void removeCVRQualifiers(unsigned mask) { |
297 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 297, __extension__ __PRETTY_FUNCTION__)); |
298 | Mask &= ~mask; |
299 | } |
300 | void removeCVRQualifiers() { |
301 | removeCVRQualifiers(CVRMask); |
302 | } |
303 | void addCVRQualifiers(unsigned mask) { |
304 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 304, __extension__ __PRETTY_FUNCTION__)); |
305 | Mask |= mask; |
306 | } |
307 | void addCVRUQualifiers(unsigned mask) { |
308 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast <bool> (!(mask & ~CVRMask & ~UMask ) && "bitmask contains non-CVRU bits") ? void (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 308, __extension__ __PRETTY_FUNCTION__)); |
309 | Mask |= mask; |
310 | } |
311 | |
312 | bool hasUnaligned() const { return Mask & UMask; } |
313 | void setUnaligned(bool flag) { |
314 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
315 | } |
316 | void removeUnaligned() { Mask &= ~UMask; } |
317 | void addUnaligned() { Mask |= UMask; } |
318 | |
319 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
320 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
321 | void setObjCGCAttr(GC type) { |
322 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
323 | } |
324 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
325 | void addObjCGCAttr(GC type) { |
326 | assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail ( "type", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 326, __extension__ __PRETTY_FUNCTION__)); |
327 | setObjCGCAttr(type); |
328 | } |
329 | Qualifiers withoutObjCGCAttr() const { |
330 | Qualifiers qs = *this; |
331 | qs.removeObjCGCAttr(); |
332 | return qs; |
333 | } |
334 | Qualifiers withoutObjCLifetime() const { |
335 | Qualifiers qs = *this; |
336 | qs.removeObjCLifetime(); |
337 | return qs; |
338 | } |
339 | |
340 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
341 | ObjCLifetime getObjCLifetime() const { |
342 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
343 | } |
344 | void setObjCLifetime(ObjCLifetime type) { |
345 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
346 | } |
347 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
348 | void addObjCLifetime(ObjCLifetime type) { |
349 | assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail ( "type", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 349, __extension__ __PRETTY_FUNCTION__)); |
350 | assert(!hasObjCLifetime())(static_cast <bool> (!hasObjCLifetime()) ? void (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 350, __extension__ __PRETTY_FUNCTION__)); |
351 | Mask |= (type << LifetimeShift); |
352 | } |
353 | |
354 | /// True if the lifetime is neither None or ExplicitNone. |
355 | bool hasNonTrivialObjCLifetime() const { |
356 | ObjCLifetime lifetime = getObjCLifetime(); |
357 | return (lifetime > OCL_ExplicitNone); |
358 | } |
359 | |
360 | /// True if the lifetime is either strong or weak. |
361 | bool hasStrongOrWeakObjCLifetime() const { |
362 | ObjCLifetime lifetime = getObjCLifetime(); |
363 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
364 | } |
365 | |
366 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
367 | LangAS getAddressSpace() const { |
368 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
369 | } |
370 | bool hasTargetSpecificAddressSpace() const { |
371 | return isTargetAddressSpace(getAddressSpace()); |
372 | } |
373 | /// Get the address space attribute value to be printed by diagnostics. |
374 | unsigned getAddressSpaceAttributePrintValue() const { |
375 | auto Addr = getAddressSpace(); |
376 | // This function is not supposed to be used with language specific |
377 | // address spaces. If that happens, the diagnostic message should consider |
378 | // printing the QualType instead of the address space value. |
379 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())(static_cast <bool> (Addr == LangAS::Default || hasTargetSpecificAddressSpace ()) ? void (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 379, __extension__ __PRETTY_FUNCTION__)); |
380 | if (Addr != LangAS::Default) |
381 | return toTargetAddressSpace(Addr); |
382 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
383 | // since it cannot differentiate the situation where 0 denotes the default |
384 | // address space or user specified __attribute__((address_space(0))). |
385 | return 0; |
386 | } |
387 | void setAddressSpace(LangAS space) { |
388 | assert((unsigned)space <= MaxAddressSpace)(static_cast <bool> ((unsigned)space <= MaxAddressSpace ) ? void (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 388, __extension__ __PRETTY_FUNCTION__)); |
389 | Mask = (Mask & ~AddressSpaceMask) |
390 | | (((uint32_t) space) << AddressSpaceShift); |
391 | } |
392 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
393 | void addAddressSpace(LangAS space) { |
394 | assert(space != LangAS::Default)(static_cast <bool> (space != LangAS::Default) ? void ( 0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 394, __extension__ __PRETTY_FUNCTION__)); |
395 | setAddressSpace(space); |
396 | } |
397 | |
398 | // Fast qualifiers are those that can be allocated directly |
399 | // on a QualType object. |
400 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
401 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
402 | void setFastQualifiers(unsigned mask) { |
403 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 403, __extension__ __PRETTY_FUNCTION__)); |
404 | Mask = (Mask & ~FastMask) | mask; |
405 | } |
406 | void removeFastQualifiers(unsigned mask) { |
407 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 407, __extension__ __PRETTY_FUNCTION__)); |
408 | Mask &= ~mask; |
409 | } |
410 | void removeFastQualifiers() { |
411 | removeFastQualifiers(FastMask); |
412 | } |
413 | void addFastQualifiers(unsigned mask) { |
414 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 414, __extension__ __PRETTY_FUNCTION__)); |
415 | Mask |= mask; |
416 | } |
417 | |
418 | /// Return true if the set contains any qualifiers which require an ExtQuals |
419 | /// node to be allocated. |
420 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
421 | Qualifiers getNonFastQualifiers() const { |
422 | Qualifiers Quals = *this; |
423 | Quals.setFastQualifiers(0); |
424 | return Quals; |
425 | } |
426 | |
427 | /// Return true if the set contains any qualifiers. |
428 | bool hasQualifiers() const { return Mask; } |
429 | bool empty() const { return !Mask; } |
430 | |
431 | /// Add the qualifiers from the given set to this set. |
432 | void addQualifiers(Qualifiers Q) { |
433 | // If the other set doesn't have any non-boolean qualifiers, just |
434 | // bit-or it in. |
435 | if (!(Q.Mask & ~CVRMask)) |
436 | Mask |= Q.Mask; |
437 | else { |
438 | Mask |= (Q.Mask & CVRMask); |
439 | if (Q.hasAddressSpace()) |
440 | addAddressSpace(Q.getAddressSpace()); |
441 | if (Q.hasObjCGCAttr()) |
442 | addObjCGCAttr(Q.getObjCGCAttr()); |
443 | if (Q.hasObjCLifetime()) |
444 | addObjCLifetime(Q.getObjCLifetime()); |
445 | } |
446 | } |
447 | |
448 | /// \brief Remove the qualifiers from the given set from this set. |
449 | void removeQualifiers(Qualifiers Q) { |
450 | // If the other set doesn't have any non-boolean qualifiers, just |
451 | // bit-and the inverse in. |
452 | if (!(Q.Mask & ~CVRMask)) |
453 | Mask &= ~Q.Mask; |
454 | else { |
455 | Mask &= ~(Q.Mask & CVRMask); |
456 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
457 | removeObjCGCAttr(); |
458 | if (getObjCLifetime() == Q.getObjCLifetime()) |
459 | removeObjCLifetime(); |
460 | if (getAddressSpace() == Q.getAddressSpace()) |
461 | removeAddressSpace(); |
462 | } |
463 | } |
464 | |
465 | /// Add the qualifiers from the given set to this set, given that |
466 | /// they don't conflict. |
467 | void addConsistentQualifiers(Qualifiers qs) { |
468 | assert(getAddressSpace() == qs.getAddressSpace() ||(static_cast <bool> (getAddressSpace() == qs.getAddressSpace () || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 469, __extension__ __PRETTY_FUNCTION__)) |
469 | !hasAddressSpace() || !qs.hasAddressSpace())(static_cast <bool> (getAddressSpace() == qs.getAddressSpace () || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 469, __extension__ __PRETTY_FUNCTION__)); |
470 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr () || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 471, __extension__ __PRETTY_FUNCTION__)) |
471 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr () || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 471, __extension__ __PRETTY_FUNCTION__)); |
472 | assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime () || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 473, __extension__ __PRETTY_FUNCTION__)) |
473 | !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime () || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 473, __extension__ __PRETTY_FUNCTION__)); |
474 | Mask |= qs.Mask; |
475 | } |
476 | |
477 | /// Returns true if this address space is a superset of the other one. |
478 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
479 | /// overlapping address spaces. |
480 | /// CL1.1 or CL1.2: |
481 | /// every address space is a superset of itself. |
482 | /// CL2.0 adds: |
483 | /// __generic is a superset of any address space except for __constant. |
484 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
485 | return |
486 | // Address spaces must match exactly. |
487 | getAddressSpace() == other.getAddressSpace() || |
488 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
489 | // for __constant can be used as __generic. |
490 | (getAddressSpace() == LangAS::opencl_generic && |
491 | other.getAddressSpace() != LangAS::opencl_constant); |
492 | } |
493 | |
494 | /// Determines if these qualifiers compatibly include another set. |
495 | /// Generally this answers the question of whether an object with the other |
496 | /// qualifiers can be safely used as an object with these qualifiers. |
497 | bool compatiblyIncludes(Qualifiers other) const { |
498 | return isAddressSpaceSupersetOf(other) && |
499 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
500 | // be changed. |
501 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
502 | !other.hasObjCGCAttr()) && |
503 | // ObjC lifetime qualifiers must match exactly. |
504 | getObjCLifetime() == other.getObjCLifetime() && |
505 | // CVR qualifiers may subset. |
506 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
507 | // U qualifier may superset. |
508 | (!other.hasUnaligned() || hasUnaligned()); |
509 | } |
510 | |
511 | /// \brief Determines if these qualifiers compatibly include another set of |
512 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
513 | /// |
514 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
515 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
516 | /// including set also contains the 'const' qualifier, or both are non-__weak |
517 | /// and one is None (which can only happen in non-ARC modes). |
518 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
519 | if (getObjCLifetime() == other.getObjCLifetime()) |
520 | return true; |
521 | |
522 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
523 | return false; |
524 | |
525 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
526 | return true; |
527 | |
528 | return hasConst(); |
529 | } |
530 | |
531 | /// \brief Determine whether this set of qualifiers is a strict superset of |
532 | /// another set of qualifiers, not considering qualifier compatibility. |
533 | bool isStrictSupersetOf(Qualifiers Other) const; |
534 | |
535 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
536 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
537 | |
538 | explicit operator bool() const { return hasQualifiers(); } |
539 | |
540 | Qualifiers &operator+=(Qualifiers R) { |
541 | addQualifiers(R); |
542 | return *this; |
543 | } |
544 | |
545 | // Union two qualifier sets. If an enumerated qualifier appears |
546 | // in both sets, use the one from the right. |
547 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
548 | L += R; |
549 | return L; |
550 | } |
551 | |
552 | Qualifiers &operator-=(Qualifiers R) { |
553 | removeQualifiers(R); |
554 | return *this; |
555 | } |
556 | |
557 | /// \brief Compute the difference between two qualifier sets. |
558 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
559 | L -= R; |
560 | return L; |
561 | } |
562 | |
563 | std::string getAsString() const; |
564 | std::string getAsString(const PrintingPolicy &Policy) const; |
565 | |
566 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
567 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
568 | bool appendSpaceIfNonEmpty = false) const; |
569 | |
570 | void Profile(llvm::FoldingSetNodeID &ID) const { |
571 | ID.AddInteger(Mask); |
572 | } |
573 | |
574 | private: |
575 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
576 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
577 | uint32_t Mask = 0; |
578 | |
579 | static const uint32_t UMask = 0x8; |
580 | static const uint32_t UShift = 3; |
581 | static const uint32_t GCAttrMask = 0x30; |
582 | static const uint32_t GCAttrShift = 4; |
583 | static const uint32_t LifetimeMask = 0x1C0; |
584 | static const uint32_t LifetimeShift = 6; |
585 | static const uint32_t AddressSpaceMask = |
586 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
587 | static const uint32_t AddressSpaceShift = 9; |
588 | }; |
589 | |
590 | /// A std::pair-like structure for storing a qualified type split |
591 | /// into its local qualifiers and its locally-unqualified type. |
592 | struct SplitQualType { |
593 | /// The locally-unqualified type. |
594 | const Type *Ty = nullptr; |
595 | |
596 | /// The local qualifiers. |
597 | Qualifiers Quals; |
598 | |
599 | SplitQualType() = default; |
600 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
601 | |
602 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
603 | |
604 | // Make std::tie work. |
605 | std::pair<const Type *,Qualifiers> asPair() const { |
606 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
607 | } |
608 | |
609 | friend bool operator==(SplitQualType a, SplitQualType b) { |
610 | return a.Ty == b.Ty && a.Quals == b.Quals; |
611 | } |
612 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
613 | return a.Ty != b.Ty || a.Quals != b.Quals; |
614 | } |
615 | }; |
616 | |
617 | /// The kind of type we are substituting Objective-C type arguments into. |
618 | /// |
619 | /// The kind of substitution affects the replacement of type parameters when |
620 | /// no concrete type information is provided, e.g., when dealing with an |
621 | /// unspecialized type. |
622 | enum class ObjCSubstitutionContext { |
623 | /// An ordinary type. |
624 | Ordinary, |
625 | |
626 | /// The result type of a method or function. |
627 | Result, |
628 | |
629 | /// The parameter type of a method or function. |
630 | Parameter, |
631 | |
632 | /// The type of a property. |
633 | Property, |
634 | |
635 | /// The superclass of a type. |
636 | Superclass, |
637 | }; |
638 | |
639 | /// A (possibly-)qualified type. |
640 | /// |
641 | /// For efficiency, we don't store CV-qualified types as nodes on their |
642 | /// own: instead each reference to a type stores the qualifiers. This |
643 | /// greatly reduces the number of nodes we need to allocate for types (for |
644 | /// example we only need one for 'int', 'const int', 'volatile int', |
645 | /// 'const volatile int', etc). |
646 | /// |
647 | /// As an added efficiency bonus, instead of making this a pair, we |
648 | /// just store the two bits we care about in the low bits of the |
649 | /// pointer. To handle the packing/unpacking, we make QualType be a |
650 | /// simple wrapper class that acts like a smart pointer. A third bit |
651 | /// indicates whether there are extended qualifiers present, in which |
652 | /// case the pointer points to a special structure. |
653 | class QualType { |
654 | friend class QualifierCollector; |
655 | |
656 | // Thankfully, these are efficiently composable. |
657 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
658 | Qualifiers::FastWidth> Value; |
659 | |
660 | const ExtQuals *getExtQualsUnsafe() const { |
661 | return Value.getPointer().get<const ExtQuals*>(); |
662 | } |
663 | |
664 | const Type *getTypePtrUnsafe() const { |
665 | return Value.getPointer().get<const Type*>(); |
666 | } |
667 | |
668 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
669 | assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast <bool> (!isNull() && "Cannot retrieve a NULL type pointer" ) ? void (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 669, __extension__ __PRETTY_FUNCTION__)); |
670 | uintptr_t CommonPtrVal |
671 | = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
672 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
673 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
674 | } |
675 | |
676 | public: |
677 | QualType() = default; |
678 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
679 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
680 | |
681 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
682 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
683 | |
684 | /// Retrieves a pointer to the underlying (unqualified) type. |
685 | /// |
686 | /// This function requires that the type not be NULL. If the type might be |
687 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
688 | const Type *getTypePtr() const; |
689 | |
690 | const Type *getTypePtrOrNull() const; |
691 | |
692 | /// Retrieves a pointer to the name of the base type. |
693 | const IdentifierInfo *getBaseTypeIdentifier() const; |
694 | |
695 | /// Divides a QualType into its unqualified type and a set of local |
696 | /// qualifiers. |
697 | SplitQualType split() const; |
698 | |
699 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
700 | |
701 | static QualType getFromOpaquePtr(const void *Ptr) { |
702 | QualType T; |
703 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
704 | return T; |
705 | } |
706 | |
707 | const Type &operator*() const { |
708 | return *getTypePtr(); |
709 | } |
710 | |
711 | const Type *operator->() const { |
712 | return getTypePtr(); |
713 | } |
714 | |
715 | bool isCanonical() const; |
716 | bool isCanonicalAsParam() const; |
717 | |
718 | /// Return true if this QualType doesn't point to a type yet. |
719 | bool isNull() const { |
720 | return Value.getPointer().isNull(); |
721 | } |
722 | |
723 | /// \brief Determine whether this particular QualType instance has the |
724 | /// "const" qualifier set, without looking through typedefs that may have |
725 | /// added "const" at a different level. |
726 | bool isLocalConstQualified() const { |
727 | return (getLocalFastQualifiers() & Qualifiers::Const); |
728 | } |
729 | |
730 | /// \brief Determine whether this type is const-qualified. |
731 | bool isConstQualified() const; |
732 | |
733 | /// \brief Determine whether this particular QualType instance has the |
734 | /// "restrict" qualifier set, without looking through typedefs that may have |
735 | /// added "restrict" at a different level. |
736 | bool isLocalRestrictQualified() const { |
737 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
738 | } |
739 | |
740 | /// \brief Determine whether this type is restrict-qualified. |
741 | bool isRestrictQualified() const; |
742 | |
743 | /// \brief Determine whether this particular QualType instance has the |
744 | /// "volatile" qualifier set, without looking through typedefs that may have |
745 | /// added "volatile" at a different level. |
746 | bool isLocalVolatileQualified() const { |
747 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
748 | } |
749 | |
750 | /// \brief Determine whether this type is volatile-qualified. |
751 | bool isVolatileQualified() const; |
752 | |
753 | /// \brief Determine whether this particular QualType instance has any |
754 | /// qualifiers, without looking through any typedefs that might add |
755 | /// qualifiers at a different level. |
756 | bool hasLocalQualifiers() const { |
757 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
758 | } |
759 | |
760 | /// \brief Determine whether this type has any qualifiers. |
761 | bool hasQualifiers() const; |
762 | |
763 | /// \brief Determine whether this particular QualType instance has any |
764 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
765 | /// instance. |
766 | bool hasLocalNonFastQualifiers() const { |
767 | return Value.getPointer().is<const ExtQuals*>(); |
768 | } |
769 | |
770 | /// \brief Retrieve the set of qualifiers local to this particular QualType |
771 | /// instance, not including any qualifiers acquired through typedefs or |
772 | /// other sugar. |
773 | Qualifiers getLocalQualifiers() const; |
774 | |
775 | /// \brief Retrieve the set of qualifiers applied to this type. |
776 | Qualifiers getQualifiers() const; |
777 | |
778 | /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers |
779 | /// local to this particular QualType instance, not including any qualifiers |
780 | /// acquired through typedefs or other sugar. |
781 | unsigned getLocalCVRQualifiers() const { |
782 | return getLocalFastQualifiers(); |
783 | } |
784 | |
785 | /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers |
786 | /// applied to this type. |
787 | unsigned getCVRQualifiers() const; |
788 | |
789 | bool isConstant(const ASTContext& Ctx) const { |
790 | return QualType::isConstant(*this, Ctx); |
791 | } |
792 | |
793 | /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
794 | bool isPODType(const ASTContext &Context) const; |
795 | |
796 | /// Return true if this is a POD type according to the rules of the C++98 |
797 | /// standard, regardless of the current compilation's language. |
798 | bool isCXX98PODType(const ASTContext &Context) const; |
799 | |
800 | /// Return true if this is a POD type according to the more relaxed rules |
801 | /// of the C++11 standard, regardless of the current compilation's language. |
802 | /// (C++0x [basic.types]p9) |
803 | bool isCXX11PODType(const ASTContext &Context) const; |
804 | |
805 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
806 | bool isTrivialType(const ASTContext &Context) const; |
807 | |
808 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
809 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
810 | |
811 | /// Determine whether this is a class whose triviality for the purpose of |
812 | /// calls is overridden to be trivial because the class or the type of one of |
813 | /// its subobjects has attribute "trivial_abi". |
814 | bool hasTrivialABIOverride() const; |
815 | |
816 | // Don't promise in the API that anything besides 'const' can be |
817 | // easily added. |
818 | |
819 | /// Add the `const` type qualifier to this QualType. |
820 | void addConst() { |
821 | addFastQualifiers(Qualifiers::Const); |
822 | } |
823 | QualType withConst() const { |
824 | return withFastQualifiers(Qualifiers::Const); |
825 | } |
826 | |
827 | /// Add the `volatile` type qualifier to this QualType. |
828 | void addVolatile() { |
829 | addFastQualifiers(Qualifiers::Volatile); |
830 | } |
831 | QualType withVolatile() const { |
832 | return withFastQualifiers(Qualifiers::Volatile); |
833 | } |
834 | |
835 | /// Add the `restrict` qualifier to this QualType. |
836 | void addRestrict() { |
837 | addFastQualifiers(Qualifiers::Restrict); |
838 | } |
839 | QualType withRestrict() const { |
840 | return withFastQualifiers(Qualifiers::Restrict); |
841 | } |
842 | |
843 | QualType withCVRQualifiers(unsigned CVR) const { |
844 | return withFastQualifiers(CVR); |
845 | } |
846 | |
847 | void addFastQualifiers(unsigned TQs) { |
848 | assert(!(TQs & ~Qualifiers::FastMask)(static_cast <bool> (!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!") ? void (0 ) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 849, __extension__ __PRETTY_FUNCTION__)) |
849 | && "non-fast qualifier bits set in mask!")(static_cast <bool> (!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!") ? void (0 ) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 849, __extension__ __PRETTY_FUNCTION__)); |
850 | Value.setInt(Value.getInt() | TQs); |
851 | } |
852 | |
853 | void removeLocalConst(); |
854 | void removeLocalVolatile(); |
855 | void removeLocalRestrict(); |
856 | void removeLocalCVRQualifiers(unsigned Mask); |
857 | |
858 | void removeLocalFastQualifiers() { Value.setInt(0); } |
859 | void removeLocalFastQualifiers(unsigned Mask) { |
860 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast <bool> (!(Mask & ~Qualifiers::FastMask ) && "mask has non-fast qualifiers") ? void (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 860, __extension__ __PRETTY_FUNCTION__)); |
861 | Value.setInt(Value.getInt() & ~Mask); |
862 | } |
863 | |
864 | // Creates a type with the given qualifiers in addition to any |
865 | // qualifiers already on this type. |
866 | QualType withFastQualifiers(unsigned TQs) const { |
867 | QualType T = *this; |
868 | T.addFastQualifiers(TQs); |
869 | return T; |
870 | } |
871 | |
872 | // Creates a type with exactly the given fast qualifiers, removing |
873 | // any existing fast qualifiers. |
874 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
875 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
876 | } |
877 | |
878 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
879 | QualType withoutLocalFastQualifiers() const { |
880 | QualType T = *this; |
881 | T.removeLocalFastQualifiers(); |
882 | return T; |
883 | } |
884 | |
885 | QualType getCanonicalType() const; |
886 | |
887 | /// \brief Return this type with all of the instance-specific qualifiers |
888 | /// removed, but without removing any qualifiers that may have been applied |
889 | /// through typedefs. |
890 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
891 | |
892 | /// \brief Retrieve the unqualified variant of the given type, |
893 | /// removing as little sugar as possible. |
894 | /// |
895 | /// This routine looks through various kinds of sugar to find the |
896 | /// least-desugared type that is unqualified. For example, given: |
897 | /// |
898 | /// \code |
899 | /// typedef int Integer; |
900 | /// typedef const Integer CInteger; |
901 | /// typedef CInteger DifferenceType; |
902 | /// \endcode |
903 | /// |
904 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
905 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
906 | /// |
907 | /// The resulting type might still be qualified if it's sugar for an array |
908 | /// type. To strip qualifiers even from within a sugared array type, use |
909 | /// ASTContext::getUnqualifiedArrayType. |
910 | inline QualType getUnqualifiedType() const; |
911 | |
912 | /// Retrieve the unqualified variant of the given type, removing as little |
913 | /// sugar as possible. |
914 | /// |
915 | /// Like getUnqualifiedType(), but also returns the set of |
916 | /// qualifiers that were built up. |
917 | /// |
918 | /// The resulting type might still be qualified if it's sugar for an array |
919 | /// type. To strip qualifiers even from within a sugared array type, use |
920 | /// ASTContext::getUnqualifiedArrayType. |
921 | inline SplitQualType getSplitUnqualifiedType() const; |
922 | |
923 | /// \brief Determine whether this type is more qualified than the other |
924 | /// given type, requiring exact equality for non-CVR qualifiers. |
925 | bool isMoreQualifiedThan(QualType Other) const; |
926 | |
927 | /// \brief Determine whether this type is at least as qualified as the other |
928 | /// given type, requiring exact equality for non-CVR qualifiers. |
929 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
930 | |
931 | QualType getNonReferenceType() const; |
932 | |
933 | /// \brief Determine the type of a (typically non-lvalue) expression with the |
934 | /// specified result type. |
935 | /// |
936 | /// This routine should be used for expressions for which the return type is |
937 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
938 | /// an lvalue. It removes a top-level reference (since there are no |
939 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
940 | /// from non-class types (in C++) or all types (in C). |
941 | QualType getNonLValueExprType(const ASTContext &Context) const; |
942 | |
943 | /// Return the specified type with any "sugar" removed from |
944 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
945 | /// the type is already concrete, it returns it unmodified. This is similar |
946 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
947 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
948 | /// concrete. |
949 | /// |
950 | /// Qualifiers are left in place. |
951 | QualType getDesugaredType(const ASTContext &Context) const { |
952 | return getDesugaredType(*this, Context); |
953 | } |
954 | |
955 | SplitQualType getSplitDesugaredType() const { |
956 | return getSplitDesugaredType(*this); |
957 | } |
958 | |
959 | /// \brief Return the specified type with one level of "sugar" removed from |
960 | /// the type. |
961 | /// |
962 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
963 | /// of the type is already concrete, it returns it unmodified. |
964 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
965 | return getSingleStepDesugaredTypeImpl(*this, Context); |
966 | } |
967 | |
968 | /// Returns the specified type after dropping any |
969 | /// outer-level parentheses. |
970 | QualType IgnoreParens() const { |
971 | if (isa<ParenType>(*this)) |
972 | return QualType::IgnoreParens(*this); |
973 | return *this; |
974 | } |
975 | |
976 | /// Indicate whether the specified types and qualifiers are identical. |
977 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
978 | return LHS.Value == RHS.Value; |
979 | } |
980 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
981 | return LHS.Value != RHS.Value; |
982 | } |
983 | |
984 | static std::string getAsString(SplitQualType split, |
985 | const PrintingPolicy &Policy) { |
986 | return getAsString(split.Ty, split.Quals, Policy); |
987 | } |
988 | static std::string getAsString(const Type *ty, Qualifiers qs, |
989 | const PrintingPolicy &Policy); |
990 | |
991 | std::string getAsString() const; |
992 | std::string getAsString(const PrintingPolicy &Policy) const; |
993 | |
994 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
995 | const Twine &PlaceHolder = Twine(), |
996 | unsigned Indentation = 0) const { |
997 | print(split(), OS, Policy, PlaceHolder, Indentation); |
998 | } |
999 | |
1000 | static void print(SplitQualType split, raw_ostream &OS, |
1001 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1002 | unsigned Indentation = 0) { |
1003 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1004 | } |
1005 | |
1006 | static void print(const Type *ty, Qualifiers qs, |
1007 | raw_ostream &OS, const PrintingPolicy &policy, |
1008 | const Twine &PlaceHolder, |
1009 | unsigned Indentation = 0); |
1010 | |
1011 | void getAsStringInternal(std::string &Str, |
1012 | const PrintingPolicy &Policy) const { |
1013 | return getAsStringInternal(split(), Str, Policy); |
1014 | } |
1015 | |
1016 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1017 | const PrintingPolicy &policy) { |
1018 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1019 | } |
1020 | |
1021 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1022 | std::string &out, |
1023 | const PrintingPolicy &policy); |
1024 | |
1025 | class StreamedQualTypeHelper { |
1026 | const QualType &T; |
1027 | const PrintingPolicy &Policy; |
1028 | const Twine &PlaceHolder; |
1029 | unsigned Indentation; |
1030 | |
1031 | public: |
1032 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1033 | const Twine &PlaceHolder, unsigned Indentation) |
1034 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1035 | Indentation(Indentation) {} |
1036 | |
1037 | friend raw_ostream &operator<<(raw_ostream &OS, |
1038 | const StreamedQualTypeHelper &SQT) { |
1039 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1040 | return OS; |
1041 | } |
1042 | }; |
1043 | |
1044 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1045 | const Twine &PlaceHolder = Twine(), |
1046 | unsigned Indentation = 0) const { |
1047 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1048 | } |
1049 | |
1050 | void dump(const char *s) const; |
1051 | void dump() const; |
1052 | void dump(llvm::raw_ostream &OS) const; |
1053 | |
1054 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1055 | ID.AddPointer(getAsOpaquePtr()); |
1056 | } |
1057 | |
1058 | /// Return the address space of this type. |
1059 | inline LangAS getAddressSpace() const; |
1060 | |
1061 | /// Returns gc attribute of this type. |
1062 | inline Qualifiers::GC getObjCGCAttr() const; |
1063 | |
1064 | /// true when Type is objc's weak. |
1065 | bool isObjCGCWeak() const { |
1066 | return getObjCGCAttr() == Qualifiers::Weak; |
1067 | } |
1068 | |
1069 | /// true when Type is objc's strong. |
1070 | bool isObjCGCStrong() const { |
1071 | return getObjCGCAttr() == Qualifiers::Strong; |
1072 | } |
1073 | |
1074 | /// Returns lifetime attribute of this type. |
1075 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1076 | return getQualifiers().getObjCLifetime(); |
1077 | } |
1078 | |
1079 | bool hasNonTrivialObjCLifetime() const { |
1080 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1081 | } |
1082 | |
1083 | bool hasStrongOrWeakObjCLifetime() const { |
1084 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1085 | } |
1086 | |
1087 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1088 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1089 | |
1090 | enum DestructionKind { |
1091 | DK_none, |
1092 | DK_cxx_destructor, |
1093 | DK_objc_strong_lifetime, |
1094 | DK_objc_weak_lifetime |
1095 | }; |
1096 | |
1097 | /// Returns a nonzero value if objects of this type require |
1098 | /// non-trivial work to clean up after. Non-zero because it's |
1099 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1100 | /// something require destruction. |
1101 | DestructionKind isDestructedType() const { |
1102 | return isDestructedTypeImpl(*this); |
1103 | } |
1104 | |
1105 | /// Determine whether expressions of the given type are forbidden |
1106 | /// from being lvalues in C. |
1107 | /// |
1108 | /// The expression types that are forbidden to be lvalues are: |
1109 | /// - 'void', but not qualified void |
1110 | /// - function types |
1111 | /// |
1112 | /// The exact rule here is C99 6.3.2.1: |
1113 | /// An lvalue is an expression with an object type or an incomplete |
1114 | /// type other than void. |
1115 | bool isCForbiddenLValueType() const; |
1116 | |
1117 | /// Substitute type arguments for the Objective-C type parameters used in the |
1118 | /// subject type. |
1119 | /// |
1120 | /// \param ctx ASTContext in which the type exists. |
1121 | /// |
1122 | /// \param typeArgs The type arguments that will be substituted for the |
1123 | /// Objective-C type parameters in the subject type, which are generally |
1124 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1125 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1126 | /// for the context. |
1127 | /// |
1128 | /// \param context The context in which the subject type was written. |
1129 | /// |
1130 | /// \returns the resulting type. |
1131 | QualType substObjCTypeArgs(ASTContext &ctx, |
1132 | ArrayRef<QualType> typeArgs, |
1133 | ObjCSubstitutionContext context) const; |
1134 | |
1135 | /// Substitute type arguments from an object type for the Objective-C type |
1136 | /// parameters used in the subject type. |
1137 | /// |
1138 | /// This operation combines the computation of type arguments for |
1139 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1140 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1141 | /// callers that need to perform a single substitution in isolation. |
1142 | /// |
1143 | /// \param objectType The type of the object whose member type we're |
1144 | /// substituting into. For example, this might be the receiver of a message |
1145 | /// or the base of a property access. |
1146 | /// |
1147 | /// \param dc The declaration context from which the subject type was |
1148 | /// retrieved, which indicates (for example) which type parameters should |
1149 | /// be substituted. |
1150 | /// |
1151 | /// \param context The context in which the subject type was written. |
1152 | /// |
1153 | /// \returns the subject type after replacing all of the Objective-C type |
1154 | /// parameters with their corresponding arguments. |
1155 | QualType substObjCMemberType(QualType objectType, |
1156 | const DeclContext *dc, |
1157 | ObjCSubstitutionContext context) const; |
1158 | |
1159 | /// Strip Objective-C "__kindof" types from the given type. |
1160 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1161 | |
1162 | /// Remove all qualifiers including _Atomic. |
1163 | QualType getAtomicUnqualifiedType() const; |
1164 | |
1165 | private: |
1166 | // These methods are implemented in a separate translation unit; |
1167 | // "static"-ize them to avoid creating temporary QualTypes in the |
1168 | // caller. |
1169 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1170 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1171 | static SplitQualType getSplitDesugaredType(QualType T); |
1172 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1173 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1174 | const ASTContext &C); |
1175 | static QualType IgnoreParens(QualType T); |
1176 | static DestructionKind isDestructedTypeImpl(QualType type); |
1177 | }; |
1178 | |
1179 | } // namespace clang |
1180 | |
1181 | namespace llvm { |
1182 | |
1183 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1184 | /// to a specific Type class. |
1185 | template<> struct simplify_type< ::clang::QualType> { |
1186 | using SimpleType = const ::clang::Type *; |
1187 | |
1188 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1189 | return Val.getTypePtr(); |
1190 | } |
1191 | }; |
1192 | |
1193 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1194 | template<> |
1195 | struct PointerLikeTypeTraits<clang::QualType> { |
1196 | static inline void *getAsVoidPointer(clang::QualType P) { |
1197 | return P.getAsOpaquePtr(); |
1198 | } |
1199 | |
1200 | static inline clang::QualType getFromVoidPointer(void *P) { |
1201 | return clang::QualType::getFromOpaquePtr(P); |
1202 | } |
1203 | |
1204 | // Various qualifiers go in low bits. |
1205 | enum { NumLowBitsAvailable = 0 }; |
1206 | }; |
1207 | |
1208 | } // namespace llvm |
1209 | |
1210 | namespace clang { |
1211 | |
1212 | /// \brief Base class that is common to both the \c ExtQuals and \c Type |
1213 | /// classes, which allows \c QualType to access the common fields between the |
1214 | /// two. |
1215 | class ExtQualsTypeCommonBase { |
1216 | friend class ExtQuals; |
1217 | friend class QualType; |
1218 | friend class Type; |
1219 | |
1220 | /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or |
1221 | /// a self-referential pointer (for \c Type). |
1222 | /// |
1223 | /// This pointer allows an efficient mapping from a QualType to its |
1224 | /// underlying type pointer. |
1225 | const Type *const BaseType; |
1226 | |
1227 | /// \brief The canonical type of this type. A QualType. |
1228 | QualType CanonicalType; |
1229 | |
1230 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1231 | : BaseType(baseType), CanonicalType(canon) {} |
1232 | }; |
1233 | |
1234 | /// We can encode up to four bits in the low bits of a |
1235 | /// type pointer, but there are many more type qualifiers that we want |
1236 | /// to be able to apply to an arbitrary type. Therefore we have this |
1237 | /// struct, intended to be heap-allocated and used by QualType to |
1238 | /// store qualifiers. |
1239 | /// |
1240 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1241 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1242 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1243 | /// Objective-C GC attributes) are much more rare. |
1244 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1245 | // NOTE: changing the fast qualifiers should be straightforward as |
1246 | // long as you don't make 'const' non-fast. |
1247 | // 1. Qualifiers: |
1248 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1249 | // Fast qualifiers must occupy the low-order bits. |
1250 | // b) Update Qualifiers::FastWidth and FastMask. |
1251 | // 2. QualType: |
1252 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1253 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1254 | // this header. |
1255 | // 3. ASTContext: |
1256 | // a) Update get{Volatile,Restrict}Type. |
1257 | |
1258 | /// The immutable set of qualifiers applied by this node. Always contains |
1259 | /// extended qualifiers. |
1260 | Qualifiers Quals; |
1261 | |
1262 | ExtQuals *this_() { return this; } |
1263 | |
1264 | public: |
1265 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1266 | : ExtQualsTypeCommonBase(baseType, |
1267 | canon.isNull() ? QualType(this_(), 0) : canon), |
1268 | Quals(quals) { |
1269 | assert(Quals.hasNonFastQualifiers()(static_cast <bool> (Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1270, __extension__ __PRETTY_FUNCTION__)) |
1270 | && "ExtQuals created with no fast qualifiers")(static_cast <bool> (Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1270, __extension__ __PRETTY_FUNCTION__)); |
1271 | assert(!Quals.hasFastQualifiers()(static_cast <bool> (!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers") ? void (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1272, __extension__ __PRETTY_FUNCTION__)) |
1272 | && "ExtQuals created with fast qualifiers")(static_cast <bool> (!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers") ? void (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1272, __extension__ __PRETTY_FUNCTION__)); |
1273 | } |
1274 | |
1275 | Qualifiers getQualifiers() const { return Quals; } |
1276 | |
1277 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1278 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1279 | |
1280 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1281 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1282 | return Quals.getObjCLifetime(); |
1283 | } |
1284 | |
1285 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1286 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1287 | |
1288 | const Type *getBaseType() const { return BaseType; } |
1289 | |
1290 | public: |
1291 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1292 | Profile(ID, getBaseType(), Quals); |
1293 | } |
1294 | |
1295 | static void Profile(llvm::FoldingSetNodeID &ID, |
1296 | const Type *BaseType, |
1297 | Qualifiers Quals) { |
1298 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast <bool> (!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!") ? void (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1298, __extension__ __PRETTY_FUNCTION__)); |
1299 | ID.AddPointer(BaseType); |
1300 | Quals.Profile(ID); |
1301 | } |
1302 | }; |
1303 | |
1304 | /// The kind of C++11 ref-qualifier associated with a function type. |
1305 | /// This determines whether a member function's "this" object can be an |
1306 | /// lvalue, rvalue, or neither. |
1307 | enum RefQualifierKind { |
1308 | /// \brief No ref-qualifier was provided. |
1309 | RQ_None = 0, |
1310 | |
1311 | /// \brief An lvalue ref-qualifier was provided (\c &). |
1312 | RQ_LValue, |
1313 | |
1314 | /// \brief An rvalue ref-qualifier was provided (\c &&). |
1315 | RQ_RValue |
1316 | }; |
1317 | |
1318 | /// Which keyword(s) were used to create an AutoType. |
1319 | enum class AutoTypeKeyword { |
1320 | /// \brief auto |
1321 | Auto, |
1322 | |
1323 | /// \brief decltype(auto) |
1324 | DecltypeAuto, |
1325 | |
1326 | /// \brief __auto_type (GNU extension) |
1327 | GNUAutoType |
1328 | }; |
1329 | |
1330 | /// The base class of the type hierarchy. |
1331 | /// |
1332 | /// A central concept with types is that each type always has a canonical |
1333 | /// type. A canonical type is the type with any typedef names stripped out |
1334 | /// of it or the types it references. For example, consider: |
1335 | /// |
1336 | /// typedef int foo; |
1337 | /// typedef foo* bar; |
1338 | /// 'int *' 'foo *' 'bar' |
1339 | /// |
1340 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1341 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1342 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1343 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1344 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1345 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1346 | /// is also 'int*'. |
1347 | /// |
1348 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1349 | /// information about typedefs being used. Canonical types are useful for type |
1350 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1351 | /// about whether something has a particular form (e.g. is a function type), |
1352 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1353 | /// |
1354 | /// Types, once created, are immutable. |
1355 | /// |
1356 | class Type : public ExtQualsTypeCommonBase { |
1357 | public: |
1358 | enum TypeClass { |
1359 | #define TYPE(Class, Base) Class, |
1360 | #define LAST_TYPE(Class) TypeLast = Class, |
1361 | #define ABSTRACT_TYPE(Class, Base) |
1362 | #include "clang/AST/TypeNodes.def" |
1363 | TagFirst = Record, TagLast = Enum |
1364 | }; |
1365 | |
1366 | private: |
1367 | /// Bitfields required by the Type class. |
1368 | class TypeBitfields { |
1369 | friend class Type; |
1370 | template <class T> friend class TypePropertyCache; |
1371 | |
1372 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1373 | unsigned TC : 8; |
1374 | |
1375 | /// Whether this type is a dependent type (C++ [temp.dep.type]). |
1376 | unsigned Dependent : 1; |
1377 | |
1378 | /// Whether this type somehow involves a template parameter, even |
1379 | /// if the resolution of the type does not depend on a template parameter. |
1380 | unsigned InstantiationDependent : 1; |
1381 | |
1382 | /// Whether this type is a variably-modified type (C99 6.7.5). |
1383 | unsigned VariablyModified : 1; |
1384 | |
1385 | /// \brief Whether this type contains an unexpanded parameter pack |
1386 | /// (for C++11 variadic templates). |
1387 | unsigned ContainsUnexpandedParameterPack : 1; |
1388 | |
1389 | /// \brief True if the cache (i.e. the bitfields here starting with |
1390 | /// 'Cache') is valid. |
1391 | mutable unsigned CacheValid : 1; |
1392 | |
1393 | /// \brief Linkage of this type. |
1394 | mutable unsigned CachedLinkage : 3; |
1395 | |
1396 | /// \brief Whether this type involves and local or unnamed types. |
1397 | mutable unsigned CachedLocalOrUnnamed : 1; |
1398 | |
1399 | /// \brief Whether this type comes from an AST file. |
1400 | mutable unsigned FromAST : 1; |
1401 | |
1402 | bool isCacheValid() const { |
1403 | return CacheValid; |
1404 | } |
1405 | |
1406 | Linkage getLinkage() const { |
1407 | assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache" ) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1407, __extension__ __PRETTY_FUNCTION__)); |
1408 | return static_cast<Linkage>(CachedLinkage); |
1409 | } |
1410 | |
1411 | bool hasLocalOrUnnamedType() const { |
1412 | assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache" ) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 1412, __extension__ __PRETTY_FUNCTION__)); |
1413 | return CachedLocalOrUnnamed; |
1414 | } |
1415 | }; |
1416 | enum { NumTypeBits = 18 }; |
1417 | |
1418 | protected: |
1419 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1420 | // into Type. |
1421 | |
1422 | class ArrayTypeBitfields { |
1423 | friend class ArrayType; |
1424 | |
1425 | unsigned : NumTypeBits; |
1426 | |
1427 | /// CVR qualifiers from declarations like |
1428 | /// 'int X[static restrict 4]'. For function parameters only. |
1429 | unsigned IndexTypeQuals : 3; |
1430 | |
1431 | /// Storage class qualifiers from declarations like |
1432 | /// 'int X[static restrict 4]'. For function parameters only. |
1433 | /// Actually an ArrayType::ArraySizeModifier. |
1434 | unsigned SizeModifier : 3; |
1435 | }; |
1436 | |
1437 | class BuiltinTypeBitfields { |
1438 | friend class BuiltinType; |
1439 | |
1440 | unsigned : NumTypeBits; |
1441 | |
1442 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1443 | unsigned Kind : 8; |
1444 | }; |
1445 | |
1446 | class FunctionTypeBitfields { |
1447 | friend class FunctionProtoType; |
1448 | friend class FunctionType; |
1449 | |
1450 | unsigned : NumTypeBits; |
1451 | |
1452 | /// Extra information which affects how the function is called, like |
1453 | /// regparm and the calling convention. |
1454 | unsigned ExtInfo : 11; |
1455 | |
1456 | /// Used only by FunctionProtoType, put here to pack with the |
1457 | /// other bitfields. |
1458 | /// The qualifiers are part of FunctionProtoType because... |
1459 | /// |
1460 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1461 | /// cv-qualifier-seq, [...], are part of the function type. |
1462 | unsigned TypeQuals : 4; |
1463 | |
1464 | /// \brief The ref-qualifier associated with a \c FunctionProtoType. |
1465 | /// |
1466 | /// This is a value of type \c RefQualifierKind. |
1467 | unsigned RefQualifier : 2; |
1468 | }; |
1469 | |
1470 | class ObjCObjectTypeBitfields { |
1471 | friend class ObjCObjectType; |
1472 | |
1473 | unsigned : NumTypeBits; |
1474 | |
1475 | /// The number of type arguments stored directly on this object type. |
1476 | unsigned NumTypeArgs : 7; |
1477 | |
1478 | /// The number of protocols stored directly on this object type. |
1479 | unsigned NumProtocols : 6; |
1480 | |
1481 | /// Whether this is a "kindof" type. |
1482 | unsigned IsKindOf : 1; |
1483 | }; |
1484 | |
1485 | static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned"); |
1486 | |
1487 | class ReferenceTypeBitfields { |
1488 | friend class ReferenceType; |
1489 | |
1490 | unsigned : NumTypeBits; |
1491 | |
1492 | /// True if the type was originally spelled with an lvalue sigil. |
1493 | /// This is never true of rvalue references but can also be false |
1494 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1495 | /// as follows: |
1496 | /// |
1497 | /// typedef int &ref; // lvalue, spelled lvalue |
1498 | /// typedef int &&rvref; // rvalue |
1499 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1500 | /// ref &&a; // lvalue, inner ref |
1501 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1502 | /// rvref &&a; // rvalue, inner ref |
1503 | unsigned SpelledAsLValue : 1; |
1504 | |
1505 | /// True if the inner type is a reference type. This only happens |
1506 | /// in non-canonical forms. |
1507 | unsigned InnerRef : 1; |
1508 | }; |
1509 | |
1510 | class TypeWithKeywordBitfields { |
1511 | friend class TypeWithKeyword; |
1512 | |
1513 | unsigned : NumTypeBits; |
1514 | |
1515 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1516 | unsigned Keyword : 8; |
1517 | }; |
1518 | |
1519 | class VectorTypeBitfields { |
1520 | friend class VectorType; |
1521 | |
1522 | unsigned : NumTypeBits; |
1523 | |
1524 | /// The kind of vector, either a generic vector type or some |
1525 | /// target-specific vector type such as for AltiVec or Neon. |
1526 | unsigned VecKind : 3; |
1527 | |
1528 | /// The number of elements in the vector. |
1529 | unsigned NumElements : 29 - NumTypeBits; |
1530 | |
1531 | enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 }; |
1532 | }; |
1533 | |
1534 | class AttributedTypeBitfields { |
1535 | friend class AttributedType; |
1536 | |
1537 | unsigned : NumTypeBits; |
1538 | |
1539 | /// An AttributedType::Kind |
1540 | unsigned AttrKind : 32 - NumTypeBits; |
1541 | }; |
1542 | |
1543 | class AutoTypeBitfields { |
1544 | friend class AutoType; |
1545 | |
1546 | unsigned : NumTypeBits; |
1547 | |
1548 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1549 | /// or '__auto_type'? AutoTypeKeyword value. |
1550 | unsigned Keyword : 2; |
1551 | }; |
1552 | |
1553 | union { |
1554 | TypeBitfields TypeBits; |
1555 | ArrayTypeBitfields ArrayTypeBits; |
1556 | AttributedTypeBitfields AttributedTypeBits; |
1557 | AutoTypeBitfields AutoTypeBits; |
1558 | BuiltinTypeBitfields BuiltinTypeBits; |
1559 | FunctionTypeBitfields FunctionTypeBits; |
1560 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1561 | ReferenceTypeBitfields ReferenceTypeBits; |
1562 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1563 | VectorTypeBitfields VectorTypeBits; |
1564 | }; |
1565 | |
1566 | private: |
1567 | template <class T> friend class TypePropertyCache; |
1568 | |
1569 | /// \brief Set whether this type comes from an AST file. |
1570 | void setFromAST(bool V = true) const { |
1571 | TypeBits.FromAST = V; |
1572 | } |
1573 | |
1574 | protected: |
1575 | friend class ASTContext; |
1576 | |
1577 | Type(TypeClass tc, QualType canon, bool Dependent, |
1578 | bool InstantiationDependent, bool VariablyModified, |
1579 | bool ContainsUnexpandedParameterPack) |
1580 | : ExtQualsTypeCommonBase(this, |
1581 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1582 | TypeBits.TC = tc; |
1583 | TypeBits.Dependent = Dependent; |
1584 | TypeBits.InstantiationDependent = Dependent || InstantiationDependent; |
1585 | TypeBits.VariablyModified = VariablyModified; |
1586 | TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1587 | TypeBits.CacheValid = false; |
1588 | TypeBits.CachedLocalOrUnnamed = false; |
1589 | TypeBits.CachedLinkage = NoLinkage; |
1590 | TypeBits.FromAST = false; |
1591 | } |
1592 | |
1593 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1594 | Type *this_() { return this; } |
1595 | |
1596 | void setDependent(bool D = true) { |
1597 | TypeBits.Dependent = D; |
1598 | if (D) |
1599 | TypeBits.InstantiationDependent = true; |
1600 | } |
1601 | |
1602 | void setInstantiationDependent(bool D = true) { |
1603 | TypeBits.InstantiationDependent = D; } |
1604 | |
1605 | void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; } |
1606 | |
1607 | void setContainsUnexpandedParameterPack(bool PP = true) { |
1608 | TypeBits.ContainsUnexpandedParameterPack = PP; |
1609 | } |
1610 | |
1611 | public: |
1612 | friend class ASTReader; |
1613 | friend class ASTWriter; |
1614 | |
1615 | Type(const Type &) = delete; |
1616 | Type &operator=(const Type &) = delete; |
1617 | |
1618 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1619 | |
1620 | /// \brief Whether this type comes from an AST file. |
1621 | bool isFromAST() const { return TypeBits.FromAST; } |
1622 | |
1623 | /// \brief Whether this type is or contains an unexpanded parameter |
1624 | /// pack, used to support C++0x variadic templates. |
1625 | /// |
1626 | /// A type that contains a parameter pack shall be expanded by the |
1627 | /// ellipsis operator at some point. For example, the typedef in the |
1628 | /// following example contains an unexpanded parameter pack 'T': |
1629 | /// |
1630 | /// \code |
1631 | /// template<typename ...T> |
1632 | /// struct X { |
1633 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1634 | /// }; |
1635 | /// \endcode |
1636 | /// |
1637 | /// Note that this routine does not specify which |
1638 | bool containsUnexpandedParameterPack() const { |
1639 | return TypeBits.ContainsUnexpandedParameterPack; |
1640 | } |
1641 | |
1642 | /// Determines if this type would be canonical if it had no further |
1643 | /// qualification. |
1644 | bool isCanonicalUnqualified() const { |
1645 | return CanonicalType == QualType(this, 0); |
1646 | } |
1647 | |
1648 | /// Pull a single level of sugar off of this locally-unqualified type. |
1649 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1650 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1651 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1652 | |
1653 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1654 | /// object types, function types, and incomplete types. |
1655 | |
1656 | /// Return true if this is an incomplete type. |
1657 | /// A type that can describe objects, but which lacks information needed to |
1658 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1659 | /// routine will need to determine if the size is actually required. |
1660 | /// |
1661 | /// \brief Def If non-null, and the type refers to some kind of declaration |
1662 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1663 | /// class), will be set to the declaration. |
1664 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1665 | |
1666 | /// Return true if this is an incomplete or object |
1667 | /// type, in other words, not a function type. |
1668 | bool isIncompleteOrObjectType() const { |
1669 | return !isFunctionType(); |
1670 | } |
1671 | |
1672 | /// \brief Determine whether this type is an object type. |
1673 | bool isObjectType() const { |
1674 | // C++ [basic.types]p8: |
1675 | // An object type is a (possibly cv-qualified) type that is not a |
1676 | // function type, not a reference type, and not a void type. |
1677 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1678 | } |
1679 | |
1680 | /// Return true if this is a literal type |
1681 | /// (C++11 [basic.types]p10) |
1682 | bool isLiteralType(const ASTContext &Ctx) const; |
1683 | |
1684 | /// Test if this type is a standard-layout type. |
1685 | /// (C++0x [basic.type]p9) |
1686 | bool isStandardLayoutType() const; |
1687 | |
1688 | /// Helper methods to distinguish type categories. All type predicates |
1689 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1690 | |
1691 | /// Returns true if the type is a builtin type. |
1692 | bool isBuiltinType() const; |
1693 | |
1694 | /// Test for a particular builtin type. |
1695 | bool isSpecificBuiltinType(unsigned K) const; |
1696 | |
1697 | /// Test for a type which does not represent an actual type-system type but |
1698 | /// is instead used as a placeholder for various convenient purposes within |
1699 | /// Clang. All such types are BuiltinTypes. |
1700 | bool isPlaceholderType() const; |
1701 | const BuiltinType *getAsPlaceholderType() const; |
1702 | |
1703 | /// Test for a specific placeholder type. |
1704 | bool isSpecificPlaceholderType(unsigned K) const; |
1705 | |
1706 | /// Test for a placeholder type other than Overload; see |
1707 | /// BuiltinType::isNonOverloadPlaceholderType. |
1708 | bool isNonOverloadPlaceholderType() const; |
1709 | |
1710 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1711 | /// isComplexIntegerType() can be used to test for complex integers. |
1712 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1713 | bool isEnumeralType() const; |
1714 | bool isBooleanType() const; |
1715 | bool isCharType() const; |
1716 | bool isWideCharType() const; |
1717 | bool isChar16Type() const; |
1718 | bool isChar32Type() const; |
1719 | bool isAnyCharacterType() const; |
1720 | bool isIntegralType(const ASTContext &Ctx) const; |
1721 | |
1722 | /// Determine whether this type is an integral or enumeration type. |
1723 | bool isIntegralOrEnumerationType() const; |
1724 | |
1725 | /// Determine whether this type is an integral or unscoped enumeration type. |
1726 | bool isIntegralOrUnscopedEnumerationType() const; |
1727 | |
1728 | /// Floating point categories. |
1729 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1730 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1731 | /// isComplexIntegerType() can be used to test for complex integers. |
1732 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1733 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1734 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1735 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1736 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1737 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1738 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1739 | bool isVoidType() const; // C99 6.2.5p19 |
1740 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1741 | bool isAggregateType() const; |
1742 | bool isFundamentalType() const; |
1743 | bool isCompoundType() const; |
1744 | |
1745 | // Type Predicates: Check to see if this type is structurally the specified |
1746 | // type, ignoring typedefs and qualifiers. |
1747 | bool isFunctionType() const; |
1748 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
1749 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
1750 | bool isPointerType() const; |
1751 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
1752 | bool isBlockPointerType() const; |
1753 | bool isVoidPointerType() const; |
1754 | bool isReferenceType() const; |
1755 | bool isLValueReferenceType() const; |
1756 | bool isRValueReferenceType() const; |
1757 | bool isFunctionPointerType() const; |
1758 | bool isMemberPointerType() const; |
1759 | bool isMemberFunctionPointerType() const; |
1760 | bool isMemberDataPointerType() const; |
1761 | bool isArrayType() const; |
1762 | bool isConstantArrayType() const; |
1763 | bool isIncompleteArrayType() const; |
1764 | bool isVariableArrayType() const; |
1765 | bool isDependentSizedArrayType() const; |
1766 | bool isRecordType() const; |
1767 | bool isClassType() const; |
1768 | bool isStructureType() const; |
1769 | bool isObjCBoxableRecordType() const; |
1770 | bool isInterfaceType() const; |
1771 | bool isStructureOrClassType() const; |
1772 | bool isUnionType() const; |
1773 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
1774 | bool isVectorType() const; // GCC vector type. |
1775 | bool isExtVectorType() const; // Extended vector type. |
1776 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
1777 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
1778 | bool isObjCRetainableType() const; // ObjC object or block pointer |
1779 | bool isObjCLifetimeType() const; // (array of)* retainable type |
1780 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
1781 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
1782 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
1783 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
1784 | // for the common case. |
1785 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
1786 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
1787 | bool isObjCQualifiedIdType() const; // id<foo> |
1788 | bool isObjCQualifiedClassType() const; // Class<foo> |
1789 | bool isObjCObjectOrInterfaceType() const; |
1790 | bool isObjCIdType() const; // id |
1791 | bool isObjCInertUnsafeUnretainedType() const; |
1792 | |
1793 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
1794 | /// object type, e.g., __kindof NSView * or __kindof id |
1795 | /// <NSCopying>. |
1796 | /// |
1797 | /// \param bound Will be set to the bound on non-id subtype types, |
1798 | /// which will be (possibly specialized) Objective-C class type, or |
1799 | /// null for 'id. |
1800 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
1801 | const ObjCObjectType *&bound) const; |
1802 | |
1803 | bool isObjCClassType() const; // Class |
1804 | |
1805 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
1806 | /// Class type, e.g., __kindof Class <NSCopying>. |
1807 | /// |
1808 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
1809 | /// here because Objective-C's type system cannot express "a class |
1810 | /// object for a subclass of NSFoo". |
1811 | bool isObjCClassOrClassKindOfType() const; |
1812 | |
1813 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
1814 | bool isObjCSelType() const; // Class |
1815 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
1816 | bool isObjCARCBridgableType() const; |
1817 | bool isCARCBridgableType() const; |
1818 | bool isTemplateTypeParmType() const; // C++ template type parameter |
1819 | bool isNullPtrType() const; // C++11 std::nullptr_t |
1820 | bool isAlignValT() const; // C++17 std::align_val_t |
1821 | bool isStdByteType() const; // C++17 std::byte |
1822 | bool isAtomicType() const; // C11 _Atomic() |
1823 | |
1824 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
1825 | bool is##Id##Type() const; |
1826 | #include "clang/Basic/OpenCLImageTypes.def" |
1827 | |
1828 | bool isImageType() const; // Any OpenCL image type |
1829 | |
1830 | bool isSamplerT() const; // OpenCL sampler_t |
1831 | bool isEventT() const; // OpenCL event_t |
1832 | bool isClkEventT() const; // OpenCL clk_event_t |
1833 | bool isQueueT() const; // OpenCL queue_t |
1834 | bool isReserveIDT() const; // OpenCL reserve_id_t |
1835 | |
1836 | bool isPipeType() const; // OpenCL pipe type |
1837 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
1838 | |
1839 | /// Determines if this type, which must satisfy |
1840 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
1841 | /// than implicitly __strong. |
1842 | bool isObjCARCImplicitlyUnretainedType() const; |
1843 | |
1844 | /// Return the implicit lifetime for this type, which must not be dependent. |
1845 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
1846 | |
1847 | enum ScalarTypeKind { |
1848 | STK_CPointer, |
1849 | STK_BlockPointer, |
1850 | STK_ObjCObjectPointer, |
1851 | STK_MemberPointer, |
1852 | STK_Bool, |
1853 | STK_Integral, |
1854 | STK_Floating, |
1855 | STK_IntegralComplex, |
1856 | STK_FloatingComplex |
1857 | }; |
1858 | |
1859 | /// Given that this is a scalar type, classify it. |
1860 | ScalarTypeKind getScalarTypeKind() const; |
1861 | |
1862 | /// Whether this type is a dependent type, meaning that its definition |
1863 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
1864 | bool isDependentType() const { return TypeBits.Dependent; } |
1865 | |
1866 | /// \brief Determine whether this type is an instantiation-dependent type, |
1867 | /// meaning that the type involves a template parameter (even if the |
1868 | /// definition does not actually depend on the type substituted for that |
1869 | /// template parameter). |
1870 | bool isInstantiationDependentType() const { |
1871 | return TypeBits.InstantiationDependent; |
1872 | } |
1873 | |
1874 | /// \brief Determine whether this type is an undeduced type, meaning that |
1875 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
1876 | /// deduced. |
1877 | bool isUndeducedType() const; |
1878 | |
1879 | /// \brief Whether this type is a variably-modified type (C99 6.7.5). |
1880 | bool isVariablyModifiedType() const { return TypeBits.VariablyModified; } |
1881 | |
1882 | /// \brief Whether this type involves a variable-length array type |
1883 | /// with a definite size. |
1884 | bool hasSizedVLAType() const; |
1885 | |
1886 | /// \brief Whether this type is or contains a local or unnamed type. |
1887 | bool hasUnnamedOrLocalType() const; |
1888 | |
1889 | bool isOverloadableType() const; |
1890 | |
1891 | /// \brief Determine wither this type is a C++ elaborated-type-specifier. |
1892 | bool isElaboratedTypeSpecifier() const; |
1893 | |
1894 | bool canDecayToPointerType() const; |
1895 | |
1896 | /// Whether this type is represented natively as a pointer. This includes |
1897 | /// pointers, references, block pointers, and Objective-C interface, |
1898 | /// qualified id, and qualified interface types, as well as nullptr_t. |
1899 | bool hasPointerRepresentation() const; |
1900 | |
1901 | /// Whether this type can represent an objective pointer type for the |
1902 | /// purpose of GC'ability |
1903 | bool hasObjCPointerRepresentation() const; |
1904 | |
1905 | /// \brief Determine whether this type has an integer representation |
1906 | /// of some sort, e.g., it is an integer type or a vector. |
1907 | bool hasIntegerRepresentation() const; |
1908 | |
1909 | /// \brief Determine whether this type has an signed integer representation |
1910 | /// of some sort, e.g., it is an signed integer type or a vector. |
1911 | bool hasSignedIntegerRepresentation() const; |
1912 | |
1913 | /// \brief Determine whether this type has an unsigned integer representation |
1914 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
1915 | bool hasUnsignedIntegerRepresentation() const; |
1916 | |
1917 | /// \brief Determine whether this type has a floating-point representation |
1918 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
1919 | bool hasFloatingRepresentation() const; |
1920 | |
1921 | // Type Checking Functions: Check to see if this type is structurally the |
1922 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
1923 | // the best type we can. |
1924 | const RecordType *getAsStructureType() const; |
1925 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
1926 | const RecordType *getAsUnionType() const; |
1927 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
1928 | const ObjCObjectType *getAsObjCInterfaceType() const; |
1929 | |
1930 | // The following is a convenience method that returns an ObjCObjectPointerType |
1931 | // for object declared using an interface. |
1932 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
1933 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
1934 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
1935 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
1936 | |
1937 | /// \brief Retrieves the CXXRecordDecl that this type refers to, either |
1938 | /// because the type is a RecordType or because it is the injected-class-name |
1939 | /// type of a class template or class template partial specialization. |
1940 | CXXRecordDecl *getAsCXXRecordDecl() const; |
1941 | |
1942 | /// \brief Retrieves the TagDecl that this type refers to, either |
1943 | /// because the type is a TagType or because it is the injected-class-name |
1944 | /// type of a class template or class template partial specialization. |
1945 | TagDecl *getAsTagDecl() const; |
1946 | |
1947 | /// If this is a pointer or reference to a RecordType, return the |
1948 | /// CXXRecordDecl that that type refers to. |
1949 | /// |
1950 | /// If this is not a pointer or reference, or the type being pointed to does |
1951 | /// not refer to a CXXRecordDecl, returns NULL. |
1952 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
1953 | |
1954 | /// Get the DeducedType whose type will be deduced for a variable with |
1955 | /// an initializer of this type. This looks through declarators like pointer |
1956 | /// types, but not through decltype or typedefs. |
1957 | DeducedType *getContainedDeducedType() const; |
1958 | |
1959 | /// Get the AutoType whose type will be deduced for a variable with |
1960 | /// an initializer of this type. This looks through declarators like pointer |
1961 | /// types, but not through decltype or typedefs. |
1962 | AutoType *getContainedAutoType() const { |
1963 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
1964 | } |
1965 | |
1966 | /// Determine whether this type was written with a leading 'auto' |
1967 | /// corresponding to a trailing return type (possibly for a nested |
1968 | /// function type within a pointer to function type or similar). |
1969 | bool hasAutoForTrailingReturnType() const; |
1970 | |
1971 | /// Member-template getAs<specific type>'. Look through sugar for |
1972 | /// an instance of \<specific type>. This scheme will eventually |
1973 | /// replace the specific getAsXXXX methods above. |
1974 | /// |
1975 | /// There are some specializations of this member template listed |
1976 | /// immediately following this class. |
1977 | template <typename T> const T *getAs() const; |
1978 | |
1979 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
1980 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
1981 | /// This is used when you need to walk over sugar nodes that represent some |
1982 | /// kind of type adjustment from a type that was written as a \<specific type> |
1983 | /// to another type that is still canonically a \<specific type>. |
1984 | template <typename T> const T *getAsAdjusted() const; |
1985 | |
1986 | /// A variant of getAs<> for array types which silently discards |
1987 | /// qualifiers from the outermost type. |
1988 | const ArrayType *getAsArrayTypeUnsafe() const; |
1989 | |
1990 | /// Member-template castAs<specific type>. Look through sugar for |
1991 | /// the underlying instance of \<specific type>. |
1992 | /// |
1993 | /// This method has the same relationship to getAs<T> as cast<T> has |
1994 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
1995 | /// have the intended type, and this method will never return null. |
1996 | template <typename T> const T *castAs() const; |
1997 | |
1998 | /// A variant of castAs<> for array type which silently discards |
1999 | /// qualifiers from the outermost type. |
2000 | const ArrayType *castAsArrayTypeUnsafe() const; |
2001 | |
2002 | /// Get the base element type of this type, potentially discarding type |
2003 | /// qualifiers. This should never be used when type qualifiers |
2004 | /// are meaningful. |
2005 | const Type *getBaseElementTypeUnsafe() const; |
2006 | |
2007 | /// If this is an array type, return the element type of the array, |
2008 | /// potentially with type qualifiers missing. |
2009 | /// This should never be used when type qualifiers are meaningful. |
2010 | const Type *getArrayElementTypeNoTypeQual() const; |
2011 | |
2012 | /// If this is a pointer type, return the pointee type. |
2013 | /// If this is an array type, return the array element type. |
2014 | /// This should never be used when type qualifiers are meaningful. |
2015 | const Type *getPointeeOrArrayElementType() const; |
2016 | |
2017 | /// If this is a pointer, ObjC object pointer, or block |
2018 | /// pointer, this returns the respective pointee. |
2019 | QualType getPointeeType() const; |
2020 | |
2021 | /// Return the specified type with any "sugar" removed from the type, |
2022 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2023 | const Type *getUnqualifiedDesugaredType() const; |
2024 | |
2025 | /// More type predicates useful for type checking/promotion |
2026 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2027 | |
2028 | /// Return true if this is an integer type that is |
2029 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2030 | /// or an enum decl which has a signed representation. |
2031 | bool isSignedIntegerType() const; |
2032 | |
2033 | /// Return true if this is an integer type that is |
2034 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2035 | /// or an enum decl which has an unsigned representation. |
2036 | bool isUnsignedIntegerType() const; |
2037 | |
2038 | /// Determines whether this is an integer type that is signed or an |
2039 | /// enumeration types whose underlying type is a signed integer type. |
2040 | bool isSignedIntegerOrEnumerationType() const; |
2041 | |
2042 | /// Determines whether this is an integer type that is unsigned or an |
2043 | /// enumeration types whose underlying type is a unsigned integer type. |
2044 | bool isUnsignedIntegerOrEnumerationType() const; |
2045 | |
2046 | /// Return true if this is not a variable sized type, |
2047 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2048 | /// incomplete types. |
2049 | bool isConstantSizeType() const; |
2050 | |
2051 | /// Returns true if this type can be represented by some |
2052 | /// set of type specifiers. |
2053 | bool isSpecifierType() const; |
2054 | |
2055 | /// Determine the linkage of this type. |
2056 | Linkage getLinkage() const; |
2057 | |
2058 | /// Determine the visibility of this type. |
2059 | Visibility getVisibility() const { |
2060 | return getLinkageAndVisibility().getVisibility(); |
2061 | } |
2062 | |
2063 | /// Return true if the visibility was explicitly set is the code. |
2064 | bool isVisibilityExplicit() const { |
2065 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2066 | } |
2067 | |
2068 | /// Determine the linkage and visibility of this type. |
2069 | LinkageInfo getLinkageAndVisibility() const; |
2070 | |
2071 | /// True if the computed linkage is valid. Used for consistency |
2072 | /// checking. Should always return true. |
2073 | bool isLinkageValid() const; |
2074 | |
2075 | /// Determine the nullability of the given type. |
2076 | /// |
2077 | /// Note that nullability is only captured as sugar within the type |
2078 | /// system, not as part of the canonical type, so nullability will |
2079 | /// be lost by canonicalization and desugaring. |
2080 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2081 | |
2082 | /// Determine whether the given type can have a nullability |
2083 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2084 | /// |
2085 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2086 | /// this type can have nullability because it is dependent. |
2087 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2088 | |
2089 | /// Retrieve the set of substitutions required when accessing a member |
2090 | /// of the Objective-C receiver type that is declared in the given context. |
2091 | /// |
2092 | /// \c *this is the type of the object we're operating on, e.g., the |
2093 | /// receiver for a message send or the base of a property access, and is |
2094 | /// expected to be of some object or object pointer type. |
2095 | /// |
2096 | /// \param dc The declaration context for which we are building up a |
2097 | /// substitution mapping, which should be an Objective-C class, extension, |
2098 | /// category, or method within. |
2099 | /// |
2100 | /// \returns an array of type arguments that can be substituted for |
2101 | /// the type parameters of the given declaration context in any type described |
2102 | /// within that context, or an empty optional to indicate that no |
2103 | /// substitution is required. |
2104 | Optional<ArrayRef<QualType>> |
2105 | getObjCSubstitutions(const DeclContext *dc) const; |
2106 | |
2107 | /// Determines if this is an ObjC interface type that may accept type |
2108 | /// parameters. |
2109 | bool acceptsObjCTypeParams() const; |
2110 | |
2111 | const char *getTypeClassName() const; |
2112 | |
2113 | QualType getCanonicalTypeInternal() const { |
2114 | return CanonicalType; |
2115 | } |
2116 | |
2117 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2118 | void dump() const; |
2119 | void dump(llvm::raw_ostream &OS) const; |
2120 | }; |
2121 | |
2122 | /// \brief This will check for a TypedefType by removing any existing sugar |
2123 | /// until it reaches a TypedefType or a non-sugared type. |
2124 | template <> const TypedefType *Type::getAs() const; |
2125 | |
2126 | /// \brief This will check for a TemplateSpecializationType by removing any |
2127 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2128 | /// non-sugared type. |
2129 | template <> const TemplateSpecializationType *Type::getAs() const; |
2130 | |
2131 | /// \brief This will check for an AttributedType by removing any existing sugar |
2132 | /// until it reaches an AttributedType or a non-sugared type. |
2133 | template <> const AttributedType *Type::getAs() const; |
2134 | |
2135 | // We can do canonical leaf types faster, because we don't have to |
2136 | // worry about preserving child type decoration. |
2137 | #define TYPE(Class, Base) |
2138 | #define LEAF_TYPE(Class) \ |
2139 | template <> inline const Class##Type *Type::getAs() const { \ |
2140 | return dyn_cast<Class##Type>(CanonicalType); \ |
2141 | } \ |
2142 | template <> inline const Class##Type *Type::castAs() const { \ |
2143 | return cast<Class##Type>(CanonicalType); \ |
2144 | } |
2145 | #include "clang/AST/TypeNodes.def" |
2146 | |
2147 | /// This class is used for builtin types like 'int'. Builtin |
2148 | /// types are always canonical and have a literal name field. |
2149 | class BuiltinType : public Type { |
2150 | public: |
2151 | enum Kind { |
2152 | // OpenCL image types |
2153 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2154 | #include "clang/Basic/OpenCLImageTypes.def" |
2155 | // All other builtin types |
2156 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2157 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2158 | #include "clang/AST/BuiltinTypes.def" |
2159 | }; |
2160 | |
2161 | public: |
2162 | BuiltinType(Kind K) |
2163 | : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent), |
2164 | /*InstantiationDependent=*/(K == Dependent), |
2165 | /*VariablyModified=*/false, |
2166 | /*Unexpanded parameter pack=*/false) { |
2167 | BuiltinTypeBits.Kind = K; |
2168 | } |
2169 | |
2170 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2171 | StringRef getName(const PrintingPolicy &Policy) const; |
2172 | |
2173 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2174 | // The StringRef is null-terminated. |
2175 | StringRef str = getName(Policy); |
2176 | assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast <bool> (!str.empty() && str.data() [str.size()] == '\0') ? void (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 2176, __extension__ __PRETTY_FUNCTION__)); |
2177 | return str.data(); |
2178 | } |
2179 | |
2180 | bool isSugared() const { return false; } |
2181 | QualType desugar() const { return QualType(this, 0); } |
2182 | |
2183 | bool isInteger() const { |
2184 | return getKind() >= Bool && getKind() <= Int128; |
2185 | } |
2186 | |
2187 | bool isSignedInteger() const { |
2188 | return getKind() >= Char_S && getKind() <= Int128; |
2189 | } |
2190 | |
2191 | bool isUnsignedInteger() const { |
2192 | return getKind() >= Bool && getKind() <= UInt128; |
2193 | } |
2194 | |
2195 | bool isFloatingPoint() const { |
2196 | return getKind() >= Half && getKind() <= Float128; |
2197 | } |
2198 | |
2199 | /// Determines whether the given kind corresponds to a placeholder type. |
2200 | static bool isPlaceholderTypeKind(Kind K) { |
2201 | return K >= Overload; |
2202 | } |
2203 | |
2204 | /// Determines whether this type is a placeholder type, i.e. a type |
2205 | /// which cannot appear in arbitrary positions in a fully-formed |
2206 | /// expression. |
2207 | bool isPlaceholderType() const { |
2208 | return isPlaceholderTypeKind(getKind()); |
2209 | } |
2210 | |
2211 | /// Determines whether this type is a placeholder type other than |
2212 | /// Overload. Most placeholder types require only syntactic |
2213 | /// information about their context in order to be resolved (e.g. |
2214 | /// whether it is a call expression), which means they can (and |
2215 | /// should) be resolved in an earlier "phase" of analysis. |
2216 | /// Overload expressions sometimes pick up further information |
2217 | /// from their context, like whether the context expects a |
2218 | /// specific function-pointer type, and so frequently need |
2219 | /// special treatment. |
2220 | bool isNonOverloadPlaceholderType() const { |
2221 | return getKind() > Overload; |
2222 | } |
2223 | |
2224 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2225 | }; |
2226 | |
2227 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2228 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2229 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2230 | friend class ASTContext; // ASTContext creates these. |
2231 | |
2232 | QualType ElementType; |
2233 | |
2234 | ComplexType(QualType Element, QualType CanonicalPtr) |
2235 | : Type(Complex, CanonicalPtr, Element->isDependentType(), |
2236 | Element->isInstantiationDependentType(), |
2237 | Element->isVariablyModifiedType(), |
2238 | Element->containsUnexpandedParameterPack()), |
2239 | ElementType(Element) {} |
2240 | |
2241 | public: |
2242 | QualType getElementType() const { return ElementType; } |
2243 | |
2244 | bool isSugared() const { return false; } |
2245 | QualType desugar() const { return QualType(this, 0); } |
2246 | |
2247 | void Profile(llvm::FoldingSetNodeID &ID) { |
2248 | Profile(ID, getElementType()); |
2249 | } |
2250 | |
2251 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2252 | ID.AddPointer(Element.getAsOpaquePtr()); |
2253 | } |
2254 | |
2255 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2256 | }; |
2257 | |
2258 | /// Sugar for parentheses used when specifying types. |
2259 | class ParenType : public Type, public llvm::FoldingSetNode { |
2260 | friend class ASTContext; // ASTContext creates these. |
2261 | |
2262 | QualType Inner; |
2263 | |
2264 | ParenType(QualType InnerType, QualType CanonType) |
2265 | : Type(Paren, CanonType, InnerType->isDependentType(), |
2266 | InnerType->isInstantiationDependentType(), |
2267 | InnerType->isVariablyModifiedType(), |
2268 | InnerType->containsUnexpandedParameterPack()), |
2269 | Inner(InnerType) {} |
2270 | |
2271 | public: |
2272 | QualType getInnerType() const { return Inner; } |
2273 | |
2274 | bool isSugared() const { return true; } |
2275 | QualType desugar() const { return getInnerType(); } |
2276 | |
2277 | void Profile(llvm::FoldingSetNodeID &ID) { |
2278 | Profile(ID, getInnerType()); |
2279 | } |
2280 | |
2281 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2282 | Inner.Profile(ID); |
2283 | } |
2284 | |
2285 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2286 | }; |
2287 | |
2288 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2289 | class PointerType : public Type, public llvm::FoldingSetNode { |
2290 | friend class ASTContext; // ASTContext creates these. |
2291 | |
2292 | QualType PointeeType; |
2293 | |
2294 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2295 | : Type(Pointer, CanonicalPtr, Pointee->isDependentType(), |
2296 | Pointee->isInstantiationDependentType(), |
2297 | Pointee->isVariablyModifiedType(), |
2298 | Pointee->containsUnexpandedParameterPack()), |
2299 | PointeeType(Pointee) {} |
2300 | |
2301 | public: |
2302 | QualType getPointeeType() const { return PointeeType; } |
2303 | |
2304 | /// Returns true if address spaces of pointers overlap. |
2305 | /// OpenCL v2.0 defines conversion rules for pointers to different |
2306 | /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping |
2307 | /// address spaces. |
2308 | /// CL1.1 or CL1.2: |
2309 | /// address spaces overlap iff they are they same. |
2310 | /// CL2.0 adds: |
2311 | /// __generic overlaps with any address space except for __constant. |
2312 | bool isAddressSpaceOverlapping(const PointerType &other) const { |
2313 | Qualifiers thisQuals = PointeeType.getQualifiers(); |
2314 | Qualifiers otherQuals = other.getPointeeType().getQualifiers(); |
2315 | // Address spaces overlap if at least one of them is a superset of another |
2316 | return thisQuals.isAddressSpaceSupersetOf(otherQuals) || |
2317 | otherQuals.isAddressSpaceSupersetOf(thisQuals); |
2318 | } |
2319 | |
2320 | bool isSugared() const { return false; } |
2321 | QualType desugar() const { return QualType(this, 0); } |
2322 | |
2323 | void Profile(llvm::FoldingSetNodeID &ID) { |
2324 | Profile(ID, getPointeeType()); |
2325 | } |
2326 | |
2327 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2328 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2329 | } |
2330 | |
2331 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2332 | }; |
2333 | |
2334 | /// Represents a type which was implicitly adjusted by the semantic |
2335 | /// engine for arbitrary reasons. For example, array and function types can |
2336 | /// decay, and function types can have their calling conventions adjusted. |
2337 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2338 | QualType OriginalTy; |
2339 | QualType AdjustedTy; |
2340 | |
2341 | protected: |
2342 | friend class ASTContext; // ASTContext creates these. |
2343 | |
2344 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2345 | QualType CanonicalPtr) |
2346 | : Type(TC, CanonicalPtr, OriginalTy->isDependentType(), |
2347 | OriginalTy->isInstantiationDependentType(), |
2348 | OriginalTy->isVariablyModifiedType(), |
2349 | OriginalTy->containsUnexpandedParameterPack()), |
2350 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2351 | |
2352 | public: |
2353 | QualType getOriginalType() const { return OriginalTy; } |
2354 | QualType getAdjustedType() const { return AdjustedTy; } |
2355 | |
2356 | bool isSugared() const { return true; } |
2357 | QualType desugar() const { return AdjustedTy; } |
2358 | |
2359 | void Profile(llvm::FoldingSetNodeID &ID) { |
2360 | Profile(ID, OriginalTy, AdjustedTy); |
2361 | } |
2362 | |
2363 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2364 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2365 | ID.AddPointer(New.getAsOpaquePtr()); |
2366 | } |
2367 | |
2368 | static bool classof(const Type *T) { |
2369 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2370 | } |
2371 | }; |
2372 | |
2373 | /// Represents a pointer type decayed from an array or function type. |
2374 | class DecayedType : public AdjustedType { |
2375 | friend class ASTContext; // ASTContext creates these. |
2376 | |
2377 | inline |
2378 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2379 | |
2380 | public: |
2381 | QualType getDecayedType() const { return getAdjustedType(); } |
2382 | |
2383 | inline QualType getPointeeType() const; |
2384 | |
2385 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2386 | }; |
2387 | |
2388 | /// Pointer to a block type. |
2389 | /// This type is to represent types syntactically represented as |
2390 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2391 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2392 | friend class ASTContext; // ASTContext creates these. |
2393 | |
2394 | // Block is some kind of pointer type |
2395 | QualType PointeeType; |
2396 | |
2397 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2398 | : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(), |
2399 | Pointee->isInstantiationDependentType(), |
2400 | Pointee->isVariablyModifiedType(), |
2401 | Pointee->containsUnexpandedParameterPack()), |
2402 | PointeeType(Pointee) {} |
2403 | |
2404 | public: |
2405 | // Get the pointee type. Pointee is required to always be a function type. |
2406 | QualType getPointeeType() const { return PointeeType; } |
2407 | |
2408 | bool isSugared() const { return false; } |
2409 | QualType desugar() const { return QualType(this, 0); } |
2410 | |
2411 | void Profile(llvm::FoldingSetNodeID &ID) { |
2412 | Profile(ID, getPointeeType()); |
2413 | } |
2414 | |
2415 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2416 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2417 | } |
2418 | |
2419 | static bool classof(const Type *T) { |
2420 | return T->getTypeClass() == BlockPointer; |
2421 | } |
2422 | }; |
2423 | |
2424 | /// Base for LValueReferenceType and RValueReferenceType |
2425 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2426 | QualType PointeeType; |
2427 | |
2428 | protected: |
2429 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2430 | bool SpelledAsLValue) |
2431 | : Type(tc, CanonicalRef, Referencee->isDependentType(), |
2432 | Referencee->isInstantiationDependentType(), |
2433 | Referencee->isVariablyModifiedType(), |
2434 | Referencee->containsUnexpandedParameterPack()), |
2435 | PointeeType(Referencee) { |
2436 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2437 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2438 | } |
2439 | |
2440 | public: |
2441 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2442 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2443 | |
2444 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2445 | |
2446 | QualType getPointeeType() const { |
2447 | // FIXME: this might strip inner qualifiers; okay? |
2448 | const ReferenceType *T = this; |
2449 | while (T->isInnerRef()) |
2450 | T = T->PointeeType->castAs<ReferenceType>(); |
2451 | return T->PointeeType; |
2452 | } |
2453 | |
2454 | void Profile(llvm::FoldingSetNodeID &ID) { |
2455 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2456 | } |
2457 | |
2458 | static void Profile(llvm::FoldingSetNodeID &ID, |
2459 | QualType Referencee, |
2460 | bool SpelledAsLValue) { |
2461 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2462 | ID.AddBoolean(SpelledAsLValue); |
2463 | } |
2464 | |
2465 | static bool classof(const Type *T) { |
2466 | return T->getTypeClass() == LValueReference || |
2467 | T->getTypeClass() == RValueReference; |
2468 | } |
2469 | }; |
2470 | |
2471 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2472 | class LValueReferenceType : public ReferenceType { |
2473 | friend class ASTContext; // ASTContext creates these |
2474 | |
2475 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2476 | bool SpelledAsLValue) |
2477 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2478 | SpelledAsLValue) {} |
2479 | |
2480 | public: |
2481 | bool isSugared() const { return false; } |
2482 | QualType desugar() const { return QualType(this, 0); } |
2483 | |
2484 | static bool classof(const Type *T) { |
2485 | return T->getTypeClass() == LValueReference; |
2486 | } |
2487 | }; |
2488 | |
2489 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2490 | class RValueReferenceType : public ReferenceType { |
2491 | friend class ASTContext; // ASTContext creates these |
2492 | |
2493 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2494 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2495 | |
2496 | public: |
2497 | bool isSugared() const { return false; } |
2498 | QualType desugar() const { return QualType(this, 0); } |
2499 | |
2500 | static bool classof(const Type *T) { |
2501 | return T->getTypeClass() == RValueReference; |
2502 | } |
2503 | }; |
2504 | |
2505 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2506 | /// |
2507 | /// This includes both pointers to data members and pointer to member functions. |
2508 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2509 | friend class ASTContext; // ASTContext creates these. |
2510 | |
2511 | QualType PointeeType; |
2512 | |
2513 | /// The class of which the pointee is a member. Must ultimately be a |
2514 | /// RecordType, but could be a typedef or a template parameter too. |
2515 | const Type *Class; |
2516 | |
2517 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2518 | : Type(MemberPointer, CanonicalPtr, |
2519 | Cls->isDependentType() || Pointee->isDependentType(), |
2520 | (Cls->isInstantiationDependentType() || |
2521 | Pointee->isInstantiationDependentType()), |
2522 | Pointee->isVariablyModifiedType(), |
2523 | (Cls->containsUnexpandedParameterPack() || |
2524 | Pointee->containsUnexpandedParameterPack())), |
2525 | PointeeType(Pointee), Class(Cls) {} |
2526 | |
2527 | public: |
2528 | QualType getPointeeType() const { return PointeeType; } |
2529 | |
2530 | /// Returns true if the member type (i.e. the pointee type) is a |
2531 | /// function type rather than a data-member type. |
2532 | bool isMemberFunctionPointer() const { |
2533 | return PointeeType->isFunctionProtoType(); |
2534 | } |
2535 | |
2536 | /// Returns true if the member type (i.e. the pointee type) is a |
2537 | /// data type rather than a function type. |
2538 | bool isMemberDataPointer() const { |
2539 | return !PointeeType->isFunctionProtoType(); |
2540 | } |
2541 | |
2542 | const Type *getClass() const { return Class; } |
2543 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2544 | |
2545 | bool isSugared() const { return false; } |
2546 | QualType desugar() const { return QualType(this, 0); } |
2547 | |
2548 | void Profile(llvm::FoldingSetNodeID &ID) { |
2549 | Profile(ID, getPointeeType(), getClass()); |
2550 | } |
2551 | |
2552 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2553 | const Type *Class) { |
2554 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2555 | ID.AddPointer(Class); |
2556 | } |
2557 | |
2558 | static bool classof(const Type *T) { |
2559 | return T->getTypeClass() == MemberPointer; |
2560 | } |
2561 | }; |
2562 | |
2563 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2564 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2565 | public: |
2566 | /// Capture whether this is a normal array (e.g. int X[4]) |
2567 | /// an array with a static size (e.g. int X[static 4]), or an array |
2568 | /// with a star size (e.g. int X[*]). |
2569 | /// 'static' is only allowed on function parameters. |
2570 | enum ArraySizeModifier { |
2571 | Normal, Static, Star |
2572 | }; |
2573 | |
2574 | private: |
2575 | /// The element type of the array. |
2576 | QualType ElementType; |
2577 | |
2578 | protected: |
2579 | friend class ASTContext; // ASTContext creates these. |
2580 | |
2581 | // C++ [temp.dep.type]p1: |
2582 | // A type is dependent if it is... |
2583 | // - an array type constructed from any dependent type or whose |
2584 | // size is specified by a constant expression that is |
2585 | // value-dependent, |
2586 | ArrayType(TypeClass tc, QualType et, QualType can, |
2587 | ArraySizeModifier sm, unsigned tq, |
2588 | bool ContainsUnexpandedParameterPack) |
2589 | : Type(tc, can, et->isDependentType() || tc == DependentSizedArray, |
2590 | et->isInstantiationDependentType() || tc == DependentSizedArray, |
2591 | (tc == VariableArray || et->isVariablyModifiedType()), |
2592 | ContainsUnexpandedParameterPack), |
2593 | ElementType(et) { |
2594 | ArrayTypeBits.IndexTypeQuals = tq; |
2595 | ArrayTypeBits.SizeModifier = sm; |
2596 | } |
2597 | |
2598 | public: |
2599 | QualType getElementType() const { return ElementType; } |
2600 | |
2601 | ArraySizeModifier getSizeModifier() const { |
2602 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2603 | } |
2604 | |
2605 | Qualifiers getIndexTypeQualifiers() const { |
2606 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2607 | } |
2608 | |
2609 | unsigned getIndexTypeCVRQualifiers() const { |
2610 | return ArrayTypeBits.IndexTypeQuals; |
2611 | } |
2612 | |
2613 | static bool classof(const Type *T) { |
2614 | return T->getTypeClass() == ConstantArray || |
2615 | T->getTypeClass() == VariableArray || |
2616 | T->getTypeClass() == IncompleteArray || |
2617 | T->getTypeClass() == DependentSizedArray; |
2618 | } |
2619 | }; |
2620 | |
2621 | /// Represents the canonical version of C arrays with a specified constant size. |
2622 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2623 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2624 | class ConstantArrayType : public ArrayType { |
2625 | llvm::APInt Size; // Allows us to unique the type. |
2626 | |
2627 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2628 | ArraySizeModifier sm, unsigned tq) |
2629 | : ArrayType(ConstantArray, et, can, sm, tq, |
2630 | et->containsUnexpandedParameterPack()), |
2631 | Size(size) {} |
2632 | |
2633 | protected: |
2634 | friend class ASTContext; // ASTContext creates these. |
2635 | |
2636 | ConstantArrayType(TypeClass tc, QualType et, QualType can, |
2637 | const llvm::APInt &size, ArraySizeModifier sm, unsigned tq) |
2638 | : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()), |
2639 | Size(size) {} |
2640 | |
2641 | public: |
2642 | const llvm::APInt &getSize() const { return Size; } |
2643 | bool isSugared() const { return false; } |
2644 | QualType desugar() const { return QualType(this, 0); } |
2645 | |
2646 | /// \brief Determine the number of bits required to address a member of |
2647 | // an array with the given element type and number of elements. |
2648 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2649 | QualType ElementType, |
2650 | const llvm::APInt &NumElements); |
2651 | |
2652 | /// \brief Determine the maximum number of active bits that an array's size |
2653 | /// can require, which limits the maximum size of the array. |
2654 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2655 | |
2656 | void Profile(llvm::FoldingSetNodeID &ID) { |
2657 | Profile(ID, getElementType(), getSize(), |
2658 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2659 | } |
2660 | |
2661 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2662 | const llvm::APInt &ArraySize, ArraySizeModifier SizeMod, |
2663 | unsigned TypeQuals) { |
2664 | ID.AddPointer(ET.getAsOpaquePtr()); |
2665 | ID.AddInteger(ArraySize.getZExtValue()); |
2666 | ID.AddInteger(SizeMod); |
2667 | ID.AddInteger(TypeQuals); |
2668 | } |
2669 | |
2670 | static bool classof(const Type *T) { |
2671 | return T->getTypeClass() == ConstantArray; |
2672 | } |
2673 | }; |
2674 | |
2675 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2676 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2677 | /// unspecified. |
2678 | class IncompleteArrayType : public ArrayType { |
2679 | friend class ASTContext; // ASTContext creates these. |
2680 | |
2681 | IncompleteArrayType(QualType et, QualType can, |
2682 | ArraySizeModifier sm, unsigned tq) |
2683 | : ArrayType(IncompleteArray, et, can, sm, tq, |
2684 | et->containsUnexpandedParameterPack()) {} |
2685 | |
2686 | public: |
2687 | friend class StmtIteratorBase; |
2688 | |
2689 | bool isSugared() const { return false; } |
2690 | QualType desugar() const { return QualType(this, 0); } |
2691 | |
2692 | static bool classof(const Type *T) { |
2693 | return T->getTypeClass() == IncompleteArray; |
2694 | } |
2695 | |
2696 | void Profile(llvm::FoldingSetNodeID &ID) { |
2697 | Profile(ID, getElementType(), getSizeModifier(), |
2698 | getIndexTypeCVRQualifiers()); |
2699 | } |
2700 | |
2701 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2702 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2703 | ID.AddPointer(ET.getAsOpaquePtr()); |
2704 | ID.AddInteger(SizeMod); |
2705 | ID.AddInteger(TypeQuals); |
2706 | } |
2707 | }; |
2708 | |
2709 | /// Represents a C array with a specified size that is not an |
2710 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
2711 | /// Since the size expression is an arbitrary expression, we store it as such. |
2712 | /// |
2713 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
2714 | /// should not be: two lexically equivalent variable array types could mean |
2715 | /// different things, for example, these variables do not have the same type |
2716 | /// dynamically: |
2717 | /// |
2718 | /// void foo(int x) { |
2719 | /// int Y[x]; |
2720 | /// ++x; |
2721 | /// int Z[x]; |
2722 | /// } |
2723 | class VariableArrayType : public ArrayType { |
2724 | friend class ASTContext; // ASTContext creates these. |
2725 | |
2726 | /// An assignment-expression. VLA's are only permitted within |
2727 | /// a function block. |
2728 | Stmt *SizeExpr; |
2729 | |
2730 | /// The range spanned by the left and right array brackets. |
2731 | SourceRange Brackets; |
2732 | |
2733 | VariableArrayType(QualType et, QualType can, Expr *e, |
2734 | ArraySizeModifier sm, unsigned tq, |
2735 | SourceRange brackets) |
2736 | : ArrayType(VariableArray, et, can, sm, tq, |
2737 | et->containsUnexpandedParameterPack()), |
2738 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
2739 | |
2740 | public: |
2741 | friend class StmtIteratorBase; |
2742 | |
2743 | Expr *getSizeExpr() const { |
2744 | // We use C-style casts instead of cast<> here because we do not wish |
2745 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
2746 | return (Expr*) SizeExpr; |
2747 | } |
2748 | |
2749 | SourceRange getBracketsRange() const { return Brackets; } |
2750 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
2751 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
2752 | |
2753 | bool isSugared() const { return false; } |
2754 | QualType desugar() const { return QualType(this, 0); } |
2755 | |
2756 | static bool classof(const Type *T) { |
2757 | return T->getTypeClass() == VariableArray; |
2758 | } |
2759 | |
2760 | void Profile(llvm::FoldingSetNodeID &ID) { |
2761 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 2761); |
2762 | } |
2763 | }; |
2764 | |
2765 | /// Represents an array type in C++ whose size is a value-dependent expression. |
2766 | /// |
2767 | /// For example: |
2768 | /// \code |
2769 | /// template<typename T, int Size> |
2770 | /// class array { |
2771 | /// T data[Size]; |
2772 | /// }; |
2773 | /// \endcode |
2774 | /// |
2775 | /// For these types, we won't actually know what the array bound is |
2776 | /// until template instantiation occurs, at which point this will |
2777 | /// become either a ConstantArrayType or a VariableArrayType. |
2778 | class DependentSizedArrayType : public ArrayType { |
2779 | friend class ASTContext; // ASTContext creates these. |
2780 | |
2781 | const ASTContext &Context; |
2782 | |
2783 | /// \brief An assignment expression that will instantiate to the |
2784 | /// size of the array. |
2785 | /// |
2786 | /// The expression itself might be null, in which case the array |
2787 | /// type will have its size deduced from an initializer. |
2788 | Stmt *SizeExpr; |
2789 | |
2790 | /// The range spanned by the left and right array brackets. |
2791 | SourceRange Brackets; |
2792 | |
2793 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
2794 | Expr *e, ArraySizeModifier sm, unsigned tq, |
2795 | SourceRange brackets); |
2796 | |
2797 | public: |
2798 | friend class StmtIteratorBase; |
2799 | |
2800 | Expr *getSizeExpr() const { |
2801 | // We use C-style casts instead of cast<> here because we do not wish |
2802 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
2803 | return (Expr*) SizeExpr; |
2804 | } |
2805 | |
2806 | SourceRange getBracketsRange() const { return Brackets; } |
2807 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
2808 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
2809 | |
2810 | bool isSugared() const { return false; } |
2811 | QualType desugar() const { return QualType(this, 0); } |
2812 | |
2813 | static bool classof(const Type *T) { |
2814 | return T->getTypeClass() == DependentSizedArray; |
2815 | } |
2816 | |
2817 | void Profile(llvm::FoldingSetNodeID &ID) { |
2818 | Profile(ID, Context, getElementType(), |
2819 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
2820 | } |
2821 | |
2822 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
2823 | QualType ET, ArraySizeModifier SizeMod, |
2824 | unsigned TypeQuals, Expr *E); |
2825 | }; |
2826 | |
2827 | /// Represents an extended address space qualifier where the input address space |
2828 | /// value is dependent. Non-dependent address spaces are not represented with a |
2829 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
2830 | /// |
2831 | /// For example: |
2832 | /// \code |
2833 | /// template<typename T, int AddrSpace> |
2834 | /// class AddressSpace { |
2835 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
2836 | /// } |
2837 | /// \endcode |
2838 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
2839 | friend class ASTContext; |
2840 | |
2841 | const ASTContext &Context; |
2842 | Expr *AddrSpaceExpr; |
2843 | QualType PointeeType; |
2844 | SourceLocation loc; |
2845 | |
2846 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
2847 | QualType can, Expr *AddrSpaceExpr, |
2848 | SourceLocation loc); |
2849 | |
2850 | public: |
2851 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
2852 | QualType getPointeeType() const { return PointeeType; } |
2853 | SourceLocation getAttributeLoc() const { return loc; } |
2854 | |
2855 | bool isSugared() const { return false; } |
2856 | QualType desugar() const { return QualType(this, 0); } |
2857 | |
2858 | static bool classof(const Type *T) { |
2859 | return T->getTypeClass() == DependentAddressSpace; |
2860 | } |
2861 | |
2862 | void Profile(llvm::FoldingSetNodeID &ID) { |
2863 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
2864 | } |
2865 | |
2866 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
2867 | QualType PointeeType, Expr *AddrSpaceExpr); |
2868 | }; |
2869 | |
2870 | /// Represents an extended vector type where either the type or size is |
2871 | /// dependent. |
2872 | /// |
2873 | /// For example: |
2874 | /// \code |
2875 | /// template<typename T, int Size> |
2876 | /// class vector { |
2877 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
2878 | /// } |
2879 | /// \endcode |
2880 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
2881 | friend class ASTContext; |
2882 | |
2883 | const ASTContext &Context; |
2884 | Expr *SizeExpr; |
2885 | |
2886 | /// The element type of the array. |
2887 | QualType ElementType; |
2888 | |
2889 | SourceLocation loc; |
2890 | |
2891 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
2892 | QualType can, Expr *SizeExpr, SourceLocation loc); |
2893 | |
2894 | public: |
2895 | Expr *getSizeExpr() const { return SizeExpr; } |
2896 | QualType getElementType() const { return ElementType; } |
2897 | SourceLocation getAttributeLoc() const { return loc; } |
2898 | |
2899 | bool isSugared() const { return false; } |
2900 | QualType desugar() const { return QualType(this, 0); } |
2901 | |
2902 | static bool classof(const Type *T) { |
2903 | return T->getTypeClass() == DependentSizedExtVector; |
2904 | } |
2905 | |
2906 | void Profile(llvm::FoldingSetNodeID &ID) { |
2907 | Profile(ID, Context, getElementType(), getSizeExpr()); |
2908 | } |
2909 | |
2910 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
2911 | QualType ElementType, Expr *SizeExpr); |
2912 | }; |
2913 | |
2914 | |
2915 | /// Represents a GCC generic vector type. This type is created using |
2916 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
2917 | /// bytes; or from an Altivec __vector or vector declaration. |
2918 | /// Since the constructor takes the number of vector elements, the |
2919 | /// client is responsible for converting the size into the number of elements. |
2920 | class VectorType : public Type, public llvm::FoldingSetNode { |
2921 | public: |
2922 | enum VectorKind { |
2923 | /// not a target-specific vector type |
2924 | GenericVector, |
2925 | |
2926 | /// is AltiVec vector |
2927 | AltiVecVector, |
2928 | |
2929 | /// is AltiVec 'vector Pixel' |
2930 | AltiVecPixel, |
2931 | |
2932 | /// is AltiVec 'vector bool ...' |
2933 | AltiVecBool, |
2934 | |
2935 | /// is ARM Neon vector |
2936 | NeonVector, |
2937 | |
2938 | /// is ARM Neon polynomial vector |
2939 | NeonPolyVector |
2940 | }; |
2941 | |
2942 | protected: |
2943 | friend class ASTContext; // ASTContext creates these. |
2944 | |
2945 | /// The element type of the vector. |
2946 | QualType ElementType; |
2947 | |
2948 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
2949 | VectorKind vecKind); |
2950 | |
2951 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
2952 | QualType canonType, VectorKind vecKind); |
2953 | |
2954 | public: |
2955 | QualType getElementType() const { return ElementType; } |
2956 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
2957 | |
2958 | static bool isVectorSizeTooLarge(unsigned NumElements) { |
2959 | return NumElements > VectorTypeBitfields::MaxNumElements; |
2960 | } |
2961 | |
2962 | bool isSugared() const { return false; } |
2963 | QualType desugar() const { return QualType(this, 0); } |
2964 | |
2965 | VectorKind getVectorKind() const { |
2966 | return VectorKind(VectorTypeBits.VecKind); |
2967 | } |
2968 | |
2969 | void Profile(llvm::FoldingSetNodeID &ID) { |
2970 | Profile(ID, getElementType(), getNumElements(), |
2971 | getTypeClass(), getVectorKind()); |
2972 | } |
2973 | |
2974 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
2975 | unsigned NumElements, TypeClass TypeClass, |
2976 | VectorKind VecKind) { |
2977 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
2978 | ID.AddInteger(NumElements); |
2979 | ID.AddInteger(TypeClass); |
2980 | ID.AddInteger(VecKind); |
2981 | } |
2982 | |
2983 | static bool classof(const Type *T) { |
2984 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
2985 | } |
2986 | }; |
2987 | |
2988 | /// ExtVectorType - Extended vector type. This type is created using |
2989 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
2990 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
2991 | /// class enables syntactic extensions, like Vector Components for accessing |
2992 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
2993 | /// Shading Language). |
2994 | class ExtVectorType : public VectorType { |
2995 | friend class ASTContext; // ASTContext creates these. |
2996 | |
2997 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
2998 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
2999 | |
3000 | public: |
3001 | static int getPointAccessorIdx(char c) { |
3002 | switch (c) { |
3003 | default: return -1; |
3004 | case 'x': case 'r': return 0; |
3005 | case 'y': case 'g': return 1; |
3006 | case 'z': case 'b': return 2; |
3007 | case 'w': case 'a': return 3; |
3008 | } |
3009 | } |
3010 | |
3011 | static int getNumericAccessorIdx(char c) { |
3012 | switch (c) { |
3013 | default: return -1; |
3014 | case '0': return 0; |
3015 | case '1': return 1; |
3016 | case '2': return 2; |
3017 | case '3': return 3; |
3018 | case '4': return 4; |
3019 | case '5': return 5; |
3020 | case '6': return 6; |
3021 | case '7': return 7; |
3022 | case '8': return 8; |
3023 | case '9': return 9; |
3024 | case 'A': |
3025 | case 'a': return 10; |
3026 | case 'B': |
3027 | case 'b': return 11; |
3028 | case 'C': |
3029 | case 'c': return 12; |
3030 | case 'D': |
3031 | case 'd': return 13; |
3032 | case 'E': |
3033 | case 'e': return 14; |
3034 | case 'F': |
3035 | case 'f': return 15; |
3036 | } |
3037 | } |
3038 | |
3039 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3040 | if (isNumericAccessor) |
3041 | return getNumericAccessorIdx(c); |
3042 | else |
3043 | return getPointAccessorIdx(c); |
3044 | } |
3045 | |
3046 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3047 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3048 | return unsigned(idx-1) < getNumElements(); |
3049 | return false; |
3050 | } |
3051 | |
3052 | bool isSugared() const { return false; } |
3053 | QualType desugar() const { return QualType(this, 0); } |
3054 | |
3055 | static bool classof(const Type *T) { |
3056 | return T->getTypeClass() == ExtVector; |
3057 | } |
3058 | }; |
3059 | |
3060 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3061 | /// class of FunctionNoProtoType and FunctionProtoType. |
3062 | class FunctionType : public Type { |
3063 | // The type returned by the function. |
3064 | QualType ResultType; |
3065 | |
3066 | public: |
3067 | /// A class which abstracts out some details necessary for |
3068 | /// making a call. |
3069 | /// |
3070 | /// It is not actually used directly for storing this information in |
3071 | /// a FunctionType, although FunctionType does currently use the |
3072 | /// same bit-pattern. |
3073 | /// |
3074 | // If you add a field (say Foo), other than the obvious places (both, |
3075 | // constructors, compile failures), what you need to update is |
3076 | // * Operator== |
3077 | // * getFoo |
3078 | // * withFoo |
3079 | // * functionType. Add Foo, getFoo. |
3080 | // * ASTContext::getFooType |
3081 | // * ASTContext::mergeFunctionTypes |
3082 | // * FunctionNoProtoType::Profile |
3083 | // * FunctionProtoType::Profile |
3084 | // * TypePrinter::PrintFunctionProto |
3085 | // * AST read and write |
3086 | // * Codegen |
3087 | class ExtInfo { |
3088 | friend class FunctionType; |
3089 | |
3090 | // Feel free to rearrange or add bits, but if you go over 11, |
3091 | // you'll need to adjust both the Bits field below and |
3092 | // Type::FunctionTypeBitfields. |
3093 | |
3094 | // | CC |noreturn|produces|nocallersavedregs|regparm| |
3095 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| |
3096 | // |
3097 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3098 | enum { CallConvMask = 0x1F }; |
3099 | enum { NoReturnMask = 0x20 }; |
3100 | enum { ProducesResultMask = 0x40 }; |
3101 | enum { NoCallerSavedRegsMask = 0x80 }; |
3102 | enum { |
3103 | RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask | |
3104 | NoCallerSavedRegsMask), |
3105 | RegParmOffset = 8 |
3106 | }; // Assumed to be the last field |
3107 | |
3108 | uint16_t Bits = CC_C; |
3109 | |
3110 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3111 | |
3112 | public: |
3113 | // Constructor with no defaults. Use this when you know that you |
3114 | // have all the elements (when reading an AST file for example). |
3115 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3116 | bool producesResult, bool noCallerSavedRegs) { |
3117 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(static_cast <bool> ((!hasRegParm || regParm < 7) && "Invalid regparm value") ? void (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3117, __extension__ __PRETTY_FUNCTION__)); |
3118 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3119 | (producesResult ? ProducesResultMask : 0) | |
3120 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3121 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0); |
3122 | } |
3123 | |
3124 | // Constructor with all defaults. Use when for example creating a |
3125 | // function known to use defaults. |
3126 | ExtInfo() = default; |
3127 | |
3128 | // Constructor with just the calling convention, which is an important part |
3129 | // of the canonical type. |
3130 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3131 | |
3132 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3133 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3134 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3135 | bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; } |
3136 | |
3137 | unsigned getRegParm() const { |
3138 | unsigned RegParm = Bits >> RegParmOffset; |
3139 | if (RegParm > 0) |
3140 | --RegParm; |
3141 | return RegParm; |
3142 | } |
3143 | |
3144 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3145 | |
3146 | bool operator==(ExtInfo Other) const { |
3147 | return Bits == Other.Bits; |
3148 | } |
3149 | bool operator!=(ExtInfo Other) const { |
3150 | return Bits != Other.Bits; |
3151 | } |
3152 | |
3153 | // Note that we don't have setters. That is by design, use |
3154 | // the following with methods instead of mutating these objects. |
3155 | |
3156 | ExtInfo withNoReturn(bool noReturn) const { |
3157 | if (noReturn) |
3158 | return ExtInfo(Bits | NoReturnMask); |
3159 | else |
3160 | return ExtInfo(Bits & ~NoReturnMask); |
3161 | } |
3162 | |
3163 | ExtInfo withProducesResult(bool producesResult) const { |
3164 | if (producesResult) |
3165 | return ExtInfo(Bits | ProducesResultMask); |
3166 | else |
3167 | return ExtInfo(Bits & ~ProducesResultMask); |
3168 | } |
3169 | |
3170 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3171 | if (noCallerSavedRegs) |
3172 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3173 | else |
3174 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3175 | } |
3176 | |
3177 | ExtInfo withRegParm(unsigned RegParm) const { |
3178 | assert(RegParm < 7 && "Invalid regparm value")(static_cast <bool> (RegParm < 7 && "Invalid regparm value" ) ? void (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3178, __extension__ __PRETTY_FUNCTION__)); |
3179 | return ExtInfo((Bits & ~RegParmMask) | |
3180 | ((RegParm + 1) << RegParmOffset)); |
3181 | } |
3182 | |
3183 | ExtInfo withCallingConv(CallingConv cc) const { |
3184 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3185 | } |
3186 | |
3187 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3188 | ID.AddInteger(Bits); |
3189 | } |
3190 | }; |
3191 | |
3192 | protected: |
3193 | FunctionType(TypeClass tc, QualType res, |
3194 | QualType Canonical, bool Dependent, |
3195 | bool InstantiationDependent, |
3196 | bool VariablyModified, bool ContainsUnexpandedParameterPack, |
3197 | ExtInfo Info) |
3198 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
3199 | ContainsUnexpandedParameterPack), |
3200 | ResultType(res) { |
3201 | FunctionTypeBits.ExtInfo = Info.Bits; |
3202 | } |
3203 | |
3204 | unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; } |
3205 | |
3206 | public: |
3207 | QualType getReturnType() const { return ResultType; } |
3208 | |
3209 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3210 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3211 | |
3212 | /// Determine whether this function type includes the GNU noreturn |
3213 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3214 | /// type. |
3215 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3216 | |
3217 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3218 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3219 | bool isConst() const { return getTypeQuals() & Qualifiers::Const; } |
3220 | bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; } |
3221 | bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; } |
3222 | |
3223 | /// \brief Determine the type of an expression that calls a function of |
3224 | /// this type. |
3225 | QualType getCallResultType(const ASTContext &Context) const { |
3226 | return getReturnType().getNonLValueExprType(Context); |
3227 | } |
3228 | |
3229 | static StringRef getNameForCallConv(CallingConv CC); |
3230 | |
3231 | static bool classof(const Type *T) { |
3232 | return T->getTypeClass() == FunctionNoProto || |
3233 | T->getTypeClass() == FunctionProto; |
3234 | } |
3235 | }; |
3236 | |
3237 | /// Represents a K&R-style 'int foo()' function, which has |
3238 | /// no information available about its arguments. |
3239 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3240 | friend class ASTContext; // ASTContext creates these. |
3241 | |
3242 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3243 | : FunctionType(FunctionNoProto, Result, Canonical, |
3244 | /*Dependent=*/false, /*InstantiationDependent=*/false, |
3245 | Result->isVariablyModifiedType(), |
3246 | /*ContainsUnexpandedParameterPack=*/false, Info) {} |
3247 | |
3248 | public: |
3249 | // No additional state past what FunctionType provides. |
3250 | |
3251 | bool isSugared() const { return false; } |
3252 | QualType desugar() const { return QualType(this, 0); } |
3253 | |
3254 | void Profile(llvm::FoldingSetNodeID &ID) { |
3255 | Profile(ID, getReturnType(), getExtInfo()); |
3256 | } |
3257 | |
3258 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3259 | ExtInfo Info) { |
3260 | Info.Profile(ID); |
3261 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3262 | } |
3263 | |
3264 | static bool classof(const Type *T) { |
3265 | return T->getTypeClass() == FunctionNoProto; |
3266 | } |
3267 | }; |
3268 | |
3269 | /// Represents a prototype with parameter type info, e.g. |
3270 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3271 | /// parameters, not as having a single void parameter. Such a type can have an |
3272 | /// exception specification, but this specification is not part of the canonical |
3273 | /// type. |
3274 | class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode { |
3275 | public: |
3276 | /// Interesting information about a specific parameter that can't simply |
3277 | /// be reflected in parameter's type. |
3278 | /// |
3279 | /// It makes sense to model language features this way when there's some |
3280 | /// sort of parameter-specific override (such as an attribute) that |
3281 | /// affects how the function is called. For example, the ARC ns_consumed |
3282 | /// attribute changes whether a parameter is passed at +0 (the default) |
3283 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3284 | /// but isn't really a change to the parameter type. |
3285 | /// |
3286 | /// One serious disadvantage of modelling language features this way is |
3287 | /// that they generally do not work with language features that attempt |
3288 | /// to destructure types. For example, template argument deduction will |
3289 | /// not be able to match a parameter declared as |
3290 | /// T (*)(U) |
3291 | /// against an argument of type |
3292 | /// void (*)(__attribute__((ns_consumed)) id) |
3293 | /// because the substitution of T=void, U=id into the former will |
3294 | /// not produce the latter. |
3295 | class ExtParameterInfo { |
3296 | enum { |
3297 | ABIMask = 0x0F, |
3298 | IsConsumed = 0x10, |
3299 | HasPassObjSize = 0x20, |
3300 | IsNoEscape = 0x40, |
3301 | }; |
3302 | unsigned char Data = 0; |
3303 | |
3304 | public: |
3305 | ExtParameterInfo() = default; |
3306 | |
3307 | /// Return the ABI treatment of this parameter. |
3308 | ParameterABI getABI() const { |
3309 | return ParameterABI(Data & ABIMask); |
3310 | } |
3311 | ExtParameterInfo withABI(ParameterABI kind) const { |
3312 | ExtParameterInfo copy = *this; |
3313 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3314 | return copy; |
3315 | } |
3316 | |
3317 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3318 | /// Consumed parameters must have retainable object type. |
3319 | bool isConsumed() const { |
3320 | return (Data & IsConsumed); |
3321 | } |
3322 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3323 | ExtParameterInfo copy = *this; |
3324 | if (consumed) { |
3325 | copy.Data |= IsConsumed; |
3326 | } else { |
3327 | copy.Data &= ~IsConsumed; |
3328 | } |
3329 | return copy; |
3330 | } |
3331 | |
3332 | bool hasPassObjectSize() const { |
3333 | return Data & HasPassObjSize; |
3334 | } |
3335 | ExtParameterInfo withHasPassObjectSize() const { |
3336 | ExtParameterInfo Copy = *this; |
3337 | Copy.Data |= HasPassObjSize; |
3338 | return Copy; |
3339 | } |
3340 | |
3341 | bool isNoEscape() const { |
3342 | return Data & IsNoEscape; |
3343 | } |
3344 | |
3345 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3346 | ExtParameterInfo Copy = *this; |
3347 | if (NoEscape) |
3348 | Copy.Data |= IsNoEscape; |
3349 | else |
3350 | Copy.Data &= ~IsNoEscape; |
3351 | return Copy; |
3352 | } |
3353 | |
3354 | unsigned char getOpaqueValue() const { return Data; } |
3355 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3356 | ExtParameterInfo result; |
3357 | result.Data = data; |
3358 | return result; |
3359 | } |
3360 | |
3361 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3362 | return lhs.Data == rhs.Data; |
3363 | } |
3364 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3365 | return lhs.Data != rhs.Data; |
3366 | } |
3367 | }; |
3368 | |
3369 | struct ExceptionSpecInfo { |
3370 | /// The kind of exception specification this is. |
3371 | ExceptionSpecificationType Type = EST_None; |
3372 | |
3373 | /// Explicitly-specified list of exception types. |
3374 | ArrayRef<QualType> Exceptions; |
3375 | |
3376 | /// Noexcept expression, if this is EST_ComputedNoexcept. |
3377 | Expr *NoexceptExpr = nullptr; |
3378 | |
3379 | /// The function whose exception specification this is, for |
3380 | /// EST_Unevaluated and EST_Uninstantiated. |
3381 | FunctionDecl *SourceDecl = nullptr; |
3382 | |
3383 | /// The function template whose exception specification this is instantiated |
3384 | /// from, for EST_Uninstantiated. |
3385 | FunctionDecl *SourceTemplate = nullptr; |
3386 | |
3387 | ExceptionSpecInfo() = default; |
3388 | |
3389 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3390 | }; |
3391 | |
3392 | /// Extra information about a function prototype. |
3393 | struct ExtProtoInfo { |
3394 | FunctionType::ExtInfo ExtInfo; |
3395 | bool Variadic : 1; |
3396 | bool HasTrailingReturn : 1; |
3397 | unsigned char TypeQuals = 0; |
3398 | RefQualifierKind RefQualifier = RQ_None; |
3399 | ExceptionSpecInfo ExceptionSpec; |
3400 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3401 | |
3402 | ExtProtoInfo() |
3403 | : Variadic(false), HasTrailingReturn(false) {} |
3404 | |
3405 | ExtProtoInfo(CallingConv CC) |
3406 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3407 | |
3408 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) { |
3409 | ExtProtoInfo Result(*this); |
3410 | Result.ExceptionSpec = O; |
3411 | return Result; |
3412 | } |
3413 | }; |
3414 | |
3415 | private: |
3416 | friend class ASTContext; // ASTContext creates these. |
3417 | |
3418 | /// \brief Determine whether there are any argument types that |
3419 | /// contain an unexpanded parameter pack. |
3420 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
3421 | unsigned numArgs) { |
3422 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
3423 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
3424 | return true; |
3425 | |
3426 | return false; |
3427 | } |
3428 | |
3429 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
3430 | QualType canonical, const ExtProtoInfo &epi); |
3431 | |
3432 | /// The number of parameters this function has, not counting '...'. |
3433 | unsigned NumParams : 15; |
3434 | |
3435 | /// The number of types in the exception spec, if any. |
3436 | unsigned NumExceptions : 9; |
3437 | |
3438 | /// The type of exception specification this function has. |
3439 | unsigned ExceptionSpecType : 4; |
3440 | |
3441 | /// Whether this function has extended parameter information. |
3442 | unsigned HasExtParameterInfos : 1; |
3443 | |
3444 | /// Whether the function is variadic. |
3445 | unsigned Variadic : 1; |
3446 | |
3447 | /// Whether this function has a trailing return type. |
3448 | unsigned HasTrailingReturn : 1; |
3449 | |
3450 | // ParamInfo - There is an variable size array after the class in memory that |
3451 | // holds the parameter types. |
3452 | |
3453 | // Exceptions - There is another variable size array after ArgInfo that |
3454 | // holds the exception types. |
3455 | |
3456 | // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing |
3457 | // to the expression in the noexcept() specifier. |
3458 | |
3459 | // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may |
3460 | // be a pair of FunctionDecl* pointing to the function which should be used to |
3461 | // instantiate this function type's exception specification, and the function |
3462 | // from which it should be instantiated. |
3463 | |
3464 | // ExtParameterInfos - A variable size array, following the exception |
3465 | // specification and of length NumParams, holding an ExtParameterInfo |
3466 | // for each of the parameters. This only appears if HasExtParameterInfos |
3467 | // is true. |
3468 | |
3469 | const ExtParameterInfo *getExtParameterInfosBuffer() const { |
3470 | assert(hasExtParameterInfos())(static_cast <bool> (hasExtParameterInfos()) ? void (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3470, __extension__ __PRETTY_FUNCTION__)); |
3471 | |
3472 | // Find the end of the exception specification. |
3473 | const char *ptr = reinterpret_cast<const char *>(exception_begin()); |
3474 | ptr += getExceptionSpecSize(); |
3475 | |
3476 | return reinterpret_cast<const ExtParameterInfo *>(ptr); |
3477 | } |
3478 | |
3479 | size_t getExceptionSpecSize() const { |
3480 | switch (getExceptionSpecType()) { |
3481 | case EST_None: return 0; |
3482 | case EST_DynamicNone: return 0; |
3483 | case EST_MSAny: return 0; |
3484 | case EST_BasicNoexcept: return 0; |
3485 | case EST_Unparsed: return 0; |
3486 | case EST_Dynamic: return getNumExceptions() * sizeof(QualType); |
3487 | case EST_ComputedNoexcept: return sizeof(Expr*); |
3488 | case EST_Uninstantiated: return 2 * sizeof(FunctionDecl*); |
3489 | case EST_Unevaluated: return sizeof(FunctionDecl*); |
3490 | } |
3491 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3491); |
3492 | } |
3493 | |
3494 | public: |
3495 | unsigned getNumParams() const { return NumParams; } |
3496 | |
3497 | QualType getParamType(unsigned i) const { |
3498 | assert(i < NumParams && "invalid parameter index")(static_cast <bool> (i < NumParams && "invalid parameter index" ) ? void (0) : __assert_fail ("i < NumParams && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3498, __extension__ __PRETTY_FUNCTION__)); |
3499 | return param_type_begin()[i]; |
3500 | } |
3501 | |
3502 | ArrayRef<QualType> getParamTypes() const { |
3503 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
3504 | } |
3505 | |
3506 | ExtProtoInfo getExtProtoInfo() const { |
3507 | ExtProtoInfo EPI; |
3508 | EPI.ExtInfo = getExtInfo(); |
3509 | EPI.Variadic = isVariadic(); |
3510 | EPI.HasTrailingReturn = hasTrailingReturn(); |
3511 | EPI.ExceptionSpec.Type = getExceptionSpecType(); |
3512 | EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals()); |
3513 | EPI.RefQualifier = getRefQualifier(); |
3514 | if (EPI.ExceptionSpec.Type == EST_Dynamic) { |
3515 | EPI.ExceptionSpec.Exceptions = exceptions(); |
3516 | } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) { |
3517 | EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr(); |
3518 | } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { |
3519 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3520 | EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate(); |
3521 | } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { |
3522 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3523 | } |
3524 | if (hasExtParameterInfos()) |
3525 | EPI.ExtParameterInfos = getExtParameterInfosBuffer(); |
3526 | return EPI; |
3527 | } |
3528 | |
3529 | /// Get the kind of exception specification on this function. |
3530 | ExceptionSpecificationType getExceptionSpecType() const { |
3531 | return static_cast<ExceptionSpecificationType>(ExceptionSpecType); |
3532 | } |
3533 | |
3534 | /// Return whether this function has any kind of exception spec. |
3535 | bool hasExceptionSpec() const { |
3536 | return getExceptionSpecType() != EST_None; |
3537 | } |
3538 | |
3539 | /// Return whether this function has a dynamic (throw) exception spec. |
3540 | bool hasDynamicExceptionSpec() const { |
3541 | return isDynamicExceptionSpec(getExceptionSpecType()); |
3542 | } |
3543 | |
3544 | /// Return whether this function has a noexcept exception spec. |
3545 | bool hasNoexceptExceptionSpec() const { |
3546 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
3547 | } |
3548 | |
3549 | /// Return whether this function has a dependent exception spec. |
3550 | bool hasDependentExceptionSpec() const; |
3551 | |
3552 | /// Return whether this function has an instantiation-dependent exception |
3553 | /// spec. |
3554 | bool hasInstantiationDependentExceptionSpec() const; |
3555 | |
3556 | /// Result type of getNoexceptSpec(). |
3557 | enum NoexceptResult { |
3558 | /// There is no noexcept specifier. |
3559 | NR_NoNoexcept, |
3560 | |
3561 | /// The noexcept specifier has a bad expression. |
3562 | NR_BadNoexcept, |
3563 | |
3564 | /// The noexcept specifier is dependent. |
3565 | NR_Dependent, |
3566 | |
3567 | /// The noexcept specifier evaluates to false. |
3568 | NR_Throw, |
3569 | |
3570 | /// The noexcept specifier evaluates to true. |
3571 | NR_Nothrow |
3572 | }; |
3573 | |
3574 | /// Get the meaning of the noexcept spec on this function, if any. |
3575 | NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const; |
3576 | unsigned getNumExceptions() const { return NumExceptions; } |
3577 | QualType getExceptionType(unsigned i) const { |
3578 | assert(i < NumExceptions && "Invalid exception number!")(static_cast <bool> (i < NumExceptions && "Invalid exception number!" ) ? void (0) : __assert_fail ("i < NumExceptions && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3578, __extension__ __PRETTY_FUNCTION__)); |
3579 | return exception_begin()[i]; |
3580 | } |
3581 | Expr *getNoexceptExpr() const { |
3582 | if (getExceptionSpecType() != EST_ComputedNoexcept) |
3583 | return nullptr; |
3584 | // NoexceptExpr sits where the arguments end. |
3585 | return *reinterpret_cast<Expr *const *>(param_type_end()); |
3586 | } |
3587 | |
3588 | /// \brief If this function type has an exception specification which hasn't |
3589 | /// been determined yet (either because it has not been evaluated or because |
3590 | /// it has not been instantiated), this is the function whose exception |
3591 | /// specification is represented by this type. |
3592 | FunctionDecl *getExceptionSpecDecl() const { |
3593 | if (getExceptionSpecType() != EST_Uninstantiated && |
3594 | getExceptionSpecType() != EST_Unevaluated) |
3595 | return nullptr; |
3596 | return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0]; |
3597 | } |
3598 | |
3599 | /// \brief If this function type has an uninstantiated exception |
3600 | /// specification, this is the function whose exception specification |
3601 | /// should be instantiated to find the exception specification for |
3602 | /// this type. |
3603 | FunctionDecl *getExceptionSpecTemplate() const { |
3604 | if (getExceptionSpecType() != EST_Uninstantiated) |
3605 | return nullptr; |
3606 | return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1]; |
3607 | } |
3608 | |
3609 | /// Determine whether this function type has a non-throwing exception |
3610 | /// specification. |
3611 | CanThrowResult canThrow(const ASTContext &Ctx) const; |
3612 | |
3613 | /// Determine whether this function type has a non-throwing exception |
3614 | /// specification. If this depends on template arguments, returns |
3615 | /// \c ResultIfDependent. |
3616 | bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const { |
3617 | return ResultIfDependent ? canThrow(Ctx) != CT_Can |
3618 | : canThrow(Ctx) == CT_Cannot; |
3619 | } |
3620 | |
3621 | bool isVariadic() const { return Variadic; } |
3622 | |
3623 | /// Determines whether this function prototype contains a |
3624 | /// parameter pack at the end. |
3625 | /// |
3626 | /// A function template whose last parameter is a parameter pack can be |
3627 | /// called with an arbitrary number of arguments, much like a variadic |
3628 | /// function. |
3629 | bool isTemplateVariadic() const; |
3630 | |
3631 | bool hasTrailingReturn() const { return HasTrailingReturn; } |
3632 | |
3633 | unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); } |
3634 | |
3635 | /// Retrieve the ref-qualifier associated with this function type. |
3636 | RefQualifierKind getRefQualifier() const { |
3637 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
3638 | } |
3639 | |
3640 | using param_type_iterator = const QualType *; |
3641 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
3642 | |
3643 | param_type_range param_types() const { |
3644 | return param_type_range(param_type_begin(), param_type_end()); |
3645 | } |
3646 | |
3647 | param_type_iterator param_type_begin() const { |
3648 | return reinterpret_cast<const QualType *>(this+1); |
3649 | } |
3650 | |
3651 | param_type_iterator param_type_end() const { |
3652 | return param_type_begin() + NumParams; |
3653 | } |
3654 | |
3655 | using exception_iterator = const QualType *; |
3656 | |
3657 | ArrayRef<QualType> exceptions() const { |
3658 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
3659 | } |
3660 | |
3661 | exception_iterator exception_begin() const { |
3662 | // exceptions begin where arguments end |
3663 | return param_type_end(); |
3664 | } |
3665 | |
3666 | exception_iterator exception_end() const { |
3667 | if (getExceptionSpecType() != EST_Dynamic) |
3668 | return exception_begin(); |
3669 | return exception_begin() + NumExceptions; |
3670 | } |
3671 | |
3672 | /// Is there any interesting extra information for any of the parameters |
3673 | /// of this function type? |
3674 | bool hasExtParameterInfos() const { return HasExtParameterInfos; } |
3675 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
3676 | assert(hasExtParameterInfos())(static_cast <bool> (hasExtParameterInfos()) ? void (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3676, __extension__ __PRETTY_FUNCTION__)); |
3677 | return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(), |
3678 | getNumParams()); |
3679 | } |
3680 | |
3681 | /// Return a pointer to the beginning of the array of extra parameter |
3682 | /// information, if present, or else null if none of the parameters |
3683 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
3684 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
3685 | if (!hasExtParameterInfos()) |
3686 | return nullptr; |
3687 | return getExtParameterInfosBuffer(); |
3688 | } |
3689 | |
3690 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
3691 | assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range" ) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3691, __extension__ __PRETTY_FUNCTION__)); |
3692 | if (hasExtParameterInfos()) |
3693 | return getExtParameterInfosBuffer()[I]; |
3694 | return ExtParameterInfo(); |
3695 | } |
3696 | |
3697 | ParameterABI getParameterABI(unsigned I) const { |
3698 | assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range" ) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3698, __extension__ __PRETTY_FUNCTION__)); |
3699 | if (hasExtParameterInfos()) |
3700 | return getExtParameterInfosBuffer()[I].getABI(); |
3701 | return ParameterABI::Ordinary; |
3702 | } |
3703 | |
3704 | bool isParamConsumed(unsigned I) const { |
3705 | assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range" ) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3705, __extension__ __PRETTY_FUNCTION__)); |
3706 | if (hasExtParameterInfos()) |
3707 | return getExtParameterInfosBuffer()[I].isConsumed(); |
3708 | return false; |
3709 | } |
3710 | |
3711 | bool isSugared() const { return false; } |
3712 | QualType desugar() const { return QualType(this, 0); } |
3713 | |
3714 | void printExceptionSpecification(raw_ostream &OS, |
3715 | const PrintingPolicy &Policy) const; |
3716 | |
3717 | static bool classof(const Type *T) { |
3718 | return T->getTypeClass() == FunctionProto; |
3719 | } |
3720 | |
3721 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
3722 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
3723 | param_type_iterator ArgTys, unsigned NumArgs, |
3724 | const ExtProtoInfo &EPI, const ASTContext &Context, |
3725 | bool Canonical); |
3726 | }; |
3727 | |
3728 | /// \brief Represents the dependent type named by a dependently-scoped |
3729 | /// typename using declaration, e.g. |
3730 | /// using typename Base<T>::foo; |
3731 | /// |
3732 | /// Template instantiation turns these into the underlying type. |
3733 | class UnresolvedUsingType : public Type { |
3734 | friend class ASTContext; // ASTContext creates these. |
3735 | |
3736 | UnresolvedUsingTypenameDecl *Decl; |
3737 | |
3738 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
3739 | : Type(UnresolvedUsing, QualType(), true, true, false, |
3740 | /*ContainsUnexpandedParameterPack=*/false), |
3741 | Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {} |
3742 | |
3743 | public: |
3744 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
3745 | |
3746 | bool isSugared() const { return false; } |
3747 | QualType desugar() const { return QualType(this, 0); } |
3748 | |
3749 | static bool classof(const Type *T) { |
3750 | return T->getTypeClass() == UnresolvedUsing; |
3751 | } |
3752 | |
3753 | void Profile(llvm::FoldingSetNodeID &ID) { |
3754 | return Profile(ID, Decl); |
3755 | } |
3756 | |
3757 | static void Profile(llvm::FoldingSetNodeID &ID, |
3758 | UnresolvedUsingTypenameDecl *D) { |
3759 | ID.AddPointer(D); |
3760 | } |
3761 | }; |
3762 | |
3763 | class TypedefType : public Type { |
3764 | TypedefNameDecl *Decl; |
3765 | |
3766 | protected: |
3767 | friend class ASTContext; // ASTContext creates these. |
3768 | |
3769 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can) |
3770 | : Type(tc, can, can->isDependentType(), |
3771 | can->isInstantiationDependentType(), |
3772 | can->isVariablyModifiedType(), |
3773 | /*ContainsUnexpandedParameterPack=*/false), |
3774 | Decl(const_cast<TypedefNameDecl*>(D)) { |
3775 | assert(!isa<TypedefType>(can) && "Invalid canonical type")(static_cast <bool> (!isa<TypedefType>(can) && "Invalid canonical type") ? void (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3775, __extension__ __PRETTY_FUNCTION__)); |
3776 | } |
3777 | |
3778 | public: |
3779 | TypedefNameDecl *getDecl() const { return Decl; } |
3780 | |
3781 | bool isSugared() const { return true; } |
3782 | QualType desugar() const; |
3783 | |
3784 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
3785 | }; |
3786 | |
3787 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
3788 | class TypeOfExprType : public Type { |
3789 | Expr *TOExpr; |
3790 | |
3791 | protected: |
3792 | friend class ASTContext; // ASTContext creates these. |
3793 | |
3794 | TypeOfExprType(Expr *E, QualType can = QualType()); |
3795 | |
3796 | public: |
3797 | Expr *getUnderlyingExpr() const { return TOExpr; } |
3798 | |
3799 | /// \brief Remove a single level of sugar. |
3800 | QualType desugar() const; |
3801 | |
3802 | /// \brief Returns whether this type directly provides sugar. |
3803 | bool isSugared() const; |
3804 | |
3805 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
3806 | }; |
3807 | |
3808 | /// \brief Internal representation of canonical, dependent |
3809 | /// `typeof(expr)` types. |
3810 | /// |
3811 | /// This class is used internally by the ASTContext to manage |
3812 | /// canonical, dependent types, only. Clients will only see instances |
3813 | /// of this class via TypeOfExprType nodes. |
3814 | class DependentTypeOfExprType |
3815 | : public TypeOfExprType, public llvm::FoldingSetNode { |
3816 | const ASTContext &Context; |
3817 | |
3818 | public: |
3819 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
3820 | : TypeOfExprType(E), Context(Context) {} |
3821 | |
3822 | void Profile(llvm::FoldingSetNodeID &ID) { |
3823 | Profile(ID, Context, getUnderlyingExpr()); |
3824 | } |
3825 | |
3826 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3827 | Expr *E); |
3828 | }; |
3829 | |
3830 | /// Represents `typeof(type)`, a GCC extension. |
3831 | class TypeOfType : public Type { |
3832 | friend class ASTContext; // ASTContext creates these. |
3833 | |
3834 | QualType TOType; |
3835 | |
3836 | TypeOfType(QualType T, QualType can) |
3837 | : Type(TypeOf, can, T->isDependentType(), |
3838 | T->isInstantiationDependentType(), |
3839 | T->isVariablyModifiedType(), |
3840 | T->containsUnexpandedParameterPack()), |
3841 | TOType(T) { |
3842 | assert(!isa<TypedefType>(can) && "Invalid canonical type")(static_cast <bool> (!isa<TypedefType>(can) && "Invalid canonical type") ? void (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 3842, __extension__ __PRETTY_FUNCTION__)); |
3843 | } |
3844 | |
3845 | public: |
3846 | QualType getUnderlyingType() const { return TOType; } |
3847 | |
3848 | /// \brief Remove a single level of sugar. |
3849 | QualType desugar() const { return getUnderlyingType(); } |
3850 | |
3851 | /// \brief Returns whether this type directly provides sugar. |
3852 | bool isSugared() const { return true; } |
3853 | |
3854 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
3855 | }; |
3856 | |
3857 | /// Represents the type `decltype(expr)` (C++11). |
3858 | class DecltypeType : public Type { |
3859 | Expr *E; |
3860 | QualType UnderlyingType; |
3861 | |
3862 | protected: |
3863 | friend class ASTContext; // ASTContext creates these. |
3864 | |
3865 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
3866 | |
3867 | public: |
3868 | Expr *getUnderlyingExpr() const { return E; } |
3869 | QualType getUnderlyingType() const { return UnderlyingType; } |
3870 | |
3871 | /// \brief Remove a single level of sugar. |
3872 | QualType desugar() const; |
3873 | |
3874 | /// \brief Returns whether this type directly provides sugar. |
3875 | bool isSugared() const; |
3876 | |
3877 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
3878 | }; |
3879 | |
3880 | /// \brief Internal representation of canonical, dependent |
3881 | /// decltype(expr) types. |
3882 | /// |
3883 | /// This class is used internally by the ASTContext to manage |
3884 | /// canonical, dependent types, only. Clients will only see instances |
3885 | /// of this class via DecltypeType nodes. |
3886 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
3887 | const ASTContext &Context; |
3888 | |
3889 | public: |
3890 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
3891 | |
3892 | void Profile(llvm::FoldingSetNodeID &ID) { |
3893 | Profile(ID, Context, getUnderlyingExpr()); |
3894 | } |
3895 | |
3896 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3897 | Expr *E); |
3898 | }; |
3899 | |
3900 | /// A unary type transform, which is a type constructed from another. |
3901 | class UnaryTransformType : public Type { |
3902 | public: |
3903 | enum UTTKind { |
3904 | EnumUnderlyingType |
3905 | }; |
3906 | |
3907 | private: |
3908 | /// The untransformed type. |
3909 | QualType BaseType; |
3910 | |
3911 | /// The transformed type if not dependent, otherwise the same as BaseType. |
3912 | QualType UnderlyingType; |
3913 | |
3914 | UTTKind UKind; |
3915 | |
3916 | protected: |
3917 | friend class ASTContext; |
3918 | |
3919 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
3920 | QualType CanonicalTy); |
3921 | |
3922 | public: |
3923 | bool isSugared() const { return !isDependentType(); } |
3924 | QualType desugar() const { return UnderlyingType; } |
3925 | |
3926 | QualType getUnderlyingType() const { return UnderlyingType; } |
3927 | QualType getBaseType() const { return BaseType; } |
3928 | |
3929 | UTTKind getUTTKind() const { return UKind; } |
3930 | |
3931 | static bool classof(const Type *T) { |
3932 | return T->getTypeClass() == UnaryTransform; |
3933 | } |
3934 | }; |
3935 | |
3936 | /// \brief Internal representation of canonical, dependent |
3937 | /// __underlying_type(type) types. |
3938 | /// |
3939 | /// This class is used internally by the ASTContext to manage |
3940 | /// canonical, dependent types, only. Clients will only see instances |
3941 | /// of this class via UnaryTransformType nodes. |
3942 | class DependentUnaryTransformType : public UnaryTransformType, |
3943 | public llvm::FoldingSetNode { |
3944 | public: |
3945 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
3946 | UTTKind UKind); |
3947 | |
3948 | void Profile(llvm::FoldingSetNodeID &ID) { |
3949 | Profile(ID, getBaseType(), getUTTKind()); |
3950 | } |
3951 | |
3952 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
3953 | UTTKind UKind) { |
3954 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
3955 | ID.AddInteger((unsigned)UKind); |
3956 | } |
3957 | }; |
3958 | |
3959 | class TagType : public Type { |
3960 | friend class ASTReader; |
3961 | |
3962 | /// Stores the TagDecl associated with this type. The decl may point to any |
3963 | /// TagDecl that declares the entity. |
3964 | TagDecl *decl; |
3965 | |
3966 | protected: |
3967 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
3968 | |
3969 | public: |
3970 | TagDecl *getDecl() const; |
3971 | |
3972 | /// Determines whether this type is in the process of being defined. |
3973 | bool isBeingDefined() const; |
3974 | |
3975 | static bool classof(const Type *T) { |
3976 | return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast; |
3977 | } |
3978 | }; |
3979 | |
3980 | /// A helper class that allows the use of isa/cast/dyncast |
3981 | /// to detect TagType objects of structs/unions/classes. |
3982 | class RecordType : public TagType { |
3983 | protected: |
3984 | friend class ASTContext; // ASTContext creates these. |
3985 | |
3986 | explicit RecordType(const RecordDecl *D) |
3987 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
3988 | explicit RecordType(TypeClass TC, RecordDecl *D) |
3989 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
3990 | |
3991 | public: |
3992 | RecordDecl *getDecl() const { |
3993 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
3994 | } |
3995 | |
3996 | /// Recursively check all fields in the record for const-ness. If any field |
3997 | /// is declared const, return true. Otherwise, return false. |
3998 | bool hasConstFields() const; |
3999 | |
4000 | bool isSugared() const { return false; } |
4001 | QualType desugar() const { return QualType(this, 0); } |
4002 | |
4003 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4004 | }; |
4005 | |
4006 | /// A helper class that allows the use of isa/cast/dyncast |
4007 | /// to detect TagType objects of enums. |
4008 | class EnumType : public TagType { |
4009 | friend class ASTContext; // ASTContext creates these. |
4010 | |
4011 | explicit EnumType(const EnumDecl *D) |
4012 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4013 | |
4014 | public: |
4015 | EnumDecl *getDecl() const { |
4016 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4017 | } |
4018 | |
4019 | bool isSugared() const { return false; } |
4020 | QualType desugar() const { return QualType(this, 0); } |
4021 | |
4022 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4023 | }; |
4024 | |
4025 | /// An attributed type is a type to which a type attribute has been applied. |
4026 | /// |
4027 | /// The "modified type" is the fully-sugared type to which the attributed |
4028 | /// type was applied; generally it is not canonically equivalent to the |
4029 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4030 | /// which the type is canonically equivalent to. |
4031 | /// |
4032 | /// For example, in the following attributed type: |
4033 | /// int32_t __attribute__((vector_size(16))) |
4034 | /// - the modified type is the TypedefType for int32_t |
4035 | /// - the equivalent type is VectorType(16, int32_t) |
4036 | /// - the canonical type is VectorType(16, int) |
4037 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4038 | public: |
4039 | // It is really silly to have yet another attribute-kind enum, but |
4040 | // clang::attr::Kind doesn't currently cover the pure type attrs. |
4041 | enum Kind { |
4042 | // Expression operand. |
4043 | attr_address_space, |
4044 | attr_regparm, |
4045 | attr_vector_size, |
4046 | attr_neon_vector_type, |
4047 | attr_neon_polyvector_type, |
4048 | |
4049 | FirstExprOperandKind = attr_address_space, |
4050 | LastExprOperandKind = attr_neon_polyvector_type, |
4051 | |
4052 | // Enumerated operand (string or keyword). |
4053 | attr_objc_gc, |
4054 | attr_objc_ownership, |
4055 | attr_pcs, |
4056 | attr_pcs_vfp, |
4057 | |
4058 | FirstEnumOperandKind = attr_objc_gc, |
4059 | LastEnumOperandKind = attr_pcs_vfp, |
4060 | |
4061 | // No operand. |
4062 | attr_noreturn, |
4063 | attr_cdecl, |
4064 | attr_fastcall, |
4065 | attr_stdcall, |
4066 | attr_thiscall, |
4067 | attr_regcall, |
4068 | attr_pascal, |
4069 | attr_swiftcall, |
4070 | attr_vectorcall, |
4071 | attr_inteloclbicc, |
4072 | attr_ms_abi, |
4073 | attr_sysv_abi, |
4074 | attr_preserve_most, |
4075 | attr_preserve_all, |
4076 | attr_ptr32, |
4077 | attr_ptr64, |
4078 | attr_sptr, |
4079 | attr_uptr, |
4080 | attr_nonnull, |
4081 | attr_ns_returns_retained, |
4082 | attr_nullable, |
4083 | attr_null_unspecified, |
4084 | attr_objc_kindof, |
4085 | attr_objc_inert_unsafe_unretained, |
4086 | }; |
4087 | |
4088 | private: |
4089 | friend class ASTContext; // ASTContext creates these |
4090 | |
4091 | QualType ModifiedType; |
4092 | QualType EquivalentType; |
4093 | |
4094 | AttributedType(QualType canon, Kind attrKind, QualType modified, |
4095 | QualType equivalent) |
4096 | : Type(Attributed, canon, equivalent->isDependentType(), |
4097 | equivalent->isInstantiationDependentType(), |
4098 | equivalent->isVariablyModifiedType(), |
4099 | equivalent->containsUnexpandedParameterPack()), |
4100 | ModifiedType(modified), EquivalentType(equivalent) { |
4101 | AttributedTypeBits.AttrKind = attrKind; |
4102 | } |
4103 | |
4104 | public: |
4105 | Kind getAttrKind() const { |
4106 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4107 | } |
4108 | |
4109 | QualType getModifiedType() const { return ModifiedType; } |
4110 | QualType getEquivalentType() const { return EquivalentType; } |
4111 | |
4112 | bool isSugared() const { return true; } |
4113 | QualType desugar() const { return getEquivalentType(); } |
4114 | |
4115 | /// Does this attribute behave like a type qualifier? |
4116 | /// |
4117 | /// A type qualifier adjusts a type to provide specialized rules for |
4118 | /// a specific object, like the standard const and volatile qualifiers. |
4119 | /// This includes attributes controlling things like nullability, |
4120 | /// address spaces, and ARC ownership. The value of the object is still |
4121 | /// largely described by the modified type. |
4122 | /// |
4123 | /// In contrast, many type attributes "rewrite" their modified type to |
4124 | /// produce a fundamentally different type, not necessarily related in any |
4125 | /// formalizable way to the original type. For example, calling convention |
4126 | /// and vector attributes are not simple type qualifiers. |
4127 | /// |
4128 | /// Type qualifiers are often, but not always, reflected in the canonical |
4129 | /// type. |
4130 | bool isQualifier() const; |
4131 | |
4132 | bool isMSTypeSpec() const; |
4133 | |
4134 | bool isCallingConv() const; |
4135 | |
4136 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4137 | |
4138 | /// Retrieve the attribute kind corresponding to the given |
4139 | /// nullability kind. |
4140 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4141 | switch (kind) { |
4142 | case NullabilityKind::NonNull: |
4143 | return attr_nonnull; |
4144 | |
4145 | case NullabilityKind::Nullable: |
4146 | return attr_nullable; |
4147 | |
4148 | case NullabilityKind::Unspecified: |
4149 | return attr_null_unspecified; |
4150 | } |
4151 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4151); |
4152 | } |
4153 | |
4154 | /// Strip off the top-level nullability annotation on the given |
4155 | /// type, if it's there. |
4156 | /// |
4157 | /// \param T The type to strip. If the type is exactly an |
4158 | /// AttributedType specifying nullability (without looking through |
4159 | /// type sugar), the nullability is returned and this type changed |
4160 | /// to the underlying modified type. |
4161 | /// |
4162 | /// \returns the top-level nullability, if present. |
4163 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4164 | |
4165 | void Profile(llvm::FoldingSetNodeID &ID) { |
4166 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4167 | } |
4168 | |
4169 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4170 | QualType modified, QualType equivalent) { |
4171 | ID.AddInteger(attrKind); |
4172 | ID.AddPointer(modified.getAsOpaquePtr()); |
4173 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4174 | } |
4175 | |
4176 | static bool classof(const Type *T) { |
4177 | return T->getTypeClass() == Attributed; |
4178 | } |
4179 | }; |
4180 | |
4181 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4182 | friend class ASTContext; // ASTContext creates these |
4183 | |
4184 | // Helper data collector for canonical types. |
4185 | struct CanonicalTTPTInfo { |
4186 | unsigned Depth : 15; |
4187 | unsigned ParameterPack : 1; |
4188 | unsigned Index : 16; |
4189 | }; |
4190 | |
4191 | union { |
4192 | // Info for the canonical type. |
4193 | CanonicalTTPTInfo CanTTPTInfo; |
4194 | |
4195 | // Info for the non-canonical type. |
4196 | TemplateTypeParmDecl *TTPDecl; |
4197 | }; |
4198 | |
4199 | /// Build a non-canonical type. |
4200 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4201 | : Type(TemplateTypeParm, Canon, /*Dependent=*/true, |
4202 | /*InstantiationDependent=*/true, |
4203 | /*VariablyModified=*/false, |
4204 | Canon->containsUnexpandedParameterPack()), |
4205 | TTPDecl(TTPDecl) {} |
4206 | |
4207 | /// Build the canonical type. |
4208 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4209 | : Type(TemplateTypeParm, QualType(this, 0), |
4210 | /*Dependent=*/true, |
4211 | /*InstantiationDependent=*/true, |
4212 | /*VariablyModified=*/false, PP) { |
4213 | CanTTPTInfo.Depth = D; |
4214 | CanTTPTInfo.Index = I; |
4215 | CanTTPTInfo.ParameterPack = PP; |
4216 | } |
4217 | |
4218 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4219 | QualType Can = getCanonicalTypeInternal(); |
4220 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4221 | } |
4222 | |
4223 | public: |
4224 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4225 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4226 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4227 | |
4228 | TemplateTypeParmDecl *getDecl() const { |
4229 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4230 | } |
4231 | |
4232 | IdentifierInfo *getIdentifier() const; |
4233 | |
4234 | bool isSugared() const { return false; } |
4235 | QualType desugar() const { return QualType(this, 0); } |
4236 | |
4237 | void Profile(llvm::FoldingSetNodeID &ID) { |
4238 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4239 | } |
4240 | |
4241 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4242 | unsigned Index, bool ParameterPack, |
4243 | TemplateTypeParmDecl *TTPDecl) { |
4244 | ID.AddInteger(Depth); |
4245 | ID.AddInteger(Index); |
4246 | ID.AddBoolean(ParameterPack); |
4247 | ID.AddPointer(TTPDecl); |
4248 | } |
4249 | |
4250 | static bool classof(const Type *T) { |
4251 | return T->getTypeClass() == TemplateTypeParm; |
4252 | } |
4253 | }; |
4254 | |
4255 | /// \brief Represents the result of substituting a type for a template |
4256 | /// type parameter. |
4257 | /// |
4258 | /// Within an instantiated template, all template type parameters have |
4259 | /// been replaced with these. They are used solely to record that a |
4260 | /// type was originally written as a template type parameter; |
4261 | /// therefore they are never canonical. |
4262 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4263 | friend class ASTContext; |
4264 | |
4265 | // The original type parameter. |
4266 | const TemplateTypeParmType *Replaced; |
4267 | |
4268 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4269 | : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(), |
4270 | Canon->isInstantiationDependentType(), |
4271 | Canon->isVariablyModifiedType(), |
4272 | Canon->containsUnexpandedParameterPack()), |
4273 | Replaced(Param) {} |
4274 | |
4275 | public: |
4276 | /// Gets the template parameter that was substituted for. |
4277 | const TemplateTypeParmType *getReplacedParameter() const { |
4278 | return Replaced; |
4279 | } |
4280 | |
4281 | /// Gets the type that was substituted for the template |
4282 | /// parameter. |
4283 | QualType getReplacementType() const { |
4284 | return getCanonicalTypeInternal(); |
4285 | } |
4286 | |
4287 | bool isSugared() const { return true; } |
4288 | QualType desugar() const { return getReplacementType(); } |
4289 | |
4290 | void Profile(llvm::FoldingSetNodeID &ID) { |
4291 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4292 | } |
4293 | |
4294 | static void Profile(llvm::FoldingSetNodeID &ID, |
4295 | const TemplateTypeParmType *Replaced, |
4296 | QualType Replacement) { |
4297 | ID.AddPointer(Replaced); |
4298 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4299 | } |
4300 | |
4301 | static bool classof(const Type *T) { |
4302 | return T->getTypeClass() == SubstTemplateTypeParm; |
4303 | } |
4304 | }; |
4305 | |
4306 | /// \brief Represents the result of substituting a set of types for a template |
4307 | /// type parameter pack. |
4308 | /// |
4309 | /// When a pack expansion in the source code contains multiple parameter packs |
4310 | /// and those parameter packs correspond to different levels of template |
4311 | /// parameter lists, this type node is used to represent a template type |
4312 | /// parameter pack from an outer level, which has already had its argument pack |
4313 | /// substituted but that still lives within a pack expansion that itself |
4314 | /// could not be instantiated. When actually performing a substitution into |
4315 | /// that pack expansion (e.g., when all template parameters have corresponding |
4316 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4317 | /// at the current pack substitution index. |
4318 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4319 | friend class ASTContext; |
4320 | |
4321 | /// \brief The original type parameter. |
4322 | const TemplateTypeParmType *Replaced; |
4323 | |
4324 | /// \brief A pointer to the set of template arguments that this |
4325 | /// parameter pack is instantiated with. |
4326 | const TemplateArgument *Arguments; |
4327 | |
4328 | /// \brief The number of template arguments in \c Arguments. |
4329 | unsigned NumArguments; |
4330 | |
4331 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4332 | QualType Canon, |
4333 | const TemplateArgument &ArgPack); |
4334 | |
4335 | public: |
4336 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4337 | |
4338 | /// Gets the template parameter that was substituted for. |
4339 | const TemplateTypeParmType *getReplacedParameter() const { |
4340 | return Replaced; |
4341 | } |
4342 | |
4343 | bool isSugared() const { return false; } |
4344 | QualType desugar() const { return QualType(this, 0); } |
4345 | |
4346 | TemplateArgument getArgumentPack() const; |
4347 | |
4348 | void Profile(llvm::FoldingSetNodeID &ID); |
4349 | static void Profile(llvm::FoldingSetNodeID &ID, |
4350 | const TemplateTypeParmType *Replaced, |
4351 | const TemplateArgument &ArgPack); |
4352 | |
4353 | static bool classof(const Type *T) { |
4354 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4355 | } |
4356 | }; |
4357 | |
4358 | /// \brief Common base class for placeholders for types that get replaced by |
4359 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4360 | /// class template types, and (eventually) constrained type names from the C++ |
4361 | /// Concepts TS. |
4362 | /// |
4363 | /// These types are usually a placeholder for a deduced type. However, before |
4364 | /// the initializer is attached, or (usually) if the initializer is |
4365 | /// type-dependent, there is no deduced type and the type is canonical. In |
4366 | /// the latter case, it is also a dependent type. |
4367 | class DeducedType : public Type { |
4368 | protected: |
4369 | DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent, |
4370 | bool IsInstantiationDependent, bool ContainsParameterPack) |
4371 | : Type(TC, |
4372 | // FIXME: Retain the sugared deduced type? |
4373 | DeducedAsType.isNull() ? QualType(this, 0) |
4374 | : DeducedAsType.getCanonicalType(), |
4375 | IsDependent, IsInstantiationDependent, |
4376 | /*VariablyModified=*/false, ContainsParameterPack) { |
4377 | if (!DeducedAsType.isNull()) { |
4378 | if (DeducedAsType->isDependentType()) |
4379 | setDependent(); |
4380 | if (DeducedAsType->isInstantiationDependentType()) |
4381 | setInstantiationDependent(); |
4382 | if (DeducedAsType->containsUnexpandedParameterPack()) |
4383 | setContainsUnexpandedParameterPack(); |
4384 | } |
4385 | } |
4386 | |
4387 | public: |
4388 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4389 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4390 | |
4391 | /// \brief Get the type deduced for this placeholder type, or null if it's |
4392 | /// either not been deduced or was deduced to a dependent type. |
4393 | QualType getDeducedType() const { |
4394 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4395 | } |
4396 | bool isDeduced() const { |
4397 | return !isCanonicalUnqualified() || isDependentType(); |
4398 | } |
4399 | |
4400 | static bool classof(const Type *T) { |
4401 | return T->getTypeClass() == Auto || |
4402 | T->getTypeClass() == DeducedTemplateSpecialization; |
4403 | } |
4404 | }; |
4405 | |
4406 | /// \brief Represents a C++11 auto or C++14 decltype(auto) type. |
4407 | class AutoType : public DeducedType, public llvm::FoldingSetNode { |
4408 | friend class ASTContext; // ASTContext creates these |
4409 | |
4410 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4411 | bool IsDeducedAsDependent) |
4412 | : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent, |
4413 | IsDeducedAsDependent, /*ContainsPack=*/false) { |
4414 | AutoTypeBits.Keyword = (unsigned)Keyword; |
4415 | } |
4416 | |
4417 | public: |
4418 | bool isDecltypeAuto() const { |
4419 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
4420 | } |
4421 | |
4422 | AutoTypeKeyword getKeyword() const { |
4423 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
4424 | } |
4425 | |
4426 | void Profile(llvm::FoldingSetNodeID &ID) { |
4427 | Profile(ID, getDeducedType(), getKeyword(), isDependentType()); |
4428 | } |
4429 | |
4430 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced, |
4431 | AutoTypeKeyword Keyword, bool IsDependent) { |
4432 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4433 | ID.AddInteger((unsigned)Keyword); |
4434 | ID.AddBoolean(IsDependent); |
4435 | } |
4436 | |
4437 | static bool classof(const Type *T) { |
4438 | return T->getTypeClass() == Auto; |
4439 | } |
4440 | }; |
4441 | |
4442 | /// \brief Represents a C++17 deduced template specialization type. |
4443 | class DeducedTemplateSpecializationType : public DeducedType, |
4444 | public llvm::FoldingSetNode { |
4445 | friend class ASTContext; // ASTContext creates these |
4446 | |
4447 | /// The name of the template whose arguments will be deduced. |
4448 | TemplateName Template; |
4449 | |
4450 | DeducedTemplateSpecializationType(TemplateName Template, |
4451 | QualType DeducedAsType, |
4452 | bool IsDeducedAsDependent) |
4453 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
4454 | IsDeducedAsDependent || Template.isDependent(), |
4455 | IsDeducedAsDependent || Template.isInstantiationDependent(), |
4456 | Template.containsUnexpandedParameterPack()), |
4457 | Template(Template) {} |
4458 | |
4459 | public: |
4460 | /// Retrieve the name of the template that we are deducing. |
4461 | TemplateName getTemplateName() const { return Template;} |
4462 | |
4463 | void Profile(llvm::FoldingSetNodeID &ID) { |
4464 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
4465 | } |
4466 | |
4467 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
4468 | QualType Deduced, bool IsDependent) { |
4469 | Template.Profile(ID); |
4470 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4471 | ID.AddBoolean(IsDependent); |
4472 | } |
4473 | |
4474 | static bool classof(const Type *T) { |
4475 | return T->getTypeClass() == DeducedTemplateSpecialization; |
4476 | } |
4477 | }; |
4478 | |
4479 | /// \brief Represents a type template specialization; the template |
4480 | /// must be a class template, a type alias template, or a template |
4481 | /// template parameter. A template which cannot be resolved to one of |
4482 | /// these, e.g. because it is written with a dependent scope |
4483 | /// specifier, is instead represented as a |
4484 | /// @c DependentTemplateSpecializationType. |
4485 | /// |
4486 | /// A non-dependent template specialization type is always "sugar", |
4487 | /// typically for a \c RecordType. For example, a class template |
4488 | /// specialization type of \c vector<int> will refer to a tag type for |
4489 | /// the instantiation \c std::vector<int, std::allocator<int>> |
4490 | /// |
4491 | /// Template specializations are dependent if either the template or |
4492 | /// any of the template arguments are dependent, in which case the |
4493 | /// type may also be canonical. |
4494 | /// |
4495 | /// Instances of this type are allocated with a trailing array of |
4496 | /// TemplateArguments, followed by a QualType representing the |
4497 | /// non-canonical aliased type when the template is a type alias |
4498 | /// template. |
4499 | class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)alignas(8) TemplateSpecializationType |
4500 | : public Type, |
4501 | public llvm::FoldingSetNode { |
4502 | friend class ASTContext; // ASTContext creates these |
4503 | |
4504 | /// The name of the template being specialized. This is |
4505 | /// either a TemplateName::Template (in which case it is a |
4506 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
4507 | /// TypeAliasTemplateDecl*), a |
4508 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
4509 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
4510 | /// replacement must, recursively, be one of these). |
4511 | TemplateName Template; |
4512 | |
4513 | /// The number of template arguments named in this class template |
4514 | /// specialization. |
4515 | unsigned NumArgs : 31; |
4516 | |
4517 | /// Whether this template specialization type is a substituted type alias. |
4518 | unsigned TypeAlias : 1; |
4519 | |
4520 | TemplateSpecializationType(TemplateName T, |
4521 | ArrayRef<TemplateArgument> Args, |
4522 | QualType Canon, |
4523 | QualType Aliased); |
4524 | |
4525 | public: |
4526 | /// Determine whether any of the given template arguments are dependent. |
4527 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
4528 | bool &InstantiationDependent); |
4529 | |
4530 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
4531 | bool &InstantiationDependent); |
4532 | |
4533 | /// True if this template specialization type matches a current |
4534 | /// instantiation in the context in which it is found. |
4535 | bool isCurrentInstantiation() const { |
4536 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
4537 | } |
4538 | |
4539 | /// \brief Determine if this template specialization type is for a type alias |
4540 | /// template that has been substituted. |
4541 | /// |
4542 | /// Nearly every template specialization type whose template is an alias |
4543 | /// template will be substituted. However, this is not the case when |
4544 | /// the specialization contains a pack expansion but the template alias |
4545 | /// does not have a corresponding parameter pack, e.g., |
4546 | /// |
4547 | /// \code |
4548 | /// template<typename T, typename U, typename V> struct S; |
4549 | /// template<typename T, typename U> using A = S<T, int, U>; |
4550 | /// template<typename... Ts> struct X { |
4551 | /// typedef A<Ts...> type; // not a type alias |
4552 | /// }; |
4553 | /// \endcode |
4554 | bool isTypeAlias() const { return TypeAlias; } |
4555 | |
4556 | /// Get the aliased type, if this is a specialization of a type alias |
4557 | /// template. |
4558 | QualType getAliasedType() const { |
4559 | assert(isTypeAlias() && "not a type alias template specialization")(static_cast <bool> (isTypeAlias() && "not a type alias template specialization" ) ? void (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4559, __extension__ __PRETTY_FUNCTION__)); |
4560 | return *reinterpret_cast<const QualType*>(end()); |
4561 | } |
4562 | |
4563 | using iterator = const TemplateArgument *; |
4564 | |
4565 | iterator begin() const { return getArgs(); } |
4566 | iterator end() const; // defined inline in TemplateBase.h |
4567 | |
4568 | /// Retrieve the name of the template that we are specializing. |
4569 | TemplateName getTemplateName() const { return Template; } |
4570 | |
4571 | /// Retrieve the template arguments. |
4572 | const TemplateArgument *getArgs() const { |
4573 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
4574 | } |
4575 | |
4576 | /// Retrieve the number of template arguments. |
4577 | unsigned getNumArgs() const { return NumArgs; } |
4578 | |
4579 | /// Retrieve a specific template argument as a type. |
4580 | /// \pre \c isArgType(Arg) |
4581 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4582 | |
4583 | ArrayRef<TemplateArgument> template_arguments() const { |
4584 | return {getArgs(), NumArgs}; |
4585 | } |
4586 | |
4587 | bool isSugared() const { |
4588 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
4589 | } |
4590 | |
4591 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4592 | |
4593 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
4594 | Profile(ID, Template, template_arguments(), Ctx); |
4595 | if (isTypeAlias()) |
4596 | getAliasedType().Profile(ID); |
4597 | } |
4598 | |
4599 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
4600 | ArrayRef<TemplateArgument> Args, |
4601 | const ASTContext &Context); |
4602 | |
4603 | static bool classof(const Type *T) { |
4604 | return T->getTypeClass() == TemplateSpecialization; |
4605 | } |
4606 | }; |
4607 | |
4608 | /// \brief Print a template argument list, including the '<' and '>' |
4609 | /// enclosing the template arguments. |
4610 | void printTemplateArgumentList(raw_ostream &OS, |
4611 | ArrayRef<TemplateArgument> Args, |
4612 | const PrintingPolicy &Policy); |
4613 | |
4614 | void printTemplateArgumentList(raw_ostream &OS, |
4615 | ArrayRef<TemplateArgumentLoc> Args, |
4616 | const PrintingPolicy &Policy); |
4617 | |
4618 | void printTemplateArgumentList(raw_ostream &OS, |
4619 | const TemplateArgumentListInfo &Args, |
4620 | const PrintingPolicy &Policy); |
4621 | |
4622 | /// The injected class name of a C++ class template or class |
4623 | /// template partial specialization. Used to record that a type was |
4624 | /// spelled with a bare identifier rather than as a template-id; the |
4625 | /// equivalent for non-templated classes is just RecordType. |
4626 | /// |
4627 | /// Injected class name types are always dependent. Template |
4628 | /// instantiation turns these into RecordTypes. |
4629 | /// |
4630 | /// Injected class name types are always canonical. This works |
4631 | /// because it is impossible to compare an injected class name type |
4632 | /// with the corresponding non-injected template type, for the same |
4633 | /// reason that it is impossible to directly compare template |
4634 | /// parameters from different dependent contexts: injected class name |
4635 | /// types can only occur within the scope of a particular templated |
4636 | /// declaration, and within that scope every template specialization |
4637 | /// will canonicalize to the injected class name (when appropriate |
4638 | /// according to the rules of the language). |
4639 | class InjectedClassNameType : public Type { |
4640 | friend class ASTContext; // ASTContext creates these. |
4641 | friend class ASTNodeImporter; |
4642 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
4643 | // currently suitable for AST reading, too much |
4644 | // interdependencies. |
4645 | |
4646 | CXXRecordDecl *Decl; |
4647 | |
4648 | /// The template specialization which this type represents. |
4649 | /// For example, in |
4650 | /// template <class T> class A { ... }; |
4651 | /// this is A<T>, whereas in |
4652 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
4653 | /// this is A<B<X,Y> >. |
4654 | /// |
4655 | /// It is always unqualified, always a template specialization type, |
4656 | /// and always dependent. |
4657 | QualType InjectedType; |
4658 | |
4659 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
4660 | : Type(InjectedClassName, QualType(), /*Dependent=*/true, |
4661 | /*InstantiationDependent=*/true, |
4662 | /*VariablyModified=*/false, |
4663 | /*ContainsUnexpandedParameterPack=*/false), |
4664 | Decl(D), InjectedType(TST) { |
4665 | assert(isa<TemplateSpecializationType>(TST))(static_cast <bool> (isa<TemplateSpecializationType> (TST)) ? void (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4665, __extension__ __PRETTY_FUNCTION__)); |
4666 | assert(!TST.hasQualifiers())(static_cast <bool> (!TST.hasQualifiers()) ? void (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4666, __extension__ __PRETTY_FUNCTION__)); |
4667 | assert(TST->isDependentType())(static_cast <bool> (TST->isDependentType()) ? void ( 0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4667, __extension__ __PRETTY_FUNCTION__)); |
4668 | } |
4669 | |
4670 | public: |
4671 | QualType getInjectedSpecializationType() const { return InjectedType; } |
4672 | |
4673 | const TemplateSpecializationType *getInjectedTST() const { |
4674 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
4675 | } |
4676 | |
4677 | TemplateName getTemplateName() const { |
4678 | return getInjectedTST()->getTemplateName(); |
4679 | } |
4680 | |
4681 | CXXRecordDecl *getDecl() const; |
4682 | |
4683 | bool isSugared() const { return false; } |
4684 | QualType desugar() const { return QualType(this, 0); } |
4685 | |
4686 | static bool classof(const Type *T) { |
4687 | return T->getTypeClass() == InjectedClassName; |
4688 | } |
4689 | }; |
4690 | |
4691 | /// \brief The kind of a tag type. |
4692 | enum TagTypeKind { |
4693 | /// \brief The "struct" keyword. |
4694 | TTK_Struct, |
4695 | |
4696 | /// \brief The "__interface" keyword. |
4697 | TTK_Interface, |
4698 | |
4699 | /// \brief The "union" keyword. |
4700 | TTK_Union, |
4701 | |
4702 | /// \brief The "class" keyword. |
4703 | TTK_Class, |
4704 | |
4705 | /// \brief The "enum" keyword. |
4706 | TTK_Enum |
4707 | }; |
4708 | |
4709 | /// \brief The elaboration keyword that precedes a qualified type name or |
4710 | /// introduces an elaborated-type-specifier. |
4711 | enum ElaboratedTypeKeyword { |
4712 | /// \brief The "struct" keyword introduces the elaborated-type-specifier. |
4713 | ETK_Struct, |
4714 | |
4715 | /// \brief The "__interface" keyword introduces the elaborated-type-specifier. |
4716 | ETK_Interface, |
4717 | |
4718 | /// \brief The "union" keyword introduces the elaborated-type-specifier. |
4719 | ETK_Union, |
4720 | |
4721 | /// \brief The "class" keyword introduces the elaborated-type-specifier. |
4722 | ETK_Class, |
4723 | |
4724 | /// \brief The "enum" keyword introduces the elaborated-type-specifier. |
4725 | ETK_Enum, |
4726 | |
4727 | /// \brief The "typename" keyword precedes the qualified type name, e.g., |
4728 | /// \c typename T::type. |
4729 | ETK_Typename, |
4730 | |
4731 | /// \brief No keyword precedes the qualified type name. |
4732 | ETK_None |
4733 | }; |
4734 | |
4735 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
4736 | /// The keyword in stored in the free bits of the base class. |
4737 | /// Also provides a few static helpers for converting and printing |
4738 | /// elaborated type keyword and tag type kind enumerations. |
4739 | class TypeWithKeyword : public Type { |
4740 | protected: |
4741 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
4742 | QualType Canonical, bool Dependent, |
4743 | bool InstantiationDependent, bool VariablyModified, |
4744 | bool ContainsUnexpandedParameterPack) |
4745 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
4746 | ContainsUnexpandedParameterPack) { |
4747 | TypeWithKeywordBits.Keyword = Keyword; |
4748 | } |
4749 | |
4750 | public: |
4751 | ElaboratedTypeKeyword getKeyword() const { |
4752 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
4753 | } |
4754 | |
4755 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
4756 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
4757 | |
4758 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
4759 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
4760 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
4761 | |
4762 | /// Converts a TagTypeKind into an elaborated type keyword. |
4763 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
4764 | |
4765 | /// Converts an elaborated type keyword into a TagTypeKind. |
4766 | /// It is an error to provide an elaborated type keyword |
4767 | /// which *isn't* a tag kind here. |
4768 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
4769 | |
4770 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
4771 | |
4772 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
4773 | |
4774 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
4775 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
4776 | } |
4777 | |
4778 | class CannotCastToThisType {}; |
4779 | static CannotCastToThisType classof(const Type *); |
4780 | }; |
4781 | |
4782 | /// \brief Represents a type that was referred to using an elaborated type |
4783 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
4784 | /// or both. |
4785 | /// |
4786 | /// This type is used to keep track of a type name as written in the |
4787 | /// source code, including tag keywords and any nested-name-specifiers. |
4788 | /// The type itself is always "sugar", used to express what was written |
4789 | /// in the source code but containing no additional semantic information. |
4790 | class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode { |
4791 | friend class ASTContext; // ASTContext creates these |
4792 | |
4793 | /// The nested name specifier containing the qualifier. |
4794 | NestedNameSpecifier *NNS; |
4795 | |
4796 | /// The type that this qualified name refers to. |
4797 | QualType NamedType; |
4798 | |
4799 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
4800 | QualType NamedType, QualType CanonType) |
4801 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
4802 | NamedType->isDependentType(), |
4803 | NamedType->isInstantiationDependentType(), |
4804 | NamedType->isVariablyModifiedType(), |
4805 | NamedType->containsUnexpandedParameterPack()), |
4806 | NNS(NNS), NamedType(NamedType) { |
4807 | assert(!(Keyword == ETK_None && NNS == nullptr) &&(static_cast <bool> (!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null.") ? void (0) : __assert_fail ( "!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4809, __extension__ __PRETTY_FUNCTION__)) |
4808 | "ElaboratedType cannot have elaborated type keyword "(static_cast <bool> (!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null.") ? void (0) : __assert_fail ( "!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4809, __extension__ __PRETTY_FUNCTION__)) |
4809 | "and name qualifier both null.")(static_cast <bool> (!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null.") ? void (0) : __assert_fail ( "!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 4809, __extension__ __PRETTY_FUNCTION__)); |
4810 | } |
4811 | |
4812 | public: |
4813 | ~ElaboratedType(); |
4814 | |
4815 | /// Retrieve the qualification on this type. |
4816 | NestedNameSpecifier *getQualifier() const { return NNS; } |
4817 | |
4818 | /// Retrieve the type named by the qualified-id. |
4819 | QualType getNamedType() const { return NamedType; } |
4820 | |
4821 | /// Remove a single level of sugar. |
4822 | QualType desugar() const { return getNamedType(); } |
4823 | |
4824 | /// Returns whether this type directly provides sugar. |
4825 | bool isSugared() const { return true; } |
4826 | |
4827 | void Profile(llvm::FoldingSetNodeID &ID) { |
4828 | Profile(ID, getKeyword(), NNS, NamedType); |
4829 | } |
4830 | |
4831 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
4832 | NestedNameSpecifier *NNS, QualType NamedType) { |
4833 | ID.AddInteger(Keyword); |
4834 | ID.AddPointer(NNS); |
4835 | NamedType.Profile(ID); |
4836 | } |
4837 | |
4838 | static bool classof(const Type *T) { |
4839 | return T->getTypeClass() == Elaborated; |
4840 | } |
4841 | }; |
4842 | |
4843 | /// \brief Represents a qualified type name for which the type name is |
4844 | /// dependent. |
4845 | /// |
4846 | /// DependentNameType represents a class of dependent types that involve a |
4847 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
4848 | /// name of a type. The DependentNameType may start with a "typename" (for a |
4849 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
4850 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
4851 | /// know that we must be referring to a type, e.g., in a base class specifier). |
4852 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
4853 | /// mode, this type is used with non-dependent names to delay name lookup until |
4854 | /// instantiation. |
4855 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
4856 | friend class ASTContext; // ASTContext creates these |
4857 | |
4858 | /// \brief The nested name specifier containing the qualifier. |
4859 | NestedNameSpecifier *NNS; |
4860 | |
4861 | /// \brief The type that this typename specifier refers to. |
4862 | const IdentifierInfo *Name; |
4863 | |
4864 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
4865 | const IdentifierInfo *Name, QualType CanonType) |
4866 | : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true, |
4867 | /*InstantiationDependent=*/true, |
4868 | /*VariablyModified=*/false, |
4869 | NNS->containsUnexpandedParameterPack()), |
4870 | NNS(NNS), Name(Name) {} |
4871 | |
4872 | public: |
4873 | /// Retrieve the qualification on this type. |
4874 | NestedNameSpecifier *getQualifier() const { return NNS; } |
4875 | |
4876 | /// Retrieve the type named by the typename specifier as an identifier. |
4877 | /// |
4878 | /// This routine will return a non-NULL identifier pointer when the |
4879 | /// form of the original typename was terminated by an identifier, |
4880 | /// e.g., "typename T::type". |
4881 | const IdentifierInfo *getIdentifier() const { |
4882 | return Name; |
4883 | } |
4884 | |
4885 | bool isSugared() const { return false; } |
4886 | QualType desugar() const { return QualType(this, 0); } |
4887 | |
4888 | void Profile(llvm::FoldingSetNodeID &ID) { |
4889 | Profile(ID, getKeyword(), NNS, Name); |
4890 | } |
4891 | |
4892 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
4893 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
4894 | ID.AddInteger(Keyword); |
4895 | ID.AddPointer(NNS); |
4896 | ID.AddPointer(Name); |
4897 | } |
4898 | |
4899 | static bool classof(const Type *T) { |
4900 | return T->getTypeClass() == DependentName; |
4901 | } |
4902 | }; |
4903 | |
4904 | /// Represents a template specialization type whose template cannot be |
4905 | /// resolved, e.g. |
4906 | /// A<T>::template B<T> |
4907 | class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)alignas(8) DependentTemplateSpecializationType |
4908 | : public TypeWithKeyword, |
4909 | public llvm::FoldingSetNode { |
4910 | friend class ASTContext; // ASTContext creates these |
4911 | |
4912 | /// The nested name specifier containing the qualifier. |
4913 | NestedNameSpecifier *NNS; |
4914 | |
4915 | /// The identifier of the template. |
4916 | const IdentifierInfo *Name; |
4917 | |
4918 | /// \brief The number of template arguments named in this class template |
4919 | /// specialization. |
4920 | unsigned NumArgs; |
4921 | |
4922 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
4923 | NestedNameSpecifier *NNS, |
4924 | const IdentifierInfo *Name, |
4925 | ArrayRef<TemplateArgument> Args, |
4926 | QualType Canon); |
4927 | |
4928 | const TemplateArgument *getArgBuffer() const { |
4929 | return reinterpret_cast<const TemplateArgument*>(this+1); |
4930 | } |
4931 | |
4932 | TemplateArgument *getArgBuffer() { |
4933 | return reinterpret_cast<TemplateArgument*>(this+1); |
4934 | } |
4935 | |
4936 | public: |
4937 | NestedNameSpecifier *getQualifier() const { return NNS; } |
4938 | const IdentifierInfo *getIdentifier() const { return Name; } |
4939 | |
4940 | /// \brief Retrieve the template arguments. |
4941 | const TemplateArgument *getArgs() const { |
4942 | return getArgBuffer(); |
4943 | } |
4944 | |
4945 | /// \brief Retrieve the number of template arguments. |
4946 | unsigned getNumArgs() const { return NumArgs; } |
4947 | |
4948 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4949 | |
4950 | ArrayRef<TemplateArgument> template_arguments() const { |
4951 | return {getArgs(), NumArgs}; |
4952 | } |
4953 | |
4954 | using iterator = const TemplateArgument *; |
4955 | |
4956 | iterator begin() const { return getArgs(); } |
4957 | iterator end() const; // inline in TemplateBase.h |
4958 | |
4959 | bool isSugared() const { return false; } |
4960 | QualType desugar() const { return QualType(this, 0); } |
4961 | |
4962 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
4963 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs}); |
4964 | } |
4965 | |
4966 | static void Profile(llvm::FoldingSetNodeID &ID, |
4967 | const ASTContext &Context, |
4968 | ElaboratedTypeKeyword Keyword, |
4969 | NestedNameSpecifier *Qualifier, |
4970 | const IdentifierInfo *Name, |
4971 | ArrayRef<TemplateArgument> Args); |
4972 | |
4973 | static bool classof(const Type *T) { |
4974 | return T->getTypeClass() == DependentTemplateSpecialization; |
4975 | } |
4976 | }; |
4977 | |
4978 | /// \brief Represents a pack expansion of types. |
4979 | /// |
4980 | /// Pack expansions are part of C++11 variadic templates. A pack |
4981 | /// expansion contains a pattern, which itself contains one or more |
4982 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
4983 | /// produces a series of types, each instantiated from the pattern of |
4984 | /// the expansion, where the Ith instantiation of the pattern uses the |
4985 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
4986 | /// pack expansion is considered to "expand" these unexpanded |
4987 | /// parameter packs. |
4988 | /// |
4989 | /// \code |
4990 | /// template<typename ...Types> struct tuple; |
4991 | /// |
4992 | /// template<typename ...Types> |
4993 | /// struct tuple_of_references { |
4994 | /// typedef tuple<Types&...> type; |
4995 | /// }; |
4996 | /// \endcode |
4997 | /// |
4998 | /// Here, the pack expansion \c Types&... is represented via a |
4999 | /// PackExpansionType whose pattern is Types&. |
5000 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5001 | friend class ASTContext; // ASTContext creates these |
5002 | |
5003 | /// \brief The pattern of the pack expansion. |
5004 | QualType Pattern; |
5005 | |
5006 | /// \brief The number of expansions that this pack expansion will |
5007 | /// generate when substituted (+1), or indicates that |
5008 | /// |
5009 | /// This field will only have a non-zero value when some of the parameter |
5010 | /// packs that occur within the pattern have been substituted but others have |
5011 | /// not. |
5012 | unsigned NumExpansions; |
5013 | |
5014 | PackExpansionType(QualType Pattern, QualType Canon, |
5015 | Optional<unsigned> NumExpansions) |
5016 | : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(), |
5017 | /*InstantiationDependent=*/true, |
5018 | /*VariablyModified=*/Pattern->isVariablyModifiedType(), |
5019 | /*ContainsUnexpandedParameterPack=*/false), |
5020 | Pattern(Pattern), |
5021 | NumExpansions(NumExpansions ? *NumExpansions + 1 : 0) {} |
5022 | |
5023 | public: |
5024 | /// \brief Retrieve the pattern of this pack expansion, which is the |
5025 | /// type that will be repeatedly instantiated when instantiating the |
5026 | /// pack expansion itself. |
5027 | QualType getPattern() const { return Pattern; } |
5028 | |
5029 | /// \brief Retrieve the number of expansions that this pack expansion will |
5030 | /// generate, if known. |
5031 | Optional<unsigned> getNumExpansions() const { |
5032 | if (NumExpansions) |
5033 | return NumExpansions - 1; |
5034 | |
5035 | return None; |
5036 | } |
5037 | |
5038 | bool isSugared() const { return !Pattern->isDependentType(); } |
5039 | QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); } |
5040 | |
5041 | void Profile(llvm::FoldingSetNodeID &ID) { |
5042 | Profile(ID, getPattern(), getNumExpansions()); |
5043 | } |
5044 | |
5045 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5046 | Optional<unsigned> NumExpansions) { |
5047 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5048 | ID.AddBoolean(NumExpansions.hasValue()); |
5049 | if (NumExpansions) |
5050 | ID.AddInteger(*NumExpansions); |
5051 | } |
5052 | |
5053 | static bool classof(const Type *T) { |
5054 | return T->getTypeClass() == PackExpansion; |
5055 | } |
5056 | }; |
5057 | |
5058 | /// This class wraps the list of protocol qualifiers. For types that can |
5059 | /// take ObjC protocol qualifers, they can subclass this class. |
5060 | template <class T> |
5061 | class ObjCProtocolQualifiers { |
5062 | protected: |
5063 | ObjCProtocolQualifiers() = default; |
5064 | |
5065 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5066 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5067 | } |
5068 | |
5069 | ObjCProtocolDecl **getProtocolStorage() { |
5070 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5071 | } |
5072 | |
5073 | void setNumProtocols(unsigned N) { |
5074 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5075 | } |
5076 | |
5077 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5078 | setNumProtocols(protocols.size()); |
5079 | assert(getNumProtocols() == protocols.size() &&(static_cast <bool> (getNumProtocols() == protocols.size () && "bitfield overflow in protocol count") ? void ( 0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 5080, __extension__ __PRETTY_FUNCTION__)) |
5080 | "bitfield overflow in protocol count")(static_cast <bool> (getNumProtocols() == protocols.size () && "bitfield overflow in protocol count") ? void ( 0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 5080, __extension__ __PRETTY_FUNCTION__)); |
5081 | if (!protocols.empty()) |
5082 | memcpy(getProtocolStorage(), protocols.data(), |
5083 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5084 | } |
5085 | |
5086 | public: |
5087 | using qual_iterator = ObjCProtocolDecl * const *; |
5088 | using qual_range = llvm::iterator_range<qual_iterator>; |
5089 | |
5090 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5091 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5092 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5093 | |
5094 | bool qual_empty() const { return getNumProtocols() == 0; } |
5095 | |
5096 | /// Return the number of qualifying protocols in this type, or 0 if |
5097 | /// there are none. |
5098 | unsigned getNumProtocols() const { |
5099 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5100 | } |
5101 | |
5102 | /// Fetch a protocol by index. |
5103 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5104 | assert(I < getNumProtocols() && "Out-of-range protocol access")(static_cast <bool> (I < getNumProtocols() && "Out-of-range protocol access") ? void (0) : __assert_fail ( "I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 5104, __extension__ __PRETTY_FUNCTION__)); |
5105 | return qual_begin()[I]; |
5106 | } |
5107 | |
5108 | /// Retrieve all of the protocol qualifiers. |
5109 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5110 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5111 | } |
5112 | }; |
5113 | |
5114 | /// Represents a type parameter type in Objective C. It can take |
5115 | /// a list of protocols. |
5116 | class ObjCTypeParamType : public Type, |
5117 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5118 | public llvm::FoldingSetNode { |
5119 | friend class ASTContext; |
5120 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5121 | |
5122 | /// The number of protocols stored on this type. |
5123 | unsigned NumProtocols : 6; |
5124 | |
5125 | ObjCTypeParamDecl *OTPDecl; |
5126 | |
5127 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5128 | /// canonical type, the list of protocols are sorted alphabetically |
5129 | /// and uniqued. |
5130 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5131 | |
5132 | /// Return the number of qualifying protocols in this interface type, |
5133 | /// or 0 if there are none. |
5134 | unsigned getNumProtocolsImpl() const { |
5135 | return NumProtocols; |
5136 | } |
5137 | |
5138 | void setNumProtocolsImpl(unsigned N) { |
5139 | NumProtocols = N; |
5140 | } |
5141 | |
5142 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5143 | QualType can, |
5144 | ArrayRef<ObjCProtocolDecl *> protocols); |
5145 | |
5146 | public: |
5147 | bool isSugared() const { return true; } |
5148 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5149 | |
5150 | static bool classof(const Type *T) { |
5151 | return T->getTypeClass() == ObjCTypeParam; |
5152 | } |
5153 | |
5154 | void Profile(llvm::FoldingSetNodeID &ID); |
5155 | static void Profile(llvm::FoldingSetNodeID &ID, |
5156 | const ObjCTypeParamDecl *OTPDecl, |
5157 | ArrayRef<ObjCProtocolDecl *> protocols); |
5158 | |
5159 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5160 | }; |
5161 | |
5162 | /// Represents a class type in Objective C. |
5163 | /// |
5164 | /// Every Objective C type is a combination of a base type, a set of |
5165 | /// type arguments (optional, for parameterized classes) and a list of |
5166 | /// protocols. |
5167 | /// |
5168 | /// Given the following declarations: |
5169 | /// \code |
5170 | /// \@class C<T>; |
5171 | /// \@protocol P; |
5172 | /// \endcode |
5173 | /// |
5174 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5175 | /// with base C and no protocols. |
5176 | /// |
5177 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5178 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5179 | /// protocol list. |
5180 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5181 | /// and protocol list [P]. |
5182 | /// |
5183 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5184 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5185 | /// and no protocols. |
5186 | /// |
5187 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5188 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5189 | /// this should get its own sugar class to better represent the source. |
5190 | class ObjCObjectType : public Type, |
5191 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5192 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5193 | |
5194 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5195 | // after the ObjCObjectPointerType node. |
5196 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5197 | // after the type arguments of ObjCObjectPointerType node. |
5198 | // |
5199 | // These protocols are those written directly on the type. If |
5200 | // protocol qualifiers ever become additive, the iterators will need |
5201 | // to get kindof complicated. |
5202 | // |
5203 | // In the canonical object type, these are sorted alphabetically |
5204 | // and uniqued. |
5205 | |
5206 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5207 | QualType BaseType; |
5208 | |
5209 | /// Cached superclass type. |
5210 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5211 | CachedSuperClassType; |
5212 | |
5213 | QualType *getTypeArgStorage(); |
5214 | const QualType *getTypeArgStorage() const { |
5215 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5216 | } |
5217 | |
5218 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5219 | /// Return the number of qualifying protocols in this interface type, |
5220 | /// or 0 if there are none. |
5221 | unsigned getNumProtocolsImpl() const { |
5222 | return ObjCObjectTypeBits.NumProtocols; |
5223 | } |
5224 | void setNumProtocolsImpl(unsigned N) { |
5225 | ObjCObjectTypeBits.NumProtocols = N; |
5226 | } |
5227 | |
5228 | protected: |
5229 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5230 | |
5231 | ObjCObjectType(QualType Canonical, QualType Base, |
5232 | ArrayRef<QualType> typeArgs, |
5233 | ArrayRef<ObjCProtocolDecl *> protocols, |
5234 | bool isKindOf); |
5235 | |
5236 | ObjCObjectType(enum Nonce_ObjCInterface) |
5237 | : Type(ObjCInterface, QualType(), false, false, false, false), |
5238 | BaseType(QualType(this_(), 0)) { |
5239 | ObjCObjectTypeBits.NumProtocols = 0; |
5240 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5241 | ObjCObjectTypeBits.IsKindOf = 0; |
5242 | } |
5243 | |
5244 | void computeSuperClassTypeSlow() const; |
5245 | |
5246 | public: |
5247 | /// Gets the base type of this object type. This is always (possibly |
5248 | /// sugar for) one of: |
5249 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5250 | /// user, which is a typedef for an ObjCObjectPointerType) |
5251 | /// - the 'Class' builtin type (same caveat) |
5252 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5253 | QualType getBaseType() const { return BaseType; } |
5254 | |
5255 | bool isObjCId() const { |
5256 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5257 | } |
5258 | |
5259 | bool isObjCClass() const { |
5260 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5261 | } |
5262 | |
5263 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5264 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5265 | bool isObjCUnqualifiedIdOrClass() const { |
5266 | if (!qual_empty()) return false; |
5267 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5268 | return T->getKind() == BuiltinType::ObjCId || |
5269 | T->getKind() == BuiltinType::ObjCClass; |
5270 | return false; |
5271 | } |
5272 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5273 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5274 | |
5275 | /// Gets the interface declaration for this object type, if the base type |
5276 | /// really is an interface. |
5277 | ObjCInterfaceDecl *getInterface() const; |
5278 | |
5279 | /// Determine whether this object type is "specialized", meaning |
5280 | /// that it has type arguments. |
5281 | bool isSpecialized() const; |
5282 | |
5283 | /// Determine whether this object type was written with type arguments. |
5284 | bool isSpecializedAsWritten() const { |
5285 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5286 | } |
5287 | |
5288 | /// Determine whether this object type is "unspecialized", meaning |
5289 | /// that it has no type arguments. |
5290 | bool isUnspecialized() const { return !isSpecialized(); } |
5291 | |
5292 | /// Determine whether this object type is "unspecialized" as |
5293 | /// written, meaning that it has no type arguments. |
5294 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5295 | |
5296 | /// Retrieve the type arguments of this object type (semantically). |
5297 | ArrayRef<QualType> getTypeArgs() const; |
5298 | |
5299 | /// Retrieve the type arguments of this object type as they were |
5300 | /// written. |
5301 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5302 | return llvm::makeArrayRef(getTypeArgStorage(), |
5303 | ObjCObjectTypeBits.NumTypeArgs); |
5304 | } |
5305 | |
5306 | /// Whether this is a "__kindof" type as written. |
5307 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5308 | |
5309 | /// Whether this ia a "__kindof" type (semantically). |
5310 | bool isKindOfType() const; |
5311 | |
5312 | /// Retrieve the type of the superclass of this object type. |
5313 | /// |
5314 | /// This operation substitutes any type arguments into the |
5315 | /// superclass of the current class type, potentially producing a |
5316 | /// specialization of the superclass type. Produces a null type if |
5317 | /// there is no superclass. |
5318 | QualType getSuperClassType() const { |
5319 | if (!CachedSuperClassType.getInt()) |
5320 | computeSuperClassTypeSlow(); |
5321 | |
5322 | assert(CachedSuperClassType.getInt() && "Superclass not set?")(static_cast <bool> (CachedSuperClassType.getInt() && "Superclass not set?") ? void (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 5322, __extension__ __PRETTY_FUNCTION__)); |
5323 | return QualType(CachedSuperClassType.getPointer(), 0); |
5324 | } |
5325 | |
5326 | /// Strip off the Objective-C "kindof" type and (with it) any |
5327 | /// protocol qualifiers. |
5328 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5329 | |
5330 | bool isSugared() const { return false; } |
5331 | QualType desugar() const { return QualType(this, 0); } |
5332 | |
5333 | static bool classof(const Type *T) { |
5334 | return T->getTypeClass() == ObjCObject || |
5335 | T->getTypeClass() == ObjCInterface; |
5336 | } |
5337 | }; |
5338 | |
5339 | /// A class providing a concrete implementation |
5340 | /// of ObjCObjectType, so as to not increase the footprint of |
5341 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5342 | /// system should not reference this type. |
5343 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5344 | friend class ASTContext; |
5345 | |
5346 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5347 | // will need to be modified. |
5348 | |
5349 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5350 | ArrayRef<QualType> typeArgs, |
5351 | ArrayRef<ObjCProtocolDecl *> protocols, |
5352 | bool isKindOf) |
5353 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5354 | |
5355 | public: |
5356 | void Profile(llvm::FoldingSetNodeID &ID); |
5357 | static void Profile(llvm::FoldingSetNodeID &ID, |
5358 | QualType Base, |
5359 | ArrayRef<QualType> typeArgs, |
5360 | ArrayRef<ObjCProtocolDecl *> protocols, |
5361 | bool isKindOf); |
5362 | }; |
5363 | |
5364 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5365 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5366 | } |
5367 | |
5368 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5369 | return reinterpret_cast<ObjCProtocolDecl**>( |
5370 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5371 | } |
5372 | |
5373 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5374 | return reinterpret_cast<ObjCProtocolDecl**>( |
5375 | static_cast<ObjCTypeParamType*>(this)+1); |
5376 | } |
5377 | |
5378 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5379 | /// They basically correspond to C++ classes. There are two kinds of interface |
5380 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5381 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5382 | /// |
5383 | /// ObjCInterfaceType guarantees the following properties when considered |
5384 | /// as a subtype of its superclass, ObjCObjectType: |
5385 | /// - There are no protocol qualifiers. To reinforce this, code which |
5386 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5387 | /// fail to compile. |
5388 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5389 | /// T->getBaseType() == QualType(T, 0). |
5390 | class ObjCInterfaceType : public ObjCObjectType { |
5391 | friend class ASTContext; // ASTContext creates these. |
5392 | friend class ASTReader; |
5393 | friend class ObjCInterfaceDecl; |
5394 | |
5395 | mutable ObjCInterfaceDecl *Decl; |
5396 | |
5397 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5398 | : ObjCObjectType(Nonce_ObjCInterface), |
5399 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5400 | |
5401 | public: |
5402 | /// Get the declaration of this interface. |
5403 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5404 | |
5405 | bool isSugared() const { return false; } |
5406 | QualType desugar() const { return QualType(this, 0); } |
5407 | |
5408 | static bool classof(const Type *T) { |
5409 | return T->getTypeClass() == ObjCInterface; |
5410 | } |
5411 | |
5412 | // Nonsense to "hide" certain members of ObjCObjectType within this |
5413 | // class. People asking for protocols on an ObjCInterfaceType are |
5414 | // not going to get what they want: ObjCInterfaceTypes are |
5415 | // guaranteed to have no protocols. |
5416 | enum { |
5417 | qual_iterator, |
5418 | qual_begin, |
5419 | qual_end, |
5420 | getNumProtocols, |
5421 | getProtocol |
5422 | }; |
5423 | }; |
5424 | |
5425 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
5426 | QualType baseType = getBaseType(); |
5427 | while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) { |
5428 | if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
5429 | return T->getDecl(); |
5430 | |
5431 | baseType = ObjT->getBaseType(); |
5432 | } |
5433 | |
5434 | return nullptr; |
5435 | } |
5436 | |
5437 | /// Represents a pointer to an Objective C object. |
5438 | /// |
5439 | /// These are constructed from pointer declarators when the pointee type is |
5440 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
5441 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
5442 | /// and 'Class<P>' are translated into these. |
5443 | /// |
5444 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
5445 | /// only the first level of pointer gets it own type implementation. |
5446 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
5447 | friend class ASTContext; // ASTContext creates these. |
5448 | |
5449 | QualType PointeeType; |
5450 | |
5451 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
5452 | : Type(ObjCObjectPointer, Canonical, |
5453 | Pointee->isDependentType(), |
5454 | Pointee->isInstantiationDependentType(), |
5455 | Pointee->isVariablyModifiedType(), |
5456 | Pointee->containsUnexpandedParameterPack()), |
5457 | PointeeType(Pointee) {} |
5458 | |
5459 | public: |
5460 | /// Gets the type pointed to by this ObjC pointer. |
5461 | /// The result will always be an ObjCObjectType or sugar thereof. |
5462 | QualType getPointeeType() const { return PointeeType; } |
5463 | |
5464 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
5465 | /// |
5466 | /// This method is equivalent to getPointeeType() except that |
5467 | /// it discards any typedefs (or other sugar) between this |
5468 | /// type and the "outermost" object type. So for: |
5469 | /// \code |
5470 | /// \@class A; \@protocol P; \@protocol Q; |
5471 | /// typedef A<P> AP; |
5472 | /// typedef A A1; |
5473 | /// typedef A1<P> A1P; |
5474 | /// typedef A1P<Q> A1PQ; |
5475 | /// \endcode |
5476 | /// For 'A*', getObjectType() will return 'A'. |
5477 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
5478 | /// For 'AP*', getObjectType() will return 'A<P>'. |
5479 | /// For 'A1*', getObjectType() will return 'A'. |
5480 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
5481 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
5482 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
5483 | /// adding protocols to a protocol-qualified base discards the |
5484 | /// old qualifiers (for now). But if it didn't, getObjectType() |
5485 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
5486 | /// qualifiers more complicated). |
5487 | const ObjCObjectType *getObjectType() const { |
5488 | return PointeeType->castAs<ObjCObjectType>(); |
5489 | } |
5490 | |
5491 | /// If this pointer points to an Objective C |
5492 | /// \@interface type, gets the type for that interface. Any protocol |
5493 | /// qualifiers on the interface are ignored. |
5494 | /// |
5495 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5496 | const ObjCInterfaceType *getInterfaceType() const; |
5497 | |
5498 | /// If this pointer points to an Objective \@interface |
5499 | /// type, gets the declaration for that interface. |
5500 | /// |
5501 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5502 | ObjCInterfaceDecl *getInterfaceDecl() const { |
5503 | return getObjectType()->getInterface(); |
5504 | } |
5505 | |
5506 | /// True if this is equivalent to the 'id' type, i.e. if |
5507 | /// its object type is the primitive 'id' type with no protocols. |
5508 | bool isObjCIdType() const { |
5509 | return getObjectType()->isObjCUnqualifiedId(); |
5510 | } |
5511 | |
5512 | /// True if this is equivalent to the 'Class' type, |
5513 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
5514 | bool isObjCClassType() const { |
5515 | return getObjectType()->isObjCUnqualifiedClass(); |
5516 | } |
5517 | |
5518 | /// True if this is equivalent to the 'id' or 'Class' type, |
5519 | bool isObjCIdOrClassType() const { |
5520 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
5521 | } |
5522 | |
5523 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
5524 | /// protocols. |
5525 | bool isObjCQualifiedIdType() const { |
5526 | return getObjectType()->isObjCQualifiedId(); |
5527 | } |
5528 | |
5529 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
5530 | /// protocols. |
5531 | bool isObjCQualifiedClassType() const { |
5532 | return getObjectType()->isObjCQualifiedClass(); |
5533 | } |
5534 | |
5535 | /// Whether this is a "__kindof" type. |
5536 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
5537 | |
5538 | /// Whether this type is specialized, meaning that it has type arguments. |
5539 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
5540 | |
5541 | /// Whether this type is specialized, meaning that it has type arguments. |
5542 | bool isSpecializedAsWritten() const { |
5543 | return getObjectType()->isSpecializedAsWritten(); |
5544 | } |
5545 | |
5546 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
5547 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
5548 | |
5549 | /// Determine whether this object type is "unspecialized" as |
5550 | /// written, meaning that it has no type arguments. |
5551 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5552 | |
5553 | /// Retrieve the type arguments for this type. |
5554 | ArrayRef<QualType> getTypeArgs() const { |
5555 | return getObjectType()->getTypeArgs(); |
5556 | } |
5557 | |
5558 | /// Retrieve the type arguments for this type. |
5559 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5560 | return getObjectType()->getTypeArgsAsWritten(); |
5561 | } |
5562 | |
5563 | /// An iterator over the qualifiers on the object type. Provided |
5564 | /// for convenience. This will always iterate over the full set of |
5565 | /// protocols on a type, not just those provided directly. |
5566 | using qual_iterator = ObjCObjectType::qual_iterator; |
5567 | using qual_range = llvm::iterator_range<qual_iterator>; |
5568 | |
5569 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5570 | |
5571 | qual_iterator qual_begin() const { |
5572 | return getObjectType()->qual_begin(); |
5573 | } |
5574 | |
5575 | qual_iterator qual_end() const { |
5576 | return getObjectType()->qual_end(); |
5577 | } |
5578 | |
5579 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
5580 | |
5581 | /// Return the number of qualifying protocols on the object type. |
5582 | unsigned getNumProtocols() const { |
5583 | return getObjectType()->getNumProtocols(); |
5584 | } |
5585 | |
5586 | /// Retrieve a qualifying protocol by index on the object type. |
5587 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5588 | return getObjectType()->getProtocol(I); |
5589 | } |
5590 | |
5591 | bool isSugared() const { return false; } |
5592 | QualType desugar() const { return QualType(this, 0); } |
5593 | |
5594 | /// Retrieve the type of the superclass of this object pointer type. |
5595 | /// |
5596 | /// This operation substitutes any type arguments into the |
5597 | /// superclass of the current class type, potentially producing a |
5598 | /// pointer to a specialization of the superclass type. Produces a |
5599 | /// null type if there is no superclass. |
5600 | QualType getSuperClassType() const; |
5601 | |
5602 | /// Strip off the Objective-C "kindof" type and (with it) any |
5603 | /// protocol qualifiers. |
5604 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
5605 | const ASTContext &ctx) const; |
5606 | |
5607 | void Profile(llvm::FoldingSetNodeID &ID) { |
5608 | Profile(ID, getPointeeType()); |
5609 | } |
5610 | |
5611 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
5612 | ID.AddPointer(T.getAsOpaquePtr()); |
5613 | } |
5614 | |
5615 | static bool classof(const Type *T) { |
5616 | return T->getTypeClass() == ObjCObjectPointer; |
5617 | } |
5618 | }; |
5619 | |
5620 | class AtomicType : public Type, public llvm::FoldingSetNode { |
5621 | friend class ASTContext; // ASTContext creates these. |
5622 | |
5623 | QualType ValueType; |
5624 | |
5625 | AtomicType(QualType ValTy, QualType Canonical) |
5626 | : Type(Atomic, Canonical, ValTy->isDependentType(), |
5627 | ValTy->isInstantiationDependentType(), |
5628 | ValTy->isVariablyModifiedType(), |
5629 | ValTy->containsUnexpandedParameterPack()), |
5630 | ValueType(ValTy) {} |
5631 | |
5632 | public: |
5633 | /// Gets the type contained by this atomic type, i.e. |
5634 | /// the type returned by performing an atomic load of this atomic type. |
5635 | QualType getValueType() const { return ValueType; } |
5636 | |
5637 | bool isSugared() const { return false; } |
5638 | QualType desugar() const { return QualType(this, 0); } |
5639 | |
5640 | void Profile(llvm::FoldingSetNodeID &ID) { |
5641 | Profile(ID, getValueType()); |
5642 | } |
5643 | |
5644 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
5645 | ID.AddPointer(T.getAsOpaquePtr()); |
5646 | } |
5647 | |
5648 | static bool classof(const Type *T) { |
5649 | return T->getTypeClass() == Atomic; |
5650 | } |
5651 | }; |
5652 | |
5653 | /// PipeType - OpenCL20. |
5654 | class PipeType : public Type, public llvm::FoldingSetNode { |
5655 | friend class ASTContext; // ASTContext creates these. |
5656 | |
5657 | QualType ElementType; |
5658 | bool isRead; |
5659 | |
5660 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
5661 | : Type(Pipe, CanonicalPtr, elemType->isDependentType(), |
5662 | elemType->isInstantiationDependentType(), |
5663 | elemType->isVariablyModifiedType(), |
5664 | elemType->containsUnexpandedParameterPack()), |
5665 | ElementType(elemType), isRead(isRead) {} |
5666 | |
5667 | public: |
5668 | QualType getElementType() const { return ElementType; } |
5669 | |
5670 | bool isSugared() const { return false; } |
5671 | |
5672 | QualType desugar() const { return QualType(this, 0); } |
5673 | |
5674 | void Profile(llvm::FoldingSetNodeID &ID) { |
5675 | Profile(ID, getElementType(), isReadOnly()); |
5676 | } |
5677 | |
5678 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
5679 | ID.AddPointer(T.getAsOpaquePtr()); |
5680 | ID.AddBoolean(isRead); |
5681 | } |
5682 | |
5683 | static bool classof(const Type *T) { |
5684 | return T->getTypeClass() == Pipe; |
5685 | } |
5686 | |
5687 | bool isReadOnly() const { return isRead; } |
5688 | }; |
5689 | |
5690 | /// A qualifier set is used to build a set of qualifiers. |
5691 | class QualifierCollector : public Qualifiers { |
5692 | public: |
5693 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
5694 | |
5695 | /// Collect any qualifiers on the given type and return an |
5696 | /// unqualified type. The qualifiers are assumed to be consistent |
5697 | /// with those already in the type. |
5698 | const Type *strip(QualType type) { |
5699 | addFastQualifiers(type.getLocalFastQualifiers()); |
5700 | if (!type.hasLocalNonFastQualifiers()) |
5701 | return type.getTypePtrUnsafe(); |
5702 | |
5703 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
5704 | addConsistentQualifiers(extQuals->getQualifiers()); |
5705 | return extQuals->getBaseType(); |
5706 | } |
5707 | |
5708 | /// Apply the collected qualifiers to the given type. |
5709 | QualType apply(const ASTContext &Context, QualType QT) const; |
5710 | |
5711 | /// Apply the collected qualifiers to the given type. |
5712 | QualType apply(const ASTContext &Context, const Type* T) const; |
5713 | }; |
5714 | |
5715 | // Inline function definitions. |
5716 | |
5717 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
5718 | SplitQualType desugar = |
5719 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
5720 | desugar.Quals.addConsistentQualifiers(Quals); |
5721 | return desugar; |
5722 | } |
5723 | |
5724 | inline const Type *QualType::getTypePtr() const { |
5725 | return getCommonPtr()->BaseType; |
5726 | } |
5727 | |
5728 | inline const Type *QualType::getTypePtrOrNull() const { |
5729 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
5730 | } |
5731 | |
5732 | inline SplitQualType QualType::split() const { |
5733 | if (!hasLocalNonFastQualifiers()) |
5734 | return SplitQualType(getTypePtrUnsafe(), |
5735 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
5736 | |
5737 | const ExtQuals *eq = getExtQualsUnsafe(); |
5738 | Qualifiers qs = eq->getQualifiers(); |
5739 | qs.addFastQualifiers(getLocalFastQualifiers()); |
5740 | return SplitQualType(eq->getBaseType(), qs); |
5741 | } |
5742 | |
5743 | inline Qualifiers QualType::getLocalQualifiers() const { |
5744 | Qualifiers Quals; |
5745 | if (hasLocalNonFastQualifiers()) |
5746 | Quals = getExtQualsUnsafe()->getQualifiers(); |
5747 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
5748 | return Quals; |
5749 | } |
5750 | |
5751 | inline Qualifiers QualType::getQualifiers() const { |
5752 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
5753 | quals.addFastQualifiers(getLocalFastQualifiers()); |
5754 | return quals; |
5755 | } |
5756 | |
5757 | inline unsigned QualType::getCVRQualifiers() const { |
5758 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
5759 | cvr |= getLocalCVRQualifiers(); |
5760 | return cvr; |
5761 | } |
5762 | |
5763 | inline QualType QualType::getCanonicalType() const { |
5764 | QualType canon = getCommonPtr()->CanonicalType; |
5765 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
5766 | } |
5767 | |
5768 | inline bool QualType::isCanonical() const { |
5769 | return getTypePtr()->isCanonicalUnqualified(); |
5770 | } |
5771 | |
5772 | inline bool QualType::isCanonicalAsParam() const { |
5773 | if (!isCanonical()) return false; |
5774 | if (hasLocalQualifiers()) return false; |
5775 | |
5776 | const Type *T = getTypePtr(); |
5777 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
5778 | return false; |
5779 | |
5780 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
5781 | } |
5782 | |
5783 | inline bool QualType::isConstQualified() const { |
5784 | return isLocalConstQualified() || |
5785 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
5786 | } |
5787 | |
5788 | inline bool QualType::isRestrictQualified() const { |
5789 | return isLocalRestrictQualified() || |
5790 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
5791 | } |
5792 | |
5793 | |
5794 | inline bool QualType::isVolatileQualified() const { |
5795 | return isLocalVolatileQualified() || |
5796 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
5797 | } |
5798 | |
5799 | inline bool QualType::hasQualifiers() const { |
5800 | return hasLocalQualifiers() || |
5801 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
5802 | } |
5803 | |
5804 | inline QualType QualType::getUnqualifiedType() const { |
5805 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
5806 | return QualType(getTypePtr(), 0); |
5807 | |
5808 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
5809 | } |
5810 | |
5811 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
5812 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
5813 | return split(); |
5814 | |
5815 | return getSplitUnqualifiedTypeImpl(*this); |
5816 | } |
5817 | |
5818 | inline void QualType::removeLocalConst() { |
5819 | removeLocalFastQualifiers(Qualifiers::Const); |
5820 | } |
5821 | |
5822 | inline void QualType::removeLocalRestrict() { |
5823 | removeLocalFastQualifiers(Qualifiers::Restrict); |
5824 | } |
5825 | |
5826 | inline void QualType::removeLocalVolatile() { |
5827 | removeLocalFastQualifiers(Qualifiers::Volatile); |
5828 | } |
5829 | |
5830 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
5831 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")(static_cast <bool> (!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits") ? void (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 5831, __extension__ __PRETTY_FUNCTION__)); |
5832 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
5833 | "Fast bits differ from CVR bits!"); |
5834 | |
5835 | // Fast path: we don't need to touch the slow qualifiers. |
5836 | removeLocalFastQualifiers(Mask); |
5837 | } |
5838 | |
5839 | /// Return the address space of this type. |
5840 | inline LangAS QualType::getAddressSpace() const { |
5841 | return getQualifiers().getAddressSpace(); |
5842 | } |
5843 | |
5844 | /// Return the gc attribute of this type. |
5845 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
5846 | return getQualifiers().getObjCGCAttr(); |
5847 | } |
5848 | |
5849 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
5850 | if (const PointerType *PT = t.getAs<PointerType>()) { |
5851 | if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>()) |
5852 | return FT->getExtInfo(); |
5853 | } else if (const FunctionType *FT = t.getAs<FunctionType>()) |
5854 | return FT->getExtInfo(); |
5855 | |
5856 | return FunctionType::ExtInfo(); |
5857 | } |
5858 | |
5859 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
5860 | return getFunctionExtInfo(*t); |
5861 | } |
5862 | |
5863 | /// Determine whether this type is more |
5864 | /// qualified than the Other type. For example, "const volatile int" |
5865 | /// is more qualified than "const int", "volatile int", and |
5866 | /// "int". However, it is not more qualified than "const volatile |
5867 | /// int". |
5868 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
5869 | Qualifiers MyQuals = getQualifiers(); |
5870 | Qualifiers OtherQuals = other.getQualifiers(); |
5871 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
5872 | } |
5873 | |
5874 | /// Determine whether this type is at last |
5875 | /// as qualified as the Other type. For example, "const volatile |
5876 | /// int" is at least as qualified as "const int", "volatile int", |
5877 | /// "int", and "const volatile int". |
5878 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
5879 | Qualifiers OtherQuals = other.getQualifiers(); |
5880 | |
5881 | // Ignore __unaligned qualifier if this type is a void. |
5882 | if (getUnqualifiedType()->isVoidType()) |
5883 | OtherQuals.removeUnaligned(); |
5884 | |
5885 | return getQualifiers().compatiblyIncludes(OtherQuals); |
5886 | } |
5887 | |
5888 | /// If Type is a reference type (e.g., const |
5889 | /// int&), returns the type that the reference refers to ("const |
5890 | /// int"). Otherwise, returns the type itself. This routine is used |
5891 | /// throughout Sema to implement C++ 5p6: |
5892 | /// |
5893 | /// If an expression initially has the type "reference to T" (8.3.2, |
5894 | /// 8.5.3), the type is adjusted to "T" prior to any further |
5895 | /// analysis, the expression designates the object or function |
5896 | /// denoted by the reference, and the expression is an lvalue. |
5897 | inline QualType QualType::getNonReferenceType() const { |
5898 | if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>()) |
5899 | return RefType->getPointeeType(); |
5900 | else |
5901 | return *this; |
5902 | } |
5903 | |
5904 | inline bool QualType::isCForbiddenLValueType() const { |
5905 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
5906 | getTypePtr()->isFunctionType()); |
5907 | } |
5908 | |
5909 | /// Tests whether the type is categorized as a fundamental type. |
5910 | /// |
5911 | /// \returns True for types specified in C++0x [basic.fundamental]. |
5912 | inline bool Type::isFundamentalType() const { |
5913 | return isVoidType() || |
5914 | // FIXME: It's really annoying that we don't have an |
5915 | // 'isArithmeticType()' which agrees with the standard definition. |
5916 | (isArithmeticType() && !isEnumeralType()); |
5917 | } |
5918 | |
5919 | /// Tests whether the type is categorized as a compound type. |
5920 | /// |
5921 | /// \returns True for types specified in C++0x [basic.compound]. |
5922 | inline bool Type::isCompoundType() const { |
5923 | // C++0x [basic.compound]p1: |
5924 | // Compound types can be constructed in the following ways: |
5925 | // -- arrays of objects of a given type [...]; |
5926 | return isArrayType() || |
5927 | // -- functions, which have parameters of given types [...]; |
5928 | isFunctionType() || |
5929 | // -- pointers to void or objects or functions [...]; |
5930 | isPointerType() || |
5931 | // -- references to objects or functions of a given type. [...] |
5932 | isReferenceType() || |
5933 | // -- classes containing a sequence of objects of various types, [...]; |
5934 | isRecordType() || |
5935 | // -- unions, which are classes capable of containing objects of different |
5936 | // types at different times; |
5937 | isUnionType() || |
5938 | // -- enumerations, which comprise a set of named constant values. [...]; |
5939 | isEnumeralType() || |
5940 | // -- pointers to non-static class members, [...]. |
5941 | isMemberPointerType(); |
5942 | } |
5943 | |
5944 | inline bool Type::isFunctionType() const { |
5945 | return isa<FunctionType>(CanonicalType); |
5946 | } |
5947 | |
5948 | inline bool Type::isPointerType() const { |
5949 | return isa<PointerType>(CanonicalType); |
5950 | } |
5951 | |
5952 | inline bool Type::isAnyPointerType() const { |
5953 | return isPointerType() || isObjCObjectPointerType(); |
5954 | } |
5955 | |
5956 | inline bool Type::isBlockPointerType() const { |
5957 | return isa<BlockPointerType>(CanonicalType); |
5958 | } |
5959 | |
5960 | inline bool Type::isReferenceType() const { |
5961 | return isa<ReferenceType>(CanonicalType); |
5962 | } |
5963 | |
5964 | inline bool Type::isLValueReferenceType() const { |
5965 | return isa<LValueReferenceType>(CanonicalType); |
5966 | } |
5967 | |
5968 | inline bool Type::isRValueReferenceType() const { |
5969 | return isa<RValueReferenceType>(CanonicalType); |
5970 | } |
5971 | |
5972 | inline bool Type::isFunctionPointerType() const { |
5973 | if (const PointerType *T = getAs<PointerType>()) |
5974 | return T->getPointeeType()->isFunctionType(); |
5975 | else |
5976 | return false; |
5977 | } |
5978 | |
5979 | inline bool Type::isMemberPointerType() const { |
5980 | return isa<MemberPointerType>(CanonicalType); |
5981 | } |
5982 | |
5983 | inline bool Type::isMemberFunctionPointerType() const { |
5984 | if (const MemberPointerType* T = getAs<MemberPointerType>()) |
5985 | return T->isMemberFunctionPointer(); |
5986 | else |
5987 | return false; |
5988 | } |
5989 | |
5990 | inline bool Type::isMemberDataPointerType() const { |
5991 | if (const MemberPointerType* T = getAs<MemberPointerType>()) |
5992 | return T->isMemberDataPointer(); |
5993 | else |
5994 | return false; |
5995 | } |
5996 | |
5997 | inline bool Type::isArrayType() const { |
5998 | return isa<ArrayType>(CanonicalType); |
5999 | } |
6000 | |
6001 | inline bool Type::isConstantArrayType() const { |
6002 | return isa<ConstantArrayType>(CanonicalType); |
6003 | } |
6004 | |
6005 | inline bool Type::isIncompleteArrayType() const { |
6006 | return isa<IncompleteArrayType>(CanonicalType); |
6007 | } |
6008 | |
6009 | inline bool Type::isVariableArrayType() const { |
6010 | return isa<VariableArrayType>(CanonicalType); |
6011 | } |
6012 | |
6013 | inline bool Type::isDependentSizedArrayType() const { |
6014 | return isa<DependentSizedArrayType>(CanonicalType); |
6015 | } |
6016 | |
6017 | inline bool Type::isBuiltinType() const { |
6018 | return isa<BuiltinType>(CanonicalType); |
6019 | } |
6020 | |
6021 | inline bool Type::isRecordType() const { |
6022 | return isa<RecordType>(CanonicalType); |
6023 | } |
6024 | |
6025 | inline bool Type::isEnumeralType() const { |
6026 | return isa<EnumType>(CanonicalType); |
6027 | } |
6028 | |
6029 | inline bool Type::isAnyComplexType() const { |
6030 | return isa<ComplexType>(CanonicalType); |
6031 | } |
6032 | |
6033 | inline bool Type::isVectorType() const { |
6034 | return isa<VectorType>(CanonicalType); |
6035 | } |
6036 | |
6037 | inline bool Type::isExtVectorType() const { |
6038 | return isa<ExtVectorType>(CanonicalType); |
6039 | } |
6040 | |
6041 | inline bool Type::isDependentAddressSpaceType() const { |
6042 | return isa<DependentAddressSpaceType>(CanonicalType); |
6043 | } |
6044 | |
6045 | inline bool Type::isObjCObjectPointerType() const { |
6046 | return isa<ObjCObjectPointerType>(CanonicalType); |
6047 | } |
6048 | |
6049 | inline bool Type::isObjCObjectType() const { |
6050 | return isa<ObjCObjectType>(CanonicalType); |
6051 | } |
6052 | |
6053 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6054 | return isa<ObjCInterfaceType>(CanonicalType) || |
6055 | isa<ObjCObjectType>(CanonicalType); |
6056 | } |
6057 | |
6058 | inline bool Type::isAtomicType() const { |
6059 | return isa<AtomicType>(CanonicalType); |
6060 | } |
6061 | |
6062 | inline bool Type::isObjCQualifiedIdType() const { |
6063 | if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) |
6064 | return OPT->isObjCQualifiedIdType(); |
6065 | return false; |
6066 | } |
6067 | |
6068 | inline bool Type::isObjCQualifiedClassType() const { |
6069 | if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) |
6070 | return OPT->isObjCQualifiedClassType(); |
6071 | return false; |
6072 | } |
6073 | |
6074 | inline bool Type::isObjCIdType() const { |
6075 | if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) |
6076 | return OPT->isObjCIdType(); |
6077 | return false; |
6078 | } |
6079 | |
6080 | inline bool Type::isObjCClassType() const { |
6081 | if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) |
6082 | return OPT->isObjCClassType(); |
6083 | return false; |
6084 | } |
6085 | |
6086 | inline bool Type::isObjCSelType() const { |
6087 | if (const PointerType *OPT = getAs<PointerType>()) |
6088 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6089 | return false; |
6090 | } |
6091 | |
6092 | inline bool Type::isObjCBuiltinType() const { |
6093 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6094 | } |
6095 | |
6096 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6097 | inline bool Type::is##Id##Type() const { \ |
6098 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6099 | } |
6100 | #include "clang/Basic/OpenCLImageTypes.def" |
6101 | |
6102 | inline bool Type::isSamplerT() const { |
6103 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6104 | } |
6105 | |
6106 | inline bool Type::isEventT() const { |
6107 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6108 | } |
6109 | |
6110 | inline bool Type::isClkEventT() const { |
6111 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6112 | } |
6113 | |
6114 | inline bool Type::isQueueT() const { |
6115 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6116 | } |
6117 | |
6118 | inline bool Type::isReserveIDT() const { |
6119 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6120 | } |
6121 | |
6122 | inline bool Type::isImageType() const { |
6123 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6124 | return |
6125 | #include "clang/Basic/OpenCLImageTypes.def" |
6126 | false; // end boolean or operation |
6127 | } |
6128 | |
6129 | inline bool Type::isPipeType() const { |
6130 | return isa<PipeType>(CanonicalType); |
6131 | } |
6132 | |
6133 | inline bool Type::isOpenCLSpecificType() const { |
6134 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6135 | isQueueT() || isReserveIDT() || isPipeType(); |
6136 | } |
6137 | |
6138 | inline bool Type::isTemplateTypeParmType() const { |
6139 | return isa<TemplateTypeParmType>(CanonicalType); |
6140 | } |
6141 | |
6142 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6143 | if (const BuiltinType *BT = getAs<BuiltinType>()) |
6144 | if (BT->getKind() == (BuiltinType::Kind) K) |
6145 | return true; |
6146 | return false; |
6147 | } |
6148 | |
6149 | inline bool Type::isPlaceholderType() const { |
6150 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(this)) |
6151 | return BT->isPlaceholderType(); |
6152 | return false; |
6153 | } |
6154 | |
6155 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6156 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(this)) |
6157 | if (BT->isPlaceholderType()) |
6158 | return BT; |
6159 | return nullptr; |
6160 | } |
6161 | |
6162 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6163 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))(static_cast <bool> (BuiltinType::isPlaceholderTypeKind ((BuiltinType::Kind) K)) ? void (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 6163, __extension__ __PRETTY_FUNCTION__)); |
6164 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(this)) |
6165 | return (BT->getKind() == (BuiltinType::Kind) K); |
6166 | return false; |
6167 | } |
6168 | |
6169 | inline bool Type::isNonOverloadPlaceholderType() const { |
6170 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(this)) |
6171 | return BT->isNonOverloadPlaceholderType(); |
6172 | return false; |
6173 | } |
6174 | |
6175 | inline bool Type::isVoidType() const { |
6176 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6177 | return BT->getKind() == BuiltinType::Void; |
6178 | return false; |
6179 | } |
6180 | |
6181 | inline bool Type::isHalfType() const { |
6182 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6183 | return BT->getKind() == BuiltinType::Half; |
6184 | // FIXME: Should we allow complex __fp16? Probably not. |
6185 | return false; |
6186 | } |
6187 | |
6188 | inline bool Type::isFloat16Type() const { |
6189 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6190 | return BT->getKind() == BuiltinType::Float16; |
6191 | return false; |
6192 | } |
6193 | |
6194 | inline bool Type::isNullPtrType() const { |
6195 | if (const BuiltinType *BT = getAs<BuiltinType>()) |
6196 | return BT->getKind() == BuiltinType::NullPtr; |
6197 | return false; |
6198 | } |
6199 | |
6200 | bool IsEnumDeclComplete(EnumDecl *); |
6201 | bool IsEnumDeclScoped(EnumDecl *); |
6202 | |
6203 | inline bool Type::isIntegerType() const { |
6204 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6205 | return BT->getKind() >= BuiltinType::Bool && |
6206 | BT->getKind() <= BuiltinType::Int128; |
6207 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6208 | // Incomplete enum types are not treated as integer types. |
6209 | // FIXME: In C++, enum types are never integer types. |
6210 | return IsEnumDeclComplete(ET->getDecl()) && |
6211 | !IsEnumDeclScoped(ET->getDecl()); |
6212 | } |
6213 | return false; |
6214 | } |
6215 | |
6216 | inline bool Type::isScalarType() const { |
6217 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6218 | return BT->getKind() > BuiltinType::Void && |
6219 | BT->getKind() <= BuiltinType::NullPtr; |
6220 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
6221 | // Enums are scalar types, but only if they are defined. Incomplete enums |
6222 | // are not treated as scalar types. |
6223 | return IsEnumDeclComplete(ET->getDecl()); |
6224 | return isa<PointerType>(CanonicalType) || |
6225 | isa<BlockPointerType>(CanonicalType) || |
6226 | isa<MemberPointerType>(CanonicalType) || |
6227 | isa<ComplexType>(CanonicalType) || |
6228 | isa<ObjCObjectPointerType>(CanonicalType); |
6229 | } |
6230 | |
6231 | inline bool Type::isIntegralOrEnumerationType() const { |
6232 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6233 | return BT->getKind() >= BuiltinType::Bool && |
6234 | BT->getKind() <= BuiltinType::Int128; |
6235 | |
6236 | // Check for a complete enum type; incomplete enum types are not properly an |
6237 | // enumeration type in the sense required here. |
6238 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
6239 | return IsEnumDeclComplete(ET->getDecl()); |
6240 | |
6241 | return false; |
6242 | } |
6243 | |
6244 | inline bool Type::isBooleanType() const { |
6245 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6246 | return BT->getKind() == BuiltinType::Bool; |
6247 | return false; |
6248 | } |
6249 | |
6250 | inline bool Type::isUndeducedType() const { |
6251 | auto *DT = getContainedDeducedType(); |
6252 | return DT && !DT->isDeduced(); |
6253 | } |
6254 | |
6255 | /// \brief Determines whether this is a type for which one can define |
6256 | /// an overloaded operator. |
6257 | inline bool Type::isOverloadableType() const { |
6258 | return isDependentType() || isRecordType() || isEnumeralType(); |
6259 | } |
6260 | |
6261 | /// \brief Determines whether this type can decay to a pointer type. |
6262 | inline bool Type::canDecayToPointerType() const { |
6263 | return isFunctionType() || isArrayType(); |
6264 | } |
6265 | |
6266 | inline bool Type::hasPointerRepresentation() const { |
6267 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
6268 | isObjCObjectPointerType() || isNullPtrType()); |
6269 | } |
6270 | |
6271 | inline bool Type::hasObjCPointerRepresentation() const { |
6272 | return isObjCObjectPointerType(); |
6273 | } |
6274 | |
6275 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
6276 | const Type *type = this; |
6277 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
6278 | type = arrayType->getElementType().getTypePtr(); |
6279 | return type; |
6280 | } |
6281 | |
6282 | inline const Type *Type::getPointeeOrArrayElementType() const { |
6283 | const Type *type = this; |
6284 | if (type->isAnyPointerType()) |
6285 | return type->getPointeeType().getTypePtr(); |
6286 | else if (type->isArrayType()) |
6287 | return type->getBaseElementTypeUnsafe(); |
6288 | return type; |
6289 | } |
6290 | |
6291 | /// Insertion operator for diagnostics. This allows sending QualType's into a |
6292 | /// diagnostic with <<. |
6293 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6294 | QualType T) { |
6295 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6296 | DiagnosticsEngine::ak_qualtype); |
6297 | return DB; |
6298 | } |
6299 | |
6300 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
6301 | /// into a diagnostic with <<. |
6302 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6303 | QualType T) { |
6304 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6305 | DiagnosticsEngine::ak_qualtype); |
6306 | return PD; |
6307 | } |
6308 | |
6309 | // Helper class template that is used by Type::getAs to ensure that one does |
6310 | // not try to look through a qualified type to get to an array type. |
6311 | template <typename T> |
6312 | using TypeIsArrayType = |
6313 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
6314 | std::is_base_of<ArrayType, T>::value>; |
6315 | |
6316 | // Member-template getAs<specific type>'. |
6317 | template <typename T> const T *Type::getAs() const { |
6318 | static_assert(!TypeIsArrayType<T>::value, |
6319 | "ArrayType cannot be used with getAs!"); |
6320 | |
6321 | // If this is directly a T type, return it. |
6322 | if (const T *Ty = dyn_cast<T>(this)) |
6323 | return Ty; |
6324 | |
6325 | // If the canonical form of this type isn't the right kind, reject it. |
6326 | if (!isa<T>(CanonicalType)) |
6327 | return nullptr; |
6328 | |
6329 | // If this is a typedef for the type, strip the typedef off without |
6330 | // losing all typedef information. |
6331 | return cast<T>(getUnqualifiedDesugaredType()); |
6332 | } |
6333 | |
6334 | template <typename T> const T *Type::getAsAdjusted() const { |
6335 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
6336 | |
6337 | // If this is directly a T type, return it. |
6338 | if (const T *Ty = dyn_cast<T>(this)) |
6339 | return Ty; |
6340 | |
6341 | // If the canonical form of this type isn't the right kind, reject it. |
6342 | if (!isa<T>(CanonicalType)) |
6343 | return nullptr; |
6344 | |
6345 | // Strip off type adjustments that do not modify the underlying nature of the |
6346 | // type. |
6347 | const Type *Ty = this; |
6348 | while (Ty) { |
6349 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
6350 | Ty = A->getModifiedType().getTypePtr(); |
6351 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
6352 | Ty = E->desugar().getTypePtr(); |
6353 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
6354 | Ty = P->desugar().getTypePtr(); |
6355 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
6356 | Ty = A->desugar().getTypePtr(); |
6357 | else |
6358 | break; |
6359 | } |
6360 | |
6361 | // Just because the canonical type is correct does not mean we can use cast<>, |
6362 | // since we may not have stripped off all the sugar down to the base type. |
6363 | return dyn_cast<T>(Ty); |
6364 | } |
6365 | |
6366 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
6367 | // If this is directly an array type, return it. |
6368 | if (const ArrayType *arr = dyn_cast<ArrayType>(this)) |
6369 | return arr; |
6370 | |
6371 | // If the canonical form of this type isn't the right kind, reject it. |
6372 | if (!isa<ArrayType>(CanonicalType)) |
6373 | return nullptr; |
6374 | |
6375 | // If this is a typedef for the type, strip the typedef off without |
6376 | // losing all typedef information. |
6377 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6378 | } |
6379 | |
6380 | template <typename T> const T *Type::castAs() const { |
6381 | static_assert(!TypeIsArrayType<T>::value, |
6382 | "ArrayType cannot be used with castAs!"); |
6383 | |
6384 | if (const T *ty = dyn_cast<T>(this)) return ty; |
6385 | assert(isa<T>(CanonicalType))(static_cast <bool> (isa<T>(CanonicalType)) ? void (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 6385, __extension__ __PRETTY_FUNCTION__)); |
6386 | return cast<T>(getUnqualifiedDesugaredType()); |
6387 | } |
6388 | |
6389 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
6390 | assert(isa<ArrayType>(CanonicalType))(static_cast <bool> (isa<ArrayType>(CanonicalType )) ? void (0) : __assert_fail ("isa<ArrayType>(CanonicalType)" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 6390, __extension__ __PRETTY_FUNCTION__)); |
6391 | if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr; |
6392 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6393 | } |
6394 | |
6395 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
6396 | QualType CanonicalPtr) |
6397 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
6398 | #ifndef NDEBUG |
6399 | QualType Adjusted = getAdjustedType(); |
6400 | (void)AttributedType::stripOuterNullability(Adjusted); |
6401 | assert(isa<PointerType>(Adjusted))(static_cast <bool> (isa<PointerType>(Adjusted)) ? void (0) : __assert_fail ("isa<PointerType>(Adjusted)" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/Type.h" , 6401, __extension__ __PRETTY_FUNCTION__)); |
6402 | #endif |
6403 | } |
6404 | |
6405 | QualType DecayedType::getPointeeType() const { |
6406 | QualType Decayed = getDecayedType(); |
6407 | (void)AttributedType::stripOuterNullability(Decayed); |
6408 | return cast<PointerType>(Decayed)->getPointeeType(); |
6409 | } |
6410 | |
6411 | } // namespace clang |
6412 | |
6413 | #endif // LLVM_CLANG_AST_TYPE_H |
1 | //===- llvm/Support/PointerLikeTypeTraits.h - Pointer Traits ----*- 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 defines the PointerLikeTypeTraits class. This allows data |
11 | // structures to reason about pointers and other things that are pointer sized. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_SUPPORT_POINTERLIKETYPETRAITS_H |
16 | #define LLVM_SUPPORT_POINTERLIKETYPETRAITS_H |
17 | |
18 | #include "llvm/Support/DataTypes.h" |
19 | #include <type_traits> |
20 | |
21 | namespace llvm { |
22 | |
23 | /// A traits type that is used to handle pointer types and things that are just |
24 | /// wrappers for pointers as a uniform entity. |
25 | template <typename T> struct PointerLikeTypeTraits; |
26 | |
27 | namespace detail { |
28 | /// A tiny meta function to compute the log2 of a compile time constant. |
29 | template <size_t N> |
30 | struct ConstantLog2 |
31 | : std::integral_constant<size_t, ConstantLog2<N / 2>::value + 1> {}; |
32 | template <> struct ConstantLog2<1> : std::integral_constant<size_t, 0> {}; |
33 | |
34 | // Provide a trait to check if T is pointer-like. |
35 | template <typename T, typename U = void> struct HasPointerLikeTypeTraits { |
36 | static const bool value = false; |
37 | }; |
38 | |
39 | // sizeof(T) is valid only for a complete T. |
40 | template <typename T> struct HasPointerLikeTypeTraits< |
41 | T, decltype((sizeof(PointerLikeTypeTraits<T>) + sizeof(T)), void())> { |
42 | static const bool value = true; |
43 | }; |
44 | |
45 | template <typename T> struct IsPointerLike { |
46 | static const bool value = HasPointerLikeTypeTraits<T>::value; |
47 | }; |
48 | |
49 | template <typename T> struct IsPointerLike<T *> { |
50 | static const bool value = true; |
51 | }; |
52 | } // namespace detail |
53 | |
54 | // Provide PointerLikeTypeTraits for non-cvr pointers. |
55 | template <typename T> struct PointerLikeTypeTraits<T *> { |
56 | static inline void *getAsVoidPointer(T *P) { return P; } |
57 | static inline T *getFromVoidPointer(void *P) { return static_cast<T *>(P); } |
58 | |
59 | enum { NumLowBitsAvailable = detail::ConstantLog2<alignof(T)>::value }; |
60 | }; |
61 | |
62 | template <> struct PointerLikeTypeTraits<void *> { |
63 | static inline void *getAsVoidPointer(void *P) { return P; } |
64 | static inline void *getFromVoidPointer(void *P) { return P; } |
65 | |
66 | /// Note, we assume here that void* is related to raw malloc'ed memory and |
67 | /// that malloc returns objects at least 4-byte aligned. However, this may be |
68 | /// wrong, or pointers may be from something other than malloc. In this case, |
69 | /// you should specify a real typed pointer or avoid this template. |
70 | /// |
71 | /// All clients should use assertions to do a run-time check to ensure that |
72 | /// this is actually true. |
73 | enum { NumLowBitsAvailable = 2 }; |
74 | }; |
75 | |
76 | // Provide PointerLikeTypeTraits for const things. |
77 | template <typename T> struct PointerLikeTypeTraits<const T> { |
78 | typedef PointerLikeTypeTraits<T> NonConst; |
79 | |
80 | static inline const void *getAsVoidPointer(const T P) { |
81 | return NonConst::getAsVoidPointer(P); |
82 | } |
83 | static inline const T getFromVoidPointer(const void *P) { |
84 | return NonConst::getFromVoidPointer(const_cast<void *>(P)); |
85 | } |
86 | enum { NumLowBitsAvailable = NonConst::NumLowBitsAvailable }; |
87 | }; |
88 | |
89 | // Provide PointerLikeTypeTraits for const pointers. |
90 | template <typename T> struct PointerLikeTypeTraits<const T *> { |
91 | typedef PointerLikeTypeTraits<T *> NonConst; |
92 | |
93 | static inline const void *getAsVoidPointer(const T *P) { |
94 | return NonConst::getAsVoidPointer(const_cast<T *>(P)); |
95 | } |
96 | static inline const T *getFromVoidPointer(const void *P) { |
97 | return NonConst::getFromVoidPointer(const_cast<void *>(P)); |
98 | } |
99 | enum { NumLowBitsAvailable = NonConst::NumLowBitsAvailable }; |
100 | }; |
101 | |
102 | // Provide PointerLikeTypeTraits for uintptr_t. |
103 | template <> struct PointerLikeTypeTraits<uintptr_t> { |
104 | static inline void *getAsVoidPointer(uintptr_t P) { |
105 | return reinterpret_cast<void *>(P); |
106 | } |
107 | static inline uintptr_t getFromVoidPointer(void *P) { |
108 | return reinterpret_cast<uintptr_t>(P); |
109 | } |
110 | // No bits are available! |
111 | enum { NumLowBitsAvailable = 0 }; |
112 | }; |
113 | |
114 | } // end namespace llvm |
115 | |
116 | #endif |
1 | //===- ASTContext.h - Context to hold long-lived AST nodes ------*- 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 Defines the clang::ASTContext interface. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_CLANG_AST_ASTCONTEXT_H |
16 | #define LLVM_CLANG_AST_ASTCONTEXT_H |
17 | |
18 | #include "clang/AST/ASTTypeTraits.h" |
19 | #include "clang/AST/CanonicalType.h" |
20 | #include "clang/AST/CommentCommandTraits.h" |
21 | #include "clang/AST/Decl.h" |
22 | #include "clang/AST/DeclBase.h" |
23 | #include "clang/AST/DeclarationName.h" |
24 | #include "clang/AST/ExternalASTSource.h" |
25 | #include "clang/AST/NestedNameSpecifier.h" |
26 | #include "clang/AST/PrettyPrinter.h" |
27 | #include "clang/AST/RawCommentList.h" |
28 | #include "clang/AST/TemplateBase.h" |
29 | #include "clang/AST/TemplateName.h" |
30 | #include "clang/AST/Type.h" |
31 | #include "clang/Basic/AddressSpaces.h" |
32 | #include "clang/Basic/IdentifierTable.h" |
33 | #include "clang/Basic/LLVM.h" |
34 | #include "clang/Basic/LangOptions.h" |
35 | #include "clang/Basic/Linkage.h" |
36 | #include "clang/Basic/OperatorKinds.h" |
37 | #include "clang/Basic/PartialDiagnostic.h" |
38 | #include "clang/Basic/SanitizerBlacklist.h" |
39 | #include "clang/Basic/SourceLocation.h" |
40 | #include "clang/Basic/Specifiers.h" |
41 | #include "clang/Basic/TargetInfo.h" |
42 | #include "clang/Basic/XRayLists.h" |
43 | #include "llvm/ADT/APSInt.h" |
44 | #include "llvm/ADT/ArrayRef.h" |
45 | #include "llvm/ADT/DenseMap.h" |
46 | #include "llvm/ADT/FoldingSet.h" |
47 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
48 | #include "llvm/ADT/MapVector.h" |
49 | #include "llvm/ADT/None.h" |
50 | #include "llvm/ADT/Optional.h" |
51 | #include "llvm/ADT/PointerIntPair.h" |
52 | #include "llvm/ADT/PointerUnion.h" |
53 | #include "llvm/ADT/SmallVector.h" |
54 | #include "llvm/ADT/StringMap.h" |
55 | #include "llvm/ADT/StringRef.h" |
56 | #include "llvm/ADT/TinyPtrVector.h" |
57 | #include "llvm/ADT/Triple.h" |
58 | #include "llvm/ADT/iterator_range.h" |
59 | #include "llvm/Support/AlignOf.h" |
60 | #include "llvm/Support/Allocator.h" |
61 | #include "llvm/Support/Casting.h" |
62 | #include "llvm/Support/Compiler.h" |
63 | #include <cassert> |
64 | #include <cstddef> |
65 | #include <cstdint> |
66 | #include <iterator> |
67 | #include <memory> |
68 | #include <string> |
69 | #include <type_traits> |
70 | #include <utility> |
71 | #include <vector> |
72 | |
73 | namespace llvm { |
74 | |
75 | struct fltSemantics; |
76 | |
77 | } // namespace llvm |
78 | |
79 | namespace clang { |
80 | |
81 | class APValue; |
82 | class ASTMutationListener; |
83 | class ASTRecordLayout; |
84 | class AtomicExpr; |
85 | class BlockExpr; |
86 | class BuiltinTemplateDecl; |
87 | class CharUnits; |
88 | class CXXABI; |
89 | class CXXConstructorDecl; |
90 | class CXXMethodDecl; |
91 | class CXXRecordDecl; |
92 | class DiagnosticsEngine; |
93 | class Expr; |
94 | class MangleContext; |
95 | class MangleNumberingContext; |
96 | class MaterializeTemporaryExpr; |
97 | class MemberSpecializationInfo; |
98 | class Module; |
99 | class ObjCCategoryDecl; |
100 | class ObjCCategoryImplDecl; |
101 | class ObjCContainerDecl; |
102 | class ObjCImplDecl; |
103 | class ObjCImplementationDecl; |
104 | class ObjCInterfaceDecl; |
105 | class ObjCIvarDecl; |
106 | class ObjCMethodDecl; |
107 | class ObjCPropertyDecl; |
108 | class ObjCPropertyImplDecl; |
109 | class ObjCProtocolDecl; |
110 | class ObjCTypeParamDecl; |
111 | class Preprocessor; |
112 | class Stmt; |
113 | class StoredDeclsMap; |
114 | class TemplateDecl; |
115 | class TemplateParameterList; |
116 | class TemplateTemplateParmDecl; |
117 | class TemplateTypeParmDecl; |
118 | class UnresolvedSetIterator; |
119 | class UsingShadowDecl; |
120 | class VarTemplateDecl; |
121 | class VTableContextBase; |
122 | |
123 | namespace Builtin { |
124 | |
125 | class Context; |
126 | |
127 | } // namespace Builtin |
128 | |
129 | enum BuiltinTemplateKind : int; |
130 | |
131 | namespace comments { |
132 | |
133 | class FullComment; |
134 | |
135 | } // namespace comments |
136 | |
137 | struct TypeInfo { |
138 | uint64_t Width = 0; |
139 | unsigned Align = 0; |
140 | bool AlignIsRequired : 1; |
141 | |
142 | TypeInfo() : AlignIsRequired(false) {} |
143 | TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired) |
144 | : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {} |
145 | }; |
146 | |
147 | /// \brief Holds long-lived AST nodes (such as types and decls) that can be |
148 | /// referred to throughout the semantic analysis of a file. |
149 | class ASTContext : public RefCountedBase<ASTContext> { |
150 | friend class NestedNameSpecifier; |
151 | |
152 | mutable SmallVector<Type *, 0> Types; |
153 | mutable llvm::FoldingSet<ExtQuals> ExtQualNodes; |
154 | mutable llvm::FoldingSet<ComplexType> ComplexTypes; |
155 | mutable llvm::FoldingSet<PointerType> PointerTypes; |
156 | mutable llvm::FoldingSet<AdjustedType> AdjustedTypes; |
157 | mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes; |
158 | mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes; |
159 | mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes; |
160 | mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes; |
161 | mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes; |
162 | mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes; |
163 | mutable std::vector<VariableArrayType*> VariableArrayTypes; |
164 | mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes; |
165 | mutable llvm::FoldingSet<DependentSizedExtVectorType> |
166 | DependentSizedExtVectorTypes; |
167 | mutable llvm::FoldingSet<DependentAddressSpaceType> |
168 | DependentAddressSpaceTypes; |
169 | mutable llvm::FoldingSet<VectorType> VectorTypes; |
170 | mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes; |
171 | mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&> |
172 | FunctionProtoTypes; |
173 | mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes; |
174 | mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes; |
175 | mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes; |
176 | mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes; |
177 | mutable llvm::FoldingSet<SubstTemplateTypeParmType> |
178 | SubstTemplateTypeParmTypes; |
179 | mutable llvm::FoldingSet<SubstTemplateTypeParmPackType> |
180 | SubstTemplateTypeParmPackTypes; |
181 | mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&> |
182 | TemplateSpecializationTypes; |
183 | mutable llvm::FoldingSet<ParenType> ParenTypes; |
184 | mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes; |
185 | mutable llvm::FoldingSet<DependentNameType> DependentNameTypes; |
186 | mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType, |
187 | ASTContext&> |
188 | DependentTemplateSpecializationTypes; |
189 | llvm::FoldingSet<PackExpansionType> PackExpansionTypes; |
190 | mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes; |
191 | mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes; |
192 | mutable llvm::FoldingSet<DependentUnaryTransformType> |
193 | DependentUnaryTransformTypes; |
194 | mutable llvm::FoldingSet<AutoType> AutoTypes; |
195 | mutable llvm::FoldingSet<DeducedTemplateSpecializationType> |
196 | DeducedTemplateSpecializationTypes; |
197 | mutable llvm::FoldingSet<AtomicType> AtomicTypes; |
198 | llvm::FoldingSet<AttributedType> AttributedTypes; |
199 | mutable llvm::FoldingSet<PipeType> PipeTypes; |
200 | |
201 | mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames; |
202 | mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames; |
203 | mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage> |
204 | SubstTemplateTemplateParms; |
205 | mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage, |
206 | ASTContext&> |
207 | SubstTemplateTemplateParmPacks; |
208 | |
209 | /// \brief The set of nested name specifiers. |
210 | /// |
211 | /// This set is managed by the NestedNameSpecifier class. |
212 | mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers; |
213 | mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr; |
214 | |
215 | /// \brief A cache mapping from RecordDecls to ASTRecordLayouts. |
216 | /// |
217 | /// This is lazily created. This is intentionally not serialized. |
218 | mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> |
219 | ASTRecordLayouts; |
220 | mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> |
221 | ObjCLayouts; |
222 | |
223 | /// \brief A cache from types to size and alignment information. |
224 | using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>; |
225 | mutable TypeInfoMap MemoizedTypeInfo; |
226 | |
227 | /// \brief A cache mapping from CXXRecordDecls to key functions. |
228 | llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions; |
229 | |
230 | /// \brief Mapping from ObjCContainers to their ObjCImplementations. |
231 | llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls; |
232 | |
233 | /// \brief Mapping from ObjCMethod to its duplicate declaration in the same |
234 | /// interface. |
235 | llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls; |
236 | |
237 | /// \brief Mapping from __block VarDecls to their copy initialization expr. |
238 | llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits; |
239 | |
240 | /// \brief Mapping from class scope functions specialization to their |
241 | /// template patterns. |
242 | llvm::DenseMap<const FunctionDecl*, FunctionDecl*> |
243 | ClassScopeSpecializationPattern; |
244 | |
245 | /// \brief Mapping from materialized temporaries with static storage duration |
246 | /// that appear in constant initializers to their evaluated values. These are |
247 | /// allocated in a std::map because their address must be stable. |
248 | llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *> |
249 | MaterializedTemporaryValues; |
250 | |
251 | /// \brief Representation of a "canonical" template template parameter that |
252 | /// is used in canonical template names. |
253 | class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode { |
254 | TemplateTemplateParmDecl *Parm; |
255 | |
256 | public: |
257 | CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm) |
258 | : Parm(Parm) {} |
259 | |
260 | TemplateTemplateParmDecl *getParam() const { return Parm; } |
261 | |
262 | void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); } |
263 | |
264 | static void Profile(llvm::FoldingSetNodeID &ID, |
265 | TemplateTemplateParmDecl *Parm); |
266 | }; |
267 | mutable llvm::FoldingSet<CanonicalTemplateTemplateParm> |
268 | CanonTemplateTemplateParms; |
269 | |
270 | TemplateTemplateParmDecl * |
271 | getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const; |
272 | |
273 | /// \brief The typedef for the __int128_t type. |
274 | mutable TypedefDecl *Int128Decl = nullptr; |
275 | |
276 | /// \brief The typedef for the __uint128_t type. |
277 | mutable TypedefDecl *UInt128Decl = nullptr; |
278 | |
279 | /// \brief The typedef for the target specific predefined |
280 | /// __builtin_va_list type. |
281 | mutable TypedefDecl *BuiltinVaListDecl = nullptr; |
282 | |
283 | /// The typedef for the predefined \c __builtin_ms_va_list type. |
284 | mutable TypedefDecl *BuiltinMSVaListDecl = nullptr; |
285 | |
286 | /// \brief The typedef for the predefined \c id type. |
287 | mutable TypedefDecl *ObjCIdDecl = nullptr; |
288 | |
289 | /// \brief The typedef for the predefined \c SEL type. |
290 | mutable TypedefDecl *ObjCSelDecl = nullptr; |
291 | |
292 | /// \brief The typedef for the predefined \c Class type. |
293 | mutable TypedefDecl *ObjCClassDecl = nullptr; |
294 | |
295 | /// \brief The typedef for the predefined \c Protocol class in Objective-C. |
296 | mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr; |
297 | |
298 | /// \brief The typedef for the predefined 'BOOL' type. |
299 | mutable TypedefDecl *BOOLDecl = nullptr; |
300 | |
301 | // Typedefs which may be provided defining the structure of Objective-C |
302 | // pseudo-builtins |
303 | QualType ObjCIdRedefinitionType; |
304 | QualType ObjCClassRedefinitionType; |
305 | QualType ObjCSelRedefinitionType; |
306 | |
307 | /// The identifier 'bool'. |
308 | mutable IdentifierInfo *BoolName = nullptr; |
309 | |
310 | /// The identifier 'NSObject'. |
311 | IdentifierInfo *NSObjectName = nullptr; |
312 | |
313 | /// The identifier 'NSCopying'. |
314 | IdentifierInfo *NSCopyingName = nullptr; |
315 | |
316 | /// The identifier '__make_integer_seq'. |
317 | mutable IdentifierInfo *MakeIntegerSeqName = nullptr; |
318 | |
319 | /// The identifier '__type_pack_element'. |
320 | mutable IdentifierInfo *TypePackElementName = nullptr; |
321 | |
322 | QualType ObjCConstantStringType; |
323 | mutable RecordDecl *CFConstantStringTagDecl = nullptr; |
324 | mutable TypedefDecl *CFConstantStringTypeDecl = nullptr; |
325 | |
326 | mutable QualType ObjCSuperType; |
327 | |
328 | QualType ObjCNSStringType; |
329 | |
330 | /// \brief The typedef declaration for the Objective-C "instancetype" type. |
331 | TypedefDecl *ObjCInstanceTypeDecl = nullptr; |
332 | |
333 | /// \brief The type for the C FILE type. |
334 | TypeDecl *FILEDecl = nullptr; |
335 | |
336 | /// \brief The type for the C jmp_buf type. |
337 | TypeDecl *jmp_bufDecl = nullptr; |
338 | |
339 | /// \brief The type for the C sigjmp_buf type. |
340 | TypeDecl *sigjmp_bufDecl = nullptr; |
341 | |
342 | /// \brief The type for the C ucontext_t type. |
343 | TypeDecl *ucontext_tDecl = nullptr; |
344 | |
345 | /// \brief Type for the Block descriptor for Blocks CodeGen. |
346 | /// |
347 | /// Since this is only used for generation of debug info, it is not |
348 | /// serialized. |
349 | mutable RecordDecl *BlockDescriptorType = nullptr; |
350 | |
351 | /// \brief Type for the Block descriptor for Blocks CodeGen. |
352 | /// |
353 | /// Since this is only used for generation of debug info, it is not |
354 | /// serialized. |
355 | mutable RecordDecl *BlockDescriptorExtendedType = nullptr; |
356 | |
357 | /// \brief Declaration for the CUDA cudaConfigureCall function. |
358 | FunctionDecl *cudaConfigureCallDecl = nullptr; |
359 | |
360 | /// \brief Keeps track of all declaration attributes. |
361 | /// |
362 | /// Since so few decls have attrs, we keep them in a hash map instead of |
363 | /// wasting space in the Decl class. |
364 | llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs; |
365 | |
366 | /// \brief A mapping from non-redeclarable declarations in modules that were |
367 | /// merged with other declarations to the canonical declaration that they were |
368 | /// merged into. |
369 | llvm::DenseMap<Decl*, Decl*> MergedDecls; |
370 | |
371 | /// \brief A mapping from a defining declaration to a list of modules (other |
372 | /// than the owning module of the declaration) that contain merged |
373 | /// definitions of that entity. |
374 | llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules; |
375 | |
376 | /// \brief Initializers for a module, in order. Each Decl will be either |
377 | /// something that has a semantic effect on startup (such as a variable with |
378 | /// a non-constant initializer), or an ImportDecl (which recursively triggers |
379 | /// initialization of another module). |
380 | struct PerModuleInitializers { |
381 | llvm::SmallVector<Decl*, 4> Initializers; |
382 | llvm::SmallVector<uint32_t, 4> LazyInitializers; |
383 | |
384 | void resolve(ASTContext &Ctx); |
385 | }; |
386 | llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers; |
387 | |
388 | ASTContext &this_() { return *this; } |
389 | |
390 | public: |
391 | /// \brief A type synonym for the TemplateOrInstantiation mapping. |
392 | using TemplateOrSpecializationInfo = |
393 | llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>; |
394 | |
395 | private: |
396 | friend class ASTDeclReader; |
397 | friend class ASTReader; |
398 | friend class ASTWriter; |
399 | friend class CXXRecordDecl; |
400 | |
401 | /// \brief A mapping to contain the template or declaration that |
402 | /// a variable declaration describes or was instantiated from, |
403 | /// respectively. |
404 | /// |
405 | /// For non-templates, this value will be NULL. For variable |
406 | /// declarations that describe a variable template, this will be a |
407 | /// pointer to a VarTemplateDecl. For static data members |
408 | /// of class template specializations, this will be the |
409 | /// MemberSpecializationInfo referring to the member variable that was |
410 | /// instantiated or specialized. Thus, the mapping will keep track of |
411 | /// the static data member templates from which static data members of |
412 | /// class template specializations were instantiated. |
413 | /// |
414 | /// Given the following example: |
415 | /// |
416 | /// \code |
417 | /// template<typename T> |
418 | /// struct X { |
419 | /// static T value; |
420 | /// }; |
421 | /// |
422 | /// template<typename T> |
423 | /// T X<T>::value = T(17); |
424 | /// |
425 | /// int *x = &X<int>::value; |
426 | /// \endcode |
427 | /// |
428 | /// This mapping will contain an entry that maps from the VarDecl for |
429 | /// X<int>::value to the corresponding VarDecl for X<T>::value (within the |
430 | /// class template X) and will be marked TSK_ImplicitInstantiation. |
431 | llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo> |
432 | TemplateOrInstantiation; |
433 | |
434 | /// \brief Keeps track of the declaration from which a using declaration was |
435 | /// created during instantiation. |
436 | /// |
437 | /// The source and target declarations are always a UsingDecl, an |
438 | /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl. |
439 | /// |
440 | /// For example: |
441 | /// \code |
442 | /// template<typename T> |
443 | /// struct A { |
444 | /// void f(); |
445 | /// }; |
446 | /// |
447 | /// template<typename T> |
448 | /// struct B : A<T> { |
449 | /// using A<T>::f; |
450 | /// }; |
451 | /// |
452 | /// template struct B<int>; |
453 | /// \endcode |
454 | /// |
455 | /// This mapping will contain an entry that maps from the UsingDecl in |
456 | /// B<int> to the UnresolvedUsingDecl in B<T>. |
457 | llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl; |
458 | |
459 | llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*> |
460 | InstantiatedFromUsingShadowDecl; |
461 | |
462 | llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl; |
463 | |
464 | /// \brief Mapping that stores the methods overridden by a given C++ |
465 | /// member function. |
466 | /// |
467 | /// Since most C++ member functions aren't virtual and therefore |
468 | /// don't override anything, we store the overridden functions in |
469 | /// this map on the side rather than within the CXXMethodDecl structure. |
470 | using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>; |
471 | llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods; |
472 | |
473 | /// \brief Mapping from each declaration context to its corresponding |
474 | /// mangling numbering context (used for constructs like lambdas which |
475 | /// need to be consistently numbered for the mangler). |
476 | llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>> |
477 | MangleNumberingContexts; |
478 | |
479 | /// \brief Side-table of mangling numbers for declarations which rarely |
480 | /// need them (like static local vars). |
481 | llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers; |
482 | llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers; |
483 | |
484 | /// \brief Mapping that stores parameterIndex values for ParmVarDecls when |
485 | /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex. |
486 | using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>; |
487 | ParameterIndexTable ParamIndices; |
488 | |
489 | ImportDecl *FirstLocalImport = nullptr; |
490 | ImportDecl *LastLocalImport = nullptr; |
491 | |
492 | TranslationUnitDecl *TUDecl; |
493 | mutable ExternCContextDecl *ExternCContext = nullptr; |
494 | mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr; |
495 | mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr; |
496 | |
497 | /// \brief The associated SourceManager object. |
498 | SourceManager &SourceMgr; |
499 | |
500 | /// \brief The language options used to create the AST associated with |
501 | /// this ASTContext object. |
502 | LangOptions &LangOpts; |
503 | |
504 | /// \brief Blacklist object that is used by sanitizers to decide which |
505 | /// entities should not be instrumented. |
506 | std::unique_ptr<SanitizerBlacklist> SanitizerBL; |
507 | |
508 | /// \brief Function filtering mechanism to determine whether a given function |
509 | /// should be imbued with the XRay "always" or "never" attributes. |
510 | std::unique_ptr<XRayFunctionFilter> XRayFilter; |
511 | |
512 | /// \brief The allocator used to create AST objects. |
513 | /// |
514 | /// AST objects are never destructed; rather, all memory associated with the |
515 | /// AST objects will be released when the ASTContext itself is destroyed. |
516 | mutable llvm::BumpPtrAllocator BumpAlloc; |
517 | |
518 | /// \brief Allocator for partial diagnostics. |
519 | PartialDiagnostic::StorageAllocator DiagAllocator; |
520 | |
521 | /// \brief The current C++ ABI. |
522 | std::unique_ptr<CXXABI> ABI; |
523 | CXXABI *createCXXABI(const TargetInfo &T); |
524 | |
525 | /// \brief The logical -> physical address space map. |
526 | const LangASMap *AddrSpaceMap = nullptr; |
527 | |
528 | /// \brief Address space map mangling must be used with language specific |
529 | /// address spaces (e.g. OpenCL/CUDA) |
530 | bool AddrSpaceMapMangling; |
531 | |
532 | const TargetInfo *Target = nullptr; |
533 | const TargetInfo *AuxTarget = nullptr; |
534 | clang::PrintingPolicy PrintingPolicy; |
535 | |
536 | public: |
537 | IdentifierTable &Idents; |
538 | SelectorTable &Selectors; |
539 | Builtin::Context &BuiltinInfo; |
540 | mutable DeclarationNameTable DeclarationNames; |
541 | IntrusiveRefCntPtr<ExternalASTSource> ExternalSource; |
542 | ASTMutationListener *Listener = nullptr; |
543 | |
544 | /// \brief Contains parents of a node. |
545 | using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>; |
546 | |
547 | /// \brief Maps from a node to its parents. This is used for nodes that have |
548 | /// pointer identity only, which are more common and we can save space by |
549 | /// only storing a unique pointer to them. |
550 | using ParentMapPointers = |
551 | llvm::DenseMap<const void *, |
552 | llvm::PointerUnion4<const Decl *, const Stmt *, |
553 | ast_type_traits::DynTypedNode *, |
554 | ParentVector *>>; |
555 | |
556 | /// Parent map for nodes without pointer identity. We store a full |
557 | /// DynTypedNode for all keys. |
558 | using ParentMapOtherNodes = |
559 | llvm::DenseMap<ast_type_traits::DynTypedNode, |
560 | llvm::PointerUnion4<const Decl *, const Stmt *, |
561 | ast_type_traits::DynTypedNode *, |
562 | ParentVector *>>; |
563 | |
564 | /// Container for either a single DynTypedNode or for an ArrayRef to |
565 | /// DynTypedNode. For use with ParentMap. |
566 | class DynTypedNodeList { |
567 | using DynTypedNode = ast_type_traits::DynTypedNode; |
568 | |
569 | llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode, |
570 | ArrayRef<DynTypedNode>> Storage; |
571 | bool IsSingleNode; |
572 | |
573 | public: |
574 | DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) { |
575 | new (Storage.buffer) DynTypedNode(N); |
576 | } |
577 | |
578 | DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) { |
579 | new (Storage.buffer) ArrayRef<DynTypedNode>(A); |
580 | } |
581 | |
582 | const ast_type_traits::DynTypedNode *begin() const { |
583 | if (!IsSingleNode) |
584 | return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer) |
585 | ->begin(); |
586 | return reinterpret_cast<const DynTypedNode *>(Storage.buffer); |
587 | } |
588 | |
589 | const ast_type_traits::DynTypedNode *end() const { |
590 | if (!IsSingleNode) |
591 | return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer) |
592 | ->end(); |
593 | return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1; |
594 | } |
595 | |
596 | size_t size() const { return end() - begin(); } |
597 | bool empty() const { return begin() == end(); } |
598 | |
599 | const DynTypedNode &operator[](size_t N) const { |
600 | assert(N < size() && "Out of bounds!")(static_cast <bool> (N < size() && "Out of bounds!" ) ? void (0) : __assert_fail ("N < size() && \"Out of bounds!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 600, __extension__ __PRETTY_FUNCTION__)); |
601 | return *(begin() + N); |
602 | } |
603 | }; |
604 | |
605 | /// \brief Returns the parents of the given node. |
606 | /// |
607 | /// Note that this will lazily compute the parents of all nodes |
608 | /// and store them for later retrieval. Thus, the first call is O(n) |
609 | /// in the number of AST nodes. |
610 | /// |
611 | /// Caveats and FIXMEs: |
612 | /// Calculating the parent map over all AST nodes will need to load the |
613 | /// full AST. This can be undesirable in the case where the full AST is |
614 | /// expensive to create (for example, when using precompiled header |
615 | /// preambles). Thus, there are good opportunities for optimization here. |
616 | /// One idea is to walk the given node downwards, looking for references |
617 | /// to declaration contexts - once a declaration context is found, compute |
618 | /// the parent map for the declaration context; if that can satisfy the |
619 | /// request, loading the whole AST can be avoided. Note that this is made |
620 | /// more complex by statements in templates having multiple parents - those |
621 | /// problems can be solved by building closure over the templated parts of |
622 | /// the AST, which also avoids touching large parts of the AST. |
623 | /// Additionally, we will want to add an interface to already give a hint |
624 | /// where to search for the parents, for example when looking at a statement |
625 | /// inside a certain function. |
626 | /// |
627 | /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc, |
628 | /// NestedNameSpecifier or NestedNameSpecifierLoc. |
629 | template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) { |
630 | return getParents(ast_type_traits::DynTypedNode::create(Node)); |
631 | } |
632 | |
633 | DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node); |
634 | |
635 | const clang::PrintingPolicy &getPrintingPolicy() const { |
636 | return PrintingPolicy; |
637 | } |
638 | |
639 | void setPrintingPolicy(const clang::PrintingPolicy &Policy) { |
640 | PrintingPolicy = Policy; |
641 | } |
642 | |
643 | SourceManager& getSourceManager() { return SourceMgr; } |
644 | const SourceManager& getSourceManager() const { return SourceMgr; } |
645 | |
646 | llvm::BumpPtrAllocator &getAllocator() const { |
647 | return BumpAlloc; |
648 | } |
649 | |
650 | void *Allocate(size_t Size, unsigned Align = 8) const { |
651 | return BumpAlloc.Allocate(Size, Align); |
652 | } |
653 | template <typename T> T *Allocate(size_t Num = 1) const { |
654 | return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T))); |
655 | } |
656 | void Deallocate(void *Ptr) const {} |
657 | |
658 | /// Return the total amount of physical memory allocated for representing |
659 | /// AST nodes and type information. |
660 | size_t getASTAllocatedMemory() const { |
661 | return BumpAlloc.getTotalMemory(); |
662 | } |
663 | |
664 | /// Return the total memory used for various side tables. |
665 | size_t getSideTableAllocatedMemory() const; |
666 | |
667 | PartialDiagnostic::StorageAllocator &getDiagAllocator() { |
668 | return DiagAllocator; |
669 | } |
670 | |
671 | const TargetInfo &getTargetInfo() const { return *Target; } |
672 | const TargetInfo *getAuxTargetInfo() const { return AuxTarget; } |
673 | |
674 | /// getIntTypeForBitwidth - |
675 | /// sets integer QualTy according to specified details: |
676 | /// bitwidth, signed/unsigned. |
677 | /// Returns empty type if there is no appropriate target types. |
678 | QualType getIntTypeForBitwidth(unsigned DestWidth, |
679 | unsigned Signed) const; |
680 | |
681 | /// getRealTypeForBitwidth - |
682 | /// sets floating point QualTy according to specified bitwidth. |
683 | /// Returns empty type if there is no appropriate target types. |
684 | QualType getRealTypeForBitwidth(unsigned DestWidth) const; |
685 | |
686 | bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const; |
687 | |
688 | const LangOptions& getLangOpts() const { return LangOpts; } |
689 | |
690 | const SanitizerBlacklist &getSanitizerBlacklist() const { |
691 | return *SanitizerBL; |
692 | } |
693 | |
694 | const XRayFunctionFilter &getXRayFilter() const { |
695 | return *XRayFilter; |
696 | } |
697 | |
698 | DiagnosticsEngine &getDiagnostics() const; |
699 | |
700 | FullSourceLoc getFullLoc(SourceLocation Loc) const { |
701 | return FullSourceLoc(Loc,SourceMgr); |
702 | } |
703 | |
704 | /// \brief All comments in this translation unit. |
705 | RawCommentList Comments; |
706 | |
707 | /// \brief True if comments are already loaded from ExternalASTSource. |
708 | mutable bool CommentsLoaded = false; |
709 | |
710 | class RawCommentAndCacheFlags { |
711 | public: |
712 | enum Kind { |
713 | /// We searched for a comment attached to the particular declaration, but |
714 | /// didn't find any. |
715 | /// |
716 | /// getRaw() == 0. |
717 | NoCommentInDecl = 0, |
718 | |
719 | /// We have found a comment attached to this particular declaration. |
720 | /// |
721 | /// getRaw() != 0. |
722 | FromDecl, |
723 | |
724 | /// This declaration does not have an attached comment, and we have |
725 | /// searched the redeclaration chain. |
726 | /// |
727 | /// If getRaw() == 0, the whole redeclaration chain does not have any |
728 | /// comments. |
729 | /// |
730 | /// If getRaw() != 0, it is a comment propagated from other |
731 | /// redeclaration. |
732 | FromRedecl |
733 | }; |
734 | |
735 | Kind getKind() const LLVM_READONLY__attribute__((__pure__)) { |
736 | return Data.getInt(); |
737 | } |
738 | |
739 | void setKind(Kind K) { |
740 | Data.setInt(K); |
741 | } |
742 | |
743 | const RawComment *getRaw() const LLVM_READONLY__attribute__((__pure__)) { |
744 | return Data.getPointer(); |
745 | } |
746 | |
747 | void setRaw(const RawComment *RC) { |
748 | Data.setPointer(RC); |
749 | } |
750 | |
751 | const Decl *getOriginalDecl() const LLVM_READONLY__attribute__((__pure__)) { |
752 | return OriginalDecl; |
753 | } |
754 | |
755 | void setOriginalDecl(const Decl *Orig) { |
756 | OriginalDecl = Orig; |
757 | } |
758 | |
759 | private: |
760 | llvm::PointerIntPair<const RawComment *, 2, Kind> Data; |
761 | const Decl *OriginalDecl; |
762 | }; |
763 | |
764 | /// \brief Mapping from declarations to comments attached to any |
765 | /// redeclaration. |
766 | /// |
767 | /// Raw comments are owned by Comments list. This mapping is populated |
768 | /// lazily. |
769 | mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments; |
770 | |
771 | /// \brief Mapping from declarations to parsed comments attached to any |
772 | /// redeclaration. |
773 | mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments; |
774 | |
775 | /// \brief Return the documentation comment attached to a given declaration, |
776 | /// without looking into cache. |
777 | RawComment *getRawCommentForDeclNoCache(const Decl *D) const; |
778 | |
779 | public: |
780 | RawCommentList &getRawCommentList() { |
781 | return Comments; |
782 | } |
783 | |
784 | void addComment(const RawComment &RC) { |
785 | assert(LangOpts.RetainCommentsFromSystemHeaders ||(static_cast <bool> (LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin( ))) ? void (0) : __assert_fail ("LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 786, __extension__ __PRETTY_FUNCTION__)) |
786 | !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()))(static_cast <bool> (LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin( ))) ? void (0) : __assert_fail ("LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 786, __extension__ __PRETTY_FUNCTION__)); |
787 | Comments.addComment(RC, BumpAlloc); |
788 | } |
789 | |
790 | /// \brief Return the documentation comment attached to a given declaration. |
791 | /// Returns nullptr if no comment is attached. |
792 | /// |
793 | /// \param OriginalDecl if not nullptr, is set to declaration AST node that |
794 | /// had the comment, if the comment we found comes from a redeclaration. |
795 | const RawComment * |
796 | getRawCommentForAnyRedecl(const Decl *D, |
797 | const Decl **OriginalDecl = nullptr) const; |
798 | |
799 | /// Return parsed documentation comment attached to a given declaration. |
800 | /// Returns nullptr if no comment is attached. |
801 | /// |
802 | /// \param PP the Preprocessor used with this TU. Could be nullptr if |
803 | /// preprocessor is not available. |
804 | comments::FullComment *getCommentForDecl(const Decl *D, |
805 | const Preprocessor *PP) const; |
806 | |
807 | /// Return parsed documentation comment attached to a given declaration. |
808 | /// Returns nullptr if no comment is attached. Does not look at any |
809 | /// redeclarations of the declaration. |
810 | comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const; |
811 | |
812 | comments::FullComment *cloneFullComment(comments::FullComment *FC, |
813 | const Decl *D) const; |
814 | |
815 | private: |
816 | mutable comments::CommandTraits CommentCommandTraits; |
817 | |
818 | /// \brief Iterator that visits import declarations. |
819 | class import_iterator { |
820 | ImportDecl *Import = nullptr; |
821 | |
822 | public: |
823 | using value_type = ImportDecl *; |
824 | using reference = ImportDecl *; |
825 | using pointer = ImportDecl *; |
826 | using difference_type = int; |
827 | using iterator_category = std::forward_iterator_tag; |
828 | |
829 | import_iterator() = default; |
830 | explicit import_iterator(ImportDecl *Import) : Import(Import) {} |
831 | |
832 | reference operator*() const { return Import; } |
833 | pointer operator->() const { return Import; } |
834 | |
835 | import_iterator &operator++() { |
836 | Import = ASTContext::getNextLocalImport(Import); |
837 | return *this; |
838 | } |
839 | |
840 | import_iterator operator++(int) { |
841 | import_iterator Other(*this); |
842 | ++(*this); |
843 | return Other; |
844 | } |
845 | |
846 | friend bool operator==(import_iterator X, import_iterator Y) { |
847 | return X.Import == Y.Import; |
848 | } |
849 | |
850 | friend bool operator!=(import_iterator X, import_iterator Y) { |
851 | return X.Import != Y.Import; |
852 | } |
853 | }; |
854 | |
855 | public: |
856 | comments::CommandTraits &getCommentCommandTraits() const { |
857 | return CommentCommandTraits; |
858 | } |
859 | |
860 | /// \brief Retrieve the attributes for the given declaration. |
861 | AttrVec& getDeclAttrs(const Decl *D); |
862 | |
863 | /// \brief Erase the attributes corresponding to the given declaration. |
864 | void eraseDeclAttrs(const Decl *D); |
865 | |
866 | /// \brief If this variable is an instantiated static data member of a |
867 | /// class template specialization, returns the templated static data member |
868 | /// from which it was instantiated. |
869 | // FIXME: Remove ? |
870 | MemberSpecializationInfo *getInstantiatedFromStaticDataMember( |
871 | const VarDecl *Var); |
872 | |
873 | TemplateOrSpecializationInfo |
874 | getTemplateOrSpecializationInfo(const VarDecl *Var); |
875 | |
876 | FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD); |
877 | |
878 | void setClassScopeSpecializationPattern(FunctionDecl *FD, |
879 | FunctionDecl *Pattern); |
880 | |
881 | /// \brief Note that the static data member \p Inst is an instantiation of |
882 | /// the static data member template \p Tmpl of a class template. |
883 | void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, |
884 | TemplateSpecializationKind TSK, |
885 | SourceLocation PointOfInstantiation = SourceLocation()); |
886 | |
887 | void setTemplateOrSpecializationInfo(VarDecl *Inst, |
888 | TemplateOrSpecializationInfo TSI); |
889 | |
890 | /// \brief If the given using decl \p Inst is an instantiation of a |
891 | /// (possibly unresolved) using decl from a template instantiation, |
892 | /// return it. |
893 | NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst); |
894 | |
895 | /// \brief Remember that the using decl \p Inst is an instantiation |
896 | /// of the using decl \p Pattern of a class template. |
897 | void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern); |
898 | |
899 | void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, |
900 | UsingShadowDecl *Pattern); |
901 | UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst); |
902 | |
903 | FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field); |
904 | |
905 | void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl); |
906 | |
907 | // Access to the set of methods overridden by the given C++ method. |
908 | using overridden_cxx_method_iterator = CXXMethodVector::const_iterator; |
909 | overridden_cxx_method_iterator |
910 | overridden_methods_begin(const CXXMethodDecl *Method) const; |
911 | |
912 | overridden_cxx_method_iterator |
913 | overridden_methods_end(const CXXMethodDecl *Method) const; |
914 | |
915 | unsigned overridden_methods_size(const CXXMethodDecl *Method) const; |
916 | |
917 | using overridden_method_range = |
918 | llvm::iterator_range<overridden_cxx_method_iterator>; |
919 | |
920 | overridden_method_range overridden_methods(const CXXMethodDecl *Method) const; |
921 | |
922 | /// \brief Note that the given C++ \p Method overrides the given \p |
923 | /// Overridden method. |
924 | void addOverriddenMethod(const CXXMethodDecl *Method, |
925 | const CXXMethodDecl *Overridden); |
926 | |
927 | /// \brief Return C++ or ObjC overridden methods for the given \p Method. |
928 | /// |
929 | /// An ObjC method is considered to override any method in the class's |
930 | /// base classes, its protocols, or its categories' protocols, that has |
931 | /// the same selector and is of the same kind (class or instance). |
932 | /// A method in an implementation is not considered as overriding the same |
933 | /// method in the interface or its categories. |
934 | void getOverriddenMethods( |
935 | const NamedDecl *Method, |
936 | SmallVectorImpl<const NamedDecl *> &Overridden) const; |
937 | |
938 | /// \brief Notify the AST context that a new import declaration has been |
939 | /// parsed or implicitly created within this translation unit. |
940 | void addedLocalImportDecl(ImportDecl *Import); |
941 | |
942 | static ImportDecl *getNextLocalImport(ImportDecl *Import) { |
943 | return Import->NextLocalImport; |
944 | } |
945 | |
946 | using import_range = llvm::iterator_range<import_iterator>; |
947 | |
948 | import_range local_imports() const { |
949 | return import_range(import_iterator(FirstLocalImport), import_iterator()); |
950 | } |
951 | |
952 | Decl *getPrimaryMergedDecl(Decl *D) { |
953 | Decl *Result = MergedDecls.lookup(D); |
954 | return Result ? Result : D; |
955 | } |
956 | void setPrimaryMergedDecl(Decl *D, Decl *Primary) { |
957 | MergedDecls[D] = Primary; |
958 | } |
959 | |
960 | /// \brief Note that the definition \p ND has been merged into module \p M, |
961 | /// and should be visible whenever \p M is visible. |
962 | void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, |
963 | bool NotifyListeners = true); |
964 | |
965 | /// \brief Clean up the merged definition list. Call this if you might have |
966 | /// added duplicates into the list. |
967 | void deduplicateMergedDefinitonsFor(NamedDecl *ND); |
968 | |
969 | /// \brief Get the additional modules in which the definition \p Def has |
970 | /// been merged. |
971 | ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) { |
972 | auto MergedIt = MergedDefModules.find(Def); |
973 | if (MergedIt == MergedDefModules.end()) |
974 | return None; |
975 | return MergedIt->second; |
976 | } |
977 | |
978 | /// Add a declaration to the list of declarations that are initialized |
979 | /// for a module. This will typically be a global variable (with internal |
980 | /// linkage) that runs module initializers, such as the iostream initializer, |
981 | /// or an ImportDecl nominating another module that has initializers. |
982 | void addModuleInitializer(Module *M, Decl *Init); |
983 | |
984 | void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs); |
985 | |
986 | /// Get the initializations to perform when importing a module, if any. |
987 | ArrayRef<Decl*> getModuleInitializers(Module *M); |
988 | |
989 | TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; } |
990 | |
991 | ExternCContextDecl *getExternCContextDecl() const; |
992 | BuiltinTemplateDecl *getMakeIntegerSeqDecl() const; |
993 | BuiltinTemplateDecl *getTypePackElementDecl() const; |
994 | |
995 | // Builtin Types. |
996 | CanQualType VoidTy; |
997 | CanQualType BoolTy; |
998 | CanQualType CharTy; |
999 | CanQualType WCharTy; // [C++ 3.9.1p5]. |
1000 | CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99. |
1001 | CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions. |
1002 | CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99. |
1003 | CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99. |
1004 | CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty; |
1005 | CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy; |
1006 | CanQualType UnsignedLongLongTy, UnsignedInt128Ty; |
1007 | CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty; |
1008 | CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON |
1009 | CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 |
1010 | CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy; |
1011 | CanQualType Float128ComplexTy; |
1012 | CanQualType VoidPtrTy, NullPtrTy; |
1013 | CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy; |
1014 | CanQualType BuiltinFnTy; |
1015 | CanQualType PseudoObjectTy, ARCUnbridgedCastTy; |
1016 | CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy; |
1017 | CanQualType ObjCBuiltinBoolTy; |
1018 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
1019 | CanQualType SingletonId; |
1020 | #include "clang/Basic/OpenCLImageTypes.def" |
1021 | CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy; |
1022 | CanQualType OCLQueueTy, OCLReserveIDTy; |
1023 | CanQualType OMPArraySectionTy; |
1024 | |
1025 | // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand. |
1026 | mutable QualType AutoDeductTy; // Deduction against 'auto'. |
1027 | mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'. |
1028 | |
1029 | // Decl used to help define __builtin_va_list for some targets. |
1030 | // The decl is built when constructing 'BuiltinVaListDecl'. |
1031 | mutable Decl *VaListTagDecl; |
1032 | |
1033 | ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, |
1034 | SelectorTable &sels, Builtin::Context &builtins); |
1035 | ASTContext(const ASTContext &) = delete; |
1036 | ASTContext &operator=(const ASTContext &) = delete; |
1037 | ~ASTContext(); |
1038 | |
1039 | /// \brief Attach an external AST source to the AST context. |
1040 | /// |
1041 | /// The external AST source provides the ability to load parts of |
1042 | /// the abstract syntax tree as needed from some external storage, |
1043 | /// e.g., a precompiled header. |
1044 | void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source); |
1045 | |
1046 | /// \brief Retrieve a pointer to the external AST source associated |
1047 | /// with this AST context, if any. |
1048 | ExternalASTSource *getExternalSource() const { |
1049 | return ExternalSource.get(); |
1050 | } |
1051 | |
1052 | /// \brief Attach an AST mutation listener to the AST context. |
1053 | /// |
1054 | /// The AST mutation listener provides the ability to track modifications to |
1055 | /// the abstract syntax tree entities committed after they were initially |
1056 | /// created. |
1057 | void setASTMutationListener(ASTMutationListener *Listener) { |
1058 | this->Listener = Listener; |
1059 | } |
1060 | |
1061 | /// \brief Retrieve a pointer to the AST mutation listener associated |
1062 | /// with this AST context, if any. |
1063 | ASTMutationListener *getASTMutationListener() const { return Listener; } |
1064 | |
1065 | void PrintStats() const; |
1066 | const SmallVectorImpl<Type *>& getTypes() const { return Types; } |
1067 | |
1068 | BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, |
1069 | const IdentifierInfo *II) const; |
1070 | |
1071 | /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl |
1072 | /// declaration. |
1073 | RecordDecl *buildImplicitRecord(StringRef Name, |
1074 | RecordDecl::TagKind TK = TTK_Struct) const; |
1075 | |
1076 | /// \brief Create a new implicit TU-level typedef declaration. |
1077 | TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const; |
1078 | |
1079 | /// \brief Retrieve the declaration for the 128-bit signed integer type. |
1080 | TypedefDecl *getInt128Decl() const; |
1081 | |
1082 | /// \brief Retrieve the declaration for the 128-bit unsigned integer type. |
1083 | TypedefDecl *getUInt128Decl() const; |
1084 | |
1085 | //===--------------------------------------------------------------------===// |
1086 | // Type Constructors |
1087 | //===--------------------------------------------------------------------===// |
1088 | |
1089 | private: |
1090 | /// \brief Return a type with extended qualifiers. |
1091 | QualType getExtQualType(const Type *Base, Qualifiers Quals) const; |
1092 | |
1093 | QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const; |
1094 | |
1095 | QualType getPipeType(QualType T, bool ReadOnly) const; |
1096 | |
1097 | public: |
1098 | /// \brief Return the uniqued reference to the type for an address space |
1099 | /// qualified type with the specified type and address space. |
1100 | /// |
1101 | /// The resulting type has a union of the qualifiers from T and the address |
1102 | /// space. If T already has an address space specifier, it is silently |
1103 | /// replaced. |
1104 | QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const; |
1105 | |
1106 | /// \brief Remove any existing address space on the type and returns the type |
1107 | /// with qualifiers intact (or that's the idea anyway) |
1108 | /// |
1109 | /// The return type should be T with all prior qualifiers minus the address |
1110 | /// space. |
1111 | QualType removeAddrSpaceQualType(QualType T) const; |
1112 | |
1113 | /// \brief Apply Objective-C protocol qualifiers to the given type. |
1114 | /// \param allowOnPointerType specifies if we can apply protocol |
1115 | /// qualifiers on ObjCObjectPointerType. It can be set to true when |
1116 | /// contructing the canonical type of a Objective-C type parameter. |
1117 | QualType applyObjCProtocolQualifiers(QualType type, |
1118 | ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError, |
1119 | bool allowOnPointerType = false) const; |
1120 | |
1121 | /// \brief Return the uniqued reference to the type for an Objective-C |
1122 | /// gc-qualified type. |
1123 | /// |
1124 | /// The retulting type has a union of the qualifiers from T and the gc |
1125 | /// attribute. |
1126 | QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const; |
1127 | |
1128 | /// \brief Return the uniqued reference to the type for a \c restrict |
1129 | /// qualified type. |
1130 | /// |
1131 | /// The resulting type has a union of the qualifiers from \p T and |
1132 | /// \c restrict. |
1133 | QualType getRestrictType(QualType T) const { |
1134 | return T.withFastQualifiers(Qualifiers::Restrict); |
1135 | } |
1136 | |
1137 | /// \brief Return the uniqued reference to the type for a \c volatile |
1138 | /// qualified type. |
1139 | /// |
1140 | /// The resulting type has a union of the qualifiers from \p T and |
1141 | /// \c volatile. |
1142 | QualType getVolatileType(QualType T) const { |
1143 | return T.withFastQualifiers(Qualifiers::Volatile); |
1144 | } |
1145 | |
1146 | /// \brief Return the uniqued reference to the type for a \c const |
1147 | /// qualified type. |
1148 | /// |
1149 | /// The resulting type has a union of the qualifiers from \p T and \c const. |
1150 | /// |
1151 | /// It can be reasonably expected that this will always be equivalent to |
1152 | /// calling T.withConst(). |
1153 | QualType getConstType(QualType T) const { return T.withConst(); } |
1154 | |
1155 | /// \brief Change the ExtInfo on a function type. |
1156 | const FunctionType *adjustFunctionType(const FunctionType *Fn, |
1157 | FunctionType::ExtInfo EInfo); |
1158 | |
1159 | /// Adjust the given function result type. |
1160 | CanQualType getCanonicalFunctionResultType(QualType ResultType) const; |
1161 | |
1162 | /// \brief Change the result type of a function type once it is deduced. |
1163 | void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType); |
1164 | |
1165 | /// Get a function type and produce the equivalent function type with the |
1166 | /// specified exception specification. Type sugar that can be present on a |
1167 | /// declaration of a function with an exception specification is permitted |
1168 | /// and preserved. Other type sugar (for instance, typedefs) is not. |
1169 | QualType getFunctionTypeWithExceptionSpec( |
1170 | QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI); |
1171 | |
1172 | /// \brief Determine whether two function types are the same, ignoring |
1173 | /// exception specifications in cases where they're part of the type. |
1174 | bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U); |
1175 | |
1176 | /// \brief Change the exception specification on a function once it is |
1177 | /// delay-parsed, instantiated, or computed. |
1178 | void adjustExceptionSpec(FunctionDecl *FD, |
1179 | const FunctionProtoType::ExceptionSpecInfo &ESI, |
1180 | bool AsWritten = false); |
1181 | |
1182 | /// Determine whether a type is a class that should be detructed in the |
1183 | /// callee function. |
1184 | bool isParamDestroyedInCallee(QualType T) const; |
1185 | |
1186 | /// \brief Return the uniqued reference to the type for a complex |
1187 | /// number with the specified element type. |
1188 | QualType getComplexType(QualType T) const; |
1189 | CanQualType getComplexType(CanQualType T) const { |
1190 | return CanQualType::CreateUnsafe(getComplexType((QualType) T)); |
1191 | } |
1192 | |
1193 | /// \brief Return the uniqued reference to the type for a pointer to |
1194 | /// the specified type. |
1195 | QualType getPointerType(QualType T) const; |
1196 | CanQualType getPointerType(CanQualType T) const { |
1197 | return CanQualType::CreateUnsafe(getPointerType((QualType) T)); |
1198 | } |
1199 | |
1200 | /// \brief Return the uniqued reference to a type adjusted from the original |
1201 | /// type to a new type. |
1202 | QualType getAdjustedType(QualType Orig, QualType New) const; |
1203 | CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const { |
1204 | return CanQualType::CreateUnsafe( |
1205 | getAdjustedType((QualType)Orig, (QualType)New)); |
1206 | } |
1207 | |
1208 | /// \brief Return the uniqued reference to the decayed version of the given |
1209 | /// type. Can only be called on array and function types which decay to |
1210 | /// pointer types. |
1211 | QualType getDecayedType(QualType T) const; |
1212 | CanQualType getDecayedType(CanQualType T) const { |
1213 | return CanQualType::CreateUnsafe(getDecayedType((QualType) T)); |
1214 | } |
1215 | |
1216 | /// \brief Return the uniqued reference to the atomic type for the specified |
1217 | /// type. |
1218 | QualType getAtomicType(QualType T) const; |
1219 | |
1220 | /// \brief Return the uniqued reference to the type for a block of the |
1221 | /// specified type. |
1222 | QualType getBlockPointerType(QualType T) const; |
1223 | |
1224 | /// Gets the struct used to keep track of the descriptor for pointer to |
1225 | /// blocks. |
1226 | QualType getBlockDescriptorType() const; |
1227 | |
1228 | /// \brief Return a read_only pipe type for the specified type. |
1229 | QualType getReadPipeType(QualType T) const; |
1230 | |
1231 | /// \brief Return a write_only pipe type for the specified type. |
1232 | QualType getWritePipeType(QualType T) const; |
1233 | |
1234 | /// Gets the struct used to keep track of the extended descriptor for |
1235 | /// pointer to blocks. |
1236 | QualType getBlockDescriptorExtendedType() const; |
1237 | |
1238 | /// Map an AST Type to an OpenCLTypeKind enum value. |
1239 | TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const; |
1240 | |
1241 | /// Get address space for OpenCL type. |
1242 | LangAS getOpenCLTypeAddrSpace(const Type *T) const; |
1243 | |
1244 | void setcudaConfigureCallDecl(FunctionDecl *FD) { |
1245 | cudaConfigureCallDecl = FD; |
1246 | } |
1247 | |
1248 | FunctionDecl *getcudaConfigureCallDecl() { |
1249 | return cudaConfigureCallDecl; |
1250 | } |
1251 | |
1252 | /// Returns true iff we need copy/dispose helpers for the given type. |
1253 | bool BlockRequiresCopying(QualType Ty, const VarDecl *D); |
1254 | |
1255 | /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set |
1256 | /// to false in this case. If HasByrefExtendedLayout returns true, byref variable |
1257 | /// has extended lifetime. |
1258 | bool getByrefLifetime(QualType Ty, |
1259 | Qualifiers::ObjCLifetime &Lifetime, |
1260 | bool &HasByrefExtendedLayout) const; |
1261 | |
1262 | /// \brief Return the uniqued reference to the type for an lvalue reference |
1263 | /// to the specified type. |
1264 | QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true) |
1265 | const; |
1266 | |
1267 | /// \brief Return the uniqued reference to the type for an rvalue reference |
1268 | /// to the specified type. |
1269 | QualType getRValueReferenceType(QualType T) const; |
1270 | |
1271 | /// \brief Return the uniqued reference to the type for a member pointer to |
1272 | /// the specified type in the specified class. |
1273 | /// |
1274 | /// The class \p Cls is a \c Type because it could be a dependent name. |
1275 | QualType getMemberPointerType(QualType T, const Type *Cls) const; |
1276 | |
1277 | /// \brief Return a non-unique reference to the type for a variable array of |
1278 | /// the specified element type. |
1279 | QualType getVariableArrayType(QualType EltTy, Expr *NumElts, |
1280 | ArrayType::ArraySizeModifier ASM, |
1281 | unsigned IndexTypeQuals, |
1282 | SourceRange Brackets) const; |
1283 | |
1284 | /// \brief Return a non-unique reference to the type for a dependently-sized |
1285 | /// array of the specified element type. |
1286 | /// |
1287 | /// FIXME: We will need these to be uniqued, or at least comparable, at some |
1288 | /// point. |
1289 | QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, |
1290 | ArrayType::ArraySizeModifier ASM, |
1291 | unsigned IndexTypeQuals, |
1292 | SourceRange Brackets) const; |
1293 | |
1294 | /// \brief Return a unique reference to the type for an incomplete array of |
1295 | /// the specified element type. |
1296 | QualType getIncompleteArrayType(QualType EltTy, |
1297 | ArrayType::ArraySizeModifier ASM, |
1298 | unsigned IndexTypeQuals) const; |
1299 | |
1300 | /// \brief Return the unique reference to the type for a constant array of |
1301 | /// the specified element type. |
1302 | QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, |
1303 | ArrayType::ArraySizeModifier ASM, |
1304 | unsigned IndexTypeQuals) const; |
1305 | |
1306 | /// \brief Returns a vla type where known sizes are replaced with [*]. |
1307 | QualType getVariableArrayDecayedType(QualType Ty) const; |
1308 | |
1309 | /// \brief Return the unique reference to a vector type of the specified |
1310 | /// element type and size. |
1311 | /// |
1312 | /// \pre \p VectorType must be a built-in type. |
1313 | QualType getVectorType(QualType VectorType, unsigned NumElts, |
1314 | VectorType::VectorKind VecKind) const; |
1315 | |
1316 | /// \brief Return the unique reference to an extended vector type |
1317 | /// of the specified element type and size. |
1318 | /// |
1319 | /// \pre \p VectorType must be a built-in type. |
1320 | QualType getExtVectorType(QualType VectorType, unsigned NumElts) const; |
1321 | |
1322 | /// \pre Return a non-unique reference to the type for a dependently-sized |
1323 | /// vector of the specified element type. |
1324 | /// |
1325 | /// FIXME: We will need these to be uniqued, or at least comparable, at some |
1326 | /// point. |
1327 | QualType getDependentSizedExtVectorType(QualType VectorType, |
1328 | Expr *SizeExpr, |
1329 | SourceLocation AttrLoc) const; |
1330 | |
1331 | QualType getDependentAddressSpaceType(QualType PointeeType, |
1332 | Expr *AddrSpaceExpr, |
1333 | SourceLocation AttrLoc) const; |
1334 | |
1335 | /// \brief Return a K&R style C function type like 'int()'. |
1336 | QualType getFunctionNoProtoType(QualType ResultTy, |
1337 | const FunctionType::ExtInfo &Info) const; |
1338 | |
1339 | QualType getFunctionNoProtoType(QualType ResultTy) const { |
1340 | return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo()); |
1341 | } |
1342 | |
1343 | /// \brief Return a normal function type with a typed argument list. |
1344 | QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args, |
1345 | const FunctionProtoType::ExtProtoInfo &EPI) const { |
1346 | return getFunctionTypeInternal(ResultTy, Args, EPI, false); |
1347 | } |
1348 | |
1349 | private: |
1350 | /// \brief Return a normal function type with a typed argument list. |
1351 | QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args, |
1352 | const FunctionProtoType::ExtProtoInfo &EPI, |
1353 | bool OnlyWantCanonical) const; |
1354 | |
1355 | public: |
1356 | /// \brief Return the unique reference to the type for the specified type |
1357 | /// declaration. |
1358 | QualType getTypeDeclType(const TypeDecl *Decl, |
1359 | const TypeDecl *PrevDecl = nullptr) const { |
1360 | assert(Decl && "Passed null for Decl param")(static_cast <bool> (Decl && "Passed null for Decl param" ) ? void (0) : __assert_fail ("Decl && \"Passed null for Decl param\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 1360, __extension__ __PRETTY_FUNCTION__)); |
1361 | if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); |
1362 | |
1363 | if (PrevDecl) { |
1364 | assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")(static_cast <bool> (PrevDecl->TypeForDecl && "previous decl has no TypeForDecl") ? void (0) : __assert_fail ("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 1364, __extension__ __PRETTY_FUNCTION__)); |
1365 | Decl->TypeForDecl = PrevDecl->TypeForDecl; |
1366 | return QualType(PrevDecl->TypeForDecl, 0); |
1367 | } |
1368 | |
1369 | return getTypeDeclTypeSlow(Decl); |
1370 | } |
1371 | |
1372 | /// \brief Return the unique reference to the type for the specified |
1373 | /// typedef-name decl. |
1374 | QualType getTypedefType(const TypedefNameDecl *Decl, |
1375 | QualType Canon = QualType()) const; |
1376 | |
1377 | QualType getRecordType(const RecordDecl *Decl) const; |
1378 | |
1379 | QualType getEnumType(const EnumDecl *Decl) const; |
1380 | |
1381 | QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; |
1382 | |
1383 | QualType getAttributedType(AttributedType::Kind attrKind, |
1384 | QualType modifiedType, |
1385 | QualType equivalentType); |
1386 | |
1387 | QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, |
1388 | QualType Replacement) const; |
1389 | QualType getSubstTemplateTypeParmPackType( |
1390 | const TemplateTypeParmType *Replaced, |
1391 | const TemplateArgument &ArgPack); |
1392 | |
1393 | QualType |
1394 | getTemplateTypeParmType(unsigned Depth, unsigned Index, |
1395 | bool ParameterPack, |
1396 | TemplateTypeParmDecl *ParmDecl = nullptr) const; |
1397 | |
1398 | QualType getTemplateSpecializationType(TemplateName T, |
1399 | ArrayRef<TemplateArgument> Args, |
1400 | QualType Canon = QualType()) const; |
1401 | |
1402 | QualType |
1403 | getCanonicalTemplateSpecializationType(TemplateName T, |
1404 | ArrayRef<TemplateArgument> Args) const; |
1405 | |
1406 | QualType getTemplateSpecializationType(TemplateName T, |
1407 | const TemplateArgumentListInfo &Args, |
1408 | QualType Canon = QualType()) const; |
1409 | |
1410 | TypeSourceInfo * |
1411 | getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, |
1412 | const TemplateArgumentListInfo &Args, |
1413 | QualType Canon = QualType()) const; |
1414 | |
1415 | QualType getParenType(QualType NamedType) const; |
1416 | |
1417 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, |
1418 | NestedNameSpecifier *NNS, |
1419 | QualType NamedType) const; |
1420 | QualType getDependentNameType(ElaboratedTypeKeyword Keyword, |
1421 | NestedNameSpecifier *NNS, |
1422 | const IdentifierInfo *Name, |
1423 | QualType Canon = QualType()) const; |
1424 | |
1425 | QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
1426 | NestedNameSpecifier *NNS, |
1427 | const IdentifierInfo *Name, |
1428 | const TemplateArgumentListInfo &Args) const; |
1429 | QualType getDependentTemplateSpecializationType( |
1430 | ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
1431 | const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const; |
1432 | |
1433 | TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl); |
1434 | |
1435 | /// Get a template argument list with one argument per template parameter |
1436 | /// in a template parameter list, such as for the injected class name of |
1437 | /// a class template. |
1438 | void getInjectedTemplateArgs(const TemplateParameterList *Params, |
1439 | SmallVectorImpl<TemplateArgument> &Args); |
1440 | |
1441 | QualType getPackExpansionType(QualType Pattern, |
1442 | Optional<unsigned> NumExpansions); |
1443 | |
1444 | QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, |
1445 | ObjCInterfaceDecl *PrevDecl = nullptr) const; |
1446 | |
1447 | /// Legacy interface: cannot provide type arguments or __kindof. |
1448 | QualType getObjCObjectType(QualType Base, |
1449 | ObjCProtocolDecl * const *Protocols, |
1450 | unsigned NumProtocols) const; |
1451 | |
1452 | QualType getObjCObjectType(QualType Base, |
1453 | ArrayRef<QualType> typeArgs, |
1454 | ArrayRef<ObjCProtocolDecl *> protocols, |
1455 | bool isKindOf) const; |
1456 | |
1457 | QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
1458 | ArrayRef<ObjCProtocolDecl *> protocols, |
1459 | QualType Canonical = QualType()) const; |
1460 | |
1461 | bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl); |
1462 | |
1463 | /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in |
1464 | /// QT's qualified-id protocol list adopt all protocols in IDecl's list |
1465 | /// of protocols. |
1466 | bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, |
1467 | ObjCInterfaceDecl *IDecl); |
1468 | |
1469 | /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType. |
1470 | QualType getObjCObjectPointerType(QualType OIT) const; |
1471 | |
1472 | /// \brief GCC extension. |
1473 | QualType getTypeOfExprType(Expr *e) const; |
1474 | QualType getTypeOfType(QualType t) const; |
1475 | |
1476 | /// \brief C++11 decltype. |
1477 | QualType getDecltypeType(Expr *e, QualType UnderlyingType) const; |
1478 | |
1479 | /// \brief Unary type transforms |
1480 | QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, |
1481 | UnaryTransformType::UTTKind UKind) const; |
1482 | |
1483 | /// \brief C++11 deduced auto type. |
1484 | QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, |
1485 | bool IsDependent) const; |
1486 | |
1487 | /// \brief C++11 deduction pattern for 'auto' type. |
1488 | QualType getAutoDeductType() const; |
1489 | |
1490 | /// \brief C++11 deduction pattern for 'auto &&' type. |
1491 | QualType getAutoRRefDeductType() const; |
1492 | |
1493 | /// \brief C++17 deduced class template specialization type. |
1494 | QualType getDeducedTemplateSpecializationType(TemplateName Template, |
1495 | QualType DeducedType, |
1496 | bool IsDependent) const; |
1497 | |
1498 | /// \brief Return the unique reference to the type for the specified TagDecl |
1499 | /// (struct/union/class/enum) decl. |
1500 | QualType getTagDeclType(const TagDecl *Decl) const; |
1501 | |
1502 | /// \brief Return the unique type for "size_t" (C99 7.17), defined in |
1503 | /// <stddef.h>. |
1504 | /// |
1505 | /// The sizeof operator requires this (C99 6.5.3.4p4). |
1506 | CanQualType getSizeType() const; |
1507 | |
1508 | /// \brief Return the unique signed counterpart of |
1509 | /// the integer type corresponding to size_t. |
1510 | CanQualType getSignedSizeType() const; |
1511 | |
1512 | /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in |
1513 | /// <stdint.h>. |
1514 | CanQualType getIntMaxType() const; |
1515 | |
1516 | /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in |
1517 | /// <stdint.h>. |
1518 | CanQualType getUIntMaxType() const; |
1519 | |
1520 | /// \brief Return the unique wchar_t type available in C++ (and available as |
1521 | /// __wchar_t as a Microsoft extension). |
1522 | QualType getWCharType() const { return WCharTy; } |
1523 | |
1524 | /// \brief Return the type of wide characters. In C++, this returns the |
1525 | /// unique wchar_t type. In C99, this returns a type compatible with the type |
1526 | /// defined in <stddef.h> as defined by the target. |
1527 | QualType getWideCharType() const { return WideCharTy; } |
1528 | |
1529 | /// \brief Return the type of "signed wchar_t". |
1530 | /// |
1531 | /// Used when in C++, as a GCC extension. |
1532 | QualType getSignedWCharType() const; |
1533 | |
1534 | /// \brief Return the type of "unsigned wchar_t". |
1535 | /// |
1536 | /// Used when in C++, as a GCC extension. |
1537 | QualType getUnsignedWCharType() const; |
1538 | |
1539 | /// \brief In C99, this returns a type compatible with the type |
1540 | /// defined in <stddef.h> as defined by the target. |
1541 | QualType getWIntType() const { return WIntTy; } |
1542 | |
1543 | /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4), |
1544 | /// as defined by the target. |
1545 | QualType getIntPtrType() const; |
1546 | |
1547 | /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4), |
1548 | /// as defined by the target. |
1549 | QualType getUIntPtrType() const; |
1550 | |
1551 | /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in |
1552 | /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). |
1553 | QualType getPointerDiffType() const; |
1554 | |
1555 | /// \brief Return the unique unsigned counterpart of "ptrdiff_t" |
1556 | /// integer type. The standard (C11 7.21.6.1p7) refers to this type |
1557 | /// in the definition of %tu format specifier. |
1558 | QualType getUnsignedPointerDiffType() const; |
1559 | |
1560 | /// \brief Return the unique type for "pid_t" defined in |
1561 | /// <sys/types.h>. We need this to compute the correct type for vfork(). |
1562 | QualType getProcessIDType() const; |
1563 | |
1564 | /// \brief Return the C structure type used to represent constant CFStrings. |
1565 | QualType getCFConstantStringType() const; |
1566 | |
1567 | /// \brief Returns the C struct type for objc_super |
1568 | QualType getObjCSuperType() const; |
1569 | void setObjCSuperType(QualType ST) { ObjCSuperType = ST; } |
1570 | |
1571 | /// Get the structure type used to representation CFStrings, or NULL |
1572 | /// if it hasn't yet been built. |
1573 | QualType getRawCFConstantStringType() const { |
1574 | if (CFConstantStringTypeDecl) |
1575 | return getTypedefType(CFConstantStringTypeDecl); |
1576 | return QualType(); |
1577 | } |
1578 | void setCFConstantStringType(QualType T); |
1579 | TypedefDecl *getCFConstantStringDecl() const; |
1580 | RecordDecl *getCFConstantStringTagDecl() const; |
1581 | |
1582 | // This setter/getter represents the ObjC type for an NSConstantString. |
1583 | void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl); |
1584 | QualType getObjCConstantStringInterface() const { |
1585 | return ObjCConstantStringType; |
1586 | } |
1587 | |
1588 | QualType getObjCNSStringType() const { |
1589 | return ObjCNSStringType; |
1590 | } |
1591 | |
1592 | void setObjCNSStringType(QualType T) { |
1593 | ObjCNSStringType = T; |
1594 | } |
1595 | |
1596 | /// \brief Retrieve the type that \c id has been defined to, which may be |
1597 | /// different from the built-in \c id if \c id has been typedef'd. |
1598 | QualType getObjCIdRedefinitionType() const { |
1599 | if (ObjCIdRedefinitionType.isNull()) |
1600 | return getObjCIdType(); |
1601 | return ObjCIdRedefinitionType; |
1602 | } |
1603 | |
1604 | /// \brief Set the user-written type that redefines \c id. |
1605 | void setObjCIdRedefinitionType(QualType RedefType) { |
1606 | ObjCIdRedefinitionType = RedefType; |
1607 | } |
1608 | |
1609 | /// \brief Retrieve the type that \c Class has been defined to, which may be |
1610 | /// different from the built-in \c Class if \c Class has been typedef'd. |
1611 | QualType getObjCClassRedefinitionType() const { |
1612 | if (ObjCClassRedefinitionType.isNull()) |
1613 | return getObjCClassType(); |
1614 | return ObjCClassRedefinitionType; |
1615 | } |
1616 | |
1617 | /// \brief Set the user-written type that redefines 'SEL'. |
1618 | void setObjCClassRedefinitionType(QualType RedefType) { |
1619 | ObjCClassRedefinitionType = RedefType; |
1620 | } |
1621 | |
1622 | /// \brief Retrieve the type that 'SEL' has been defined to, which may be |
1623 | /// different from the built-in 'SEL' if 'SEL' has been typedef'd. |
1624 | QualType getObjCSelRedefinitionType() const { |
1625 | if (ObjCSelRedefinitionType.isNull()) |
1626 | return getObjCSelType(); |
1627 | return ObjCSelRedefinitionType; |
1628 | } |
1629 | |
1630 | /// \brief Set the user-written type that redefines 'SEL'. |
1631 | void setObjCSelRedefinitionType(QualType RedefType) { |
1632 | ObjCSelRedefinitionType = RedefType; |
1633 | } |
1634 | |
1635 | /// Retrieve the identifier 'NSObject'. |
1636 | IdentifierInfo *getNSObjectName() { |
1637 | if (!NSObjectName) { |
1638 | NSObjectName = &Idents.get("NSObject"); |
1639 | } |
1640 | |
1641 | return NSObjectName; |
1642 | } |
1643 | |
1644 | /// Retrieve the identifier 'NSCopying'. |
1645 | IdentifierInfo *getNSCopyingName() { |
1646 | if (!NSCopyingName) { |
1647 | NSCopyingName = &Idents.get("NSCopying"); |
1648 | } |
1649 | |
1650 | return NSCopyingName; |
1651 | } |
1652 | |
1653 | CanQualType getNSUIntegerType() const { |
1654 | assert(Target && "Expected target to be initialized")(static_cast <bool> (Target && "Expected target to be initialized" ) ? void (0) : __assert_fail ("Target && \"Expected target to be initialized\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 1654, __extension__ __PRETTY_FUNCTION__)); |
1655 | const llvm::Triple &T = Target->getTriple(); |
1656 | // Windows is LLP64 rather than LP64 |
1657 | if (T.isOSWindows() && T.isArch64Bit()) |
1658 | return UnsignedLongLongTy; |
1659 | return UnsignedLongTy; |
1660 | } |
1661 | |
1662 | CanQualType getNSIntegerType() const { |
1663 | assert(Target && "Expected target to be initialized")(static_cast <bool> (Target && "Expected target to be initialized" ) ? void (0) : __assert_fail ("Target && \"Expected target to be initialized\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 1663, __extension__ __PRETTY_FUNCTION__)); |
1664 | const llvm::Triple &T = Target->getTriple(); |
1665 | // Windows is LLP64 rather than LP64 |
1666 | if (T.isOSWindows() && T.isArch64Bit()) |
1667 | return LongLongTy; |
1668 | return LongTy; |
1669 | } |
1670 | |
1671 | /// Retrieve the identifier 'bool'. |
1672 | IdentifierInfo *getBoolName() const { |
1673 | if (!BoolName) |
1674 | BoolName = &Idents.get("bool"); |
1675 | return BoolName; |
1676 | } |
1677 | |
1678 | IdentifierInfo *getMakeIntegerSeqName() const { |
1679 | if (!MakeIntegerSeqName) |
1680 | MakeIntegerSeqName = &Idents.get("__make_integer_seq"); |
1681 | return MakeIntegerSeqName; |
1682 | } |
1683 | |
1684 | IdentifierInfo *getTypePackElementName() const { |
1685 | if (!TypePackElementName) |
1686 | TypePackElementName = &Idents.get("__type_pack_element"); |
1687 | return TypePackElementName; |
1688 | } |
1689 | |
1690 | /// \brief Retrieve the Objective-C "instancetype" type, if already known; |
1691 | /// otherwise, returns a NULL type; |
1692 | QualType getObjCInstanceType() { |
1693 | return getTypeDeclType(getObjCInstanceTypeDecl()); |
1694 | } |
1695 | |
1696 | /// \brief Retrieve the typedef declaration corresponding to the Objective-C |
1697 | /// "instancetype" type. |
1698 | TypedefDecl *getObjCInstanceTypeDecl(); |
1699 | |
1700 | /// \brief Set the type for the C FILE type. |
1701 | void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; } |
1702 | |
1703 | /// \brief Retrieve the C FILE type. |
1704 | QualType getFILEType() const { |
1705 | if (FILEDecl) |
1706 | return getTypeDeclType(FILEDecl); |
1707 | return QualType(); |
1708 | } |
1709 | |
1710 | /// \brief Set the type for the C jmp_buf type. |
1711 | void setjmp_bufDecl(TypeDecl *jmp_bufDecl) { |
1712 | this->jmp_bufDecl = jmp_bufDecl; |
1713 | } |
1714 | |
1715 | /// \brief Retrieve the C jmp_buf type. |
1716 | QualType getjmp_bufType() const { |
1717 | if (jmp_bufDecl) |
1718 | return getTypeDeclType(jmp_bufDecl); |
1719 | return QualType(); |
1720 | } |
1721 | |
1722 | /// \brief Set the type for the C sigjmp_buf type. |
1723 | void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) { |
1724 | this->sigjmp_bufDecl = sigjmp_bufDecl; |
1725 | } |
1726 | |
1727 | /// \brief Retrieve the C sigjmp_buf type. |
1728 | QualType getsigjmp_bufType() const { |
1729 | if (sigjmp_bufDecl) |
1730 | return getTypeDeclType(sigjmp_bufDecl); |
1731 | return QualType(); |
1732 | } |
1733 | |
1734 | /// \brief Set the type for the C ucontext_t type. |
1735 | void setucontext_tDecl(TypeDecl *ucontext_tDecl) { |
1736 | this->ucontext_tDecl = ucontext_tDecl; |
1737 | } |
1738 | |
1739 | /// \brief Retrieve the C ucontext_t type. |
1740 | QualType getucontext_tType() const { |
1741 | if (ucontext_tDecl) |
1742 | return getTypeDeclType(ucontext_tDecl); |
1743 | return QualType(); |
1744 | } |
1745 | |
1746 | /// \brief The result type of logical operations, '<', '>', '!=', etc. |
1747 | QualType getLogicalOperationType() const { |
1748 | return getLangOpts().CPlusPlus ? BoolTy : IntTy; |
1749 | } |
1750 | |
1751 | /// \brief Emit the Objective-CC type encoding for the given type \p T into |
1752 | /// \p S. |
1753 | /// |
1754 | /// If \p Field is specified then record field names are also encoded. |
1755 | void getObjCEncodingForType(QualType T, std::string &S, |
1756 | const FieldDecl *Field=nullptr, |
1757 | QualType *NotEncodedT=nullptr) const; |
1758 | |
1759 | /// \brief Emit the Objective-C property type encoding for the given |
1760 | /// type \p T into \p S. |
1761 | void getObjCEncodingForPropertyType(QualType T, std::string &S) const; |
1762 | |
1763 | void getLegacyIntegralTypeEncoding(QualType &t) const; |
1764 | |
1765 | /// \brief Put the string version of the type qualifiers \p QT into \p S. |
1766 | void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, |
1767 | std::string &S) const; |
1768 | |
1769 | /// \brief Emit the encoded type for the function \p Decl into \p S. |
1770 | /// |
1771 | /// This is in the same format as Objective-C method encodings. |
1772 | /// |
1773 | /// \returns true if an error occurred (e.g., because one of the parameter |
1774 | /// types is incomplete), false otherwise. |
1775 | std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const; |
1776 | |
1777 | /// \brief Emit the encoded type for the method declaration \p Decl into |
1778 | /// \p S. |
1779 | std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, |
1780 | bool Extended = false) const; |
1781 | |
1782 | /// \brief Return the encoded type for this block declaration. |
1783 | std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const; |
1784 | |
1785 | /// getObjCEncodingForPropertyDecl - Return the encoded type for |
1786 | /// this method declaration. If non-NULL, Container must be either |
1787 | /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should |
1788 | /// only be NULL when getting encodings for protocol properties. |
1789 | std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, |
1790 | const Decl *Container) const; |
1791 | |
1792 | bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, |
1793 | ObjCProtocolDecl *rProto) const; |
1794 | |
1795 | ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl( |
1796 | const ObjCPropertyDecl *PD, |
1797 | const Decl *Container) const; |
1798 | |
1799 | /// \brief Return the size of type \p T for Objective-C encoding purpose, |
1800 | /// in characters. |
1801 | CharUnits getObjCEncodingTypeSize(QualType T) const; |
1802 | |
1803 | /// \brief Retrieve the typedef corresponding to the predefined \c id type |
1804 | /// in Objective-C. |
1805 | TypedefDecl *getObjCIdDecl() const; |
1806 | |
1807 | /// \brief Represents the Objective-CC \c id type. |
1808 | /// |
1809 | /// This is set up lazily, by Sema. \c id is always a (typedef for a) |
1810 | /// pointer type, a pointer to a struct. |
1811 | QualType getObjCIdType() const { |
1812 | return getTypeDeclType(getObjCIdDecl()); |
1813 | } |
1814 | |
1815 | /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type |
1816 | /// in Objective-C. |
1817 | TypedefDecl *getObjCSelDecl() const; |
1818 | |
1819 | /// \brief Retrieve the type that corresponds to the predefined Objective-C |
1820 | /// 'SEL' type. |
1821 | QualType getObjCSelType() const { |
1822 | return getTypeDeclType(getObjCSelDecl()); |
1823 | } |
1824 | |
1825 | /// \brief Retrieve the typedef declaration corresponding to the predefined |
1826 | /// Objective-C 'Class' type. |
1827 | TypedefDecl *getObjCClassDecl() const; |
1828 | |
1829 | /// \brief Represents the Objective-C \c Class type. |
1830 | /// |
1831 | /// This is set up lazily, by Sema. \c Class is always a (typedef for a) |
1832 | /// pointer type, a pointer to a struct. |
1833 | QualType getObjCClassType() const { |
1834 | return getTypeDeclType(getObjCClassDecl()); |
1835 | } |
1836 | |
1837 | /// \brief Retrieve the Objective-C class declaration corresponding to |
1838 | /// the predefined \c Protocol class. |
1839 | ObjCInterfaceDecl *getObjCProtocolDecl() const; |
1840 | |
1841 | /// \brief Retrieve declaration of 'BOOL' typedef |
1842 | TypedefDecl *getBOOLDecl() const { |
1843 | return BOOLDecl; |
1844 | } |
1845 | |
1846 | /// \brief Save declaration of 'BOOL' typedef |
1847 | void setBOOLDecl(TypedefDecl *TD) { |
1848 | BOOLDecl = TD; |
1849 | } |
1850 | |
1851 | /// \brief type of 'BOOL' type. |
1852 | QualType getBOOLType() const { |
1853 | return getTypeDeclType(getBOOLDecl()); |
1854 | } |
1855 | |
1856 | /// \brief Retrieve the type of the Objective-C \c Protocol class. |
1857 | QualType getObjCProtoType() const { |
1858 | return getObjCInterfaceType(getObjCProtocolDecl()); |
1859 | } |
1860 | |
1861 | /// \brief Retrieve the C type declaration corresponding to the predefined |
1862 | /// \c __builtin_va_list type. |
1863 | TypedefDecl *getBuiltinVaListDecl() const; |
1864 | |
1865 | /// \brief Retrieve the type of the \c __builtin_va_list type. |
1866 | QualType getBuiltinVaListType() const { |
1867 | return getTypeDeclType(getBuiltinVaListDecl()); |
1868 | } |
1869 | |
1870 | /// \brief Retrieve the C type declaration corresponding to the predefined |
1871 | /// \c __va_list_tag type used to help define the \c __builtin_va_list type |
1872 | /// for some targets. |
1873 | Decl *getVaListTagDecl() const; |
1874 | |
1875 | /// Retrieve the C type declaration corresponding to the predefined |
1876 | /// \c __builtin_ms_va_list type. |
1877 | TypedefDecl *getBuiltinMSVaListDecl() const; |
1878 | |
1879 | /// Retrieve the type of the \c __builtin_ms_va_list type. |
1880 | QualType getBuiltinMSVaListType() const { |
1881 | return getTypeDeclType(getBuiltinMSVaListDecl()); |
1882 | } |
1883 | |
1884 | /// \brief Return a type with additional \c const, \c volatile, or |
1885 | /// \c restrict qualifiers. |
1886 | QualType getCVRQualifiedType(QualType T, unsigned CVR) const { |
1887 | return getQualifiedType(T, Qualifiers::fromCVRMask(CVR)); |
1888 | } |
1889 | |
1890 | /// \brief Un-split a SplitQualType. |
1891 | QualType getQualifiedType(SplitQualType split) const { |
1892 | return getQualifiedType(split.Ty, split.Quals); |
1893 | } |
1894 | |
1895 | /// \brief Return a type with additional qualifiers. |
1896 | QualType getQualifiedType(QualType T, Qualifiers Qs) const { |
1897 | if (!Qs.hasNonFastQualifiers()) |
1898 | return T.withFastQualifiers(Qs.getFastQualifiers()); |
1899 | QualifierCollector Qc(Qs); |
1900 | const Type *Ptr = Qc.strip(T); |
1901 | return getExtQualType(Ptr, Qc); |
1902 | } |
1903 | |
1904 | /// \brief Return a type with additional qualifiers. |
1905 | QualType getQualifiedType(const Type *T, Qualifiers Qs) const { |
1906 | if (!Qs.hasNonFastQualifiers()) |
1907 | return QualType(T, Qs.getFastQualifiers()); |
1908 | return getExtQualType(T, Qs); |
1909 | } |
1910 | |
1911 | /// \brief Return a type with the given lifetime qualifier. |
1912 | /// |
1913 | /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None. |
1914 | QualType getLifetimeQualifiedType(QualType type, |
1915 | Qualifiers::ObjCLifetime lifetime) { |
1916 | assert(type.getObjCLifetime() == Qualifiers::OCL_None)(static_cast <bool> (type.getObjCLifetime() == Qualifiers ::OCL_None) ? void (0) : __assert_fail ("type.getObjCLifetime() == Qualifiers::OCL_None" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 1916, __extension__ __PRETTY_FUNCTION__)); |
1917 | assert(lifetime != Qualifiers::OCL_None)(static_cast <bool> (lifetime != Qualifiers::OCL_None) ? void (0) : __assert_fail ("lifetime != Qualifiers::OCL_None" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h" , 1917, __extension__ __PRETTY_FUNCTION__)); |
1918 | |
1919 | Qualifiers qs; |
1920 | qs.addObjCLifetime(lifetime); |
1921 | return getQualifiedType(type, qs); |
1922 | } |
1923 | |
1924 | /// getUnqualifiedObjCPointerType - Returns version of |
1925 | /// Objective-C pointer type with lifetime qualifier removed. |
1926 | QualType getUnqualifiedObjCPointerType(QualType type) const { |
1927 | if (!type.getTypePtr()->isObjCObjectPointerType() || |
1928 | !type.getQualifiers().hasObjCLifetime()) |
1929 | return type; |
1930 | Qualifiers Qs = type.getQualifiers(); |
1931 | Qs.removeObjCLifetime(); |
1932 | return getQualifiedType(type.getUnqualifiedType(), Qs); |
1933 | } |
1934 | |
1935 | DeclarationNameInfo getNameForTemplate(TemplateName Name, |
1936 | SourceLocation NameLoc) const; |
1937 | |
1938 | TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, |
1939 | UnresolvedSetIterator End) const; |
1940 | |
1941 | TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, |
1942 | bool TemplateKeyword, |
1943 | TemplateDecl *Template) const; |
1944 | |
1945 | TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, |
1946 | const IdentifierInfo *Name) const; |
1947 | TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, |
1948 | OverloadedOperatorKind Operator) const; |
1949 | TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, |
1950 | TemplateName replacement) const; |
1951 | TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, |
1952 | const TemplateArgument &ArgPack) const; |
1953 | |
1954 | enum GetBuiltinTypeError { |
1955 | /// No error |
1956 | GE_None, |
1957 | |
1958 | /// Missing a type from <stdio.h> |
1959 | GE_Missing_stdio, |
1960 | |
1961 | /// Missing a type from <setjmp.h> |
1962 | GE_Missing_setjmp, |
1963 | |
1964 | /// Missing a type from <ucontext.h> |
1965 | GE_Missing_ucontext |
1966 | }; |
1967 | |
1968 | /// \brief Return the type for the specified builtin. |
1969 | /// |
1970 | /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of |
1971 | /// arguments to the builtin that are required to be integer constant |
1972 | /// expressions. |
1973 | QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, |
1974 | unsigned *IntegerConstantArgs = nullptr) const; |
1975 | |
1976 | private: |
1977 | CanQualType getFromTargetType(unsigned Type) const; |
1978 | TypeInfo getTypeInfoImpl(const Type *T) const; |
1979 | |
1980 | //===--------------------------------------------------------------------===// |
1981 | // Type Predicates. |
1982 | //===--------------------------------------------------------------------===// |
1983 | |
1984 | public: |
1985 | /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage |
1986 | /// collection attributes. |
1987 | Qualifiers::GC getObjCGCAttrKind(QualType Ty) const; |
1988 | |
1989 | /// \brief Return true if the given vector types are of the same unqualified |
1990 | /// type or if they are equivalent to the same GCC vector type. |
1991 | /// |
1992 | /// \note This ignores whether they are target-specific (AltiVec or Neon) |
1993 | /// types. |
1994 | bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec); |
1995 | |
1996 | /// \brief Return true if this is an \c NSObject object with its \c NSObject |
1997 | /// attribute set. |
1998 | static bool isObjCNSObjectType(QualType Ty) { |
1999 | return Ty->isObjCNSObjectType(); |
2000 | } |
2001 | |
2002 | //===--------------------------------------------------------------------===// |
2003 | // Type Sizing and Analysis |
2004 | //===--------------------------------------------------------------------===// |
2005 | |
2006 | /// \brief Return the APFloat 'semantics' for the specified scalar floating |
2007 | /// point type. |
2008 | const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const; |
2009 | |
2010 | /// \brief Get the size and alignment of the specified complete type in bits. |
2011 | TypeInfo getTypeInfo(const Type *T) const; |
2012 | TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); } |
2013 | |
2014 | /// \brief Get default simd alignment of the specified complete type in bits. |
2015 | unsigned getOpenMPDefaultSimdAlign(QualType T) const; |
2016 | |
2017 | /// \brief Return the size of the specified (complete) type \p T, in bits. |
2018 | uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; } |
2019 | uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; } |
2020 | |
2021 | /// \brief Return the size of the character type, in bits. |
2022 | uint64_t getCharWidth() const { |
2023 | return getTypeSize(CharTy); |
2024 | } |
2025 | |
2026 | /// \brief Convert a size in bits to a size in characters. |
2027 | CharUnits toCharUnitsFromBits(int64_t BitSize) const; |
2028 | |
2029 | /// \brief Convert a size in characters to a size in bits. |
2030 | int64_t toBits(CharUnits CharSize) const; |
2031 | |
2032 | /// \brief Return the size of the specified (complete) type \p T, in |
2033 | /// characters. |
2034 | CharUnits getTypeSizeInChars(QualType T) const; |
2035 | CharUnits getTypeSizeInChars(const Type *T) const; |
2036 | |
2037 | /// \brief Return the ABI-specified alignment of a (complete) type \p T, in |
2038 | /// bits. |
2039 | unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; } |
2040 | unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; } |
2041 | |
2042 | /// \brief Return the ABI-specified alignment of a type, in bits, or 0 if |
2043 | /// the type is incomplete and we cannot determine the alignment (for |
2044 | /// example, from alignment attributes). |
2045 | unsigned getTypeAlignIfKnown(QualType T) const; |
2046 | |
2047 | /// \brief Return the ABI-specified alignment of a (complete) type \p T, in |
2048 | /// characters. |
2049 | CharUnits getTypeAlignInChars(QualType T) const; |
2050 | CharUnits getTypeAlignInChars(const Type *T) const; |
2051 | |
2052 | // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the |
2053 | // type is a record, its data size is returned. |
2054 | std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const; |
2055 | |
2056 | std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const; |
2057 | std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const; |
2058 | |
2059 | /// \brief Determine if the alignment the type has was required using an |
2060 | /// alignment attribute. |
2061 | bool isAlignmentRequired(const Type *T) const; |
2062 | bool isAlignmentRequired(QualType T) const; |
2063 | |
2064 | /// \brief Return the "preferred" alignment of the specified type \p T for |
2065 | /// the current target, in bits. |
2066 | /// |
2067 | /// This can be different than the ABI alignment in cases where it is |
2068 | /// beneficial for performance to overalign a data type. |
2069 | unsigned getPreferredTypeAlign(const Type *T) const; |
2070 | |
2071 | /// \brief Return the default alignment for __attribute__((aligned)) on |
2072 | /// this target, to be used if no alignment value is specified. |
2073 | unsigned getTargetDefaultAlignForAttributeAligned() const; |
2074 | |
2075 | /// \brief Return the alignment in bits that should be given to a |
2076 | /// global variable with type \p T. |
2077 | unsigned getAlignOfGlobalVar(QualType T) const; |
2078 | |
2079 | /// \brief Return the alignment in characters that should be given to a |
2080 | /// global variable with type \p T. |
2081 | CharUnits getAlignOfGlobalVarInChars(QualType T) const; |
2082 | |
2083 | /// \brief Return a conservative estimate of the alignment of the specified |
2084 | /// decl \p D. |
2085 | /// |
2086 | /// \pre \p D must not be a bitfield type, as bitfields do not have a valid |
2087 | /// alignment. |
2088 | /// |
2089 | /// If \p ForAlignof, references are treated like their underlying type |
2090 | /// and large arrays don't get any special treatment. If not \p ForAlignof |
2091 | /// it computes the value expected by CodeGen: references are treated like |
2092 | /// pointers and large arrays get extra alignment. |
2093 | CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const; |
2094 | |
2095 | /// \brief Get or compute information about the layout of the specified |
2096 | /// record (struct/union/class) \p D, which indicates its size and field |
2097 | /// position information. |
2098 | const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const; |
2099 | |
2100 | /// \brief Get or compute information about the layout of the specified |
2101 | /// Objective-C interface. |
2102 | const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) |
2103 | const; |
2104 | |
2105 | void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, |
2106 | bool Simple = false) const; |
2107 | |
2108 | /// \brief Get or compute information about the layout of the specified |
2109 | /// Objective-C implementation. |
2110 | /// |
2111 | /// This may differ from the interface if synthesized ivars are present. |
2112 | const ASTRecordLayout & |
2113 | getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const; |
2114 | |
2115 | /// \brief Get our current best idea for the key function of the |
2116 | /// given record decl, or nullptr if there isn't one. |
2117 | /// |
2118 | /// The key function is, according to the Itanium C++ ABI section 5.2.3: |
2119 | /// ...the first non-pure virtual function that is not inline at the |
2120 | /// point of class definition. |
2121 | /// |
2122 | /// Other ABIs use the same idea. However, the ARM C++ ABI ignores |
2123 | /// virtual functions that are defined 'inline', which means that |
2124 | /// the result of this computation can change. |
2125 | const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD); |
2126 | |
2127 | /// \brief Observe that the given method cannot be a key function. |
2128 | /// Checks the key-function cache for the method's class and clears it |
2129 | /// if matches the given declaration. |
2130 | /// |
2131 | /// This is used in ABIs where out-of-line definitions marked |
2132 | /// inline are not considered to be key functions. |
2133 | /// |
2134 | /// \param method should be the declaration from the class definition |
2135 | void setNonKeyFunction(const CXXMethodDecl *method); |
2136 | |
2137 | /// Loading virtual member pointers using the virtual inheritance model |
2138 | /// always results in an adjustment using the vbtable even if the index is |
2139 | /// zero. |
2140 | /// |
2141 | /// This is usually OK because the first slot in the vbtable points |
2142 | /// backwards to the top of the MDC. However, the MDC might be reusing a |
2143 | /// vbptr from an nv-base. In this case, the first slot in the vbtable |
2144 | /// points to the start of the nv-base which introduced the vbptr and *not* |
2145 | /// the MDC. Modify the NonVirtualBaseAdjustment to account for this. |
2146 | CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const; |
2147 | |
2148 | /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits. |
2149 | uint64_t getFieldOffset(const ValueDecl *FD) const; |
2150 | |
2151 | /// Get the offset of an ObjCIvarDecl in bits. |
2152 | uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, |
2153 | const ObjCImplementationDecl *ID, |
2154 | const ObjCIvarDecl *Ivar) const; |
2155 | |
2156 | bool isNearlyEmpty(const CXXRecordDecl *RD) const; |
2157 | |
2158 | VTableContextBase *getVTableContext(); |
2159 | |
2160 | MangleContext *createMangleContext(); |
2161 | |
2162 | void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, |
2163 | SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const; |
2164 | |
2165 | unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const; |
2166 | void CollectInheritedProtocols(const Decl *CDecl, |
2167 | llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols); |
2168 | |
2169 | /// \brief Return true if the specified type has unique object representations |
2170 | /// according to (C++17 [meta.unary.prop]p9) |
2171 | bool hasUniqueObjectRepresentations(QualType Ty) const; |
2172 | |
2173 | //===--------------------------------------------------------------------===// |
2174 | // Type Operators |
2175 | //===--------------------------------------------------------------------===// |
2176 | |
2177 | /// \brief Return the canonical (structural) type corresponding to the |
2178 | /// specified potentially non-canonical type \p T. |
2179 | /// |
2180 | /// The non-canonical version of a type may have many "decorated" versions of |
2181 | /// types. Decorators can include typedefs, 'typeof' operators, etc. The |
2182 | /// returned type is guaranteed to be free of any of these, allowing two |
2183 | /// canonical types to be compared for exact equality with a simple pointer |
2184 | /// comparison. |
2185 | CanQualType getCanonicalType(QualType T) const { |
2186 | return CanQualType::CreateUnsafe(T.getCanonicalType()); |
2187 | } |
2188 | |
2189 | const Type *getCanonicalType(const Type *T) const { |
2190 | return T->getCanonicalTypeInternal().getTypePtr(); |
2191 | } |
2192 | |
2193 | /// \brief Return the canonical parameter type corresponding to the specific |
2194 | /// potentially non-canonical one. |
2195 | /// |
2196 | /// Qualifiers are stripped off, functions are turned into function |
2197 | /// pointers, and arrays decay one level into pointers. |
2198 | CanQualType getCanonicalParamType(QualType T) const; |
2199 | |
2200 | /// \brief Determine whether the given types \p T1 and \p T2 are equivalent. |
2201 | bool hasSameType(QualType T1, QualType T2) const { |
2202 | return getCanonicalType(T1) == getCanonicalType(T2); |
2203 | } |
2204 | bool hasSameType(const Type *T1, const Type *T2) const { |
2205 | return getCanonicalType(T1) == getCanonicalType(T2); |
2206 | } |
2207 | |
2208 | /// \brief Return this type as a completely-unqualified array type, |
2209 | /// capturing the qualifiers in \p Quals. |
2210 | /// |
2211 | /// This will remove the minimal amount of sugaring from the types, similar |
2212 | /// to the behavior of QualType::getUnqualifiedType(). |
2213 | /// |
2214 | /// \param T is the qualified type, which may be an ArrayType |
2215 | /// |
2216 | /// \param Quals will receive the full set of qualifiers that were |
2217 | /// applied to the array. |
2218 | /// |
2219 | /// \returns if this is an array type, the completely unqualified array type |
2220 | /// that corresponds to it. Otherwise, returns T.getUnqualifiedType(). |
2221 | QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals); |
2222 | |
2223 | /// \brief Determine whether the given types are equivalent after |
2224 | /// cvr-qualifiers have been removed. |
2225 | bool hasSameUnqualifiedType(QualType T1, QualType T2) const { |
2226 | return getCanonicalType(T1).getTypePtr() == |
2227 | getCanonicalType(T2).getTypePtr(); |
2228 | } |
2229 | |
2230 | bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT, |
2231 | bool IsParam) const { |
2232 | auto SubTnullability = SubT->getNullability(*this); |
2233 | auto SuperTnullability = SuperT->getNullability(*this); |
2234 | if (SubTnullability.hasValue() == SuperTnullability.hasValue()) { |
2235 | // Neither has nullability; return true |
2236 | if (!SubTnullability) |
2237 | return true; |
2238 | // Both have nullability qualifier. |
2239 | if (*SubTnullability == *SuperTnullability || |
2240 | *SubTnullability == NullabilityKind::Unspecified || |
2241 | *SuperTnullability == NullabilityKind::Unspecified) |
2242 | return true; |
2243 | |
2244 | if (IsParam) { |
2245 | // Ok for the superclass method parameter to be "nonnull" and the subclass |
2246 | // method parameter to be "nullable" |
2247 | return (*SuperTnullability == NullabilityKind::NonNull && |
2248 | *SubTnullability == NullabilityKind::Nullable); |
2249 | } |
2250 | else { |
2251 | // For the return type, it's okay for the superclass method to specify |
2252 | // "nullable" and the subclass method specify "nonnull" |
2253 | return (*SuperTnullability == NullabilityKind::Nullable && |
2254 | *SubTnullability == NullabilityKind::NonNull); |
2255 | } |
2256 | } |
2257 | return true; |
2258 | } |
2259 | |
2260 | bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, |
2261 | const ObjCMethodDecl *MethodImp); |
2262 | |
2263 | bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2); |
2264 | |
2265 | /// \brief Retrieves the "canonical" nested name specifier for a |
2266 | /// given nested name specifier. |
2267 | /// |
2268 | /// The canonical nested name specifier is a nested name specifier |
2269 | /// that uniquely identifies a type or namespace within the type |
2270 | /// system. For example, given: |
2271 | /// |
2272 | /// \code |
2273 | /// namespace N { |
2274 | /// struct S { |
2275 | /// template<typename T> struct X { typename T* type; }; |
2276 | /// }; |
2277 | /// } |
2278 | /// |
2279 | /// template<typename T> struct Y { |
2280 | /// typename N::S::X<T>::type member; |
2281 | /// }; |
2282 | /// \endcode |
2283 | /// |
2284 | /// Here, the nested-name-specifier for N::S::X<T>:: will be |
2285 | /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined |
2286 | /// by declarations in the type system and the canonical type for |
2287 | /// the template type parameter 'T' is template-param-0-0. |
2288 | NestedNameSpecifier * |
2289 | getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const; |
2290 | |
2291 | /// \brief Retrieves the default calling convention for the current target. |
2292 | CallingConv getDefaultCallingConvention(bool IsVariadic, |
2293 | bool IsCXXMethod) const; |
2294 | |
2295 | /// \brief Retrieves the "canonical" template name that refers to a |
2296 | /// given template. |
2297 | /// |
2298 | /// The canonical template name is the simplest expression that can |
2299 | /// be used to refer to a given template. For most templates, this |
2300 | /// expression is just the template declaration itself. For example, |
2301 | /// the template std::vector can be referred to via a variety of |
2302 | /// names---std::vector, \::std::vector, vector (if vector is in |
2303 | /// scope), etc.---but all of these names map down to the same |
2304 | /// TemplateDecl, which is used to form the canonical template name. |
2305 | /// |
2306 | /// Dependent template names are more interesting. Here, the |
2307 | /// template name could be something like T::template apply or |
2308 | /// std::allocator<T>::template rebind, where the nested name |
2309 | /// specifier itself is dependent. In this case, the canonical |
2310 | /// template name uses the shortest form of the dependent |
2311 | /// nested-name-specifier, which itself contains all canonical |
2312 | /// types, values, and templates. |
2313 | TemplateName getCanonicalTemplateName(TemplateName Name) const; |
2314 | |
2315 | /// \brief Determine whether the given template names refer to the same |
2316 | /// template. |
2317 | bool hasSameTemplateName(TemplateName X, TemplateName Y); |
2318 | |
2319 | /// \brief Retrieve the "canonical" template argument. |
2320 | /// |
2321 | /// The canonical template argument is the simplest template argument |
2322 | /// (which may be a type, value, expression, or declaration) that |
2323 | /// expresses the value of the argument. |
2324 | TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) |
2325 | const; |
2326 | |
2327 | /// Type Query functions. If the type is an instance of the specified class, |
2328 | /// return the Type pointer for the underlying maximally pretty type. This |
2329 | /// is a member of ASTContext because this may need to do some amount of |
2330 | /// canonicalization, e.g. to move type qualifiers into the element type. |
2331 | const ArrayType *getAsArrayType(QualType T) const; |
2332 | const ConstantArrayType *getAsConstantArrayType(QualType T) const { |
2333 | return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T)); |
2334 | } |
2335 | const VariableArrayType *getAsVariableArrayType(QualType T) const { |
2336 | return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T)); |
2337 | } |
2338 | const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const { |
2339 | return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T)); |
2340 | } |
2341 | const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) |
2342 | const { |
2343 | return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T)); |
2344 | } |
2345 | |
2346 | /// \brief Return the innermost element type of an array type. |
2347 | /// |
2348 | /// For example, will return "int" for int[m][n] |
2349 | QualType getBaseElementType(const ArrayType *VAT) const; |
2350 | |
2351 | /// \brief Return the innermost element type of a type (which needn't |
2352 | /// actually be an array type). |
2353 | QualType getBaseElementType(QualType QT) const; |
2354 | |
2355 | /// \brief Return number of constant array elements. |
2356 | uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const; |
2357 | |
2358 | /// \brief Perform adjustment on the parameter type of a function. |
2359 | /// |
2360 | /// This routine adjusts the given parameter type @p T to the actual |
2361 | /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], |
2362 | /// C++ [dcl.fct]p3). The adjusted parameter type is returned. |
2363 | QualType getAdjustedParameterType(QualType T) const; |
2364 | |
2365 | /// \brief Retrieve the parameter type as adjusted for use in the signature |
2366 | /// of a function, decaying array and function types and removing top-level |
2367 | /// cv-qualifiers. |
2368 | QualType getSignatureParameterType(QualType T) const; |
2369 | |
2370 | QualType getExceptionObjectType(QualType T) const; |
2371 | |
2372 | /// \brief Return the properly qualified result of decaying the specified |
2373 | /// array type to a pointer. |
2374 | /// |
2375 | /// This operation is non-trivial when handling typedefs etc. The canonical |
2376 | /// type of \p T must be an array type, this returns a pointer to a properly |
2377 | /// qualified element of the array. |
2378 | /// |
2379 | /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. |
2380 | QualType getArrayDecayedType(QualType T) const; |
2381 | |
2382 | /// \brief Return the type that \p PromotableType will promote to: C99 |
2383 | /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type. |
2384 | QualType getPromotedIntegerType(QualType PromotableType) const; |
2385 | |
2386 | /// \brief Recurses in pointer/array types until it finds an Objective-C |
2387 | /// retainable type and returns its ownership. |
2388 | Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const; |
2389 | |
2390 | /// \brief Whether this is a promotable bitfield reference according |
2391 | /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). |
2392 | /// |
2393 | /// \returns the type this bit-field will promote to, or NULL if no |
2394 | /// promotion occurs. |
2395 | QualType isPromotableBitField(Expr *E) const; |
2396 | |
2397 | /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1. |
2398 | /// |
2399 | /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If |
2400 | /// \p LHS < \p RHS, return -1. |
2401 | int getIntegerTypeOrder(QualType LHS, QualType RHS) const; |
2402 | |
2403 | /// \brief Compare the rank of the two specified floating point types, |
2404 | /// ignoring the domain of the type (i.e. 'double' == '_Complex double'). |
2405 | /// |
2406 | /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If |
2407 | /// \p LHS < \p RHS, return -1. |
2408 | int getFloatingTypeOrder(QualType LHS, QualType RHS) const; |
2409 | |
2410 | /// \brief Return a real floating point or a complex type (based on |
2411 | /// \p typeDomain/\p typeSize). |
2412 | /// |
2413 | /// \param typeDomain a real floating point or complex type. |
2414 | /// \param typeSize a real floating point or complex type. |
2415 | QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, |
2416 | QualType typeDomain) const; |
2417 | |
2418 | unsigned getTargetAddressSpace(QualType T) const { |
2419 | return getTargetAddressSpace(T.getQualifiers()); |
2420 | } |
2421 | |
2422 | unsigned getTargetAddressSpace(Qualifiers Q) const { |
2423 | return getTargetAddressSpace(Q.getAddressSpace()); |
2424 | } |
2425 | |
2426 | unsigned getTargetAddressSpace(LangAS AS) const; |
2427 | |
2428 | /// Get target-dependent integer value for null pointer which is used for |
2429 | /// constant folding. |
2430 | uint64_t getTargetNullPointerValue(QualType QT) const; |
2431 | |
2432 | bool addressSpaceMapManglingFor(LangAS AS) const { |
2433 | return AddrSpaceMapMangling || isTargetAddressSpace(AS); |
2434 | } |
2435 | |
2436 | private: |
2437 | // Helper for integer ordering |
2438 | unsigned getIntegerRank(const Type *T) const; |
2439 | |
2440 | public: |
2441 | //===--------------------------------------------------------------------===// |
2442 | // Type Compatibility Predicates |
2443 | //===--------------------------------------------------------------------===// |
2444 | |
2445 | /// Compatibility predicates used to check assignment expressions. |
2446 | bool typesAreCompatible(QualType T1, QualType T2, |
2447 | bool CompareUnqualified = false); // C99 6.2.7p1 |
2448 | |
2449 | bool propertyTypesAreCompatible(QualType, QualType); |
2450 | bool typesAreBlockPointerCompatible(QualType, QualType); |
2451 | |
2452 | bool isObjCIdType(QualType T) const { |
2453 | return T == getObjCIdType(); |
2454 | } |
2455 | |
2456 | bool isObjCClassType(QualType T) const { |
2457 | return T == getObjCClassType(); |
2458 | } |
2459 | |
2460 | bool isObjCSelType(QualType T) const { |
2461 | return T == getObjCSelType(); |
2462 | } |
2463 | |
2464 | bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, |
2465 | bool ForCompare); |
2466 | |
2467 | bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS); |
2468 | |
2469 | // Check the safety of assignment from LHS to RHS |
2470 | bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, |
2471 | const ObjCObjectPointerType *RHSOPT); |
2472 | bool canAssignObjCInterfaces(const ObjCObjectType *LHS, |
2473 | const ObjCObjectType *RHS); |
2474 | bool canAssignObjCInterfacesInBlockPointer( |
2475 | const ObjCObjectPointerType *LHSOPT, |
2476 | const ObjCObjectPointerType *RHSOPT, |
2477 | bool BlockReturnType); |
2478 | bool areComparableObjCPointerTypes(QualType LHS, QualType RHS); |
2479 | QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, |
2480 | const ObjCObjectPointerType *RHSOPT); |
2481 | bool canBindObjCObjectType(QualType To, QualType From); |
2482 | |
2483 | // Functions for calculating composite types |
2484 | QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, |
2485 | bool Unqualified = false, bool BlockReturnType = false); |
2486 | QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, |
2487 | bool Unqualified = false); |
2488 | QualType mergeFunctionParameterTypes(QualType, QualType, |
2489 | bool OfBlockPointer = false, |
2490 | bool Unqualified = false); |
2491 | QualType mergeTransparentUnionType(QualType, QualType, |
2492 | bool OfBlockPointer=false, |
2493 | bool Unqualified = false); |
2494 | |
2495 | QualType mergeObjCGCQualifiers(QualType, QualType); |
2496 | |
2497 | /// This function merges the ExtParameterInfo lists of two functions. It |
2498 | /// returns true if the lists are compatible. The merged list is returned in |
2499 | /// NewParamInfos. |
2500 | /// |
2501 | /// \param FirstFnType The type of the first function. |
2502 | /// |
2503 | /// \param SecondFnType The type of the second function. |
2504 | /// |
2505 | /// \param CanUseFirst This flag is set to true if the first function's |
2506 | /// ExtParameterInfo list can be used as the composite list of |
2507 | /// ExtParameterInfo. |
2508 | /// |
2509 | /// \param CanUseSecond This flag is set to true if the second function's |
2510 | /// ExtParameterInfo list can be used as the composite list of |
2511 | /// ExtParameterInfo. |
2512 | /// |
2513 | /// \param NewParamInfos The composite list of ExtParameterInfo. The list is |
2514 | /// empty if none of the flags are set. |
2515 | /// |
2516 | bool mergeExtParameterInfo( |
2517 | const FunctionProtoType *FirstFnType, |
2518 | const FunctionProtoType *SecondFnType, |
2519 | bool &CanUseFirst, bool &CanUseSecond, |
2520 | SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos); |
2521 | |
2522 | void ResetObjCLayout(const ObjCContainerDecl *CD); |
2523 | |
2524 | //===--------------------------------------------------------------------===// |
2525 | // Integer Predicates |
2526 | //===--------------------------------------------------------------------===// |
2527 | |
2528 | // The width of an integer, as defined in C99 6.2.6.2. This is the number |
2529 | // of bits in an integer type excluding any padding bits. |
2530 | unsigned getIntWidth(QualType T) const; |
2531 | |
2532 | // Per C99 6.2.5p6, for every signed integer type, there is a corresponding |
2533 | // unsigned integer type. This method takes a signed type, and returns the |
2534 | // corresponding unsigned integer type. |
2535 | QualType getCorrespondingUnsignedType(QualType T) const; |
2536 | |
2537 | //===--------------------------------------------------------------------===// |
2538 | // Integer Values |
2539 | //===--------------------------------------------------------------------===// |
2540 | |
2541 | /// \brief Make an APSInt of the appropriate width and signedness for the |
2542 | /// given \p Value and integer \p Type. |
2543 | llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const { |
2544 | // If Type is a signed integer type larger than 64 bits, we need to be sure |
2545 | // to sign extend Res appropriately. |
2546 | llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType()); |
2547 | Res = Value; |
2548 | unsigned Width = getIntWidth(Type); |
2549 | if (Width != Res.getBitWidth()) |
2550 | return Res.extOrTrunc(Width); |
2551 | return Res; |
2552 | } |
2553 | |
2554 | bool isSentinelNullExpr(const Expr *E); |
2555 | |
2556 | /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if |
2557 | /// none exists. |
2558 | ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D); |
2559 | |
2560 | /// \brief Get the implementation of the ObjCCategoryDecl \p D, or nullptr if |
2561 | /// none exists. |
2562 | ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D); |
2563 | |
2564 | /// \brief Return true if there is at least one \@implementation in the TU. |
2565 | bool AnyObjCImplementation() { |
2566 | return !ObjCImpls.empty(); |
2567 | } |
2568 | |
2569 | /// \brief Set the implementation of ObjCInterfaceDecl. |
2570 | void setObjCImplementation(ObjCInterfaceDecl *IFaceD, |
2571 | ObjCImplementationDecl *ImplD); |
2572 | |
2573 | /// \brief Set the implementation of ObjCCategoryDecl. |
2574 | void setObjCImplementation(ObjCCategoryDecl *CatD, |
2575 | ObjCCategoryImplDecl *ImplD); |
2576 | |
2577 | /// \brief Get the duplicate declaration of a ObjCMethod in the same |
2578 | /// interface, or null if none exists. |
2579 | const ObjCMethodDecl * |
2580 | getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const; |
2581 | |
2582 | void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, |
2583 | const ObjCMethodDecl *Redecl); |
2584 | |
2585 | /// \brief Returns the Objective-C interface that \p ND belongs to if it is |
2586 | /// an Objective-C method/property/ivar etc. that is part of an interface, |
2587 | /// otherwise returns null. |
2588 | const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const; |
2589 | |
2590 | /// \brief Set the copy inialization expression of a block var decl. |
2591 | void setBlockVarCopyInits(VarDecl*VD, Expr* Init); |
2592 | |
2593 | /// \brief Get the copy initialization expression of the VarDecl \p VD, or |
2594 | /// nullptr if none exists. |
2595 | Expr *getBlockVarCopyInits(const VarDecl* VD); |
2596 | |
2597 | /// \brief Allocate an uninitialized TypeSourceInfo. |
2598 | /// |
2599 | /// The caller should initialize the memory held by TypeSourceInfo using |
2600 | /// the TypeLoc wrappers. |
2601 | /// |
2602 | /// \param T the type that will be the basis for type source info. This type |
2603 | /// should refer to how the declarator was written in source code, not to |
2604 | /// what type semantic analysis resolved the declarator to. |
2605 | /// |
2606 | /// \param Size the size of the type info to create, or 0 if the size |
2607 | /// should be calculated based on the type. |
2608 | TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const; |
2609 | |
2610 | /// \brief Allocate a TypeSourceInfo where all locations have been |
2611 | /// initialized to a given location, which defaults to the empty |
2612 | /// location. |
2613 | TypeSourceInfo * |
2614 | getTrivialTypeSourceInfo(QualType T, |
2615 | SourceLocation Loc = SourceLocation()) const; |
2616 | |
2617 | /// \brief Add a deallocation callback that will be invoked when the |
2618 | /// ASTContext is destroyed. |
2619 | /// |
2620 | /// \param Callback A callback function that will be invoked on destruction. |
2621 | /// |
2622 | /// \param Data Pointer data that will be provided to the callback function |
2623 | /// when it is called. |
2624 | void AddDeallocation(void (*Callback)(void*), void *Data); |
2625 | |
2626 | /// If T isn't trivially destructible, calls AddDeallocation to register it |
2627 | /// for destruction. |
2628 | template <typename T> |
2629 | void addDestruction(T *Ptr) { |
2630 | if (!std::is_trivially_destructible<T>::value) { |
2631 | auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); }; |
2632 | AddDeallocation(DestroyPtr, Ptr); |
2633 | } |
2634 | } |
2635 | |
2636 | GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const; |
2637 | GVALinkage GetGVALinkageForVariable(const VarDecl *VD); |
2638 | |
2639 | /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH |
2640 | /// lazily, only when used; this is only relevant for function or file scoped |
2641 | /// var definitions. |
2642 | /// |
2643 | /// \returns true if the function/var must be CodeGen'ed/deserialized even if |
2644 | /// it is not used. |
2645 | bool DeclMustBeEmitted(const Decl *D); |
2646 | |
2647 | /// \brief Visits all versions of a multiversioned function with the passed |
2648 | /// predicate. |
2649 | void forEachMultiversionedFunctionVersion( |
2650 | const FunctionDecl *FD, |
2651 | llvm::function_ref<void(const FunctionDecl *)> Pred) const; |
2652 | |
2653 | const CXXConstructorDecl * |
2654 | getCopyConstructorForExceptionObject(CXXRecordDecl *RD); |
2655 | |
2656 | void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, |
2657 | CXXConstructorDecl *CD); |
2658 | |
2659 | void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND); |
2660 | |
2661 | TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD); |
2662 | |
2663 | void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD); |
2664 | |
2665 | DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD); |
2666 | |
2667 | void setManglingNumber(const NamedDecl *ND, unsigned Number); |
2668 | unsigned getManglingNumber(const NamedDecl *ND) const; |
2669 | |
2670 | void setStaticLocalNumber(const VarDecl *VD, unsigned Number); |
2671 | unsigned getStaticLocalNumber(const VarDecl *VD) const; |
2672 | |
2673 | /// \brief Retrieve the context for computing mangling numbers in the given |
2674 | /// DeclContext. |
2675 | MangleNumberingContext &getManglingNumberContext(const DeclContext *DC); |
2676 | |
2677 | std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const; |
2678 | |
2679 | /// \brief Used by ParmVarDecl to store on the side the |
2680 | /// index of the parameter when it exceeds the size of the normal bitfield. |
2681 | void setParameterIndex(const ParmVarDecl *D, unsigned index); |
2682 | |
2683 | /// \brief Used by ParmVarDecl to retrieve on the side the |
2684 | /// index of the parameter when it exceeds the size of the normal bitfield. |
2685 | unsigned getParameterIndex(const ParmVarDecl *D) const; |
2686 | |
2687 | /// \brief Get the storage for the constant value of a materialized temporary |
2688 | /// of static storage duration. |
2689 | APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, |
2690 | bool MayCreate); |
2691 | |
2692 | //===--------------------------------------------------------------------===// |
2693 | // Statistics |
2694 | //===--------------------------------------------------------------------===// |
2695 | |
2696 | /// \brief The number of implicitly-declared default constructors. |
2697 | static unsigned NumImplicitDefaultConstructors; |
2698 | |
2699 | /// \brief The number of implicitly-declared default constructors for |
2700 | /// which declarations were built. |
2701 | static unsigned NumImplicitDefaultConstructorsDeclared; |
2702 | |
2703 | /// \brief The number of implicitly-declared copy constructors. |
2704 | static unsigned NumImplicitCopyConstructors; |
2705 | |
2706 | /// \brief The number of implicitly-declared copy constructors for |
2707 | /// which declarations were built. |
2708 | static unsigned NumImplicitCopyConstructorsDeclared; |
2709 | |
2710 | /// \brief The number of implicitly-declared move constructors. |
2711 | static unsigned NumImplicitMoveConstructors; |
2712 | |
2713 | /// \brief The number of implicitly-declared move constructors for |
2714 | /// which declarations were built. |
2715 | static unsigned NumImplicitMoveConstructorsDeclared; |
2716 | |
2717 | /// \brief The number of implicitly-declared copy assignment operators. |
2718 | static unsigned NumImplicitCopyAssignmentOperators; |
2719 | |
2720 | /// \brief The number of implicitly-declared copy assignment operators for |
2721 | /// which declarations were built. |
2722 | static unsigned NumImplicitCopyAssignmentOperatorsDeclared; |
2723 | |
2724 | /// \brief The number of implicitly-declared move assignment operators. |
2725 | static unsigned NumImplicitMoveAssignmentOperators; |
2726 | |
2727 | /// \brief The number of implicitly-declared move assignment operators for |
2728 | /// which declarations were built. |
2729 | static unsigned NumImplicitMoveAssignmentOperatorsDeclared; |
2730 | |
2731 | /// \brief The number of implicitly-declared destructors. |
2732 | static unsigned NumImplicitDestructors; |
2733 | |
2734 | /// \brief The number of implicitly-declared destructors for which |
2735 | /// declarations were built. |
2736 | static unsigned NumImplicitDestructorsDeclared; |
2737 | |
2738 | public: |
2739 | /// \brief Initialize built-in types. |
2740 | /// |
2741 | /// This routine may only be invoked once for a given ASTContext object. |
2742 | /// It is normally invoked after ASTContext construction. |
2743 | /// |
2744 | /// \param Target The target |
2745 | void InitBuiltinTypes(const TargetInfo &Target, |
2746 | const TargetInfo *AuxTarget = nullptr); |
2747 | |
2748 | private: |
2749 | void InitBuiltinType(CanQualType &R, BuiltinType::Kind K); |
2750 | |
2751 | // Return the Objective-C type encoding for a given type. |
2752 | void getObjCEncodingForTypeImpl(QualType t, std::string &S, |
2753 | bool ExpandPointedToStructures, |
2754 | bool ExpandStructures, |
2755 | const FieldDecl *Field, |
2756 | bool OutermostType = false, |
2757 | bool EncodingProperty = false, |
2758 | bool StructField = false, |
2759 | bool EncodeBlockParameters = false, |
2760 | bool EncodeClassNames = false, |
2761 | bool EncodePointerToObjCTypedef = false, |
2762 | QualType *NotEncodedT=nullptr) const; |
2763 | |
2764 | // Adds the encoding of the structure's members. |
2765 | void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S, |
2766 | const FieldDecl *Field, |
2767 | bool includeVBases = true, |
2768 | QualType *NotEncodedT=nullptr) const; |
2769 | |
2770 | public: |
2771 | // Adds the encoding of a method parameter or return type. |
2772 | void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, |
2773 | QualType T, std::string& S, |
2774 | bool Extended) const; |
2775 | |
2776 | /// \brief Returns true if this is an inline-initialized static data member |
2777 | /// which is treated as a definition for MSVC compatibility. |
2778 | bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const; |
2779 | |
2780 | enum class InlineVariableDefinitionKind { |
2781 | /// Not an inline variable. |
2782 | None, |
2783 | |
2784 | /// Weak definition of inline variable. |
2785 | Weak, |
2786 | |
2787 | /// Weak for now, might become strong later in this TU. |
2788 | WeakUnknown, |
2789 | |
2790 | /// Strong definition. |
2791 | Strong |
2792 | }; |
2793 | |
2794 | /// \brief Determine whether a definition of this inline variable should |
2795 | /// be treated as a weak or strong definition. For compatibility with |
2796 | /// C++14 and before, for a constexpr static data member, if there is an |
2797 | /// out-of-line declaration of the member, we may promote it from weak to |
2798 | /// strong. |
2799 | InlineVariableDefinitionKind |
2800 | getInlineVariableDefinitionKind(const VarDecl *VD) const; |
2801 | |
2802 | private: |
2803 | friend class DeclarationNameTable; |
2804 | friend class DeclContext; |
2805 | |
2806 | const ASTRecordLayout & |
2807 | getObjCLayout(const ObjCInterfaceDecl *D, |
2808 | const ObjCImplementationDecl *Impl) const; |
2809 | |
2810 | /// \brief A set of deallocations that should be performed when the |
2811 | /// ASTContext is destroyed. |
2812 | // FIXME: We really should have a better mechanism in the ASTContext to |
2813 | // manage running destructors for types which do variable sized allocation |
2814 | // within the AST. In some places we thread the AST bump pointer allocator |
2815 | // into the datastructures which avoids this mess during deallocation but is |
2816 | // wasteful of memory, and here we require a lot of error prone book keeping |
2817 | // in order to track and run destructors while we're tearing things down. |
2818 | using DeallocationFunctionsAndArguments = |
2819 | llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>; |
2820 | DeallocationFunctionsAndArguments Deallocations; |
2821 | |
2822 | // FIXME: This currently contains the set of StoredDeclMaps used |
2823 | // by DeclContext objects. This probably should not be in ASTContext, |
2824 | // but we include it here so that ASTContext can quickly deallocate them. |
2825 | llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM; |
2826 | |
2827 | std::unique_ptr<ParentMapPointers> PointerParents; |
2828 | std::unique_ptr<ParentMapOtherNodes> OtherParents; |
2829 | |
2830 | std::unique_ptr<VTableContextBase> VTContext; |
2831 | |
2832 | void ReleaseDeclContextMaps(); |
2833 | void ReleaseParentMapEntries(); |
2834 | |
2835 | public: |
2836 | enum PragmaSectionFlag : unsigned { |
2837 | PSF_None = 0, |
2838 | PSF_Read = 0x1, |
2839 | PSF_Write = 0x2, |
2840 | PSF_Execute = 0x4, |
2841 | PSF_Implicit = 0x8, |
2842 | PSF_Invalid = 0x80000000U, |
2843 | }; |
2844 | |
2845 | struct SectionInfo { |
2846 | DeclaratorDecl *Decl; |
2847 | SourceLocation PragmaSectionLocation; |
2848 | int SectionFlags; |
2849 | |
2850 | SectionInfo() = default; |
2851 | SectionInfo(DeclaratorDecl *Decl, |
2852 | SourceLocation PragmaSectionLocation, |
2853 | int SectionFlags) |
2854 | : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation), |
2855 | SectionFlags(SectionFlags) {} |
2856 | }; |
2857 | |
2858 | llvm::StringMap<SectionInfo> SectionInfos; |
2859 | }; |
2860 | |
2861 | /// \brief Utility function for constructing a nullary selector. |
2862 | inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) { |
2863 | IdentifierInfo* II = &Ctx.Idents.get(name); |
2864 | return Ctx.Selectors.getSelector(0, &II); |
2865 | } |
2866 | |
2867 | /// \brief Utility function for constructing an unary selector. |
2868 | inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) { |
2869 | IdentifierInfo* II = &Ctx.Idents.get(name); |
2870 | return Ctx.Selectors.getSelector(1, &II); |
2871 | } |
2872 | |
2873 | } // namespace clang |
2874 | |
2875 | // operator new and delete aren't allowed inside namespaces. |
2876 | |
2877 | /// @brief Placement new for using the ASTContext's allocator. |
2878 | /// |
2879 | /// This placement form of operator new uses the ASTContext's allocator for |
2880 | /// obtaining memory. |
2881 | /// |
2882 | /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes |
2883 | /// here need to also be made there. |
2884 | /// |
2885 | /// We intentionally avoid using a nothrow specification here so that the calls |
2886 | /// to this operator will not perform a null check on the result -- the |
2887 | /// underlying allocator never returns null pointers. |
2888 | /// |
2889 | /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): |
2890 | /// @code |
2891 | /// // Default alignment (8) |
2892 | /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); |
2893 | /// // Specific alignment |
2894 | /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments); |
2895 | /// @endcode |
2896 | /// Memory allocated through this placement new operator does not need to be |
2897 | /// explicitly freed, as ASTContext will free all of this memory when it gets |
2898 | /// destroyed. Please note that you cannot use delete on the pointer. |
2899 | /// |
2900 | /// @param Bytes The number of bytes to allocate. Calculated by the compiler. |
2901 | /// @param C The ASTContext that provides the allocator. |
2902 | /// @param Alignment The alignment of the allocated memory (if the underlying |
2903 | /// allocator supports it). |
2904 | /// @return The allocated memory. Could be nullptr. |
2905 | inline void *operator new(size_t Bytes, const clang::ASTContext &C, |
2906 | size_t Alignment) { |
2907 | return C.Allocate(Bytes, Alignment); |
2908 | } |
2909 | |
2910 | /// @brief Placement delete companion to the new above. |
2911 | /// |
2912 | /// This operator is just a companion to the new above. There is no way of |
2913 | /// invoking it directly; see the new operator for more details. This operator |
2914 | /// is called implicitly by the compiler if a placement new expression using |
2915 | /// the ASTContext throws in the object constructor. |
2916 | inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) { |
2917 | C.Deallocate(Ptr); |
2918 | } |
2919 | |
2920 | /// This placement form of operator new[] uses the ASTContext's allocator for |
2921 | /// obtaining memory. |
2922 | /// |
2923 | /// We intentionally avoid using a nothrow specification here so that the calls |
2924 | /// to this operator will not perform a null check on the result -- the |
2925 | /// underlying allocator never returns null pointers. |
2926 | /// |
2927 | /// Usage looks like this (assuming there's an ASTContext 'Context' in scope): |
2928 | /// @code |
2929 | /// // Default alignment (8) |
2930 | /// char *data = new (Context) char[10]; |
2931 | /// // Specific alignment |
2932 | /// char *data = new (Context, 4) char[10]; |
2933 | /// @endcode |
2934 | /// Memory allocated through this placement new[] operator does not need to be |
2935 | /// explicitly freed, as ASTContext will free all of this memory when it gets |
2936 | /// destroyed. Please note that you cannot use delete on the pointer. |
2937 | /// |
2938 | /// @param Bytes The number of bytes to allocate. Calculated by the compiler. |
2939 | /// @param C The ASTContext that provides the allocator. |
2940 | /// @param Alignment The alignment of the allocated memory (if the underlying |
2941 | /// allocator supports it). |
2942 | /// @return The allocated memory. Could be nullptr. |
2943 | inline void *operator new[](size_t Bytes, const clang::ASTContext& C, |
2944 | size_t Alignment = 8) { |
2945 | return C.Allocate(Bytes, Alignment); |
2946 | } |
2947 | |
2948 | /// @brief Placement delete[] companion to the new[] above. |
2949 | /// |
2950 | /// This operator is just a companion to the new[] above. There is no way of |
2951 | /// invoking it directly; see the new[] operator for more details. This operator |
2952 | /// is called implicitly by the compiler if a placement new[] expression using |
2953 | /// the ASTContext throws in the object constructor. |
2954 | inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) { |
2955 | C.Deallocate(Ptr); |
2956 | } |
2957 | |
2958 | /// \brief Create the representation of a LazyGenerationalUpdatePtr. |
2959 | template <typename Owner, typename T, |
2960 | void (clang::ExternalASTSource::*Update)(Owner)> |
2961 | typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType |
2962 | clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue( |
2963 | const clang::ASTContext &Ctx, T Value) { |
2964 | // Note, this is implemented here so that ExternalASTSource.h doesn't need to |
2965 | // include ASTContext.h. We explicitly instantiate it for all relevant types |
2966 | // in ASTContext.cpp. |
2967 | if (auto *Source = Ctx.getExternalSource()) |
2968 | return new (Ctx) LazyData(Source, Value); |
2969 | return Value; |
2970 | } |
2971 | |
2972 | #endif // LLVM_CLANG_AST_ASTCONTEXT_H |
1 | //===- CanonicalType.h - C Language Family Type Representation --*- 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 defines the CanQual class template, which provides access to |
11 | // canonical types. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_CLANG_AST_CANONICALTYPE_H |
16 | #define LLVM_CLANG_AST_CANONICALTYPE_H |
17 | |
18 | #include "clang/AST/Type.h" |
19 | #include "clang/Basic/Diagnostic.h" |
20 | #include "clang/Basic/SourceLocation.h" |
21 | #include "llvm/ADT/ArrayRef.h" |
22 | #include "llvm/ADT/FoldingSet.h" |
23 | #include "llvm/ADT/iterator.h" |
24 | #include "llvm/Support/Casting.h" |
25 | #include "llvm/Support/PointerLikeTypeTraits.h" |
26 | #include <cassert> |
27 | #include <iterator> |
28 | #include <type_traits> |
29 | |
30 | namespace clang { |
31 | |
32 | template<typename T> class CanProxy; |
33 | template<typename T> struct CanProxyAdaptor; |
34 | class CXXRecordDecl; |
35 | class EnumDecl; |
36 | class Expr; |
37 | class IdentifierInfo; |
38 | class ObjCInterfaceDecl; |
39 | class RecordDecl; |
40 | class TagDecl; |
41 | class TemplateTypeParmDecl; |
42 | |
43 | //----------------------------------------------------------------------------// |
44 | // Canonical, qualified type template |
45 | //----------------------------------------------------------------------------// |
46 | |
47 | /// \brief Represents a canonical, potentially-qualified type. |
48 | /// |
49 | /// The CanQual template is a lightweight smart pointer that provides access |
50 | /// to the canonical representation of a type, where all typedefs and other |
51 | /// syntactic sugar has been eliminated. A CanQualType may also have various |
52 | /// qualifiers (const, volatile, restrict) attached to it. |
53 | /// |
54 | /// The template type parameter @p T is one of the Type classes (PointerType, |
55 | /// BuiltinType, etc.). The type stored within @c CanQual<T> will be of that |
56 | /// type (or some subclass of that type). The typedef @c CanQualType is just |
57 | /// a shorthand for @c CanQual<Type>. |
58 | /// |
59 | /// An instance of @c CanQual<T> can be implicitly converted to a |
60 | /// @c CanQual<U> when T is derived from U, which essentially provides an |
61 | /// implicit upcast. For example, @c CanQual<LValueReferenceType> can be |
62 | /// converted to @c CanQual<ReferenceType>. Note that any @c CanQual type can |
63 | /// be implicitly converted to a QualType, but the reverse operation requires |
64 | /// a call to ASTContext::getCanonicalType(). |
65 | template<typename T = Type> |
66 | class CanQual { |
67 | /// \brief The actual, canonical type. |
68 | QualType Stored; |
69 | |
70 | public: |
71 | /// \brief Constructs a NULL canonical type. |
72 | CanQual() = default; |
73 | |
74 | /// \brief Converting constructor that permits implicit upcasting of |
75 | /// canonical type pointers. |
76 | template <typename U> |
77 | CanQual(const CanQual<U> &Other, |
78 | typename std::enable_if<std::is_base_of<T, U>::value, int>::type = 0); |
79 | |
80 | /// \brief Retrieve the underlying type pointer, which refers to a |
81 | /// canonical type. |
82 | /// |
83 | /// The underlying pointer must not be nullptr. |
84 | const T *getTypePtr() const { return cast<T>(Stored.getTypePtr()); } |
85 | |
86 | /// \brief Retrieve the underlying type pointer, which refers to a |
87 | /// canonical type, or nullptr. |
88 | const T *getTypePtrOrNull() const { |
89 | return cast_or_null<T>(Stored.getTypePtrOrNull()); |
90 | } |
91 | |
92 | /// \brief Implicit conversion to a qualified type. |
93 | operator QualType() const { return Stored; } |
94 | |
95 | /// \brief Implicit conversion to bool. |
96 | explicit operator bool() const { return !isNull(); } |
97 | |
98 | bool isNull() const { |
99 | return Stored.isNull(); |
100 | } |
101 | |
102 | SplitQualType split() const { return Stored.split(); } |
103 | |
104 | /// \brief Retrieve a canonical type pointer with a different static type, |
105 | /// upcasting or downcasting as needed. |
106 | /// |
107 | /// The getAs() function is typically used to try to downcast to a |
108 | /// more specific (canonical) type in the type system. For example: |
109 | /// |
110 | /// @code |
111 | /// void f(CanQual<Type> T) { |
112 | /// if (CanQual<PointerType> Ptr = T->getAs<PointerType>()) { |
113 | /// // look at Ptr's pointee type |
114 | /// } |
115 | /// } |
116 | /// @endcode |
117 | /// |
118 | /// \returns A proxy pointer to the same type, but with the specified |
119 | /// static type (@p U). If the dynamic type is not the specified static type |
120 | /// or a derived class thereof, a NULL canonical type. |
121 | template<typename U> CanProxy<U> getAs() const; |
122 | |
123 | template<typename U> CanProxy<U> castAs() const; |
124 | |
125 | /// \brief Overloaded arrow operator that produces a canonical type |
126 | /// proxy. |
127 | CanProxy<T> operator->() const; |
128 | |
129 | /// \brief Retrieve all qualifiers. |
130 | Qualifiers getQualifiers() const { return Stored.getLocalQualifiers(); } |
131 | |
132 | /// \brief Retrieve the const/volatile/restrict qualifiers. |
133 | unsigned getCVRQualifiers() const { return Stored.getLocalCVRQualifiers(); } |
134 | |
135 | /// \brief Determines whether this type has any qualifiers |
136 | bool hasQualifiers() const { return Stored.hasLocalQualifiers(); } |
137 | |
138 | bool isConstQualified() const { |
139 | return Stored.isLocalConstQualified(); |
140 | } |
141 | |
142 | bool isVolatileQualified() const { |
143 | return Stored.isLocalVolatileQualified(); |
144 | } |
145 | |
146 | bool isRestrictQualified() const { |
147 | return Stored.isLocalRestrictQualified(); |
148 | } |
149 | |
150 | /// \brief Determines if this canonical type is furthermore |
151 | /// canonical as a parameter. The parameter-canonicalization |
152 | /// process decays arrays to pointers and drops top-level qualifiers. |
153 | bool isCanonicalAsParam() const { |
154 | return Stored.isCanonicalAsParam(); |
155 | } |
156 | |
157 | /// \brief Retrieve the unqualified form of this type. |
158 | CanQual<T> getUnqualifiedType() const; |
159 | |
160 | /// \brief Retrieves a version of this type with const applied. |
161 | /// Note that this does not always yield a canonical type. |
162 | QualType withConst() const { |
163 | return Stored.withConst(); |
164 | } |
165 | |
166 | /// \brief Determines whether this canonical type is more qualified than |
167 | /// the @p Other canonical type. |
168 | bool isMoreQualifiedThan(CanQual<T> Other) const { |
169 | return Stored.isMoreQualifiedThan(Other.Stored); |
170 | } |
171 | |
172 | /// \brief Determines whether this canonical type is at least as qualified as |
173 | /// the @p Other canonical type. |
174 | bool isAtLeastAsQualifiedAs(CanQual<T> Other) const { |
175 | return Stored.isAtLeastAsQualifiedAs(Other.Stored); |
176 | } |
177 | |
178 | /// \brief If the canonical type is a reference type, returns the type that |
179 | /// it refers to; otherwise, returns the type itself. |
180 | CanQual<Type> getNonReferenceType() const; |
181 | |
182 | /// \brief Retrieve the internal representation of this canonical type. |
183 | void *getAsOpaquePtr() const { return Stored.getAsOpaquePtr(); } |
184 | |
185 | /// \brief Construct a canonical type from its internal representation. |
186 | static CanQual<T> getFromOpaquePtr(void *Ptr); |
187 | |
188 | /// \brief Builds a canonical type from a QualType. |
189 | /// |
190 | /// This routine is inherently unsafe, because it requires the user to |
191 | /// ensure that the given type is a canonical type with the correct |
192 | // (dynamic) type. |
193 | static CanQual<T> CreateUnsafe(QualType Other); |
194 | |
195 | void dump() const { Stored.dump(); } |
196 | |
197 | void Profile(llvm::FoldingSetNodeID &ID) const { |
198 | ID.AddPointer(getAsOpaquePtr()); |
199 | } |
200 | }; |
201 | |
202 | template<typename T, typename U> |
203 | inline bool operator==(CanQual<T> x, CanQual<U> y) { |
204 | return x.getAsOpaquePtr() == y.getAsOpaquePtr(); |
205 | } |
206 | |
207 | template<typename T, typename U> |
208 | inline bool operator!=(CanQual<T> x, CanQual<U> y) { |
209 | return x.getAsOpaquePtr() != y.getAsOpaquePtr(); |
210 | } |
211 | |
212 | /// \brief Represents a canonical, potentially-qualified type. |
213 | using CanQualType = CanQual<Type>; |
214 | |
215 | inline CanQualType Type::getCanonicalTypeUnqualified() const { |
216 | return CanQualType::CreateUnsafe(getCanonicalTypeInternal()); |
217 | } |
218 | |
219 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
220 | CanQualType T) { |
221 | DB << static_cast<QualType>(T); |
222 | return DB; |
223 | } |
224 | |
225 | //----------------------------------------------------------------------------// |
226 | // Internal proxy classes used by canonical types |
227 | //----------------------------------------------------------------------------// |
228 | |
229 | #define LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(Accessor)CanQualType Accessor() const { return CanQualType::CreateUnsafe (this->getTypePtr()->Accessor()); } \ |
230 | CanQualType Accessor() const { \ |
231 | return CanQualType::CreateUnsafe(this->getTypePtr()->Accessor()); \ |
232 | } |
233 | |
234 | #define LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Type, Accessor)Type Accessor() const { return this->getTypePtr()->Accessor (); } \ |
235 | Type Accessor() const { return this->getTypePtr()->Accessor(); } |
236 | |
237 | /// \brief Base class of all canonical proxy types, which is responsible for |
238 | /// storing the underlying canonical type and providing basic conversions. |
239 | template<typename T> |
240 | class CanProxyBase { |
241 | protected: |
242 | CanQual<T> Stored; |
243 | |
244 | public: |
245 | /// \brief Retrieve the pointer to the underlying Type |
246 | const T *getTypePtr() const { return Stored.getTypePtr(); } |
247 | |
248 | /// \brief Implicit conversion to the underlying pointer. |
249 | /// |
250 | /// Also provides the ability to use canonical type proxies in a Boolean |
251 | // context,e.g., |
252 | /// @code |
253 | /// if (CanQual<PointerType> Ptr = T->getAs<PointerType>()) { ... } |
254 | /// @endcode |
255 | operator const T*() const { return this->Stored.getTypePtrOrNull(); } |
256 | |
257 | /// \brief Try to convert the given canonical type to a specific structural |
258 | /// type. |
259 | template<typename U> CanProxy<U> getAs() const { |
260 | return this->Stored.template getAs<U>(); |
261 | } |
262 | |
263 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Type::TypeClass, getTypeClass)Type::TypeClass getTypeClass() const { return this->getTypePtr ()->getTypeClass(); } |
264 | |
265 | // Type predicates |
266 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjectType)bool isObjectType() const { return this->getTypePtr()-> isObjectType(); } |
267 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIncompleteType)bool isIncompleteType() const { return this->getTypePtr()-> isIncompleteType(); } |
268 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIncompleteOrObjectType)bool isIncompleteOrObjectType() const { return this->getTypePtr ()->isIncompleteOrObjectType(); } |
269 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVariablyModifiedType)bool isVariablyModifiedType() const { return this->getTypePtr ()->isVariablyModifiedType(); } |
270 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIntegerType)bool isIntegerType() const { return this->getTypePtr()-> isIntegerType(); } |
271 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isEnumeralType)bool isEnumeralType() const { return this->getTypePtr()-> isEnumeralType(); } |
272 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBooleanType)bool isBooleanType() const { return this->getTypePtr()-> isBooleanType(); } |
273 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isCharType)bool isCharType() const { return this->getTypePtr()->isCharType (); } |
274 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isWideCharType)bool isWideCharType() const { return this->getTypePtr()-> isWideCharType(); } |
275 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIntegralType)bool isIntegralType() const { return this->getTypePtr()-> isIntegralType(); } |
276 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isIntegralOrEnumerationType)bool isIntegralOrEnumerationType() const { return this->getTypePtr ()->isIntegralOrEnumerationType(); } |
277 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isRealFloatingType)bool isRealFloatingType() const { return this->getTypePtr( )->isRealFloatingType(); } |
278 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isComplexType)bool isComplexType() const { return this->getTypePtr()-> isComplexType(); } |
279 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isAnyComplexType)bool isAnyComplexType() const { return this->getTypePtr()-> isAnyComplexType(); } |
280 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isFloatingType)bool isFloatingType() const { return this->getTypePtr()-> isFloatingType(); } |
281 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isRealType)bool isRealType() const { return this->getTypePtr()->isRealType (); } |
282 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isArithmeticType)bool isArithmeticType() const { return this->getTypePtr()-> isArithmeticType(); } |
283 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVoidType)bool isVoidType() const { return this->getTypePtr()->isVoidType (); } |
284 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isDerivedType)bool isDerivedType() const { return this->getTypePtr()-> isDerivedType(); } |
285 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isScalarType)bool isScalarType() const { return this->getTypePtr()-> isScalarType(); } |
286 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isAggregateType)bool isAggregateType() const { return this->getTypePtr()-> isAggregateType(); } |
287 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isAnyPointerType)bool isAnyPointerType() const { return this->getTypePtr()-> isAnyPointerType(); } |
288 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVoidPointerType)bool isVoidPointerType() const { return this->getTypePtr() ->isVoidPointerType(); } |
289 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isFunctionPointerType)bool isFunctionPointerType() const { return this->getTypePtr ()->isFunctionPointerType(); } |
290 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isMemberFunctionPointerType)bool isMemberFunctionPointerType() const { return this->getTypePtr ()->isMemberFunctionPointerType(); } |
291 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isClassType)bool isClassType() const { return this->getTypePtr()->isClassType (); } |
292 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isStructureType)bool isStructureType() const { return this->getTypePtr()-> isStructureType(); } |
293 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isInterfaceType)bool isInterfaceType() const { return this->getTypePtr()-> isInterfaceType(); } |
294 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isStructureOrClassType)bool isStructureOrClassType() const { return this->getTypePtr ()->isStructureOrClassType(); } |
295 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isUnionType)bool isUnionType() const { return this->getTypePtr()->isUnionType (); } |
296 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isComplexIntegerType)bool isComplexIntegerType() const { return this->getTypePtr ()->isComplexIntegerType(); } |
297 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isNullPtrType)bool isNullPtrType() const { return this->getTypePtr()-> isNullPtrType(); } |
298 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isDependentType)bool isDependentType() const { return this->getTypePtr()-> isDependentType(); } |
299 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isOverloadableType)bool isOverloadableType() const { return this->getTypePtr( )->isOverloadableType(); } |
300 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isArrayType)bool isArrayType() const { return this->getTypePtr()->isArrayType (); } |
301 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasPointerRepresentation)bool hasPointerRepresentation() const { return this->getTypePtr ()->hasPointerRepresentation(); } |
302 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasObjCPointerRepresentation)bool hasObjCPointerRepresentation() const { return this->getTypePtr ()->hasObjCPointerRepresentation(); } |
303 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasIntegerRepresentation)bool hasIntegerRepresentation() const { return this->getTypePtr ()->hasIntegerRepresentation(); } |
304 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasSignedIntegerRepresentation)bool hasSignedIntegerRepresentation() const { return this-> getTypePtr()->hasSignedIntegerRepresentation(); } |
305 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasUnsignedIntegerRepresentation)bool hasUnsignedIntegerRepresentation() const { return this-> getTypePtr()->hasUnsignedIntegerRepresentation(); } |
306 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasFloatingRepresentation)bool hasFloatingRepresentation() const { return this->getTypePtr ()->hasFloatingRepresentation(); } |
307 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isPromotableIntegerType)bool isPromotableIntegerType() const { return this->getTypePtr ()->isPromotableIntegerType(); } |
308 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSignedIntegerType)bool isSignedIntegerType() const { return this->getTypePtr ()->isSignedIntegerType(); } |
309 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isUnsignedIntegerType)bool isUnsignedIntegerType() const { return this->getTypePtr ()->isUnsignedIntegerType(); } |
310 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSignedIntegerOrEnumerationType)bool isSignedIntegerOrEnumerationType() const { return this-> getTypePtr()->isSignedIntegerOrEnumerationType(); } |
311 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isUnsignedIntegerOrEnumerationType)bool isUnsignedIntegerOrEnumerationType() const { return this ->getTypePtr()->isUnsignedIntegerOrEnumerationType(); } |
312 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isConstantSizeType)bool isConstantSizeType() const { return this->getTypePtr( )->isConstantSizeType(); } |
313 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isSpecifierType)bool isSpecifierType() const { return this->getTypePtr()-> isSpecifierType(); } |
314 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(CXXRecordDecl*, getAsCXXRecordDecl)CXXRecordDecl* getAsCXXRecordDecl() const { return this->getTypePtr ()->getAsCXXRecordDecl(); } |
315 | |
316 | /// \brief Retrieve the proxy-adaptor type. |
317 | /// |
318 | /// This arrow operator is used when CanProxyAdaptor has been specialized |
319 | /// for the given type T. In that case, we reference members of the |
320 | /// CanProxyAdaptor specialization. Otherwise, this operator will be hidden |
321 | /// by the arrow operator in the primary CanProxyAdaptor template. |
322 | const CanProxyAdaptor<T> *operator->() const { |
323 | return static_cast<const CanProxyAdaptor<T> *>(this); |
324 | } |
325 | }; |
326 | |
327 | /// \brief Replacable canonical proxy adaptor class that provides the link |
328 | /// between a canonical type and the accessors of the type. |
329 | /// |
330 | /// The CanProxyAdaptor is a replaceable class template that is instantiated |
331 | /// as part of each canonical proxy type. The primary template merely provides |
332 | /// redirection to the underlying type (T), e.g., @c PointerType. One can |
333 | /// provide specializations of this class template for each underlying type |
334 | /// that provide accessors returning canonical types (@c CanQualType) rather |
335 | /// than the more typical @c QualType, to propagate the notion of "canonical" |
336 | /// through the system. |
337 | template<typename T> |
338 | struct CanProxyAdaptor : CanProxyBase<T> {}; |
339 | |
340 | /// \brief Canonical proxy type returned when retrieving the members of a |
341 | /// canonical type or as the result of the @c CanQual<T>::getAs member |
342 | /// function. |
343 | /// |
344 | /// The CanProxy type mainly exists as a proxy through which operator-> will |
345 | /// look to either map down to a raw T* (e.g., PointerType*) or to a proxy |
346 | /// type that provides canonical-type access to the fields of the type. |
347 | template<typename T> |
348 | class CanProxy : public CanProxyAdaptor<T> { |
349 | public: |
350 | /// \brief Build a NULL proxy. |
351 | CanProxy() = default; |
352 | |
353 | /// \brief Build a proxy to the given canonical type. |
354 | CanProxy(CanQual<T> Stored) { this->Stored = Stored; } |
355 | |
356 | /// \brief Implicit conversion to the stored canonical type. |
357 | operator CanQual<T>() const { return this->Stored; } |
358 | }; |
359 | |
360 | } // namespace clang |
361 | |
362 | namespace llvm { |
363 | |
364 | /// Implement simplify_type for CanQual<T>, so that we can dyn_cast from |
365 | /// CanQual<T> to a specific Type class. We're prefer isa/dyn_cast/cast/etc. |
366 | /// to return smart pointer (proxies?). |
367 | template<typename T> |
368 | struct simplify_type< ::clang::CanQual<T>> { |
369 | using SimpleType = const T *; |
370 | |
371 | static SimpleType getSimplifiedValue(::clang::CanQual<T> Val) { |
372 | return Val.getTypePtr(); |
373 | } |
374 | }; |
375 | |
376 | // Teach SmallPtrSet that CanQual<T> is "basically a pointer". |
377 | template<typename T> |
378 | struct PointerLikeTypeTraits<clang::CanQual<T>> { |
379 | static void *getAsVoidPointer(clang::CanQual<T> P) { |
380 | return P.getAsOpaquePtr(); |
381 | } |
382 | |
383 | static clang::CanQual<T> getFromVoidPointer(void *P) { |
384 | return clang::CanQual<T>::getFromOpaquePtr(P); |
385 | } |
386 | |
387 | // qualifier information is encoded in the low bits. |
388 | enum { NumLowBitsAvailable = 0 }; |
389 | }; |
390 | |
391 | } // namespace llvm |
392 | |
393 | namespace clang { |
394 | |
395 | //----------------------------------------------------------------------------// |
396 | // Canonical proxy adaptors for canonical type nodes. |
397 | //----------------------------------------------------------------------------// |
398 | |
399 | /// \brief Iterator adaptor that turns an iterator over canonical QualTypes |
400 | /// into an iterator over CanQualTypes. |
401 | template <typename InputIterator> |
402 | struct CanTypeIterator |
403 | : llvm::iterator_adaptor_base< |
404 | CanTypeIterator<InputIterator>, InputIterator, |
405 | typename std::iterator_traits<InputIterator>::iterator_category, |
406 | CanQualType, |
407 | typename std::iterator_traits<InputIterator>::difference_type, |
408 | CanProxy<Type>, CanQualType> { |
409 | CanTypeIterator() = default; |
410 | explicit CanTypeIterator(InputIterator Iter) |
411 | : CanTypeIterator::iterator_adaptor_base(std::move(Iter)) {} |
412 | |
413 | CanQualType operator*() const { return CanQualType::CreateUnsafe(*this->I); } |
414 | CanProxy<Type> operator->() const; |
415 | }; |
416 | |
417 | template<> |
418 | struct CanProxyAdaptor<ComplexType> : public CanProxyBase<ComplexType> { |
419 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType)CanQualType getElementType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getElementType()); } |
420 | }; |
421 | |
422 | template<> |
423 | struct CanProxyAdaptor<PointerType> : public CanProxyBase<PointerType> { |
424 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
425 | }; |
426 | |
427 | template<> |
428 | struct CanProxyAdaptor<BlockPointerType> |
429 | : public CanProxyBase<BlockPointerType> { |
430 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
431 | }; |
432 | |
433 | template<> |
434 | struct CanProxyAdaptor<ReferenceType> : public CanProxyBase<ReferenceType> { |
435 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
436 | }; |
437 | |
438 | template<> |
439 | struct CanProxyAdaptor<LValueReferenceType> |
440 | : public CanProxyBase<LValueReferenceType> { |
441 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
442 | }; |
443 | |
444 | template<> |
445 | struct CanProxyAdaptor<RValueReferenceType> |
446 | : public CanProxyBase<RValueReferenceType> { |
447 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
448 | }; |
449 | |
450 | template<> |
451 | struct CanProxyAdaptor<MemberPointerType> |
452 | : public CanProxyBase<MemberPointerType> { |
453 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
454 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const Type *, getClass)const Type * getClass() const { return this->getTypePtr()-> getClass(); } |
455 | }; |
456 | |
457 | // CanProxyAdaptors for arrays are intentionally unimplemented because |
458 | // they are not safe. |
459 | template<> struct CanProxyAdaptor<ArrayType>; |
460 | template<> struct CanProxyAdaptor<ConstantArrayType>; |
461 | template<> struct CanProxyAdaptor<IncompleteArrayType>; |
462 | template<> struct CanProxyAdaptor<VariableArrayType>; |
463 | template<> struct CanProxyAdaptor<DependentSizedArrayType>; |
464 | |
465 | template<> |
466 | struct CanProxyAdaptor<DependentSizedExtVectorType> |
467 | : public CanProxyBase<DependentSizedExtVectorType> { |
468 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType)CanQualType getElementType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getElementType()); } |
469 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const Expr *, getSizeExpr)const Expr * getSizeExpr() const { return this->getTypePtr ()->getSizeExpr(); } |
470 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(SourceLocation, getAttributeLoc)SourceLocation getAttributeLoc() const { return this->getTypePtr ()->getAttributeLoc(); } |
471 | }; |
472 | |
473 | template<> |
474 | struct CanProxyAdaptor<VectorType> : public CanProxyBase<VectorType> { |
475 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType)CanQualType getElementType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getElementType()); } |
476 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumElements)unsigned getNumElements() const { return this->getTypePtr( )->getNumElements(); } |
477 | }; |
478 | |
479 | template<> |
480 | struct CanProxyAdaptor<ExtVectorType> : public CanProxyBase<ExtVectorType> { |
481 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getElementType)CanQualType getElementType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getElementType()); } |
482 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumElements)unsigned getNumElements() const { return this->getTypePtr( )->getNumElements(); } |
483 | }; |
484 | |
485 | template<> |
486 | struct CanProxyAdaptor<FunctionType> : public CanProxyBase<FunctionType> { |
487 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getReturnType)CanQualType getReturnType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getReturnType()); } |
488 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(FunctionType::ExtInfo, getExtInfo)FunctionType::ExtInfo getExtInfo() const { return this->getTypePtr ()->getExtInfo(); } |
489 | }; |
490 | |
491 | template<> |
492 | struct CanProxyAdaptor<FunctionNoProtoType> |
493 | : public CanProxyBase<FunctionNoProtoType> { |
494 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getReturnType)CanQualType getReturnType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getReturnType()); } |
495 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(FunctionType::ExtInfo, getExtInfo)FunctionType::ExtInfo getExtInfo() const { return this->getTypePtr ()->getExtInfo(); } |
496 | }; |
497 | |
498 | template<> |
499 | struct CanProxyAdaptor<FunctionProtoType> |
500 | : public CanProxyBase<FunctionProtoType> { |
501 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getReturnType)CanQualType getReturnType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getReturnType()); } |
502 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(FunctionType::ExtInfo, getExtInfo)FunctionType::ExtInfo getExtInfo() const { return this->getTypePtr ()->getExtInfo(); } |
503 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumParams)unsigned getNumParams() const { return this->getTypePtr()-> getNumParams(); } |
504 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasExtParameterInfos)bool hasExtParameterInfos() const { return this->getTypePtr ()->hasExtParameterInfos(); } |
505 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(ArrayRef<FunctionProtoType::ExtParameterInfo> getExtParameterInfos () const { return this->getTypePtr()->getExtParameterInfos (); } |
506 | ArrayRef<FunctionProtoType::ExtParameterInfo>, getExtParameterInfos)ArrayRef<FunctionProtoType::ExtParameterInfo> getExtParameterInfos () const { return this->getTypePtr()->getExtParameterInfos (); } |
507 | |
508 | CanQualType getParamType(unsigned i) const { |
509 | return CanQualType::CreateUnsafe(this->getTypePtr()->getParamType(i)); |
510 | } |
511 | |
512 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isVariadic)bool isVariadic() const { return this->getTypePtr()->isVariadic (); } |
513 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getTypeQuals)unsigned getTypeQuals() const { return this->getTypePtr()-> getTypeQuals(); } |
514 | |
515 | using param_type_iterator = |
516 | CanTypeIterator<FunctionProtoType::param_type_iterator>; |
517 | |
518 | param_type_iterator param_type_begin() const { |
519 | return param_type_iterator(this->getTypePtr()->param_type_begin()); |
520 | } |
521 | |
522 | param_type_iterator param_type_end() const { |
523 | return param_type_iterator(this->getTypePtr()->param_type_end()); |
524 | } |
525 | |
526 | // Note: canonical function types never have exception specifications |
527 | }; |
528 | |
529 | template<> |
530 | struct CanProxyAdaptor<TypeOfType> : public CanProxyBase<TypeOfType> { |
531 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType)CanQualType getUnderlyingType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getUnderlyingType()); } |
532 | }; |
533 | |
534 | template<> |
535 | struct CanProxyAdaptor<DecltypeType> : public CanProxyBase<DecltypeType> { |
536 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(Expr *, getUnderlyingExpr)Expr * getUnderlyingExpr() const { return this->getTypePtr ()->getUnderlyingExpr(); } |
537 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType)CanQualType getUnderlyingType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getUnderlyingType()); } |
538 | }; |
539 | |
540 | template <> |
541 | struct CanProxyAdaptor<UnaryTransformType> |
542 | : public CanProxyBase<UnaryTransformType> { |
543 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getBaseType)CanQualType getBaseType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getBaseType()); } |
544 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getUnderlyingType)CanQualType getUnderlyingType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getUnderlyingType()); } |
545 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(UnaryTransformType::UTTKind, getUTTKind)UnaryTransformType::UTTKind getUTTKind() const { return this-> getTypePtr()->getUTTKind(); } |
546 | }; |
547 | |
548 | template<> |
549 | struct CanProxyAdaptor<TagType> : public CanProxyBase<TagType> { |
550 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(TagDecl *, getDecl)TagDecl * getDecl() const { return this->getTypePtr()-> getDecl(); } |
551 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined)bool isBeingDefined() const { return this->getTypePtr()-> isBeingDefined(); } |
552 | }; |
553 | |
554 | template<> |
555 | struct CanProxyAdaptor<RecordType> : public CanProxyBase<RecordType> { |
556 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(RecordDecl *, getDecl)RecordDecl * getDecl() const { return this->getTypePtr()-> getDecl(); } |
557 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined)bool isBeingDefined() const { return this->getTypePtr()-> isBeingDefined(); } |
558 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, hasConstFields)bool hasConstFields() const { return this->getTypePtr()-> hasConstFields(); } |
559 | }; |
560 | |
561 | template<> |
562 | struct CanProxyAdaptor<EnumType> : public CanProxyBase<EnumType> { |
563 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(EnumDecl *, getDecl)EnumDecl * getDecl() const { return this->getTypePtr()-> getDecl(); } |
564 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isBeingDefined)bool isBeingDefined() const { return this->getTypePtr()-> isBeingDefined(); } |
565 | }; |
566 | |
567 | template<> |
568 | struct CanProxyAdaptor<TemplateTypeParmType> |
569 | : public CanProxyBase<TemplateTypeParmType> { |
570 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getDepth)unsigned getDepth() const { return this->getTypePtr()-> getDepth(); } |
571 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getIndex)unsigned getIndex() const { return this->getTypePtr()-> getIndex(); } |
572 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isParameterPack)bool isParameterPack() const { return this->getTypePtr()-> isParameterPack(); } |
573 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(TemplateTypeParmDecl *, getDecl)TemplateTypeParmDecl * getDecl() const { return this->getTypePtr ()->getDecl(); } |
574 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(IdentifierInfo *, getIdentifier)IdentifierInfo * getIdentifier() const { return this->getTypePtr ()->getIdentifier(); } |
575 | }; |
576 | |
577 | template<> |
578 | struct CanProxyAdaptor<ObjCObjectType> |
579 | : public CanProxyBase<ObjCObjectType> { |
580 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getBaseType)CanQualType getBaseType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getBaseType()); } |
581 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const ObjCInterfaceDecl *,const ObjCInterfaceDecl * getInterface() const { return this-> getTypePtr()->getInterface(); } |
582 | getInterface)const ObjCInterfaceDecl * getInterface() const { return this-> getTypePtr()->getInterface(); } |
583 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCUnqualifiedId)bool isObjCUnqualifiedId() const { return this->getTypePtr ()->isObjCUnqualifiedId(); } |
584 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCUnqualifiedClass)bool isObjCUnqualifiedClass() const { return this->getTypePtr ()->isObjCUnqualifiedClass(); } |
585 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedId)bool isObjCQualifiedId() const { return this->getTypePtr() ->isObjCQualifiedId(); } |
586 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedClass)bool isObjCQualifiedClass() const { return this->getTypePtr ()->isObjCQualifiedClass(); } |
587 | |
588 | using qual_iterator = ObjCObjectPointerType::qual_iterator; |
589 | |
590 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_begin)qual_iterator qual_begin() const { return this->getTypePtr ()->qual_begin(); } |
591 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_end)qual_iterator qual_end() const { return this->getTypePtr() ->qual_end(); } |
592 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, qual_empty)bool qual_empty() const { return this->getTypePtr()->qual_empty (); } |
593 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumProtocols)unsigned getNumProtocols() const { return this->getTypePtr ()->getNumProtocols(); } |
594 | }; |
595 | |
596 | template<> |
597 | struct CanProxyAdaptor<ObjCObjectPointerType> |
598 | : public CanProxyBase<ObjCObjectPointerType> { |
599 | LLVM_CLANG_CANPROXY_TYPE_ACCESSOR(getPointeeType)CanQualType getPointeeType() const { return CanQualType::CreateUnsafe (this->getTypePtr()->getPointeeType()); } |
600 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(const ObjCInterfaceType *,const ObjCInterfaceType * getInterfaceType() const { return this ->getTypePtr()->getInterfaceType(); } |
601 | getInterfaceType)const ObjCInterfaceType * getInterfaceType() const { return this ->getTypePtr()->getInterfaceType(); } |
602 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCIdType)bool isObjCIdType() const { return this->getTypePtr()-> isObjCIdType(); } |
603 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCClassType)bool isObjCClassType() const { return this->getTypePtr()-> isObjCClassType(); } |
604 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedIdType)bool isObjCQualifiedIdType() const { return this->getTypePtr ()->isObjCQualifiedIdType(); } |
605 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, isObjCQualifiedClassType)bool isObjCQualifiedClassType() const { return this->getTypePtr ()->isObjCQualifiedClassType(); } |
606 | |
607 | using qual_iterator = ObjCObjectPointerType::qual_iterator; |
608 | |
609 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_begin)qual_iterator qual_begin() const { return this->getTypePtr ()->qual_begin(); } |
610 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(qual_iterator, qual_end)qual_iterator qual_end() const { return this->getTypePtr() ->qual_end(); } |
611 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(bool, qual_empty)bool qual_empty() const { return this->getTypePtr()->qual_empty (); } |
612 | LLVM_CLANG_CANPROXY_SIMPLE_ACCESSOR(unsigned, getNumProtocols)unsigned getNumProtocols() const { return this->getTypePtr ()->getNumProtocols(); } |
613 | }; |
614 | |
615 | //----------------------------------------------------------------------------// |
616 | // Method and function definitions |
617 | //----------------------------------------------------------------------------// |
618 | template<typename T> |
619 | inline CanQual<T> CanQual<T>::getUnqualifiedType() const { |
620 | return CanQual<T>::CreateUnsafe(Stored.getLocalUnqualifiedType()); |
621 | } |
622 | |
623 | template<typename T> |
624 | inline CanQual<Type> CanQual<T>::getNonReferenceType() const { |
625 | if (CanQual<ReferenceType> RefType = getAs<ReferenceType>()) |
626 | return RefType->getPointeeType(); |
627 | else |
628 | return *this; |
629 | } |
630 | |
631 | template<typename T> |
632 | CanQual<T> CanQual<T>::getFromOpaquePtr(void *Ptr) { |
633 | CanQual<T> Result; |
634 | Result.Stored = QualType::getFromOpaquePtr(Ptr); |
635 | assert((!Result || Result.Stored.getAsOpaquePtr() == (void*)-1 ||(static_cast <bool> ((!Result || Result.Stored.getAsOpaquePtr () == (void*)-1 || Result.Stored.isCanonical()) && "Type is not canonical!" ) ? void (0) : __assert_fail ("(!Result || Result.Stored.getAsOpaquePtr() == (void*)-1 || Result.Stored.isCanonical()) && \"Type is not canonical!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/CanonicalType.h" , 636, __extension__ __PRETTY_FUNCTION__)) |
636 | Result.Stored.isCanonical()) && "Type is not canonical!")(static_cast <bool> ((!Result || Result.Stored.getAsOpaquePtr () == (void*)-1 || Result.Stored.isCanonical()) && "Type is not canonical!" ) ? void (0) : __assert_fail ("(!Result || Result.Stored.getAsOpaquePtr() == (void*)-1 || Result.Stored.isCanonical()) && \"Type is not canonical!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/CanonicalType.h" , 636, __extension__ __PRETTY_FUNCTION__)); |
637 | return Result; |
638 | } |
639 | |
640 | template<typename T> |
641 | CanQual<T> CanQual<T>::CreateUnsafe(QualType Other) { |
642 | assert((Other.isNull() || Other.isCanonical()) && "Type is not canonical!")(static_cast <bool> ((Other.isNull() || Other.isCanonical ()) && "Type is not canonical!") ? void (0) : __assert_fail ("(Other.isNull() || Other.isCanonical()) && \"Type is not canonical!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/CanonicalType.h" , 642, __extension__ __PRETTY_FUNCTION__)); |
643 | assert((Other.isNull() || isa<T>(Other.getTypePtr())) &&(static_cast <bool> ((Other.isNull() || isa<T>(Other .getTypePtr())) && "Dynamic type does not meet the static type's requires" ) ? void (0) : __assert_fail ("(Other.isNull() || isa<T>(Other.getTypePtr())) && \"Dynamic type does not meet the static type's requires\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/CanonicalType.h" , 644, __extension__ __PRETTY_FUNCTION__)) |
644 | "Dynamic type does not meet the static type's requires")(static_cast <bool> ((Other.isNull() || isa<T>(Other .getTypePtr())) && "Dynamic type does not meet the static type's requires" ) ? void (0) : __assert_fail ("(Other.isNull() || isa<T>(Other.getTypePtr())) && \"Dynamic type does not meet the static type's requires\"" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/CanonicalType.h" , 644, __extension__ __PRETTY_FUNCTION__)); |
645 | CanQual<T> Result; |
646 | Result.Stored = Other; |
647 | return Result; |
648 | } |
649 | |
650 | template<typename T> |
651 | template<typename U> |
652 | CanProxy<U> CanQual<T>::getAs() const { |
653 | static_assert(!TypeIsArrayType<T>::value, |
654 | "ArrayType cannot be used with getAs!"); |
655 | |
656 | if (Stored.isNull()) |
657 | return CanProxy<U>(); |
658 | |
659 | if (isa<U>(Stored.getTypePtr())) |
660 | return CanQual<U>::CreateUnsafe(Stored); |
661 | |
662 | return CanProxy<U>(); |
663 | } |
664 | |
665 | template<typename T> |
666 | template<typename U> |
667 | CanProxy<U> CanQual<T>::castAs() const { |
668 | static_assert(!TypeIsArrayType<U>::value, |
669 | "ArrayType cannot be used with castAs!"); |
670 | |
671 | assert(!Stored.isNull() && isa<U>(Stored.getTypePtr()))(static_cast <bool> (!Stored.isNull() && isa< U>(Stored.getTypePtr())) ? void (0) : __assert_fail ("!Stored.isNull() && isa<U>(Stored.getTypePtr())" , "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/CanonicalType.h" , 671, __extension__ __PRETTY_FUNCTION__)); |
672 | return CanQual<U>::CreateUnsafe(Stored); |
673 | } |
674 | |
675 | template<typename T> |
676 | CanProxy<T> CanQual<T>::operator->() const { |
677 | return CanProxy<T>(*this); |
678 | } |
679 | |
680 | template <typename InputIterator> |
681 | CanProxy<Type> CanTypeIterator<InputIterator>::operator->() const { |
682 | return CanProxy<Type>(*this); |
683 | } |
684 | |
685 | } // namespace clang |
686 | |
687 | #endif // LLVM_CLANG_AST_CANONICALTYPE_H |