File: | clang/lib/Sema/SemaDecl.cpp |
Warning: | line 12656, column 16 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// | ||||||
2 | // | ||||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||||
6 | // | ||||||
7 | //===----------------------------------------------------------------------===// | ||||||
8 | // | ||||||
9 | // This file implements semantic analysis for declarations. | ||||||
10 | // | ||||||
11 | //===----------------------------------------------------------------------===// | ||||||
12 | |||||||
13 | #include "TypeLocBuilder.h" | ||||||
14 | #include "clang/AST/ASTConsumer.h" | ||||||
15 | #include "clang/AST/ASTContext.h" | ||||||
16 | #include "clang/AST/ASTLambda.h" | ||||||
17 | #include "clang/AST/CXXInheritance.h" | ||||||
18 | #include "clang/AST/CharUnits.h" | ||||||
19 | #include "clang/AST/CommentDiagnostic.h" | ||||||
20 | #include "clang/AST/DeclCXX.h" | ||||||
21 | #include "clang/AST/DeclObjC.h" | ||||||
22 | #include "clang/AST/DeclTemplate.h" | ||||||
23 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||||
24 | #include "clang/AST/ExprCXX.h" | ||||||
25 | #include "clang/AST/NonTrivialTypeVisitor.h" | ||||||
26 | #include "clang/AST/StmtCXX.h" | ||||||
27 | #include "clang/Basic/Builtins.h" | ||||||
28 | #include "clang/Basic/PartialDiagnostic.h" | ||||||
29 | #include "clang/Basic/SourceManager.h" | ||||||
30 | #include "clang/Basic/TargetInfo.h" | ||||||
31 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | ||||||
32 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | ||||||
33 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | ||||||
34 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | ||||||
35 | #include "clang/Sema/CXXFieldCollector.h" | ||||||
36 | #include "clang/Sema/DeclSpec.h" | ||||||
37 | #include "clang/Sema/DelayedDiagnostic.h" | ||||||
38 | #include "clang/Sema/Initialization.h" | ||||||
39 | #include "clang/Sema/Lookup.h" | ||||||
40 | #include "clang/Sema/ParsedTemplate.h" | ||||||
41 | #include "clang/Sema/Scope.h" | ||||||
42 | #include "clang/Sema/ScopeInfo.h" | ||||||
43 | #include "clang/Sema/SemaInternal.h" | ||||||
44 | #include "clang/Sema/Template.h" | ||||||
45 | #include "llvm/ADT/SmallString.h" | ||||||
46 | #include "llvm/ADT/Triple.h" | ||||||
47 | #include <algorithm> | ||||||
48 | #include <cstring> | ||||||
49 | #include <functional> | ||||||
50 | |||||||
51 | using namespace clang; | ||||||
52 | using namespace sema; | ||||||
53 | |||||||
54 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | ||||||
55 | if (OwnedType) { | ||||||
56 | Decl *Group[2] = { OwnedType, Ptr }; | ||||||
57 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | ||||||
58 | } | ||||||
59 | |||||||
60 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | ||||||
61 | } | ||||||
62 | |||||||
63 | namespace { | ||||||
64 | |||||||
65 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { | ||||||
66 | public: | ||||||
67 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | ||||||
68 | bool AllowTemplates = false, | ||||||
69 | bool AllowNonTemplates = true) | ||||||
70 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | ||||||
71 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | ||||||
72 | WantExpressionKeywords = false; | ||||||
73 | WantCXXNamedCasts = false; | ||||||
74 | WantRemainingKeywords = false; | ||||||
75 | } | ||||||
76 | |||||||
77 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||
78 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | ||||||
79 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | ||||||
80 | return false; | ||||||
81 | |||||||
82 | if (getAsTypeTemplateDecl(ND)) | ||||||
83 | return AllowTemplates; | ||||||
84 | |||||||
85 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | ||||||
86 | if (!IsType) | ||||||
87 | return false; | ||||||
88 | |||||||
89 | if (AllowNonTemplates) | ||||||
90 | return true; | ||||||
91 | |||||||
92 | // An injected-class-name of a class template (specialization) is valid | ||||||
93 | // as a template or as a non-template. | ||||||
94 | if (AllowTemplates) { | ||||||
95 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | ||||||
96 | if (!RD || !RD->isInjectedClassName()) | ||||||
97 | return false; | ||||||
98 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | ||||||
99 | return RD->getDescribedClassTemplate() || | ||||||
100 | isa<ClassTemplateSpecializationDecl>(RD); | ||||||
101 | } | ||||||
102 | |||||||
103 | return false; | ||||||
104 | } | ||||||
105 | |||||||
106 | return !WantClassName && candidate.isKeyword(); | ||||||
107 | } | ||||||
108 | |||||||
109 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||
110 | return std::make_unique<TypeNameValidatorCCC>(*this); | ||||||
111 | } | ||||||
112 | |||||||
113 | private: | ||||||
114 | bool AllowInvalidDecl; | ||||||
115 | bool WantClassName; | ||||||
116 | bool AllowTemplates; | ||||||
117 | bool AllowNonTemplates; | ||||||
118 | }; | ||||||
119 | |||||||
120 | } // end anonymous namespace | ||||||
121 | |||||||
122 | /// Determine whether the token kind starts a simple-type-specifier. | ||||||
123 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | ||||||
124 | switch (Kind) { | ||||||
125 | // FIXME: Take into account the current language when deciding whether a | ||||||
126 | // token kind is a valid type specifier | ||||||
127 | case tok::kw_short: | ||||||
128 | case tok::kw_long: | ||||||
129 | case tok::kw___int64: | ||||||
130 | case tok::kw___int128: | ||||||
131 | case tok::kw_signed: | ||||||
132 | case tok::kw_unsigned: | ||||||
133 | case tok::kw_void: | ||||||
134 | case tok::kw_char: | ||||||
135 | case tok::kw_int: | ||||||
136 | case tok::kw_half: | ||||||
137 | case tok::kw_float: | ||||||
138 | case tok::kw_double: | ||||||
139 | case tok::kw__Float16: | ||||||
140 | case tok::kw___float128: | ||||||
141 | case tok::kw_wchar_t: | ||||||
142 | case tok::kw_bool: | ||||||
143 | case tok::kw___underlying_type: | ||||||
144 | case tok::kw___auto_type: | ||||||
145 | return true; | ||||||
146 | |||||||
147 | case tok::annot_typename: | ||||||
148 | case tok::kw_char16_t: | ||||||
149 | case tok::kw_char32_t: | ||||||
150 | case tok::kw_typeof: | ||||||
151 | case tok::annot_decltype: | ||||||
152 | case tok::kw_decltype: | ||||||
153 | return getLangOpts().CPlusPlus; | ||||||
154 | |||||||
155 | case tok::kw_char8_t: | ||||||
156 | return getLangOpts().Char8; | ||||||
157 | |||||||
158 | default: | ||||||
159 | break; | ||||||
160 | } | ||||||
161 | |||||||
162 | return false; | ||||||
163 | } | ||||||
164 | |||||||
165 | namespace { | ||||||
166 | enum class UnqualifiedTypeNameLookupResult { | ||||||
167 | NotFound, | ||||||
168 | FoundNonType, | ||||||
169 | FoundType | ||||||
170 | }; | ||||||
171 | } // end anonymous namespace | ||||||
172 | |||||||
173 | /// Tries to perform unqualified lookup of the type decls in bases for | ||||||
174 | /// dependent class. | ||||||
175 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | ||||||
176 | /// type decl, \a FoundType if only type decls are found. | ||||||
177 | static UnqualifiedTypeNameLookupResult | ||||||
178 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | ||||||
179 | SourceLocation NameLoc, | ||||||
180 | const CXXRecordDecl *RD) { | ||||||
181 | if (!RD->hasDefinition()) | ||||||
182 | return UnqualifiedTypeNameLookupResult::NotFound; | ||||||
183 | // Look for type decls in base classes. | ||||||
184 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||||
185 | UnqualifiedTypeNameLookupResult::NotFound; | ||||||
186 | for (const auto &Base : RD->bases()) { | ||||||
187 | const CXXRecordDecl *BaseRD = nullptr; | ||||||
188 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | ||||||
189 | BaseRD = BaseTT->getAsCXXRecordDecl(); | ||||||
190 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | ||||||
191 | // Look for type decls in dependent base classes that have known primary | ||||||
192 | // templates. | ||||||
193 | if (!TST || !TST->isDependentType()) | ||||||
194 | continue; | ||||||
195 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | ||||||
196 | if (!TD) | ||||||
197 | continue; | ||||||
198 | if (auto *BasePrimaryTemplate = | ||||||
199 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | ||||||
200 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||||
201 | BaseRD = BasePrimaryTemplate; | ||||||
202 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | ||||||
203 | if (const ClassTemplatePartialSpecializationDecl *PS = | ||||||
204 | CTD->findPartialSpecialization(Base.getType())) | ||||||
205 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||||
206 | BaseRD = PS; | ||||||
207 | } | ||||||
208 | } | ||||||
209 | } | ||||||
210 | if (BaseRD) { | ||||||
211 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | ||||||
212 | if (!isa<TypeDecl>(ND)) | ||||||
213 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||||
214 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||||
215 | } | ||||||
216 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | ||||||
217 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | ||||||
218 | case UnqualifiedTypeNameLookupResult::FoundNonType: | ||||||
219 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||||
220 | case UnqualifiedTypeNameLookupResult::FoundType: | ||||||
221 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||||
222 | break; | ||||||
223 | case UnqualifiedTypeNameLookupResult::NotFound: | ||||||
224 | break; | ||||||
225 | } | ||||||
226 | } | ||||||
227 | } | ||||||
228 | } | ||||||
229 | |||||||
230 | return FoundTypeDecl; | ||||||
231 | } | ||||||
232 | |||||||
233 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | ||||||
234 | const IdentifierInfo &II, | ||||||
235 | SourceLocation NameLoc) { | ||||||
236 | // Lookup in the parent class template context, if any. | ||||||
237 | const CXXRecordDecl *RD = nullptr; | ||||||
238 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||||
239 | UnqualifiedTypeNameLookupResult::NotFound; | ||||||
240 | for (DeclContext *DC = S.CurContext; | ||||||
241 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | ||||||
242 | DC = DC->getParent()) { | ||||||
243 | // Look for type decls in dependent base classes that have known primary | ||||||
244 | // templates. | ||||||
245 | RD = dyn_cast<CXXRecordDecl>(DC); | ||||||
246 | if (RD && RD->getDescribedClassTemplate()) | ||||||
247 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | ||||||
248 | } | ||||||
249 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | ||||||
250 | return nullptr; | ||||||
251 | |||||||
252 | // We found some types in dependent base classes. Recover as if the user | ||||||
253 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | ||||||
254 | // lookup during template instantiation. | ||||||
255 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; | ||||||
256 | |||||||
257 | ASTContext &Context = S.Context; | ||||||
258 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | ||||||
259 | cast<Type>(Context.getRecordType(RD))); | ||||||
260 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | ||||||
261 | |||||||
262 | CXXScopeSpec SS; | ||||||
263 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
264 | |||||||
265 | TypeLocBuilder Builder; | ||||||
266 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||||
267 | DepTL.setNameLoc(NameLoc); | ||||||
268 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
269 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||
270 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
271 | } | ||||||
272 | |||||||
273 | /// If the identifier refers to a type name within this scope, | ||||||
274 | /// return the declaration of that type. | ||||||
275 | /// | ||||||
276 | /// This routine performs ordinary name lookup of the identifier II | ||||||
277 | /// within the given scope, with optional C++ scope specifier SS, to | ||||||
278 | /// determine whether the name refers to a type. If so, returns an | ||||||
279 | /// opaque pointer (actually a QualType) corresponding to that | ||||||
280 | /// type. Otherwise, returns NULL. | ||||||
281 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | ||||||
282 | Scope *S, CXXScopeSpec *SS, | ||||||
283 | bool isClassName, bool HasTrailingDot, | ||||||
284 | ParsedType ObjectTypePtr, | ||||||
285 | bool IsCtorOrDtorName, | ||||||
286 | bool WantNontrivialTypeSourceInfo, | ||||||
287 | bool IsClassTemplateDeductionContext, | ||||||
288 | IdentifierInfo **CorrectedII) { | ||||||
289 | // FIXME: Consider allowing this outside C++1z mode as an extension. | ||||||
290 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | ||||||
291 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | ||||||
292 | !isClassName && !HasTrailingDot; | ||||||
293 | |||||||
294 | // Determine where we will perform name lookup. | ||||||
295 | DeclContext *LookupCtx = nullptr; | ||||||
296 | if (ObjectTypePtr) { | ||||||
297 | QualType ObjectType = ObjectTypePtr.get(); | ||||||
298 | if (ObjectType->isRecordType()) | ||||||
299 | LookupCtx = computeDeclContext(ObjectType); | ||||||
300 | } else if (SS && SS->isNotEmpty()) { | ||||||
301 | LookupCtx = computeDeclContext(*SS, false); | ||||||
302 | |||||||
303 | if (!LookupCtx) { | ||||||
304 | if (isDependentScopeSpecifier(*SS)) { | ||||||
305 | // C++ [temp.res]p3: | ||||||
306 | // A qualified-id that refers to a type and in which the | ||||||
307 | // nested-name-specifier depends on a template-parameter (14.6.2) | ||||||
308 | // shall be prefixed by the keyword typename to indicate that the | ||||||
309 | // qualified-id denotes a type, forming an | ||||||
310 | // elaborated-type-specifier (7.1.5.3). | ||||||
311 | // | ||||||
312 | // We therefore do not perform any name lookup if the result would | ||||||
313 | // refer to a member of an unknown specialization. | ||||||
314 | if (!isClassName && !IsCtorOrDtorName) | ||||||
315 | return nullptr; | ||||||
316 | |||||||
317 | // We know from the grammar that this name refers to a type, | ||||||
318 | // so build a dependent node to describe the type. | ||||||
319 | if (WantNontrivialTypeSourceInfo) | ||||||
320 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | ||||||
321 | |||||||
322 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | ||||||
323 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | ||||||
324 | II, NameLoc); | ||||||
325 | return ParsedType::make(T); | ||||||
326 | } | ||||||
327 | |||||||
328 | return nullptr; | ||||||
329 | } | ||||||
330 | |||||||
331 | if (!LookupCtx->isDependentContext() && | ||||||
332 | RequireCompleteDeclContext(*SS, LookupCtx)) | ||||||
333 | return nullptr; | ||||||
334 | } | ||||||
335 | |||||||
336 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | ||||||
337 | // lookup for class-names. | ||||||
338 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | ||||||
339 | LookupOrdinaryName; | ||||||
340 | LookupResult Result(*this, &II, NameLoc, Kind); | ||||||
341 | if (LookupCtx) { | ||||||
342 | // Perform "qualified" name lookup into the declaration context we | ||||||
343 | // computed, which is either the type of the base of a member access | ||||||
344 | // expression or the declaration context associated with a prior | ||||||
345 | // nested-name-specifier. | ||||||
346 | LookupQualifiedName(Result, LookupCtx); | ||||||
347 | |||||||
348 | if (ObjectTypePtr && Result.empty()) { | ||||||
349 | // C++ [basic.lookup.classref]p3: | ||||||
350 | // If the unqualified-id is ~type-name, the type-name is looked up | ||||||
351 | // in the context of the entire postfix-expression. If the type T of | ||||||
352 | // the object expression is of a class type C, the type-name is also | ||||||
353 | // looked up in the scope of class C. At least one of the lookups shall | ||||||
354 | // find a name that refers to (possibly cv-qualified) T. | ||||||
355 | LookupName(Result, S); | ||||||
356 | } | ||||||
357 | } else { | ||||||
358 | // Perform unqualified name lookup. | ||||||
359 | LookupName(Result, S); | ||||||
360 | |||||||
361 | // For unqualified lookup in a class template in MSVC mode, look into | ||||||
362 | // dependent base classes where the primary class template is known. | ||||||
363 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | ||||||
364 | if (ParsedType TypeInBase = | ||||||
365 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | ||||||
366 | return TypeInBase; | ||||||
367 | } | ||||||
368 | } | ||||||
369 | |||||||
370 | NamedDecl *IIDecl = nullptr; | ||||||
371 | switch (Result.getResultKind()) { | ||||||
372 | case LookupResult::NotFound: | ||||||
373 | case LookupResult::NotFoundInCurrentInstantiation: | ||||||
374 | if (CorrectedII) { | ||||||
375 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | ||||||
376 | AllowDeducedTemplate); | ||||||
377 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | ||||||
378 | S, SS, CCC, CTK_ErrorRecovery); | ||||||
379 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | ||||||
380 | TemplateTy Template; | ||||||
381 | bool MemberOfUnknownSpecialization; | ||||||
382 | UnqualifiedId TemplateName; | ||||||
383 | TemplateName.setIdentifier(NewII, NameLoc); | ||||||
384 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | ||||||
385 | CXXScopeSpec NewSS, *NewSSPtr = SS; | ||||||
386 | if (SS && NNS) { | ||||||
387 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
388 | NewSSPtr = &NewSS; | ||||||
389 | } | ||||||
390 | if (Correction && (NNS || NewII != &II) && | ||||||
391 | // Ignore a correction to a template type as the to-be-corrected | ||||||
392 | // identifier is not a template (typo correction for template names | ||||||
393 | // is handled elsewhere). | ||||||
394 | !(getLangOpts().CPlusPlus && NewSSPtr && | ||||||
395 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | ||||||
396 | Template, MemberOfUnknownSpecialization))) { | ||||||
397 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | ||||||
398 | isClassName, HasTrailingDot, ObjectTypePtr, | ||||||
399 | IsCtorOrDtorName, | ||||||
400 | WantNontrivialTypeSourceInfo, | ||||||
401 | IsClassTemplateDeductionContext); | ||||||
402 | if (Ty) { | ||||||
403 | diagnoseTypo(Correction, | ||||||
404 | PDiag(diag::err_unknown_type_or_class_name_suggest) | ||||||
405 | << Result.getLookupName() << isClassName); | ||||||
406 | if (SS && NNS) | ||||||
407 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
408 | *CorrectedII = NewII; | ||||||
409 | return Ty; | ||||||
410 | } | ||||||
411 | } | ||||||
412 | } | ||||||
413 | // If typo correction failed or was not performed, fall through | ||||||
414 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
415 | case LookupResult::FoundOverloaded: | ||||||
416 | case LookupResult::FoundUnresolvedValue: | ||||||
417 | Result.suppressDiagnostics(); | ||||||
418 | return nullptr; | ||||||
419 | |||||||
420 | case LookupResult::Ambiguous: | ||||||
421 | // Recover from type-hiding ambiguities by hiding the type. We'll | ||||||
422 | // do the lookup again when looking for an object, and we can | ||||||
423 | // diagnose the error then. If we don't do this, then the error | ||||||
424 | // about hiding the type will be immediately followed by an error | ||||||
425 | // that only makes sense if the identifier was treated like a type. | ||||||
426 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | ||||||
427 | Result.suppressDiagnostics(); | ||||||
428 | return nullptr; | ||||||
429 | } | ||||||
430 | |||||||
431 | // Look to see if we have a type anywhere in the list of results. | ||||||
432 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | ||||||
433 | Res != ResEnd; ++Res) { | ||||||
434 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || | ||||||
435 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { | ||||||
436 | if (!IIDecl || | ||||||
437 | (*Res)->getLocation().getRawEncoding() < | ||||||
438 | IIDecl->getLocation().getRawEncoding()) | ||||||
439 | IIDecl = *Res; | ||||||
440 | } | ||||||
441 | } | ||||||
442 | |||||||
443 | if (!IIDecl) { | ||||||
444 | // None of the entities we found is a type, so there is no way | ||||||
445 | // to even assume that the result is a type. In this case, don't | ||||||
446 | // complain about the ambiguity. The parser will either try to | ||||||
447 | // perform this lookup again (e.g., as an object name), which | ||||||
448 | // will produce the ambiguity, or will complain that it expected | ||||||
449 | // a type name. | ||||||
450 | Result.suppressDiagnostics(); | ||||||
451 | return nullptr; | ||||||
452 | } | ||||||
453 | |||||||
454 | // We found a type within the ambiguous lookup; diagnose the | ||||||
455 | // ambiguity and then return that type. This might be the right | ||||||
456 | // answer, or it might not be, but it suppresses any attempt to | ||||||
457 | // perform the name lookup again. | ||||||
458 | break; | ||||||
459 | |||||||
460 | case LookupResult::Found: | ||||||
461 | IIDecl = Result.getFoundDecl(); | ||||||
462 | break; | ||||||
463 | } | ||||||
464 | |||||||
465 | assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void > (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 465, __PRETTY_FUNCTION__)); | ||||||
466 | |||||||
467 | QualType T; | ||||||
468 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | ||||||
469 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | ||||||
470 | // instead names the constructors of the class, except when naming a class. | ||||||
471 | // This is ill-formed when we're not actually forming a ctor or dtor name. | ||||||
472 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | ||||||
473 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | ||||||
474 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | ||||||
475 | FoundRD->isInjectedClassName() && | ||||||
476 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | ||||||
477 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | ||||||
478 | << &II << /*Type*/1; | ||||||
479 | |||||||
480 | DiagnoseUseOfDecl(IIDecl, NameLoc); | ||||||
481 | |||||||
482 | T = Context.getTypeDeclType(TD); | ||||||
483 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | ||||||
484 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | ||||||
485 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | ||||||
486 | if (!HasTrailingDot) | ||||||
487 | T = Context.getObjCInterfaceType(IDecl); | ||||||
488 | } else if (AllowDeducedTemplate) { | ||||||
489 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) | ||||||
490 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | ||||||
491 | QualType(), false); | ||||||
492 | } | ||||||
493 | |||||||
494 | if (T.isNull()) { | ||||||
495 | // If it's not plausibly a type, suppress diagnostics. | ||||||
496 | Result.suppressDiagnostics(); | ||||||
497 | return nullptr; | ||||||
498 | } | ||||||
499 | |||||||
500 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | ||||||
501 | // constructor or destructor name (in such a case, the scope specifier | ||||||
502 | // will be attached to the enclosing Expr or Decl node). | ||||||
503 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | ||||||
504 | !isa<ObjCInterfaceDecl>(IIDecl)) { | ||||||
505 | if (WantNontrivialTypeSourceInfo) { | ||||||
506 | // Construct a type with type-source information. | ||||||
507 | TypeLocBuilder Builder; | ||||||
508 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||||
509 | |||||||
510 | T = getElaboratedType(ETK_None, *SS, T); | ||||||
511 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||||
512 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
513 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | ||||||
514 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
515 | } else { | ||||||
516 | T = getElaboratedType(ETK_None, *SS, T); | ||||||
517 | } | ||||||
518 | } | ||||||
519 | |||||||
520 | return ParsedType::make(T); | ||||||
521 | } | ||||||
522 | |||||||
523 | // Builds a fake NNS for the given decl context. | ||||||
524 | static NestedNameSpecifier * | ||||||
525 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | ||||||
526 | for (;; DC = DC->getLookupParent()) { | ||||||
527 | DC = DC->getPrimaryContext(); | ||||||
528 | auto *ND = dyn_cast<NamespaceDecl>(DC); | ||||||
529 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | ||||||
530 | return NestedNameSpecifier::Create(Context, nullptr, ND); | ||||||
531 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||||
532 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||||
533 | RD->getTypeForDecl()); | ||||||
534 | else if (isa<TranslationUnitDecl>(DC)) | ||||||
535 | return NestedNameSpecifier::GlobalSpecifier(Context); | ||||||
536 | } | ||||||
537 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 537); | ||||||
538 | } | ||||||
539 | |||||||
540 | /// Find the parent class with dependent bases of the innermost enclosing method | ||||||
541 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | ||||||
542 | /// up allowing unqualified dependent type names at class-level, which MSVC | ||||||
543 | /// correctly rejects. | ||||||
544 | static const CXXRecordDecl * | ||||||
545 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | ||||||
546 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | ||||||
547 | DC = DC->getPrimaryContext(); | ||||||
548 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||||
549 | if (MD->getParent()->hasAnyDependentBases()) | ||||||
550 | return MD->getParent(); | ||||||
551 | } | ||||||
552 | return nullptr; | ||||||
553 | } | ||||||
554 | |||||||
555 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | ||||||
556 | SourceLocation NameLoc, | ||||||
557 | bool IsTemplateTypeArg) { | ||||||
558 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 558, __PRETTY_FUNCTION__)); | ||||||
559 | |||||||
560 | NestedNameSpecifier *NNS = nullptr; | ||||||
561 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | ||||||
562 | // If we weren't able to parse a default template argument, delay lookup | ||||||
563 | // until instantiation time by making a non-dependent DependentTypeName. We | ||||||
564 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | ||||||
565 | // lookup is retried. | ||||||
566 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | ||||||
567 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | ||||||
568 | // name specifiers. | ||||||
569 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | ||||||
570 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | ||||||
571 | } else if (const CXXRecordDecl *RD = | ||||||
572 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | ||||||
573 | // Build a DependentNameType that will perform lookup into RD at | ||||||
574 | // instantiation time. | ||||||
575 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||||
576 | RD->getTypeForDecl()); | ||||||
577 | |||||||
578 | // Diagnose that this identifier was undeclared, and retry the lookup during | ||||||
579 | // template instantiation. | ||||||
580 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | ||||||
581 | << RD; | ||||||
582 | } else { | ||||||
583 | // This is not a situation that we should recover from. | ||||||
584 | return ParsedType(); | ||||||
585 | } | ||||||
586 | |||||||
587 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | ||||||
588 | |||||||
589 | // Build type location information. We synthesized the qualifier, so we have | ||||||
590 | // to build a fake NestedNameSpecifierLoc. | ||||||
591 | NestedNameSpecifierLocBuilder NNSLocBuilder; | ||||||
592 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
593 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | ||||||
594 | |||||||
595 | TypeLocBuilder Builder; | ||||||
596 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||||
597 | DepTL.setNameLoc(NameLoc); | ||||||
598 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
599 | DepTL.setQualifierLoc(QualifierLoc); | ||||||
600 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
601 | } | ||||||
602 | |||||||
603 | /// isTagName() - This method is called *for error recovery purposes only* | ||||||
604 | /// to determine if the specified name is a valid tag name ("struct foo"). If | ||||||
605 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | ||||||
606 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | ||||||
607 | /// cases in C where the user forgot to specify the tag. | ||||||
608 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | ||||||
609 | // Do a tag name lookup in this scope. | ||||||
610 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | ||||||
611 | LookupName(R, S, false); | ||||||
612 | R.suppressDiagnostics(); | ||||||
613 | if (R.getResultKind() == LookupResult::Found) | ||||||
614 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | ||||||
615 | switch (TD->getTagKind()) { | ||||||
616 | case TTK_Struct: return DeclSpec::TST_struct; | ||||||
617 | case TTK_Interface: return DeclSpec::TST_interface; | ||||||
618 | case TTK_Union: return DeclSpec::TST_union; | ||||||
619 | case TTK_Class: return DeclSpec::TST_class; | ||||||
620 | case TTK_Enum: return DeclSpec::TST_enum; | ||||||
621 | } | ||||||
622 | } | ||||||
623 | |||||||
624 | return DeclSpec::TST_unspecified; | ||||||
625 | } | ||||||
626 | |||||||
627 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | ||||||
628 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | ||||||
629 | /// then downgrade the missing typename error to a warning. | ||||||
630 | /// This is needed for MSVC compatibility; Example: | ||||||
631 | /// @code | ||||||
632 | /// template<class T> class A { | ||||||
633 | /// public: | ||||||
634 | /// typedef int TYPE; | ||||||
635 | /// }; | ||||||
636 | /// template<class T> class B : public A<T> { | ||||||
637 | /// public: | ||||||
638 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | ||||||
639 | /// }; | ||||||
640 | /// @endcode | ||||||
641 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | ||||||
642 | if (CurContext->isRecord()) { | ||||||
643 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | ||||||
644 | return true; | ||||||
645 | |||||||
646 | const Type *Ty = SS->getScopeRep()->getAsType(); | ||||||
647 | |||||||
648 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | ||||||
649 | for (const auto &Base : RD->bases()) | ||||||
650 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | ||||||
651 | return true; | ||||||
652 | return S->isFunctionPrototypeScope(); | ||||||
653 | } | ||||||
654 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | ||||||
655 | } | ||||||
656 | |||||||
657 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | ||||||
658 | SourceLocation IILoc, | ||||||
659 | Scope *S, | ||||||
660 | CXXScopeSpec *SS, | ||||||
661 | ParsedType &SuggestedType, | ||||||
662 | bool IsTemplateName) { | ||||||
663 | // Don't report typename errors for editor placeholders. | ||||||
664 | if (II->isEditorPlaceholder()) | ||||||
665 | return; | ||||||
666 | // We don't have anything to suggest (yet). | ||||||
667 | SuggestedType = nullptr; | ||||||
668 | |||||||
669 | // There may have been a typo in the name of the type. Look up typo | ||||||
670 | // results, in case we have something that we can suggest. | ||||||
671 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | ||||||
672 | /*AllowTemplates=*/IsTemplateName, | ||||||
673 | /*AllowNonTemplates=*/!IsTemplateName); | ||||||
674 | if (TypoCorrection Corrected = | ||||||
675 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | ||||||
676 | CCC, CTK_ErrorRecovery)) { | ||||||
677 | // FIXME: Support error recovery for the template-name case. | ||||||
678 | bool CanRecover = !IsTemplateName; | ||||||
679 | if (Corrected.isKeyword()) { | ||||||
680 | // We corrected to a keyword. | ||||||
681 | diagnoseTypo(Corrected, | ||||||
682 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||||
683 | : diag::err_unknown_typename_suggest) | ||||||
684 | << II); | ||||||
685 | II = Corrected.getCorrectionAsIdentifierInfo(); | ||||||
686 | } else { | ||||||
687 | // We found a similarly-named type or interface; suggest that. | ||||||
688 | if (!SS || !SS->isSet()) { | ||||||
689 | diagnoseTypo(Corrected, | ||||||
690 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||||
691 | : diag::err_unknown_typename_suggest) | ||||||
692 | << II, CanRecover); | ||||||
693 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | ||||||
694 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||
695 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||||
696 | II->getName().equals(CorrectedStr); | ||||||
697 | diagnoseTypo(Corrected, | ||||||
698 | PDiag(IsTemplateName | ||||||
699 | ? diag::err_no_member_template_suggest | ||||||
700 | : diag::err_unknown_nested_typename_suggest) | ||||||
701 | << II << DC << DroppedSpecifier << SS->getRange(), | ||||||
702 | CanRecover); | ||||||
703 | } else { | ||||||
704 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 704); | ||||||
705 | } | ||||||
706 | |||||||
707 | if (!CanRecover) | ||||||
708 | return; | ||||||
709 | |||||||
710 | CXXScopeSpec tmpSS; | ||||||
711 | if (Corrected.getCorrectionSpecifier()) | ||||||
712 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | ||||||
713 | SourceRange(IILoc)); | ||||||
714 | // FIXME: Support class template argument deduction here. | ||||||
715 | SuggestedType = | ||||||
716 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | ||||||
717 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | ||||||
718 | /*IsCtorOrDtorName=*/false, | ||||||
719 | /*WantNontrivialTypeSourceInfo=*/true); | ||||||
720 | } | ||||||
721 | return; | ||||||
722 | } | ||||||
723 | |||||||
724 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | ||||||
725 | // See if II is a class template that the user forgot to pass arguments to. | ||||||
726 | UnqualifiedId Name; | ||||||
727 | Name.setIdentifier(II, IILoc); | ||||||
728 | CXXScopeSpec EmptySS; | ||||||
729 | TemplateTy TemplateResult; | ||||||
730 | bool MemberOfUnknownSpecialization; | ||||||
731 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | ||||||
732 | Name, nullptr, true, TemplateResult, | ||||||
733 | MemberOfUnknownSpecialization) == TNK_Type_template) { | ||||||
734 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | ||||||
735 | return; | ||||||
736 | } | ||||||
737 | } | ||||||
738 | |||||||
739 | // FIXME: Should we move the logic that tries to recover from a missing tag | ||||||
740 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | ||||||
741 | |||||||
742 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | ||||||
743 | Diag(IILoc, IsTemplateName ? diag::err_no_template | ||||||
744 | : diag::err_unknown_typename) | ||||||
745 | << II; | ||||||
746 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | ||||||
747 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | ||||||
748 | : diag::err_typename_nested_not_found) | ||||||
749 | << II << DC << SS->getRange(); | ||||||
750 | else if (isDependentScopeSpecifier(*SS)) { | ||||||
751 | unsigned DiagID = diag::err_typename_missing; | ||||||
752 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | ||||||
753 | DiagID = diag::ext_typename_missing; | ||||||
754 | |||||||
755 | Diag(SS->getRange().getBegin(), DiagID) | ||||||
756 | << SS->getScopeRep() << II->getName() | ||||||
757 | << SourceRange(SS->getRange().getBegin(), IILoc) | ||||||
758 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | ||||||
759 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | ||||||
760 | *SS, *II, IILoc).get(); | ||||||
761 | } else { | ||||||
762 | assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 763, __PRETTY_FUNCTION__)) | ||||||
763 | "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 763, __PRETTY_FUNCTION__)); | ||||||
764 | } | ||||||
765 | } | ||||||
766 | |||||||
767 | /// Determine whether the given result set contains either a type name | ||||||
768 | /// or | ||||||
769 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | ||||||
770 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | ||||||
771 | NextToken.is(tok::less); | ||||||
772 | |||||||
773 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | ||||||
774 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | ||||||
775 | return true; | ||||||
776 | |||||||
777 | if (CheckTemplate && isa<TemplateDecl>(*I)) | ||||||
778 | return true; | ||||||
779 | } | ||||||
780 | |||||||
781 | return false; | ||||||
782 | } | ||||||
783 | |||||||
784 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | ||||||
785 | Scope *S, CXXScopeSpec &SS, | ||||||
786 | IdentifierInfo *&Name, | ||||||
787 | SourceLocation NameLoc) { | ||||||
788 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | ||||||
789 | SemaRef.LookupParsedName(R, S, &SS); | ||||||
790 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | ||||||
791 | StringRef FixItTagName; | ||||||
792 | switch (Tag->getTagKind()) { | ||||||
793 | case TTK_Class: | ||||||
794 | FixItTagName = "class "; | ||||||
795 | break; | ||||||
796 | |||||||
797 | case TTK_Enum: | ||||||
798 | FixItTagName = "enum "; | ||||||
799 | break; | ||||||
800 | |||||||
801 | case TTK_Struct: | ||||||
802 | FixItTagName = "struct "; | ||||||
803 | break; | ||||||
804 | |||||||
805 | case TTK_Interface: | ||||||
806 | FixItTagName = "__interface "; | ||||||
807 | break; | ||||||
808 | |||||||
809 | case TTK_Union: | ||||||
810 | FixItTagName = "union "; | ||||||
811 | break; | ||||||
812 | } | ||||||
813 | |||||||
814 | StringRef TagName = FixItTagName.drop_back(); | ||||||
815 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | ||||||
816 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | ||||||
817 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | ||||||
818 | |||||||
819 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | ||||||
820 | I != IEnd; ++I) | ||||||
821 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | ||||||
822 | << Name << TagName; | ||||||
823 | |||||||
824 | // Replace lookup results with just the tag decl. | ||||||
825 | Result.clear(Sema::LookupTagName); | ||||||
826 | SemaRef.LookupParsedName(Result, S, &SS); | ||||||
827 | return true; | ||||||
828 | } | ||||||
829 | |||||||
830 | return false; | ||||||
831 | } | ||||||
832 | |||||||
833 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. | ||||||
834 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, | ||||||
835 | QualType T, SourceLocation NameLoc) { | ||||||
836 | ASTContext &Context = S.Context; | ||||||
837 | |||||||
838 | TypeLocBuilder Builder; | ||||||
839 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||||
840 | |||||||
841 | T = S.getElaboratedType(ETK_None, SS, T); | ||||||
842 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||||
843 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
844 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||
845 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
846 | } | ||||||
847 | |||||||
848 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, | ||||||
849 | IdentifierInfo *&Name, | ||||||
850 | SourceLocation NameLoc, | ||||||
851 | const Token &NextToken, | ||||||
852 | CorrectionCandidateCallback *CCC) { | ||||||
853 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||||
854 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||
855 | |||||||
856 | assert(NextToken.isNot(tok::coloncolon) &&((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName" ) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 857, __PRETTY_FUNCTION__)) | ||||||
857 | "parse nested name specifiers before calling ClassifyName")((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName" ) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 857, __PRETTY_FUNCTION__)); | ||||||
858 | if (getLangOpts().CPlusPlus && SS.isSet() && | ||||||
859 | isCurrentClassName(*Name, S, &SS)) { | ||||||
860 | // Per [class.qual]p2, this names the constructors of SS, not the | ||||||
861 | // injected-class-name. We don't have a classification for that. | ||||||
862 | // There's not much point caching this result, since the parser | ||||||
863 | // will reject it later. | ||||||
864 | return NameClassification::Unknown(); | ||||||
865 | } | ||||||
866 | |||||||
867 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||||
868 | LookupParsedName(Result, S, &SS, !CurMethod); | ||||||
869 | |||||||
870 | if (SS.isInvalid()) | ||||||
871 | return NameClassification::Error(); | ||||||
872 | |||||||
873 | // For unqualified lookup in a class template in MSVC mode, look into | ||||||
874 | // dependent base classes where the primary class template is known. | ||||||
875 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||||
876 | if (ParsedType TypeInBase = | ||||||
877 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | ||||||
878 | return TypeInBase; | ||||||
879 | } | ||||||
880 | |||||||
881 | // Perform lookup for Objective-C instance variables (including automatically | ||||||
882 | // synthesized instance variables), if we're in an Objective-C method. | ||||||
883 | // FIXME: This lookup really, really needs to be folded in to the normal | ||||||
884 | // unqualified lookup mechanism. | ||||||
885 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | ||||||
886 | DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); | ||||||
887 | if (Ivar.isInvalid()) | ||||||
888 | return NameClassification::Error(); | ||||||
889 | if (Ivar.isUsable()) | ||||||
890 | return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); | ||||||
891 | |||||||
892 | // We defer builtin creation until after ivar lookup inside ObjC methods. | ||||||
893 | if (Result.empty()) | ||||||
894 | LookupBuiltin(Result); | ||||||
895 | } | ||||||
896 | |||||||
897 | bool SecondTry = false; | ||||||
898 | bool IsFilteredTemplateName = false; | ||||||
899 | |||||||
900 | Corrected: | ||||||
901 | switch (Result.getResultKind()) { | ||||||
902 | case LookupResult::NotFound: | ||||||
903 | // If an unqualified-id is followed by a '(', then we have a function | ||||||
904 | // call. | ||||||
905 | if (SS.isEmpty() && NextToken.is(tok::l_paren)) { | ||||||
906 | // In C++, this is an ADL-only call. | ||||||
907 | // FIXME: Reference? | ||||||
908 | if (getLangOpts().CPlusPlus) | ||||||
909 | return NameClassification::UndeclaredNonType(); | ||||||
910 | |||||||
911 | // C90 6.3.2.2: | ||||||
912 | // If the expression that precedes the parenthesized argument list in a | ||||||
913 | // function call consists solely of an identifier, and if no | ||||||
914 | // declaration is visible for this identifier, the identifier is | ||||||
915 | // implicitly declared exactly as if, in the innermost block containing | ||||||
916 | // the function call, the declaration | ||||||
917 | // | ||||||
918 | // extern int identifier (); | ||||||
919 | // | ||||||
920 | // appeared. | ||||||
921 | // | ||||||
922 | // We also allow this in C99 as an extension. | ||||||
923 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) | ||||||
924 | return NameClassification::NonType(D); | ||||||
925 | } | ||||||
926 | |||||||
927 | if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) { | ||||||
928 | // In C++20 onwards, this could be an ADL-only call to a function | ||||||
929 | // template, and we're required to assume that this is a template name. | ||||||
930 | // | ||||||
931 | // FIXME: Find a way to still do typo correction in this case. | ||||||
932 | TemplateName Template = | ||||||
933 | Context.getAssumedTemplateName(NameInfo.getName()); | ||||||
934 | return NameClassification::UndeclaredTemplate(Template); | ||||||
935 | } | ||||||
936 | |||||||
937 | // In C, we first see whether there is a tag type by the same name, in | ||||||
938 | // which case it's likely that the user just forgot to write "enum", | ||||||
939 | // "struct", or "union". | ||||||
940 | if (!getLangOpts().CPlusPlus && !SecondTry && | ||||||
941 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||||
942 | break; | ||||||
943 | } | ||||||
944 | |||||||
945 | // Perform typo correction to determine if there is another name that is | ||||||
946 | // close to this name. | ||||||
947 | if (!SecondTry && CCC) { | ||||||
948 | SecondTry = true; | ||||||
949 | if (TypoCorrection Corrected = | ||||||
950 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | ||||||
951 | &SS, *CCC, CTK_ErrorRecovery)) { | ||||||
952 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | ||||||
953 | unsigned QualifiedDiag = diag::err_no_member_suggest; | ||||||
954 | |||||||
955 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | ||||||
956 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | ||||||
957 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
958 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | ||||||
959 | UnqualifiedDiag = diag::err_no_template_suggest; | ||||||
960 | QualifiedDiag = diag::err_no_member_template_suggest; | ||||||
961 | } else if (UnderlyingFirstDecl && | ||||||
962 | (isa<TypeDecl>(UnderlyingFirstDecl) || | ||||||
963 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | ||||||
964 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | ||||||
965 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | ||||||
966 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | ||||||
967 | } | ||||||
968 | |||||||
969 | if (SS.isEmpty()) { | ||||||
970 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | ||||||
971 | } else {// FIXME: is this even reachable? Test it. | ||||||
972 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||
973 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||||
974 | Name->getName().equals(CorrectedStr); | ||||||
975 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | ||||||
976 | << Name << computeDeclContext(SS, false) | ||||||
977 | << DroppedSpecifier << SS.getRange()); | ||||||
978 | } | ||||||
979 | |||||||
980 | // Update the name, so that the caller has the new name. | ||||||
981 | Name = Corrected.getCorrectionAsIdentifierInfo(); | ||||||
982 | |||||||
983 | // Typo correction corrected to a keyword. | ||||||
984 | if (Corrected.isKeyword()) | ||||||
985 | return Name; | ||||||
986 | |||||||
987 | // Also update the LookupResult... | ||||||
988 | // FIXME: This should probably go away at some point | ||||||
989 | Result.clear(); | ||||||
990 | Result.setLookupName(Corrected.getCorrection()); | ||||||
991 | if (FirstDecl) | ||||||
992 | Result.addDecl(FirstDecl); | ||||||
993 | |||||||
994 | // If we found an Objective-C instance variable, let | ||||||
995 | // LookupInObjCMethod build the appropriate expression to | ||||||
996 | // reference the ivar. | ||||||
997 | // FIXME: This is a gross hack. | ||||||
998 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | ||||||
999 | DeclResult R = | ||||||
1000 | LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); | ||||||
1001 | if (R.isInvalid()) | ||||||
1002 | return NameClassification::Error(); | ||||||
1003 | if (R.isUsable()) | ||||||
1004 | return NameClassification::NonType(Ivar); | ||||||
1005 | } | ||||||
1006 | |||||||
1007 | goto Corrected; | ||||||
1008 | } | ||||||
1009 | } | ||||||
1010 | |||||||
1011 | // We failed to correct; just fall through and let the parser deal with it. | ||||||
1012 | Result.suppressDiagnostics(); | ||||||
1013 | return NameClassification::Unknown(); | ||||||
1014 | |||||||
1015 | case LookupResult::NotFoundInCurrentInstantiation: { | ||||||
1016 | // We performed name lookup into the current instantiation, and there were | ||||||
1017 | // dependent bases, so we treat this result the same way as any other | ||||||
1018 | // dependent nested-name-specifier. | ||||||
1019 | |||||||
1020 | // C++ [temp.res]p2: | ||||||
1021 | // A name used in a template declaration or definition and that is | ||||||
1022 | // dependent on a template-parameter is assumed not to name a type | ||||||
1023 | // unless the applicable name lookup finds a type name or the name is | ||||||
1024 | // qualified by the keyword typename. | ||||||
1025 | // | ||||||
1026 | // FIXME: If the next token is '<', we might want to ask the parser to | ||||||
1027 | // perform some heroics to see if we actually have a | ||||||
1028 | // template-argument-list, which would indicate a missing 'template' | ||||||
1029 | // keyword here. | ||||||
1030 | return NameClassification::DependentNonType(); | ||||||
1031 | } | ||||||
1032 | |||||||
1033 | case LookupResult::Found: | ||||||
1034 | case LookupResult::FoundOverloaded: | ||||||
1035 | case LookupResult::FoundUnresolvedValue: | ||||||
1036 | break; | ||||||
1037 | |||||||
1038 | case LookupResult::Ambiguous: | ||||||
1039 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
1040 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | ||||||
1041 | /*AllowDependent=*/false)) { | ||||||
1042 | // C++ [temp.local]p3: | ||||||
1043 | // A lookup that finds an injected-class-name (10.2) can result in an | ||||||
1044 | // ambiguity in certain cases (for example, if it is found in more than | ||||||
1045 | // one base class). If all of the injected-class-names that are found | ||||||
1046 | // refer to specializations of the same class template, and if the name | ||||||
1047 | // is followed by a template-argument-list, the reference refers to the | ||||||
1048 | // class template itself and not a specialization thereof, and is not | ||||||
1049 | // ambiguous. | ||||||
1050 | // | ||||||
1051 | // This filtering can make an ambiguous result into an unambiguous one, | ||||||
1052 | // so try again after filtering out template names. | ||||||
1053 | FilterAcceptableTemplateNames(Result); | ||||||
1054 | if (!Result.isAmbiguous()) { | ||||||
1055 | IsFilteredTemplateName = true; | ||||||
1056 | break; | ||||||
1057 | } | ||||||
1058 | } | ||||||
1059 | |||||||
1060 | // Diagnose the ambiguity and return an error. | ||||||
1061 | return NameClassification::Error(); | ||||||
1062 | } | ||||||
1063 | |||||||
1064 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
1065 | (IsFilteredTemplateName || | ||||||
1066 | hasAnyAcceptableTemplateNames( | ||||||
1067 | Result, /*AllowFunctionTemplates=*/true, | ||||||
1068 | /*AllowDependent=*/false, | ||||||
1069 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && | ||||||
1070 | getLangOpts().CPlusPlus2a))) { | ||||||
1071 | // C++ [temp.names]p3: | ||||||
1072 | // After name lookup (3.4) finds that a name is a template-name or that | ||||||
1073 | // an operator-function-id or a literal- operator-id refers to a set of | ||||||
1074 | // overloaded functions any member of which is a function template if | ||||||
1075 | // this is followed by a <, the < is always taken as the delimiter of a | ||||||
1076 | // template-argument-list and never as the less-than operator. | ||||||
1077 | // C++2a [temp.names]p2: | ||||||
1078 | // A name is also considered to refer to a template if it is an | ||||||
1079 | // unqualified-id followed by a < and name lookup finds either one | ||||||
1080 | // or more functions or finds nothing. | ||||||
1081 | if (!IsFilteredTemplateName) | ||||||
1082 | FilterAcceptableTemplateNames(Result); | ||||||
1083 | |||||||
1084 | bool IsFunctionTemplate; | ||||||
1085 | bool IsVarTemplate; | ||||||
1086 | TemplateName Template; | ||||||
1087 | if (Result.end() - Result.begin() > 1) { | ||||||
1088 | IsFunctionTemplate = true; | ||||||
1089 | Template = Context.getOverloadedTemplateName(Result.begin(), | ||||||
1090 | Result.end()); | ||||||
1091 | } else if (!Result.empty()) { | ||||||
1092 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | ||||||
1093 | *Result.begin(), /*AllowFunctionTemplates=*/true, | ||||||
1094 | /*AllowDependent=*/false)); | ||||||
1095 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | ||||||
1096 | IsVarTemplate = isa<VarTemplateDecl>(TD); | ||||||
1097 | |||||||
1098 | if (SS.isNotEmpty()) | ||||||
1099 | Template = | ||||||
1100 | Context.getQualifiedTemplateName(SS.getScopeRep(), | ||||||
1101 | /*TemplateKeyword=*/false, TD); | ||||||
1102 | else | ||||||
1103 | Template = TemplateName(TD); | ||||||
1104 | } else { | ||||||
1105 | // All results were non-template functions. This is a function template | ||||||
1106 | // name. | ||||||
1107 | IsFunctionTemplate = true; | ||||||
1108 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | ||||||
1109 | } | ||||||
1110 | |||||||
1111 | if (IsFunctionTemplate) { | ||||||
1112 | // Function templates always go through overload resolution, at which | ||||||
1113 | // point we'll perform the various checks (e.g., accessibility) we need | ||||||
1114 | // to based on which function we selected. | ||||||
1115 | Result.suppressDiagnostics(); | ||||||
1116 | |||||||
1117 | return NameClassification::FunctionTemplate(Template); | ||||||
1118 | } | ||||||
1119 | |||||||
1120 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | ||||||
1121 | : NameClassification::TypeTemplate(Template); | ||||||
1122 | } | ||||||
1123 | |||||||
1124 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | ||||||
1125 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | ||||||
1126 | DiagnoseUseOfDecl(Type, NameLoc); | ||||||
1127 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | ||||||
1128 | QualType T = Context.getTypeDeclType(Type); | ||||||
1129 | if (SS.isNotEmpty()) | ||||||
1130 | return buildNestedType(*this, SS, T, NameLoc); | ||||||
1131 | return ParsedType::make(T); | ||||||
1132 | } | ||||||
1133 | |||||||
1134 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | ||||||
1135 | if (!Class) { | ||||||
1136 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | ||||||
1137 | if (ObjCCompatibleAliasDecl *Alias = | ||||||
1138 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | ||||||
1139 | Class = Alias->getClassInterface(); | ||||||
1140 | } | ||||||
1141 | |||||||
1142 | if (Class) { | ||||||
1143 | DiagnoseUseOfDecl(Class, NameLoc); | ||||||
1144 | |||||||
1145 | if (NextToken.is(tok::period)) { | ||||||
1146 | // Interface. <something> is parsed as a property reference expression. | ||||||
1147 | // Just return "unknown" as a fall-through for now. | ||||||
1148 | Result.suppressDiagnostics(); | ||||||
1149 | return NameClassification::Unknown(); | ||||||
1150 | } | ||||||
1151 | |||||||
1152 | QualType T = Context.getObjCInterfaceType(Class); | ||||||
1153 | return ParsedType::make(T); | ||||||
1154 | } | ||||||
1155 | |||||||
1156 | // We can have a type template here if we're classifying a template argument. | ||||||
1157 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | ||||||
1158 | !isa<VarTemplateDecl>(FirstDecl)) | ||||||
1159 | return NameClassification::TypeTemplate( | ||||||
1160 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||||
1161 | |||||||
1162 | // Check for a tag type hidden by a non-type decl in a few cases where it | ||||||
1163 | // seems likely a type is wanted instead of the non-type that was found. | ||||||
1164 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | ||||||
1165 | if ((NextToken.is(tok::identifier) || | ||||||
1166 | (NextIsOp && | ||||||
1167 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | ||||||
1168 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||||
1169 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | ||||||
1170 | DiagnoseUseOfDecl(Type, NameLoc); | ||||||
1171 | QualType T = Context.getTypeDeclType(Type); | ||||||
1172 | if (SS.isNotEmpty()) | ||||||
1173 | return buildNestedType(*this, SS, T, NameLoc); | ||||||
1174 | return ParsedType::make(T); | ||||||
1175 | } | ||||||
1176 | |||||||
1177 | // FIXME: This is context-dependent. We need to defer building the member | ||||||
1178 | // expression until the classification is consumed. | ||||||
1179 | if (FirstDecl->isCXXClassMember()) | ||||||
1180 | return NameClassification::ContextIndependentExpr( | ||||||
1181 | BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, | ||||||
1182 | S)); | ||||||
1183 | |||||||
1184 | // If we already know which single declaration is referenced, just annotate | ||||||
1185 | // that declaration directly. | ||||||
1186 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||||
1187 | if (Result.isSingleResult() && !ADL) | ||||||
1188 | return NameClassification::NonType(Result.getRepresentativeDecl()); | ||||||
1189 | |||||||
1190 | // Build an UnresolvedLookupExpr. Note that this doesn't depend on the | ||||||
1191 | // context in which we performed classification, so it's safe to do now. | ||||||
1192 | return NameClassification::ContextIndependentExpr( | ||||||
1193 | BuildDeclarationNameExpr(SS, Result, ADL)); | ||||||
1194 | } | ||||||
1195 | |||||||
1196 | ExprResult | ||||||
1197 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, | ||||||
1198 | SourceLocation NameLoc) { | ||||||
1199 | assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((getLangOpts().CPlusPlus && "ADL-only call in C?") ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1199, __PRETTY_FUNCTION__)); | ||||||
1200 | CXXScopeSpec SS; | ||||||
1201 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||||
1202 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | ||||||
1203 | } | ||||||
1204 | |||||||
1205 | ExprResult | ||||||
1206 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, | ||||||
1207 | IdentifierInfo *Name, | ||||||
1208 | SourceLocation NameLoc, | ||||||
1209 | bool IsAddressOfOperand) { | ||||||
1210 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||||
1211 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||
1212 | NameInfo, IsAddressOfOperand, | ||||||
1213 | /*TemplateArgs=*/nullptr); | ||||||
1214 | } | ||||||
1215 | |||||||
1216 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, | ||||||
1217 | NamedDecl *Found, | ||||||
1218 | SourceLocation NameLoc, | ||||||
1219 | const Token &NextToken) { | ||||||
1220 | if (getCurMethodDecl() && SS.isEmpty()) | ||||||
1221 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) | ||||||
1222 | return BuildIvarRefExpr(S, NameLoc, Ivar); | ||||||
1223 | |||||||
1224 | // Reconstruct the lookup result. | ||||||
1225 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); | ||||||
1226 | Result.addDecl(Found); | ||||||
1227 | Result.resolveKind(); | ||||||
1228 | |||||||
1229 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||||
1230 | return BuildDeclarationNameExpr(SS, Result, ADL); | ||||||
1231 | } | ||||||
1232 | |||||||
1233 | Sema::TemplateNameKindForDiagnostics | ||||||
1234 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | ||||||
1235 | auto *TD = Name.getAsTemplateDecl(); | ||||||
1236 | if (!TD) | ||||||
1237 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||||
1238 | if (isa<ClassTemplateDecl>(TD)) | ||||||
1239 | return TemplateNameKindForDiagnostics::ClassTemplate; | ||||||
1240 | if (isa<FunctionTemplateDecl>(TD)) | ||||||
1241 | return TemplateNameKindForDiagnostics::FunctionTemplate; | ||||||
1242 | if (isa<VarTemplateDecl>(TD)) | ||||||
1243 | return TemplateNameKindForDiagnostics::VarTemplate; | ||||||
1244 | if (isa<TypeAliasTemplateDecl>(TD)) | ||||||
1245 | return TemplateNameKindForDiagnostics::AliasTemplate; | ||||||
1246 | if (isa<TemplateTemplateParmDecl>(TD)) | ||||||
1247 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | ||||||
1248 | if (isa<ConceptDecl>(TD)) | ||||||
1249 | return TemplateNameKindForDiagnostics::Concept; | ||||||
1250 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||||
1251 | } | ||||||
1252 | |||||||
1253 | // Determines the context to return to after temporarily entering a | ||||||
1254 | // context. This depends in an unnecessarily complicated way on the | ||||||
1255 | // exact ordering of callbacks from the parser. | ||||||
1256 | DeclContext *Sema::getContainingDC(DeclContext *DC) { | ||||||
1257 | |||||||
1258 | // Functions defined inline within classes aren't parsed until we've | ||||||
1259 | // finished parsing the top-level class, so the top-level class is | ||||||
1260 | // the context we'll need to return to. | ||||||
1261 | // A Lambda call operator whose parent is a class must not be treated | ||||||
1262 | // as an inline member function. A Lambda can be used legally | ||||||
1263 | // either as an in-class member initializer or a default argument. These | ||||||
1264 | // are parsed once the class has been marked complete and so the containing | ||||||
1265 | // context would be the nested class (when the lambda is defined in one); | ||||||
1266 | // If the class is not complete, then the lambda is being used in an | ||||||
1267 | // ill-formed fashion (such as to specify the width of a bit-field, or | ||||||
1268 | // in an array-bound) - in which case we still want to return the | ||||||
1269 | // lexically containing DC (which could be a nested class). | ||||||
1270 | if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { | ||||||
1271 | DC = DC->getLexicalParent(); | ||||||
1272 | |||||||
1273 | // A function not defined within a class will always return to its | ||||||
1274 | // lexical context. | ||||||
1275 | if (!isa<CXXRecordDecl>(DC)) | ||||||
1276 | return DC; | ||||||
1277 | |||||||
1278 | // A C++ inline method/friend is parsed *after* the topmost class | ||||||
1279 | // it was declared in is fully parsed ("complete"); the topmost | ||||||
1280 | // class is the context we need to return to. | ||||||
1281 | while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) | ||||||
1282 | DC = RD; | ||||||
1283 | |||||||
1284 | // Return the declaration context of the topmost class the inline method is | ||||||
1285 | // declared in. | ||||||
1286 | return DC; | ||||||
1287 | } | ||||||
1288 | |||||||
1289 | return DC->getLexicalParent(); | ||||||
1290 | } | ||||||
1291 | |||||||
1292 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | ||||||
1293 | assert(getContainingDC(DC) == CurContext &&((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1294, __PRETTY_FUNCTION__)) | ||||||
1294 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1294, __PRETTY_FUNCTION__)); | ||||||
1295 | CurContext = DC; | ||||||
1296 | S->setEntity(DC); | ||||||
1297 | } | ||||||
1298 | |||||||
1299 | void Sema::PopDeclContext() { | ||||||
1300 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1300, __PRETTY_FUNCTION__)); | ||||||
1301 | |||||||
1302 | CurContext = getContainingDC(CurContext); | ||||||
1303 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1303, __PRETTY_FUNCTION__)); | ||||||
1304 | } | ||||||
1305 | |||||||
1306 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | ||||||
1307 | Decl *D) { | ||||||
1308 | // Unlike PushDeclContext, the context to which we return is not necessarily | ||||||
1309 | // the containing DC of TD, because the new context will be some pre-existing | ||||||
1310 | // TagDecl definition instead of a fresh one. | ||||||
1311 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | ||||||
1312 | CurContext = cast<TagDecl>(D)->getDefinition(); | ||||||
1313 | assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag" ) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1313, __PRETTY_FUNCTION__)); | ||||||
1314 | // Start lookups from the parent of the current context; we don't want to look | ||||||
1315 | // into the pre-existing complete definition. | ||||||
1316 | S->setEntity(CurContext->getLookupParent()); | ||||||
1317 | return Result; | ||||||
1318 | } | ||||||
1319 | |||||||
1320 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | ||||||
1321 | CurContext = static_cast<decltype(CurContext)>(Context); | ||||||
1322 | } | ||||||
1323 | |||||||
1324 | /// EnterDeclaratorContext - Used when we must lookup names in the context | ||||||
1325 | /// of a declarator's nested name specifier. | ||||||
1326 | /// | ||||||
1327 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | ||||||
1328 | // C++0x [basic.lookup.unqual]p13: | ||||||
1329 | // A name used in the definition of a static data member of class | ||||||
1330 | // X (after the qualified-id of the static member) is looked up as | ||||||
1331 | // if the name was used in a member function of X. | ||||||
1332 | // C++0x [basic.lookup.unqual]p14: | ||||||
1333 | // If a variable member of a namespace is defined outside of the | ||||||
1334 | // scope of its namespace then any name used in the definition of | ||||||
1335 | // the variable member (after the declarator-id) is looked up as | ||||||
1336 | // if the definition of the variable member occurred in its | ||||||
1337 | // namespace. | ||||||
1338 | // Both of these imply that we should push a scope whose context | ||||||
1339 | // is the semantic context of the declaration. We can't use | ||||||
1340 | // PushDeclContext here because that context is not necessarily | ||||||
1341 | // lexically contained in the current context. Fortunately, | ||||||
1342 | // the containing scope should have the appropriate information. | ||||||
1343 | |||||||
1344 | assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ? static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1344, __PRETTY_FUNCTION__)); | ||||||
1345 | |||||||
1346 | #ifndef NDEBUG | ||||||
1347 | Scope *Ancestor = S->getParent(); | ||||||
1348 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||||
1349 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch" ) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1349, __PRETTY_FUNCTION__)); | ||||||
1350 | #endif | ||||||
1351 | |||||||
1352 | CurContext = DC; | ||||||
1353 | S->setEntity(DC); | ||||||
1354 | } | ||||||
1355 | |||||||
1356 | void Sema::ExitDeclaratorContext(Scope *S) { | ||||||
1357 | assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!" ) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1357, __PRETTY_FUNCTION__)); | ||||||
1358 | |||||||
1359 | // Switch back to the lexical context. The safety of this is | ||||||
1360 | // enforced by an assert in EnterDeclaratorContext. | ||||||
1361 | Scope *Ancestor = S->getParent(); | ||||||
1362 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||||
1363 | CurContext = Ancestor->getEntity(); | ||||||
1364 | |||||||
1365 | // We don't need to do anything with the scope, which is going to | ||||||
1366 | // disappear. | ||||||
1367 | } | ||||||
1368 | |||||||
1369 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | ||||||
1370 | // We assume that the caller has already called | ||||||
1371 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | ||||||
1372 | FunctionDecl *FD = D->getAsFunction(); | ||||||
1373 | if (!FD) | ||||||
1374 | return; | ||||||
1375 | |||||||
1376 | // Same implementation as PushDeclContext, but enters the context | ||||||
1377 | // from the lexical parent, rather than the top-level class. | ||||||
1378 | assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1379, __PRETTY_FUNCTION__)) | ||||||
1379 | "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1379, __PRETTY_FUNCTION__)); | ||||||
1380 | CurContext = FD; | ||||||
1381 | S->setEntity(CurContext); | ||||||
1382 | |||||||
1383 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | ||||||
1384 | ParmVarDecl *Param = FD->getParamDecl(P); | ||||||
1385 | // If the parameter has an identifier, then add it to the scope | ||||||
1386 | if (Param->getIdentifier()) { | ||||||
1387 | S->AddDecl(Param); | ||||||
1388 | IdResolver.AddDecl(Param); | ||||||
1389 | } | ||||||
1390 | } | ||||||
1391 | } | ||||||
1392 | |||||||
1393 | void Sema::ActOnExitFunctionContext() { | ||||||
1394 | // Same implementation as PopDeclContext, but returns to the lexical parent, | ||||||
1395 | // rather than the top-level class. | ||||||
1396 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1396, __PRETTY_FUNCTION__)); | ||||||
1397 | CurContext = CurContext->getLexicalParent(); | ||||||
1398 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1398, __PRETTY_FUNCTION__)); | ||||||
1399 | } | ||||||
1400 | |||||||
1401 | /// Determine whether we allow overloading of the function | ||||||
1402 | /// PrevDecl with another declaration. | ||||||
1403 | /// | ||||||
1404 | /// This routine determines whether overloading is possible, not | ||||||
1405 | /// whether some new function is actually an overload. It will return | ||||||
1406 | /// true in C++ (where we can always provide overloads) or, as an | ||||||
1407 | /// extension, in C when the previous function is already an | ||||||
1408 | /// overloaded function declaration or has the "overloadable" | ||||||
1409 | /// attribute. | ||||||
1410 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | ||||||
1411 | ASTContext &Context, | ||||||
1412 | const FunctionDecl *New) { | ||||||
1413 | if (Context.getLangOpts().CPlusPlus) | ||||||
1414 | return true; | ||||||
1415 | |||||||
1416 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | ||||||
1417 | return true; | ||||||
1418 | |||||||
1419 | return Previous.getResultKind() == LookupResult::Found && | ||||||
1420 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | ||||||
1421 | New->hasAttr<OverloadableAttr>()); | ||||||
1422 | } | ||||||
1423 | |||||||
1424 | /// Add this decl to the scope shadowed decl chains. | ||||||
1425 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | ||||||
1426 | // Move up the scope chain until we find the nearest enclosing | ||||||
1427 | // non-transparent context. The declaration will be introduced into this | ||||||
1428 | // scope. | ||||||
1429 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | ||||||
1430 | S = S->getParent(); | ||||||
1431 | |||||||
1432 | // Add scoped declarations into their context, so that they can be | ||||||
1433 | // found later. Declarations without a context won't be inserted | ||||||
1434 | // into any context. | ||||||
1435 | if (AddToContext) | ||||||
1436 | CurContext->addDecl(D); | ||||||
1437 | |||||||
1438 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | ||||||
1439 | // are function-local declarations. | ||||||
1440 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && | ||||||
1441 | !D->getDeclContext()->getRedeclContext()->Equals( | ||||||
1442 | D->getLexicalDeclContext()->getRedeclContext()) && | ||||||
1443 | !D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
1444 | return; | ||||||
1445 | |||||||
1446 | // Template instantiations should also not be pushed into scope. | ||||||
1447 | if (isa<FunctionDecl>(D) && | ||||||
1448 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | ||||||
1449 | return; | ||||||
1450 | |||||||
1451 | // If this replaces anything in the current scope, | ||||||
1452 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | ||||||
1453 | IEnd = IdResolver.end(); | ||||||
1454 | for (; I != IEnd; ++I) { | ||||||
1455 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | ||||||
1456 | S->RemoveDecl(*I); | ||||||
1457 | IdResolver.RemoveDecl(*I); | ||||||
1458 | |||||||
1459 | // Should only need to replace one decl. | ||||||
1460 | break; | ||||||
1461 | } | ||||||
1462 | } | ||||||
1463 | |||||||
1464 | S->AddDecl(D); | ||||||
1465 | |||||||
1466 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | ||||||
1467 | // Implicitly-generated labels may end up getting generated in an order that | ||||||
1468 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | ||||||
1469 | // the label at the appropriate place in the identifier chain. | ||||||
1470 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | ||||||
1471 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | ||||||
1472 | if (IDC == CurContext) { | ||||||
1473 | if (!S->isDeclScope(*I)) | ||||||
1474 | continue; | ||||||
1475 | } else if (IDC->Encloses(CurContext)) | ||||||
1476 | break; | ||||||
1477 | } | ||||||
1478 | |||||||
1479 | IdResolver.InsertDeclAfter(I, D); | ||||||
1480 | } else { | ||||||
1481 | IdResolver.AddDecl(D); | ||||||
1482 | } | ||||||
1483 | } | ||||||
1484 | |||||||
1485 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | ||||||
1486 | bool AllowInlineNamespace) { | ||||||
1487 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | ||||||
1488 | } | ||||||
1489 | |||||||
1490 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | ||||||
1491 | DeclContext *TargetDC = DC->getPrimaryContext(); | ||||||
1492 | do { | ||||||
1493 | if (DeclContext *ScopeDC = S->getEntity()) | ||||||
1494 | if (ScopeDC->getPrimaryContext() == TargetDC) | ||||||
1495 | return S; | ||||||
1496 | } while ((S = S->getParent())); | ||||||
1497 | |||||||
1498 | return nullptr; | ||||||
1499 | } | ||||||
1500 | |||||||
1501 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | ||||||
1502 | DeclContext*, | ||||||
1503 | ASTContext&); | ||||||
1504 | |||||||
1505 | /// Filters out lookup results that don't fall within the given scope | ||||||
1506 | /// as determined by isDeclInScope. | ||||||
1507 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | ||||||
1508 | bool ConsiderLinkage, | ||||||
1509 | bool AllowInlineNamespace) { | ||||||
1510 | LookupResult::Filter F = R.makeFilter(); | ||||||
1511 | while (F.hasNext()) { | ||||||
1512 | NamedDecl *D = F.next(); | ||||||
1513 | |||||||
1514 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | ||||||
1515 | continue; | ||||||
1516 | |||||||
1517 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | ||||||
1518 | continue; | ||||||
1519 | |||||||
1520 | F.erase(); | ||||||
1521 | } | ||||||
1522 | |||||||
1523 | F.done(); | ||||||
1524 | } | ||||||
1525 | |||||||
1526 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | ||||||
1527 | /// have compatible owning modules. | ||||||
1528 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | ||||||
1529 | // FIXME: The Modules TS is not clear about how friend declarations are | ||||||
1530 | // to be treated. It's not meaningful to have different owning modules for | ||||||
1531 | // linkage in redeclarations of the same entity, so for now allow the | ||||||
1532 | // redeclaration and change the owning modules to match. | ||||||
1533 | if (New->getFriendObjectKind() && | ||||||
1534 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | ||||||
1535 | New->setLocalOwningModule(Old->getOwningModule()); | ||||||
1536 | makeMergedDefinitionVisible(New); | ||||||
1537 | return false; | ||||||
1538 | } | ||||||
1539 | |||||||
1540 | Module *NewM = New->getOwningModule(); | ||||||
1541 | Module *OldM = Old->getOwningModule(); | ||||||
1542 | |||||||
1543 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | ||||||
1544 | NewM = NewM->Parent; | ||||||
1545 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | ||||||
1546 | OldM = OldM->Parent; | ||||||
1547 | |||||||
1548 | if (NewM == OldM) | ||||||
1549 | return false; | ||||||
1550 | |||||||
1551 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | ||||||
1552 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | ||||||
1553 | if (NewIsModuleInterface || OldIsModuleInterface) { | ||||||
1554 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | ||||||
1555 | // if a declaration of D [...] appears in the purview of a module, all | ||||||
1556 | // other such declarations shall appear in the purview of the same module | ||||||
1557 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | ||||||
1558 | << New | ||||||
1559 | << NewIsModuleInterface | ||||||
1560 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | ||||||
1561 | << OldIsModuleInterface | ||||||
1562 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | ||||||
1563 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
1564 | New->setInvalidDecl(); | ||||||
1565 | return true; | ||||||
1566 | } | ||||||
1567 | |||||||
1568 | return false; | ||||||
1569 | } | ||||||
1570 | |||||||
1571 | static bool isUsingDecl(NamedDecl *D) { | ||||||
1572 | return isa<UsingShadowDecl>(D) || | ||||||
1573 | isa<UnresolvedUsingTypenameDecl>(D) || | ||||||
1574 | isa<UnresolvedUsingValueDecl>(D); | ||||||
1575 | } | ||||||
1576 | |||||||
1577 | /// Removes using shadow declarations from the lookup results. | ||||||
1578 | static void RemoveUsingDecls(LookupResult &R) { | ||||||
1579 | LookupResult::Filter F = R.makeFilter(); | ||||||
1580 | while (F.hasNext()) | ||||||
1581 | if (isUsingDecl(F.next())) | ||||||
1582 | F.erase(); | ||||||
1583 | |||||||
1584 | F.done(); | ||||||
1585 | } | ||||||
1586 | |||||||
1587 | /// Check for this common pattern: | ||||||
1588 | /// @code | ||||||
1589 | /// class S { | ||||||
1590 | /// S(const S&); // DO NOT IMPLEMENT | ||||||
1591 | /// void operator=(const S&); // DO NOT IMPLEMENT | ||||||
1592 | /// }; | ||||||
1593 | /// @endcode | ||||||
1594 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | ||||||
1595 | // FIXME: Should check for private access too but access is set after we get | ||||||
1596 | // the decl here. | ||||||
1597 | if (D->doesThisDeclarationHaveABody()) | ||||||
1598 | return false; | ||||||
1599 | |||||||
1600 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | ||||||
1601 | return CD->isCopyConstructor(); | ||||||
1602 | return D->isCopyAssignmentOperator(); | ||||||
1603 | } | ||||||
1604 | |||||||
1605 | // We need this to handle | ||||||
1606 | // | ||||||
1607 | // typedef struct { | ||||||
1608 | // void *foo() { return 0; } | ||||||
1609 | // } A; | ||||||
1610 | // | ||||||
1611 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | ||||||
1612 | // for example. If 'A', foo will have external linkage. If we have '*A', | ||||||
1613 | // foo will have no linkage. Since we can't know until we get to the end | ||||||
1614 | // of the typedef, this function finds out if D might have non-external linkage. | ||||||
1615 | // Callers should verify at the end of the TU if it D has external linkage or | ||||||
1616 | // not. | ||||||
1617 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | ||||||
1618 | const DeclContext *DC = D->getDeclContext(); | ||||||
1619 | while (!DC->isTranslationUnit()) { | ||||||
1620 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | ||||||
1621 | if (!RD->hasNameForLinkage()) | ||||||
1622 | return true; | ||||||
1623 | } | ||||||
1624 | DC = DC->getParent(); | ||||||
1625 | } | ||||||
1626 | |||||||
1627 | return !D->isExternallyVisible(); | ||||||
1628 | } | ||||||
1629 | |||||||
1630 | // FIXME: This needs to be refactored; some other isInMainFile users want | ||||||
1631 | // these semantics. | ||||||
1632 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | ||||||
1633 | if (S.TUKind != TU_Complete) | ||||||
1634 | return false; | ||||||
1635 | return S.SourceMgr.isInMainFile(Loc); | ||||||
1636 | } | ||||||
1637 | |||||||
1638 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | ||||||
1639 | assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1639, __PRETTY_FUNCTION__)); | ||||||
1640 | |||||||
1641 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | ||||||
1642 | return false; | ||||||
1643 | |||||||
1644 | // Ignore all entities declared within templates, and out-of-line definitions | ||||||
1645 | // of members of class templates. | ||||||
1646 | if (D->getDeclContext()->isDependentContext() || | ||||||
1647 | D->getLexicalDeclContext()->isDependentContext()) | ||||||
1648 | return false; | ||||||
1649 | |||||||
1650 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||
1651 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||||
1652 | return false; | ||||||
1653 | // A non-out-of-line declaration of a member specialization was implicitly | ||||||
1654 | // instantiated; it's the out-of-line declaration that we're interested in. | ||||||
1655 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||||
1656 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | ||||||
1657 | return false; | ||||||
1658 | |||||||
1659 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
1660 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | ||||||
1661 | return false; | ||||||
1662 | } else { | ||||||
1663 | // 'static inline' functions are defined in headers; don't warn. | ||||||
1664 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | ||||||
1665 | return false; | ||||||
1666 | } | ||||||
1667 | |||||||
1668 | if (FD->doesThisDeclarationHaveABody() && | ||||||
1669 | Context.DeclMustBeEmitted(FD)) | ||||||
1670 | return false; | ||||||
1671 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1672 | // Constants and utility variables are defined in headers with internal | ||||||
1673 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | ||||||
1674 | // like "inline".) | ||||||
1675 | if (!isMainFileLoc(*this, VD->getLocation())) | ||||||
1676 | return false; | ||||||
1677 | |||||||
1678 | if (Context.DeclMustBeEmitted(VD)) | ||||||
1679 | return false; | ||||||
1680 | |||||||
1681 | if (VD->isStaticDataMember() && | ||||||
1682 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||||
1683 | return false; | ||||||
1684 | if (VD->isStaticDataMember() && | ||||||
1685 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||||
1686 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | ||||||
1687 | return false; | ||||||
1688 | |||||||
1689 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | ||||||
1690 | return false; | ||||||
1691 | } else { | ||||||
1692 | return false; | ||||||
1693 | } | ||||||
1694 | |||||||
1695 | // Only warn for unused decls internal to the translation unit. | ||||||
1696 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | ||||||
1697 | // for inline functions defined in the main source file, for instance. | ||||||
1698 | return mightHaveNonExternalLinkage(D); | ||||||
1699 | } | ||||||
1700 | |||||||
1701 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | ||||||
1702 | if (!D) | ||||||
1703 | return; | ||||||
1704 | |||||||
1705 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||
1706 | const FunctionDecl *First = FD->getFirstDecl(); | ||||||
1707 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||||
1708 | return; // First should already be in the vector. | ||||||
1709 | } | ||||||
1710 | |||||||
1711 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1712 | const VarDecl *First = VD->getFirstDecl(); | ||||||
1713 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||||
1714 | return; // First should already be in the vector. | ||||||
1715 | } | ||||||
1716 | |||||||
1717 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | ||||||
1718 | UnusedFileScopedDecls.push_back(D); | ||||||
1719 | } | ||||||
1720 | |||||||
1721 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | ||||||
1722 | if (D->isInvalidDecl()) | ||||||
1723 | return false; | ||||||
1724 | |||||||
1725 | bool Referenced = false; | ||||||
1726 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | ||||||
1727 | // For a decomposition declaration, warn if none of the bindings are | ||||||
1728 | // referenced, instead of if the variable itself is referenced (which | ||||||
1729 | // it is, by the bindings' expressions). | ||||||
1730 | for (auto *BD : DD->bindings()) { | ||||||
1731 | if (BD->isReferenced()) { | ||||||
1732 | Referenced = true; | ||||||
1733 | break; | ||||||
1734 | } | ||||||
1735 | } | ||||||
1736 | } else if (!D->getDeclName()) { | ||||||
1737 | return false; | ||||||
1738 | } else if (D->isReferenced() || D->isUsed()) { | ||||||
1739 | Referenced = true; | ||||||
1740 | } | ||||||
1741 | |||||||
1742 | if (Referenced || D->hasAttr<UnusedAttr>() || | ||||||
1743 | D->hasAttr<ObjCPreciseLifetimeAttr>()) | ||||||
1744 | return false; | ||||||
1745 | |||||||
1746 | if (isa<LabelDecl>(D)) | ||||||
1747 | return true; | ||||||
1748 | |||||||
1749 | // Except for labels, we only care about unused decls that are local to | ||||||
1750 | // functions. | ||||||
1751 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | ||||||
1752 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | ||||||
1753 | // For dependent types, the diagnostic is deferred. | ||||||
1754 | WithinFunction = | ||||||
1755 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | ||||||
1756 | if (!WithinFunction) | ||||||
1757 | return false; | ||||||
1758 | |||||||
1759 | if (isa<TypedefNameDecl>(D)) | ||||||
1760 | return true; | ||||||
1761 | |||||||
1762 | // White-list anything that isn't a local variable. | ||||||
1763 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | ||||||
1764 | return false; | ||||||
1765 | |||||||
1766 | // Types of valid local variables should be complete, so this should succeed. | ||||||
1767 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1768 | |||||||
1769 | // White-list anything with an __attribute__((unused)) type. | ||||||
1770 | const auto *Ty = VD->getType().getTypePtr(); | ||||||
1771 | |||||||
1772 | // Only look at the outermost level of typedef. | ||||||
1773 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | ||||||
1774 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | ||||||
1775 | return false; | ||||||
1776 | } | ||||||
1777 | |||||||
1778 | // If we failed to complete the type for some reason, or if the type is | ||||||
1779 | // dependent, don't diagnose the variable. | ||||||
1780 | if (Ty->isIncompleteType() || Ty->isDependentType()) | ||||||
1781 | return false; | ||||||
1782 | |||||||
1783 | // Look at the element type to ensure that the warning behaviour is | ||||||
1784 | // consistent for both scalars and arrays. | ||||||
1785 | Ty = Ty->getBaseElementTypeUnsafe(); | ||||||
1786 | |||||||
1787 | if (const TagType *TT = Ty->getAs<TagType>()) { | ||||||
1788 | const TagDecl *Tag = TT->getDecl(); | ||||||
1789 | if (Tag->hasAttr<UnusedAttr>()) | ||||||
1790 | return false; | ||||||
1791 | |||||||
1792 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | ||||||
1793 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | ||||||
1794 | return false; | ||||||
1795 | |||||||
1796 | if (const Expr *Init = VD->getInit()) { | ||||||
1797 | if (const ExprWithCleanups *Cleanups = | ||||||
1798 | dyn_cast<ExprWithCleanups>(Init)) | ||||||
1799 | Init = Cleanups->getSubExpr(); | ||||||
1800 | const CXXConstructExpr *Construct = | ||||||
1801 | dyn_cast<CXXConstructExpr>(Init); | ||||||
1802 | if (Construct && !Construct->isElidable()) { | ||||||
1803 | CXXConstructorDecl *CD = Construct->getConstructor(); | ||||||
1804 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | ||||||
1805 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | ||||||
1806 | return false; | ||||||
1807 | } | ||||||
1808 | |||||||
1809 | // Suppress the warning if we don't know how this is constructed, and | ||||||
1810 | // it could possibly be non-trivial constructor. | ||||||
1811 | if (Init->isTypeDependent()) | ||||||
1812 | for (const CXXConstructorDecl *Ctor : RD->ctors()) | ||||||
1813 | if (!Ctor->isTrivial()) | ||||||
1814 | return false; | ||||||
1815 | } | ||||||
1816 | } | ||||||
1817 | } | ||||||
1818 | |||||||
1819 | // TODO: __attribute__((unused)) templates? | ||||||
1820 | } | ||||||
1821 | |||||||
1822 | return true; | ||||||
1823 | } | ||||||
1824 | |||||||
1825 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | ||||||
1826 | FixItHint &Hint) { | ||||||
1827 | if (isa<LabelDecl>(D)) { | ||||||
1828 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | ||||||
1829 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | ||||||
1830 | true); | ||||||
1831 | if (AfterColon.isInvalid()) | ||||||
1832 | return; | ||||||
1833 | Hint = FixItHint::CreateRemoval( | ||||||
1834 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | ||||||
1835 | } | ||||||
1836 | } | ||||||
1837 | |||||||
1838 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | ||||||
1839 | if (D->getTypeForDecl()->isDependentType()) | ||||||
1840 | return; | ||||||
1841 | |||||||
1842 | for (auto *TmpD : D->decls()) { | ||||||
1843 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | ||||||
1844 | DiagnoseUnusedDecl(T); | ||||||
1845 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | ||||||
1846 | DiagnoseUnusedNestedTypedefs(R); | ||||||
1847 | } | ||||||
1848 | } | ||||||
1849 | |||||||
1850 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | ||||||
1851 | /// unless they are marked attr(unused). | ||||||
1852 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | ||||||
1853 | if (!ShouldDiagnoseUnusedDecl(D)) | ||||||
1854 | return; | ||||||
1855 | |||||||
1856 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | ||||||
1857 | // typedefs can be referenced later on, so the diagnostics are emitted | ||||||
1858 | // at end-of-translation-unit. | ||||||
1859 | UnusedLocalTypedefNameCandidates.insert(TD); | ||||||
1860 | return; | ||||||
1861 | } | ||||||
1862 | |||||||
1863 | FixItHint Hint; | ||||||
1864 | GenerateFixForUnusedDecl(D, Context, Hint); | ||||||
1865 | |||||||
1866 | unsigned DiagID; | ||||||
1867 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | ||||||
1868 | DiagID = diag::warn_unused_exception_param; | ||||||
1869 | else if (isa<LabelDecl>(D)) | ||||||
1870 | DiagID = diag::warn_unused_label; | ||||||
1871 | else | ||||||
1872 | DiagID = diag::warn_unused_variable; | ||||||
1873 | |||||||
1874 | Diag(D->getLocation(), DiagID) << D << Hint; | ||||||
1875 | } | ||||||
1876 | |||||||
1877 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | ||||||
1878 | // Verify that we have no forward references left. If so, there was a goto | ||||||
1879 | // or address of a label taken, but no definition of it. Label fwd | ||||||
1880 | // definitions are indicated with a null substmt which is also not a resolved | ||||||
1881 | // MS inline assembly label name. | ||||||
1882 | bool Diagnose = false; | ||||||
1883 | if (L->isMSAsmLabel()) | ||||||
1884 | Diagnose = !L->isResolvedMSAsmLabel(); | ||||||
1885 | else | ||||||
1886 | Diagnose = L->getStmt() == nullptr; | ||||||
1887 | if (Diagnose) | ||||||
1888 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); | ||||||
1889 | } | ||||||
1890 | |||||||
1891 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | ||||||
1892 | S->mergeNRVOIntoParent(); | ||||||
1893 | |||||||
1894 | if (S->decl_empty()) return; | ||||||
1895 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1896, __PRETTY_FUNCTION__)) | ||||||
1896 | "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1896, __PRETTY_FUNCTION__)); | ||||||
1897 | |||||||
1898 | for (auto *TmpD : S->decls()) { | ||||||
1899 | assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast <void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1899, __PRETTY_FUNCTION__)); | ||||||
1900 | |||||||
1901 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?" ) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 1901, __PRETTY_FUNCTION__)); | ||||||
1902 | NamedDecl *D = cast<NamedDecl>(TmpD); | ||||||
1903 | |||||||
1904 | // Diagnose unused variables in this scope. | ||||||
1905 | if (!S->hasUnrecoverableErrorOccurred()) { | ||||||
1906 | DiagnoseUnusedDecl(D); | ||||||
1907 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | ||||||
1908 | DiagnoseUnusedNestedTypedefs(RD); | ||||||
1909 | } | ||||||
1910 | |||||||
1911 | if (!D->getDeclName()) continue; | ||||||
1912 | |||||||
1913 | // If this was a forward reference to a label, verify it was defined. | ||||||
1914 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | ||||||
1915 | CheckPoppedLabel(LD, *this); | ||||||
1916 | |||||||
1917 | // Remove this name from our lexical scope, and warn on it if we haven't | ||||||
1918 | // already. | ||||||
1919 | IdResolver.RemoveDecl(D); | ||||||
1920 | auto ShadowI = ShadowingDecls.find(D); | ||||||
1921 | if (ShadowI != ShadowingDecls.end()) { | ||||||
1922 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | ||||||
1923 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | ||||||
1924 | << D << FD << FD->getParent(); | ||||||
1925 | Diag(FD->getLocation(), diag::note_previous_declaration); | ||||||
1926 | } | ||||||
1927 | ShadowingDecls.erase(ShadowI); | ||||||
1928 | } | ||||||
1929 | } | ||||||
1930 | } | ||||||
1931 | |||||||
1932 | /// Look for an Objective-C class in the translation unit. | ||||||
1933 | /// | ||||||
1934 | /// \param Id The name of the Objective-C class we're looking for. If | ||||||
1935 | /// typo-correction fixes this name, the Id will be updated | ||||||
1936 | /// to the fixed name. | ||||||
1937 | /// | ||||||
1938 | /// \param IdLoc The location of the name in the translation unit. | ||||||
1939 | /// | ||||||
1940 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | ||||||
1941 | /// if there is no class with the given name. | ||||||
1942 | /// | ||||||
1943 | /// \returns The declaration of the named Objective-C class, or NULL if the | ||||||
1944 | /// class could not be found. | ||||||
1945 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | ||||||
1946 | SourceLocation IdLoc, | ||||||
1947 | bool DoTypoCorrection) { | ||||||
1948 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | ||||||
1949 | // creation from this context. | ||||||
1950 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | ||||||
1951 | |||||||
1952 | if (!IDecl && DoTypoCorrection) { | ||||||
1953 | // Perform typo correction at the given location, but only if we | ||||||
1954 | // find an Objective-C class name. | ||||||
1955 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | ||||||
1956 | if (TypoCorrection C = | ||||||
1957 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | ||||||
1958 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | ||||||
1959 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | ||||||
1960 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | ||||||
1961 | Id = IDecl->getIdentifier(); | ||||||
1962 | } | ||||||
1963 | } | ||||||
1964 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | ||||||
1965 | // This routine must always return a class definition, if any. | ||||||
1966 | if (Def && Def->getDefinition()) | ||||||
1967 | Def = Def->getDefinition(); | ||||||
1968 | return Def; | ||||||
1969 | } | ||||||
1970 | |||||||
1971 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | ||||||
1972 | /// from S, where a non-field would be declared. This routine copes | ||||||
1973 | /// with the difference between C and C++ scoping rules in structs and | ||||||
1974 | /// unions. For example, the following code is well-formed in C but | ||||||
1975 | /// ill-formed in C++: | ||||||
1976 | /// @code | ||||||
1977 | /// struct S6 { | ||||||
1978 | /// enum { BAR } e; | ||||||
1979 | /// }; | ||||||
1980 | /// | ||||||
1981 | /// void test_S6() { | ||||||
1982 | /// struct S6 a; | ||||||
1983 | /// a.e = BAR; | ||||||
1984 | /// } | ||||||
1985 | /// @endcode | ||||||
1986 | /// For the declaration of BAR, this routine will return a different | ||||||
1987 | /// scope. The scope S will be the scope of the unnamed enumeration | ||||||
1988 | /// within S6. In C++, this routine will return the scope associated | ||||||
1989 | /// with S6, because the enumeration's scope is a transparent | ||||||
1990 | /// context but structures can contain non-field names. In C, this | ||||||
1991 | /// routine will return the translation unit scope, since the | ||||||
1992 | /// enumeration's scope is a transparent context and structures cannot | ||||||
1993 | /// contain non-field names. | ||||||
1994 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | ||||||
1995 | while (((S->getFlags() & Scope::DeclScope) == 0) || | ||||||
1996 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | ||||||
1997 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | ||||||
1998 | S = S->getParent(); | ||||||
1999 | return S; | ||||||
2000 | } | ||||||
2001 | |||||||
2002 | /// Looks up the declaration of "struct objc_super" and | ||||||
2003 | /// saves it for later use in building builtin declaration of | ||||||
2004 | /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such | ||||||
2005 | /// pre-existing declaration exists no action takes place. | ||||||
2006 | static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, | ||||||
2007 | IdentifierInfo *II) { | ||||||
2008 | if (!II->isStr("objc_msgSendSuper")) | ||||||
2009 | return; | ||||||
2010 | ASTContext &Context = ThisSema.Context; | ||||||
2011 | |||||||
2012 | LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), | ||||||
2013 | SourceLocation(), Sema::LookupTagName); | ||||||
2014 | ThisSema.LookupName(Result, S); | ||||||
2015 | if (Result.getResultKind() == LookupResult::Found) | ||||||
2016 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) | ||||||
2017 | Context.setObjCSuperType(Context.getTagDeclType(TD)); | ||||||
2018 | } | ||||||
2019 | |||||||
2020 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | ||||||
2021 | ASTContext::GetBuiltinTypeError Error) { | ||||||
2022 | switch (Error) { | ||||||
2023 | case ASTContext::GE_None: | ||||||
2024 | return ""; | ||||||
2025 | case ASTContext::GE_Missing_type: | ||||||
2026 | return BuiltinInfo.getHeaderName(ID); | ||||||
2027 | case ASTContext::GE_Missing_stdio: | ||||||
2028 | return "stdio.h"; | ||||||
2029 | case ASTContext::GE_Missing_setjmp: | ||||||
2030 | return "setjmp.h"; | ||||||
2031 | case ASTContext::GE_Missing_ucontext: | ||||||
2032 | return "ucontext.h"; | ||||||
2033 | } | ||||||
2034 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 2034); | ||||||
2035 | } | ||||||
2036 | |||||||
2037 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | ||||||
2038 | /// file scope. lazily create a decl for it. ForRedeclaration is true | ||||||
2039 | /// if we're creating this built-in in anticipation of redeclaring the | ||||||
2040 | /// built-in. | ||||||
2041 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | ||||||
2042 | Scope *S, bool ForRedeclaration, | ||||||
2043 | SourceLocation Loc) { | ||||||
2044 | LookupPredefedObjCSuperType(*this, S, II); | ||||||
2045 | |||||||
2046 | ASTContext::GetBuiltinTypeError Error; | ||||||
2047 | QualType R = Context.GetBuiltinType(ID, Error); | ||||||
2048 | if (Error) { | ||||||
2049 | if (!ForRedeclaration) | ||||||
2050 | return nullptr; | ||||||
2051 | |||||||
2052 | // If we have a builtin without an associated type we should not emit a | ||||||
2053 | // warning when we were not able to find a type for it. | ||||||
2054 | if (Error == ASTContext::GE_Missing_type) | ||||||
2055 | return nullptr; | ||||||
2056 | |||||||
2057 | // If we could not find a type for setjmp it is because the jmp_buf type was | ||||||
2058 | // not defined prior to the setjmp declaration. | ||||||
2059 | if (Error == ASTContext::GE_Missing_setjmp) { | ||||||
2060 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) | ||||||
2061 | << Context.BuiltinInfo.getName(ID); | ||||||
2062 | return nullptr; | ||||||
2063 | } | ||||||
2064 | |||||||
2065 | // Generally, we emit a warning that the declaration requires the | ||||||
2066 | // appropriate header. | ||||||
2067 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | ||||||
2068 | << getHeaderName(Context.BuiltinInfo, ID, Error) | ||||||
2069 | << Context.BuiltinInfo.getName(ID); | ||||||
2070 | return nullptr; | ||||||
2071 | } | ||||||
2072 | |||||||
2073 | if (!ForRedeclaration && | ||||||
2074 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | ||||||
2075 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | ||||||
2076 | Diag(Loc, diag::ext_implicit_lib_function_decl) | ||||||
2077 | << Context.BuiltinInfo.getName(ID) << R; | ||||||
2078 | if (Context.BuiltinInfo.getHeaderName(ID) && | ||||||
2079 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) | ||||||
2080 | Diag(Loc, diag::note_include_header_or_declare) | ||||||
2081 | << Context.BuiltinInfo.getHeaderName(ID) | ||||||
2082 | << Context.BuiltinInfo.getName(ID); | ||||||
2083 | } | ||||||
2084 | |||||||
2085 | if (R.isNull()) | ||||||
2086 | return nullptr; | ||||||
2087 | |||||||
2088 | DeclContext *Parent = Context.getTranslationUnitDecl(); | ||||||
2089 | if (getLangOpts().CPlusPlus) { | ||||||
2090 | LinkageSpecDecl *CLinkageDecl = | ||||||
2091 | LinkageSpecDecl::Create(Context, Parent, Loc, Loc, | ||||||
2092 | LinkageSpecDecl::lang_c, false); | ||||||
2093 | CLinkageDecl->setImplicit(); | ||||||
2094 | Parent->addDecl(CLinkageDecl); | ||||||
2095 | Parent = CLinkageDecl; | ||||||
2096 | } | ||||||
2097 | |||||||
2098 | FunctionDecl *New = FunctionDecl::Create(Context, | ||||||
2099 | Parent, | ||||||
2100 | Loc, Loc, II, R, /*TInfo=*/nullptr, | ||||||
2101 | SC_Extern, | ||||||
2102 | false, | ||||||
2103 | R->isFunctionProtoType()); | ||||||
2104 | New->setImplicit(); | ||||||
2105 | |||||||
2106 | // Create Decl objects for each parameter, adding them to the | ||||||
2107 | // FunctionDecl. | ||||||
2108 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { | ||||||
2109 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
2110 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||||
2111 | ParmVarDecl *parm = | ||||||
2112 | ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), | ||||||
2113 | nullptr, FT->getParamType(i), /*TInfo=*/nullptr, | ||||||
2114 | SC_None, nullptr); | ||||||
2115 | parm->setScopeInfo(0, i); | ||||||
2116 | Params.push_back(parm); | ||||||
2117 | } | ||||||
2118 | New->setParams(Params); | ||||||
2119 | } | ||||||
2120 | |||||||
2121 | AddKnownFunctionAttributes(New); | ||||||
2122 | RegisterLocallyScopedExternCDecl(New, S); | ||||||
2123 | |||||||
2124 | // TUScope is the translation-unit scope to insert this function into. | ||||||
2125 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | ||||||
2126 | // relate Scopes to DeclContexts, and probably eliminate CurContext | ||||||
2127 | // entirely, but we're not there yet. | ||||||
2128 | DeclContext *SavedContext = CurContext; | ||||||
2129 | CurContext = Parent; | ||||||
2130 | PushOnScopeChains(New, TUScope); | ||||||
2131 | CurContext = SavedContext; | ||||||
2132 | return New; | ||||||
2133 | } | ||||||
2134 | |||||||
2135 | /// Typedef declarations don't have linkage, but they still denote the same | ||||||
2136 | /// entity if their types are the same. | ||||||
2137 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | ||||||
2138 | /// isSameEntity. | ||||||
2139 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | ||||||
2140 | TypedefNameDecl *Decl, | ||||||
2141 | LookupResult &Previous) { | ||||||
2142 | // This is only interesting when modules are enabled. | ||||||
2143 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | ||||||
2144 | return; | ||||||
2145 | |||||||
2146 | // Empty sets are uninteresting. | ||||||
2147 | if (Previous.empty()) | ||||||
2148 | return; | ||||||
2149 | |||||||
2150 | LookupResult::Filter Filter = Previous.makeFilter(); | ||||||
2151 | while (Filter.hasNext()) { | ||||||
2152 | NamedDecl *Old = Filter.next(); | ||||||
2153 | |||||||
2154 | // Non-hidden declarations are never ignored. | ||||||
2155 | if (S.isVisible(Old)) | ||||||
2156 | continue; | ||||||
2157 | |||||||
2158 | // Declarations of the same entity are not ignored, even if they have | ||||||
2159 | // different linkages. | ||||||
2160 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2161 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | ||||||
2162 | Decl->getUnderlyingType())) | ||||||
2163 | continue; | ||||||
2164 | |||||||
2165 | // If both declarations give a tag declaration a typedef name for linkage | ||||||
2166 | // purposes, then they declare the same entity. | ||||||
2167 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | ||||||
2168 | Decl->getAnonDeclWithTypedefName()) | ||||||
2169 | continue; | ||||||
2170 | } | ||||||
2171 | |||||||
2172 | Filter.erase(); | ||||||
2173 | } | ||||||
2174 | |||||||
2175 | Filter.done(); | ||||||
2176 | } | ||||||
2177 | |||||||
2178 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | ||||||
2179 | QualType OldType; | ||||||
2180 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | ||||||
2181 | OldType = OldTypedef->getUnderlyingType(); | ||||||
2182 | else | ||||||
2183 | OldType = Context.getTypeDeclType(Old); | ||||||
2184 | QualType NewType = New->getUnderlyingType(); | ||||||
2185 | |||||||
2186 | if (NewType->isVariablyModifiedType()) { | ||||||
2187 | // Must not redefine a typedef with a variably-modified type. | ||||||
2188 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||||
2189 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | ||||||
2190 | << Kind << NewType; | ||||||
2191 | if (Old->getLocation().isValid()) | ||||||
2192 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2193 | New->setInvalidDecl(); | ||||||
2194 | return true; | ||||||
2195 | } | ||||||
2196 | |||||||
2197 | if (OldType != NewType && | ||||||
2198 | !OldType->isDependentType() && | ||||||
2199 | !NewType->isDependentType() && | ||||||
2200 | !Context.hasSameType(OldType, NewType)) { | ||||||
2201 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||||
2202 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | ||||||
2203 | << Kind << NewType << OldType; | ||||||
2204 | if (Old->getLocation().isValid()) | ||||||
2205 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2206 | New->setInvalidDecl(); | ||||||
2207 | return true; | ||||||
2208 | } | ||||||
2209 | return false; | ||||||
2210 | } | ||||||
2211 | |||||||
2212 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | ||||||
2213 | /// same name and scope as a previous declaration 'Old'. Figure out | ||||||
2214 | /// how to resolve this situation, merging decls or emitting | ||||||
2215 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | ||||||
2216 | /// | ||||||
2217 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | ||||||
2218 | LookupResult &OldDecls) { | ||||||
2219 | // If the new decl is known invalid already, don't bother doing any | ||||||
2220 | // merging checks. | ||||||
2221 | if (New->isInvalidDecl()) return; | ||||||
2222 | |||||||
2223 | // Allow multiple definitions for ObjC built-in typedefs. | ||||||
2224 | // FIXME: Verify the underlying types are equivalent! | ||||||
2225 | if (getLangOpts().ObjC) { | ||||||
2226 | const IdentifierInfo *TypeID = New->getIdentifier(); | ||||||
2227 | switch (TypeID->getLength()) { | ||||||
2228 | default: break; | ||||||
2229 | case 2: | ||||||
2230 | { | ||||||
2231 | if (!TypeID->isStr("id")) | ||||||
2232 | break; | ||||||
2233 | QualType T = New->getUnderlyingType(); | ||||||
2234 | if (!T->isPointerType()) | ||||||
2235 | break; | ||||||
2236 | if (!T->isVoidPointerType()) { | ||||||
2237 | QualType PT = T->castAs<PointerType>()->getPointeeType(); | ||||||
2238 | if (!PT->isStructureType()) | ||||||
2239 | break; | ||||||
2240 | } | ||||||
2241 | Context.setObjCIdRedefinitionType(T); | ||||||
2242 | // Install the built-in type for 'id', ignoring the current definition. | ||||||
2243 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | ||||||
2244 | return; | ||||||
2245 | } | ||||||
2246 | case 5: | ||||||
2247 | if (!TypeID->isStr("Class")) | ||||||
2248 | break; | ||||||
2249 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | ||||||
2250 | // Install the built-in type for 'Class', ignoring the current definition. | ||||||
2251 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | ||||||
2252 | return; | ||||||
2253 | case 3: | ||||||
2254 | if (!TypeID->isStr("SEL")) | ||||||
2255 | break; | ||||||
2256 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | ||||||
2257 | // Install the built-in type for 'SEL', ignoring the current definition. | ||||||
2258 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | ||||||
2259 | return; | ||||||
2260 | } | ||||||
2261 | // Fall through - the typedef name was not a builtin type. | ||||||
2262 | } | ||||||
2263 | |||||||
2264 | // Verify the old decl was also a type. | ||||||
2265 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | ||||||
2266 | if (!Old) { | ||||||
2267 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
2268 | << New->getDeclName(); | ||||||
2269 | |||||||
2270 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | ||||||
2271 | if (OldD->getLocation().isValid()) | ||||||
2272 | notePreviousDefinition(OldD, New->getLocation()); | ||||||
2273 | |||||||
2274 | return New->setInvalidDecl(); | ||||||
2275 | } | ||||||
2276 | |||||||
2277 | // If the old declaration is invalid, just give up here. | ||||||
2278 | if (Old->isInvalidDecl()) | ||||||
2279 | return New->setInvalidDecl(); | ||||||
2280 | |||||||
2281 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2282 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | ||||||
2283 | auto *NewTag = New->getAnonDeclWithTypedefName(); | ||||||
2284 | NamedDecl *Hidden = nullptr; | ||||||
2285 | if (OldTag && NewTag && | ||||||
2286 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | ||||||
2287 | !hasVisibleDefinition(OldTag, &Hidden)) { | ||||||
2288 | // There is a definition of this tag, but it is not visible. Use it | ||||||
2289 | // instead of our tag. | ||||||
2290 | New->setTypeForDecl(OldTD->getTypeForDecl()); | ||||||
2291 | if (OldTD->isModed()) | ||||||
2292 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | ||||||
2293 | OldTD->getUnderlyingType()); | ||||||
2294 | else | ||||||
2295 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | ||||||
2296 | |||||||
2297 | // Make the old tag definition visible. | ||||||
2298 | makeMergedDefinitionVisible(Hidden); | ||||||
2299 | |||||||
2300 | // If this was an unscoped enumeration, yank all of its enumerators | ||||||
2301 | // out of the scope. | ||||||
2302 | if (isa<EnumDecl>(NewTag)) { | ||||||
2303 | Scope *EnumScope = getNonFieldDeclScope(S); | ||||||
2304 | for (auto *D : NewTag->decls()) { | ||||||
2305 | auto *ED = cast<EnumConstantDecl>(D); | ||||||
2306 | assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0 ) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 2306, __PRETTY_FUNCTION__)); | ||||||
2307 | EnumScope->RemoveDecl(ED); | ||||||
2308 | IdResolver.RemoveDecl(ED); | ||||||
2309 | ED->getLexicalDeclContext()->removeDecl(ED); | ||||||
2310 | } | ||||||
2311 | } | ||||||
2312 | } | ||||||
2313 | } | ||||||
2314 | |||||||
2315 | // If the typedef types are not identical, reject them in all languages and | ||||||
2316 | // with any extensions enabled. | ||||||
2317 | if (isIncompatibleTypedef(Old, New)) | ||||||
2318 | return; | ||||||
2319 | |||||||
2320 | // The types match. Link up the redeclaration chain and merge attributes if | ||||||
2321 | // the old declaration was a typedef. | ||||||
2322 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2323 | New->setPreviousDecl(Typedef); | ||||||
2324 | mergeDeclAttributes(New, Old); | ||||||
2325 | } | ||||||
2326 | |||||||
2327 | if (getLangOpts().MicrosoftExt) | ||||||
2328 | return; | ||||||
2329 | |||||||
2330 | if (getLangOpts().CPlusPlus) { | ||||||
2331 | // C++ [dcl.typedef]p2: | ||||||
2332 | // In a given non-class scope, a typedef specifier can be used to | ||||||
2333 | // redefine the name of any type declared in that scope to refer | ||||||
2334 | // to the type to which it already refers. | ||||||
2335 | if (!isa<CXXRecordDecl>(CurContext)) | ||||||
2336 | return; | ||||||
2337 | |||||||
2338 | // C++0x [dcl.typedef]p4: | ||||||
2339 | // In a given class scope, a typedef specifier can be used to redefine | ||||||
2340 | // any class-name declared in that scope that is not also a typedef-name | ||||||
2341 | // to refer to the type to which it already refers. | ||||||
2342 | // | ||||||
2343 | // This wording came in via DR424, which was a correction to the | ||||||
2344 | // wording in DR56, which accidentally banned code like: | ||||||
2345 | // | ||||||
2346 | // struct S { | ||||||
2347 | // typedef struct A { } A; | ||||||
2348 | // }; | ||||||
2349 | // | ||||||
2350 | // in the C++03 standard. We implement the C++0x semantics, which | ||||||
2351 | // allow the above but disallow | ||||||
2352 | // | ||||||
2353 | // struct S { | ||||||
2354 | // typedef int I; | ||||||
2355 | // typedef int I; | ||||||
2356 | // }; | ||||||
2357 | // | ||||||
2358 | // since that was the intent of DR56. | ||||||
2359 | if (!isa<TypedefNameDecl>(Old)) | ||||||
2360 | return; | ||||||
2361 | |||||||
2362 | Diag(New->getLocation(), diag::err_redefinition) | ||||||
2363 | << New->getDeclName(); | ||||||
2364 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2365 | return New->setInvalidDecl(); | ||||||
2366 | } | ||||||
2367 | |||||||
2368 | // Modules always permit redefinition of typedefs, as does C11. | ||||||
2369 | if (getLangOpts().Modules || getLangOpts().C11) | ||||||
2370 | return; | ||||||
2371 | |||||||
2372 | // If we have a redefinition of a typedef in C, emit a warning. This warning | ||||||
2373 | // is normally mapped to an error, but can be controlled with | ||||||
2374 | // -Wtypedef-redefinition. If either the original or the redefinition is | ||||||
2375 | // in a system header, don't emit this for compatibility with GCC. | ||||||
2376 | if (getDiagnostics().getSuppressSystemWarnings() && | ||||||
2377 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | ||||||
2378 | (Old->isImplicit() || | ||||||
2379 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | ||||||
2380 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | ||||||
2381 | return; | ||||||
2382 | |||||||
2383 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | ||||||
2384 | << New->getDeclName(); | ||||||
2385 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2386 | } | ||||||
2387 | |||||||
2388 | /// DeclhasAttr - returns true if decl Declaration already has the target | ||||||
2389 | /// attribute. | ||||||
2390 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | ||||||
2391 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | ||||||
2392 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | ||||||
2393 | for (const auto *i : D->attrs()) | ||||||
2394 | if (i->getKind() == A->getKind()) { | ||||||
2395 | if (Ann) { | ||||||
2396 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | ||||||
2397 | return true; | ||||||
2398 | continue; | ||||||
2399 | } | ||||||
2400 | // FIXME: Don't hardcode this check | ||||||
2401 | if (OA && isa<OwnershipAttr>(i)) | ||||||
2402 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | ||||||
2403 | return true; | ||||||
2404 | } | ||||||
2405 | |||||||
2406 | return false; | ||||||
2407 | } | ||||||
2408 | |||||||
2409 | static bool isAttributeTargetADefinition(Decl *D) { | ||||||
2410 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||||
2411 | return VD->isThisDeclarationADefinition(); | ||||||
2412 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||||
2413 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | ||||||
2414 | return true; | ||||||
2415 | } | ||||||
2416 | |||||||
2417 | /// Merge alignment attributes from \p Old to \p New, taking into account the | ||||||
2418 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | ||||||
2419 | /// | ||||||
2420 | /// \return \c true if any attributes were added to \p New. | ||||||
2421 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | ||||||
2422 | // Look for alignas attributes on Old, and pick out whichever attribute | ||||||
2423 | // specifies the strictest alignment requirement. | ||||||
2424 | AlignedAttr *OldAlignasAttr = nullptr; | ||||||
2425 | AlignedAttr *OldStrictestAlignAttr = nullptr; | ||||||
2426 | unsigned OldAlign = 0; | ||||||
2427 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | ||||||
2428 | // FIXME: We have no way of representing inherited dependent alignments | ||||||
2429 | // in a case like: | ||||||
2430 | // template<int A, int B> struct alignas(A) X; | ||||||
2431 | // template<int A, int B> struct alignas(B) X {}; | ||||||
2432 | // For now, we just ignore any alignas attributes which are not on the | ||||||
2433 | // definition in such a case. | ||||||
2434 | if (I->isAlignmentDependent()) | ||||||
2435 | return false; | ||||||
2436 | |||||||
2437 | if (I->isAlignas()) | ||||||
2438 | OldAlignasAttr = I; | ||||||
2439 | |||||||
2440 | unsigned Align = I->getAlignment(S.Context); | ||||||
2441 | if (Align > OldAlign) { | ||||||
2442 | OldAlign = Align; | ||||||
2443 | OldStrictestAlignAttr = I; | ||||||
2444 | } | ||||||
2445 | } | ||||||
2446 | |||||||
2447 | // Look for alignas attributes on New. | ||||||
2448 | AlignedAttr *NewAlignasAttr = nullptr; | ||||||
2449 | unsigned NewAlign = 0; | ||||||
2450 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | ||||||
2451 | if (I->isAlignmentDependent()) | ||||||
2452 | return false; | ||||||
2453 | |||||||
2454 | if (I->isAlignas()) | ||||||
2455 | NewAlignasAttr = I; | ||||||
2456 | |||||||
2457 | unsigned Align = I->getAlignment(S.Context); | ||||||
2458 | if (Align > NewAlign) | ||||||
2459 | NewAlign = Align; | ||||||
2460 | } | ||||||
2461 | |||||||
2462 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | ||||||
2463 | // Both declarations have 'alignas' attributes. We require them to match. | ||||||
2464 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | ||||||
2465 | // fall short. (If two declarations both have alignas, they must both match | ||||||
2466 | // every definition, and so must match each other if there is a definition.) | ||||||
2467 | |||||||
2468 | // If either declaration only contains 'alignas(0)' specifiers, then it | ||||||
2469 | // specifies the natural alignment for the type. | ||||||
2470 | if (OldAlign == 0 || NewAlign == 0) { | ||||||
2471 | QualType Ty; | ||||||
2472 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | ||||||
2473 | Ty = VD->getType(); | ||||||
2474 | else | ||||||
2475 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | ||||||
2476 | |||||||
2477 | if (OldAlign == 0) | ||||||
2478 | OldAlign = S.Context.getTypeAlign(Ty); | ||||||
2479 | if (NewAlign == 0) | ||||||
2480 | NewAlign = S.Context.getTypeAlign(Ty); | ||||||
2481 | } | ||||||
2482 | |||||||
2483 | if (OldAlign != NewAlign) { | ||||||
2484 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | ||||||
2485 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | ||||||
2486 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | ||||||
2487 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | ||||||
2488 | } | ||||||
2489 | } | ||||||
2490 | |||||||
2491 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | ||||||
2492 | // C++11 [dcl.align]p6: | ||||||
2493 | // if any declaration of an entity has an alignment-specifier, | ||||||
2494 | // every defining declaration of that entity shall specify an | ||||||
2495 | // equivalent alignment. | ||||||
2496 | // C11 6.7.5/7: | ||||||
2497 | // If the definition of an object does not have an alignment | ||||||
2498 | // specifier, any other declaration of that object shall also | ||||||
2499 | // have no alignment specifier. | ||||||
2500 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | ||||||
2501 | << OldAlignasAttr; | ||||||
2502 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | ||||||
2503 | << OldAlignasAttr; | ||||||
2504 | } | ||||||
2505 | |||||||
2506 | bool AnyAdded = false; | ||||||
2507 | |||||||
2508 | // Ensure we have an attribute representing the strictest alignment. | ||||||
2509 | if (OldAlign > NewAlign) { | ||||||
2510 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | ||||||
2511 | Clone->setInherited(true); | ||||||
2512 | New->addAttr(Clone); | ||||||
2513 | AnyAdded = true; | ||||||
2514 | } | ||||||
2515 | |||||||
2516 | // Ensure we have an alignas attribute if the old declaration had one. | ||||||
2517 | if (OldAlignasAttr && !NewAlignasAttr && | ||||||
2518 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | ||||||
2519 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | ||||||
2520 | Clone->setInherited(true); | ||||||
2521 | New->addAttr(Clone); | ||||||
2522 | AnyAdded = true; | ||||||
2523 | } | ||||||
2524 | |||||||
2525 | return AnyAdded; | ||||||
2526 | } | ||||||
2527 | |||||||
2528 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | ||||||
2529 | const InheritableAttr *Attr, | ||||||
2530 | Sema::AvailabilityMergeKind AMK) { | ||||||
2531 | // This function copies an attribute Attr from a previous declaration to the | ||||||
2532 | // new declaration D if the new declaration doesn't itself have that attribute | ||||||
2533 | // yet or if that attribute allows duplicates. | ||||||
2534 | // If you're adding a new attribute that requires logic different from | ||||||
2535 | // "use explicit attribute on decl if present, else use attribute from | ||||||
2536 | // previous decl", for example if the attribute needs to be consistent | ||||||
2537 | // between redeclarations, you need to call a custom merge function here. | ||||||
2538 | InheritableAttr *NewAttr = nullptr; | ||||||
2539 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | ||||||
2540 | NewAttr = S.mergeAvailabilityAttr( | ||||||
2541 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), | ||||||
2542 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), | ||||||
2543 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, | ||||||
2544 | AA->getPriority()); | ||||||
2545 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | ||||||
2546 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||||
2547 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | ||||||
2548 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||||
2549 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | ||||||
2550 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); | ||||||
2551 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | ||||||
2552 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); | ||||||
2553 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | ||||||
2554 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), | ||||||
2555 | FA->getFirstArg()); | ||||||
2556 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | ||||||
2557 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); | ||||||
2558 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | ||||||
2559 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); | ||||||
2560 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | ||||||
2561 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), | ||||||
2562 | IA->getInheritanceModel()); | ||||||
2563 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | ||||||
2564 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, | ||||||
2565 | &S.Context.Idents.get(AA->getSpelling())); | ||||||
2566 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | ||||||
2567 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | ||||||
2568 | isa<CUDAGlobalAttr>(Attr))) { | ||||||
2569 | // CUDA target attributes are part of function signature for | ||||||
2570 | // overloading purposes and must not be merged. | ||||||
2571 | return false; | ||||||
2572 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | ||||||
2573 | NewAttr = S.mergeMinSizeAttr(D, *MA); | ||||||
2574 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | ||||||
2575 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); | ||||||
2576 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | ||||||
2577 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | ||||||
2578 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) | ||||||
2579 | NewAttr = S.mergeCommonAttr(D, *CommonA); | ||||||
2580 | else if (isa<AlignedAttr>(Attr)) | ||||||
2581 | // AlignedAttrs are handled separately, because we need to handle all | ||||||
2582 | // such attributes on a declaration at the same time. | ||||||
2583 | NewAttr = nullptr; | ||||||
2584 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | ||||||
2585 | (AMK == Sema::AMK_Override || | ||||||
2586 | AMK == Sema::AMK_ProtocolImplementation)) | ||||||
2587 | NewAttr = nullptr; | ||||||
2588 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | ||||||
2589 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); | ||||||
2590 | else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) | ||||||
2591 | NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); | ||||||
2592 | else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) | ||||||
2593 | NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); | ||||||
2594 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | ||||||
2595 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | ||||||
2596 | |||||||
2597 | if (NewAttr) { | ||||||
2598 | NewAttr->setInherited(true); | ||||||
2599 | D->addAttr(NewAttr); | ||||||
2600 | if (isa<MSInheritanceAttr>(NewAttr)) | ||||||
2601 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | ||||||
2602 | return true; | ||||||
2603 | } | ||||||
2604 | |||||||
2605 | return false; | ||||||
2606 | } | ||||||
2607 | |||||||
2608 | static const NamedDecl *getDefinition(const Decl *D) { | ||||||
2609 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||||
2610 | return TD->getDefinition(); | ||||||
2611 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
2612 | const VarDecl *Def = VD->getDefinition(); | ||||||
2613 | if (Def) | ||||||
2614 | return Def; | ||||||
2615 | return VD->getActingDefinition(); | ||||||
2616 | } | ||||||
2617 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) | ||||||
2618 | return FD->getDefinition(); | ||||||
2619 | return nullptr; | ||||||
2620 | } | ||||||
2621 | |||||||
2622 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | ||||||
2623 | for (const auto *Attribute : D->attrs()) | ||||||
2624 | if (Attribute->getKind() == Kind) | ||||||
2625 | return true; | ||||||
2626 | return false; | ||||||
2627 | } | ||||||
2628 | |||||||
2629 | /// checkNewAttributesAfterDef - If we already have a definition, check that | ||||||
2630 | /// there are no new attributes in this declaration. | ||||||
2631 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | ||||||
2632 | if (!New->hasAttrs()) | ||||||
2633 | return; | ||||||
2634 | |||||||
2635 | const NamedDecl *Def = getDefinition(Old); | ||||||
2636 | if (!Def || Def == New) | ||||||
2637 | return; | ||||||
2638 | |||||||
2639 | AttrVec &NewAttributes = New->getAttrs(); | ||||||
2640 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | ||||||
2641 | const Attr *NewAttribute = NewAttributes[I]; | ||||||
2642 | |||||||
2643 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | ||||||
2644 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | ||||||
2645 | Sema::SkipBodyInfo SkipBody; | ||||||
2646 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | ||||||
2647 | |||||||
2648 | // If we're skipping this definition, drop the "alias" attribute. | ||||||
2649 | if (SkipBody.ShouldSkip) { | ||||||
2650 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2651 | --E; | ||||||
2652 | continue; | ||||||
2653 | } | ||||||
2654 | } else { | ||||||
2655 | VarDecl *VD = cast<VarDecl>(New); | ||||||
2656 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | ||||||
2657 | VarDecl::TentativeDefinition | ||||||
2658 | ? diag::err_alias_after_tentative | ||||||
2659 | : diag::err_redefinition; | ||||||
2660 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | ||||||
2661 | if (Diag == diag::err_redefinition) | ||||||
2662 | S.notePreviousDefinition(Def, VD->getLocation()); | ||||||
2663 | else | ||||||
2664 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2665 | VD->setInvalidDecl(); | ||||||
2666 | } | ||||||
2667 | ++I; | ||||||
2668 | continue; | ||||||
2669 | } | ||||||
2670 | |||||||
2671 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | ||||||
2672 | // Tentative definitions are only interesting for the alias check above. | ||||||
2673 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | ||||||
2674 | ++I; | ||||||
2675 | continue; | ||||||
2676 | } | ||||||
2677 | } | ||||||
2678 | |||||||
2679 | if (hasAttribute(Def, NewAttribute->getKind())) { | ||||||
2680 | ++I; | ||||||
2681 | continue; // regular attr merging will take care of validating this. | ||||||
2682 | } | ||||||
2683 | |||||||
2684 | if (isa<C11NoReturnAttr>(NewAttribute)) { | ||||||
2685 | // C's _Noreturn is allowed to be added to a function after it is defined. | ||||||
2686 | ++I; | ||||||
2687 | continue; | ||||||
2688 | } else if (isa<UuidAttr>(NewAttribute)) { | ||||||
2689 | // msvc will allow a subsequent definition to add an uuid to a class | ||||||
2690 | ++I; | ||||||
2691 | continue; | ||||||
2692 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | ||||||
2693 | if (AA->isAlignas()) { | ||||||
2694 | // C++11 [dcl.align]p6: | ||||||
2695 | // if any declaration of an entity has an alignment-specifier, | ||||||
2696 | // every defining declaration of that entity shall specify an | ||||||
2697 | // equivalent alignment. | ||||||
2698 | // C11 6.7.5/7: | ||||||
2699 | // If the definition of an object does not have an alignment | ||||||
2700 | // specifier, any other declaration of that object shall also | ||||||
2701 | // have no alignment specifier. | ||||||
2702 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | ||||||
2703 | << AA; | ||||||
2704 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | ||||||
2705 | << AA; | ||||||
2706 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2707 | --E; | ||||||
2708 | continue; | ||||||
2709 | } | ||||||
2710 | } else if (isa<SelectAnyAttr>(NewAttribute) && | ||||||
2711 | cast<VarDecl>(New)->isInline() && | ||||||
2712 | !cast<VarDecl>(New)->isInlineSpecified()) { | ||||||
2713 | // Don't warn about applying selectany to implicitly inline variables. | ||||||
2714 | // Older compilers and language modes would require the use of selectany | ||||||
2715 | // to make such variables inline, and it would have no effect if we | ||||||
2716 | // honored it. | ||||||
2717 | ++I; | ||||||
2718 | continue; | ||||||
2719 | } | ||||||
2720 | |||||||
2721 | S.Diag(NewAttribute->getLocation(), | ||||||
2722 | diag::warn_attribute_precede_definition); | ||||||
2723 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2724 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2725 | --E; | ||||||
2726 | } | ||||||
2727 | } | ||||||
2728 | |||||||
2729 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, | ||||||
2730 | const ConstInitAttr *CIAttr, | ||||||
2731 | bool AttrBeforeInit) { | ||||||
2732 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); | ||||||
2733 | |||||||
2734 | // Figure out a good way to write this specifier on the old declaration. | ||||||
2735 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve | ||||||
2736 | // enough of the attribute list spelling information to extract that without | ||||||
2737 | // heroics. | ||||||
2738 | std::string SuitableSpelling; | ||||||
2739 | if (S.getLangOpts().CPlusPlus2a) | ||||||
2740 | SuitableSpelling = | ||||||
2741 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}); | ||||||
2742 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||||
2743 | SuitableSpelling = S.PP.getLastMacroWithSpelling( | ||||||
2744 | InsertLoc, | ||||||
2745 | {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"), | ||||||
2746 | tok::coloncolon, | ||||||
2747 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||||
2748 | tok::r_square, tok::r_square}); | ||||||
2749 | if (SuitableSpelling.empty()) | ||||||
2750 | SuitableSpelling = S.PP.getLastMacroWithSpelling( | ||||||
2751 | InsertLoc, | ||||||
2752 | {tok::kw___attribute, tok::l_paren, tok::r_paren, | ||||||
2753 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||||
2754 | tok::r_paren, tok::r_paren}); | ||||||
2755 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) | ||||||
2756 | SuitableSpelling = "constinit"; | ||||||
2757 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||||
2758 | SuitableSpelling = "[[clang::require_constant_initialization]]"; | ||||||
2759 | if (SuitableSpelling.empty()) | ||||||
2760 | SuitableSpelling = "__attribute__((require_constant_initialization))"; | ||||||
2761 | SuitableSpelling += " "; | ||||||
2762 | |||||||
2763 | if (AttrBeforeInit) { | ||||||
2764 | // extern constinit int a; | ||||||
2765 | // int a = 0; // error (missing 'constinit'), accepted as extension | ||||||
2766 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute" ) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 2766, __PRETTY_FUNCTION__)); | ||||||
2767 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) | ||||||
2768 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||||
2769 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); | ||||||
2770 | } else { | ||||||
2771 | // int a = 0; | ||||||
2772 | // constinit extern int a; // error (missing 'constinit') | ||||||
2773 | S.Diag(CIAttr->getLocation(), | ||||||
2774 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late | ||||||
2775 | : diag::warn_require_const_init_added_too_late) | ||||||
2776 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); | ||||||
2777 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) | ||||||
2778 | << CIAttr->isConstinit() | ||||||
2779 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||||
2780 | } | ||||||
2781 | } | ||||||
2782 | |||||||
2783 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | ||||||
2784 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | ||||||
2785 | AvailabilityMergeKind AMK) { | ||||||
2786 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | ||||||
2787 | UsedAttr *NewAttr = OldAttr->clone(Context); | ||||||
2788 | NewAttr->setInherited(true); | ||||||
2789 | New->addAttr(NewAttr); | ||||||
2790 | } | ||||||
2791 | |||||||
2792 | if (!Old->hasAttrs() && !New->hasAttrs()) | ||||||
2793 | return; | ||||||
2794 | |||||||
2795 | // [dcl.constinit]p1: | ||||||
2796 | // If the [constinit] specifier is applied to any declaration of a | ||||||
2797 | // variable, it shall be applied to the initializing declaration. | ||||||
2798 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); | ||||||
2799 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); | ||||||
2800 | if (bool(OldConstInit) != bool(NewConstInit)) { | ||||||
2801 | const auto *OldVD = cast<VarDecl>(Old); | ||||||
2802 | auto *NewVD = cast<VarDecl>(New); | ||||||
2803 | |||||||
2804 | // Find the initializing declaration. Note that we might not have linked | ||||||
2805 | // the new declaration into the redeclaration chain yet. | ||||||
2806 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); | ||||||
2807 | if (!InitDecl && | ||||||
2808 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) | ||||||
2809 | InitDecl = NewVD; | ||||||
2810 | |||||||
2811 | if (InitDecl == NewVD) { | ||||||
2812 | // This is the initializing declaration. If it would inherit 'constinit', | ||||||
2813 | // that's ill-formed. (Note that we do not apply this to the attribute | ||||||
2814 | // form). | ||||||
2815 | if (OldConstInit && OldConstInit->isConstinit()) | ||||||
2816 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, | ||||||
2817 | /*AttrBeforeInit=*/true); | ||||||
2818 | } else if (NewConstInit) { | ||||||
2819 | // This is the first time we've been told that this declaration should | ||||||
2820 | // have a constant initializer. If we already saw the initializing | ||||||
2821 | // declaration, this is too late. | ||||||
2822 | if (InitDecl && InitDecl != NewVD) { | ||||||
2823 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, | ||||||
2824 | /*AttrBeforeInit=*/false); | ||||||
2825 | NewVD->dropAttr<ConstInitAttr>(); | ||||||
2826 | } | ||||||
2827 | } | ||||||
2828 | } | ||||||
2829 | |||||||
2830 | // Attributes declared post-definition are currently ignored. | ||||||
2831 | checkNewAttributesAfterDef(*this, New, Old); | ||||||
2832 | |||||||
2833 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | ||||||
2834 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | ||||||
2835 | if (!OldA->isEquivalent(NewA)) { | ||||||
2836 | // This redeclaration changes __asm__ label. | ||||||
2837 | Diag(New->getLocation(), diag::err_different_asm_label); | ||||||
2838 | Diag(OldA->getLocation(), diag::note_previous_declaration); | ||||||
2839 | } | ||||||
2840 | } else if (Old->isUsed()) { | ||||||
2841 | // This redeclaration adds an __asm__ label to a declaration that has | ||||||
2842 | // already been ODR-used. | ||||||
2843 | Diag(New->getLocation(), diag::err_late_asm_label_name) | ||||||
2844 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | ||||||
2845 | } | ||||||
2846 | } | ||||||
2847 | |||||||
2848 | // Re-declaration cannot add abi_tag's. | ||||||
2849 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | ||||||
2850 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | ||||||
2851 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | ||||||
2852 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), | ||||||
2853 | NewTag) == OldAbiTagAttr->tags_end()) { | ||||||
2854 | Diag(NewAbiTagAttr->getLocation(), | ||||||
2855 | diag::err_new_abi_tag_on_redeclaration) | ||||||
2856 | << NewTag; | ||||||
2857 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | ||||||
2858 | } | ||||||
2859 | } | ||||||
2860 | } else { | ||||||
2861 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | ||||||
2862 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2863 | } | ||||||
2864 | } | ||||||
2865 | |||||||
2866 | // This redeclaration adds a section attribute. | ||||||
2867 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | ||||||
2868 | if (auto *VD = dyn_cast<VarDecl>(New)) { | ||||||
2869 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | ||||||
2870 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | ||||||
2871 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2872 | } | ||||||
2873 | } | ||||||
2874 | } | ||||||
2875 | |||||||
2876 | // Redeclaration adds code-seg attribute. | ||||||
2877 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | ||||||
2878 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | ||||||
2879 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | ||||||
2880 | Diag(New->getLocation(), diag::warn_mismatched_section) | ||||||
2881 | << 0 /*codeseg*/; | ||||||
2882 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2883 | } | ||||||
2884 | |||||||
2885 | if (!Old->hasAttrs()) | ||||||
2886 | return; | ||||||
2887 | |||||||
2888 | bool foundAny = New->hasAttrs(); | ||||||
2889 | |||||||
2890 | // Ensure that any moving of objects within the allocated map is done before | ||||||
2891 | // we process them. | ||||||
2892 | if (!foundAny) New->setAttrs(AttrVec()); | ||||||
2893 | |||||||
2894 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | ||||||
2895 | // Ignore deprecated/unavailable/availability attributes if requested. | ||||||
2896 | AvailabilityMergeKind LocalAMK = AMK_None; | ||||||
2897 | if (isa<DeprecatedAttr>(I) || | ||||||
2898 | isa<UnavailableAttr>(I) || | ||||||
2899 | isa<AvailabilityAttr>(I)) { | ||||||
2900 | switch (AMK) { | ||||||
2901 | case AMK_None: | ||||||
2902 | continue; | ||||||
2903 | |||||||
2904 | case AMK_Redeclaration: | ||||||
2905 | case AMK_Override: | ||||||
2906 | case AMK_ProtocolImplementation: | ||||||
2907 | LocalAMK = AMK; | ||||||
2908 | break; | ||||||
2909 | } | ||||||
2910 | } | ||||||
2911 | |||||||
2912 | // Already handled. | ||||||
2913 | if (isa<UsedAttr>(I)) | ||||||
2914 | continue; | ||||||
2915 | |||||||
2916 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | ||||||
2917 | foundAny = true; | ||||||
2918 | } | ||||||
2919 | |||||||
2920 | if (mergeAlignedAttrs(*this, New, Old)) | ||||||
2921 | foundAny = true; | ||||||
2922 | |||||||
2923 | if (!foundAny) New->dropAttrs(); | ||||||
2924 | } | ||||||
2925 | |||||||
2926 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | ||||||
2927 | /// to the new one. | ||||||
2928 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | ||||||
2929 | const ParmVarDecl *oldDecl, | ||||||
2930 | Sema &S) { | ||||||
2931 | // C++11 [dcl.attr.depend]p2: | ||||||
2932 | // The first declaration of a function shall specify the | ||||||
2933 | // carries_dependency attribute for its declarator-id if any declaration | ||||||
2934 | // of the function specifies the carries_dependency attribute. | ||||||
2935 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | ||||||
2936 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | ||||||
2937 | S.Diag(CDA->getLocation(), | ||||||
2938 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | ||||||
2939 | // Find the first declaration of the parameter. | ||||||
2940 | // FIXME: Should we build redeclaration chains for function parameters? | ||||||
2941 | const FunctionDecl *FirstFD = | ||||||
2942 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | ||||||
2943 | const ParmVarDecl *FirstVD = | ||||||
2944 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | ||||||
2945 | S.Diag(FirstVD->getLocation(), | ||||||
2946 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | ||||||
2947 | } | ||||||
2948 | |||||||
2949 | if (!oldDecl->hasAttrs()) | ||||||
2950 | return; | ||||||
2951 | |||||||
2952 | bool foundAny = newDecl->hasAttrs(); | ||||||
2953 | |||||||
2954 | // Ensure that any moving of objects within the allocated map is | ||||||
2955 | // done before we process them. | ||||||
2956 | if (!foundAny) newDecl->setAttrs(AttrVec()); | ||||||
2957 | |||||||
2958 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | ||||||
2959 | if (!DeclHasAttr(newDecl, I)) { | ||||||
2960 | InheritableAttr *newAttr = | ||||||
2961 | cast<InheritableParamAttr>(I->clone(S.Context)); | ||||||
2962 | newAttr->setInherited(true); | ||||||
2963 | newDecl->addAttr(newAttr); | ||||||
2964 | foundAny = true; | ||||||
2965 | } | ||||||
2966 | } | ||||||
2967 | |||||||
2968 | if (!foundAny) newDecl->dropAttrs(); | ||||||
2969 | } | ||||||
2970 | |||||||
2971 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | ||||||
2972 | const ParmVarDecl *OldParam, | ||||||
2973 | Sema &S) { | ||||||
2974 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | ||||||
2975 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | ||||||
2976 | if (*Oldnullability != *Newnullability) { | ||||||
2977 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | ||||||
2978 | << DiagNullabilityKind( | ||||||
2979 | *Newnullability, | ||||||
2980 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||||
2981 | != 0)) | ||||||
2982 | << DiagNullabilityKind( | ||||||
2983 | *Oldnullability, | ||||||
2984 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||||
2985 | != 0)); | ||||||
2986 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | ||||||
2987 | } | ||||||
2988 | } else { | ||||||
2989 | QualType NewT = NewParam->getType(); | ||||||
2990 | NewT = S.Context.getAttributedType( | ||||||
2991 | AttributedType::getNullabilityAttrKind(*Oldnullability), | ||||||
2992 | NewT, NewT); | ||||||
2993 | NewParam->setType(NewT); | ||||||
2994 | } | ||||||
2995 | } | ||||||
2996 | } | ||||||
2997 | |||||||
2998 | namespace { | ||||||
2999 | |||||||
3000 | /// Used in MergeFunctionDecl to keep track of function parameters in | ||||||
3001 | /// C. | ||||||
3002 | struct GNUCompatibleParamWarning { | ||||||
3003 | ParmVarDecl *OldParm; | ||||||
3004 | ParmVarDecl *NewParm; | ||||||
3005 | QualType PromotedType; | ||||||
3006 | }; | ||||||
3007 | |||||||
3008 | } // end anonymous namespace | ||||||
3009 | |||||||
3010 | // Determine whether the previous declaration was a definition, implicit | ||||||
3011 | // declaration, or a declaration. | ||||||
3012 | template <typename T> | ||||||
3013 | static std::pair<diag::kind, SourceLocation> | ||||||
3014 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | ||||||
3015 | diag::kind PrevDiag; | ||||||
3016 | SourceLocation OldLocation = Old->getLocation(); | ||||||
3017 | if (Old->isThisDeclarationADefinition()) | ||||||
3018 | PrevDiag = diag::note_previous_definition; | ||||||
3019 | else if (Old->isImplicit()) { | ||||||
3020 | PrevDiag = diag::note_previous_implicit_declaration; | ||||||
3021 | if (OldLocation.isInvalid()) | ||||||
3022 | OldLocation = New->getLocation(); | ||||||
3023 | } else | ||||||
3024 | PrevDiag = diag::note_previous_declaration; | ||||||
3025 | return std::make_pair(PrevDiag, OldLocation); | ||||||
3026 | } | ||||||
3027 | |||||||
3028 | /// canRedefineFunction - checks if a function can be redefined. Currently, | ||||||
3029 | /// only extern inline functions can be redefined, and even then only in | ||||||
3030 | /// GNU89 mode. | ||||||
3031 | static bool canRedefineFunction(const FunctionDecl *FD, | ||||||
3032 | const LangOptions& LangOpts) { | ||||||
3033 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | ||||||
3034 | !LangOpts.CPlusPlus && | ||||||
3035 | FD->isInlineSpecified() && | ||||||
3036 | FD->getStorageClass() == SC_Extern); | ||||||
3037 | } | ||||||
3038 | |||||||
3039 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | ||||||
3040 | const AttributedType *AT = T->getAs<AttributedType>(); | ||||||
3041 | while (AT && !AT->isCallingConv()) | ||||||
3042 | AT = AT->getModifiedType()->getAs<AttributedType>(); | ||||||
3043 | return AT; | ||||||
3044 | } | ||||||
3045 | |||||||
3046 | template <typename T> | ||||||
3047 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | ||||||
3048 | const DeclContext *DC = Old->getDeclContext(); | ||||||
3049 | if (DC->isRecord()) | ||||||
3050 | return false; | ||||||
3051 | |||||||
3052 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | ||||||
3053 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | ||||||
3054 | return true; | ||||||
3055 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | ||||||
3056 | return true; | ||||||
3057 | return false; | ||||||
3058 | } | ||||||
3059 | |||||||
3060 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | ||||||
3061 | static bool isExternC(VarTemplateDecl *) { return false; } | ||||||
3062 | |||||||
3063 | /// Check whether a redeclaration of an entity introduced by a | ||||||
3064 | /// using-declaration is valid, given that we know it's not an overload | ||||||
3065 | /// (nor a hidden tag declaration). | ||||||
3066 | template<typename ExpectedDecl> | ||||||
3067 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | ||||||
3068 | ExpectedDecl *New) { | ||||||
3069 | // C++11 [basic.scope.declarative]p4: | ||||||
3070 | // Given a set of declarations in a single declarative region, each of | ||||||
3071 | // which specifies the same unqualified name, | ||||||
3072 | // -- they shall all refer to the same entity, or all refer to functions | ||||||
3073 | // and function templates; or | ||||||
3074 | // -- exactly one declaration shall declare a class name or enumeration | ||||||
3075 | // name that is not a typedef name and the other declarations shall all | ||||||
3076 | // refer to the same variable or enumerator, or all refer to functions | ||||||
3077 | // and function templates; in this case the class name or enumeration | ||||||
3078 | // name is hidden (3.3.10). | ||||||
3079 | |||||||
3080 | // C++11 [namespace.udecl]p14: | ||||||
3081 | // If a function declaration in namespace scope or block scope has the | ||||||
3082 | // same name and the same parameter-type-list as a function introduced | ||||||
3083 | // by a using-declaration, and the declarations do not declare the same | ||||||
3084 | // function, the program is ill-formed. | ||||||
3085 | |||||||
3086 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | ||||||
3087 | if (Old && | ||||||
3088 | !Old->getDeclContext()->getRedeclContext()->Equals( | ||||||
3089 | New->getDeclContext()->getRedeclContext()) && | ||||||
3090 | !(isExternC(Old) && isExternC(New))) | ||||||
3091 | Old = nullptr; | ||||||
3092 | |||||||
3093 | if (!Old) { | ||||||
3094 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | ||||||
3095 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | ||||||
3096 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; | ||||||
3097 | return true; | ||||||
3098 | } | ||||||
3099 | return false; | ||||||
3100 | } | ||||||
3101 | |||||||
3102 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | ||||||
3103 | const FunctionDecl *B) { | ||||||
3104 | assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast <void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3104, __PRETTY_FUNCTION__)); | ||||||
3105 | |||||||
3106 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | ||||||
3107 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | ||||||
3108 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | ||||||
3109 | if (AttrA == AttrB) | ||||||
3110 | return true; | ||||||
3111 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | ||||||
3112 | AttrA->isDynamic() == AttrB->isDynamic(); | ||||||
3113 | }; | ||||||
3114 | |||||||
3115 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | ||||||
3116 | } | ||||||
3117 | |||||||
3118 | /// If necessary, adjust the semantic declaration context for a qualified | ||||||
3119 | /// declaration to name the correct inline namespace within the qualifier. | ||||||
3120 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | ||||||
3121 | DeclaratorDecl *OldD) { | ||||||
3122 | // The only case where we need to update the DeclContext is when | ||||||
3123 | // redeclaration lookup for a qualified name finds a declaration | ||||||
3124 | // in an inline namespace within the context named by the qualifier: | ||||||
3125 | // | ||||||
3126 | // inline namespace N { int f(); } | ||||||
3127 | // int ::f(); // Sema DC needs adjusting from :: to N::. | ||||||
3128 | // | ||||||
3129 | // For unqualified declarations, the semantic context *can* change | ||||||
3130 | // along the redeclaration chain (for local extern declarations, | ||||||
3131 | // extern "C" declarations, and friend declarations in particular). | ||||||
3132 | if (!NewD->getQualifier()) | ||||||
3133 | return; | ||||||
3134 | |||||||
3135 | // NewD is probably already in the right context. | ||||||
3136 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | ||||||
3137 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | ||||||
3138 | if (NamedDC->Equals(SemaDC)) | ||||||
3139 | return; | ||||||
3140 | |||||||
3141 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3143, __PRETTY_FUNCTION__)) | ||||||
3142 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3143, __PRETTY_FUNCTION__)) | ||||||
3143 | "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3143, __PRETTY_FUNCTION__)); | ||||||
3144 | |||||||
3145 | auto *LexDC = NewD->getLexicalDeclContext(); | ||||||
3146 | auto FixSemaDC = [=](NamedDecl *D) { | ||||||
3147 | if (!D) | ||||||
3148 | return; | ||||||
3149 | D->setDeclContext(SemaDC); | ||||||
3150 | D->setLexicalDeclContext(LexDC); | ||||||
3151 | }; | ||||||
3152 | |||||||
3153 | FixSemaDC(NewD); | ||||||
3154 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | ||||||
3155 | FixSemaDC(FD->getDescribedFunctionTemplate()); | ||||||
3156 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | ||||||
3157 | FixSemaDC(VD->getDescribedVarTemplate()); | ||||||
3158 | } | ||||||
3159 | |||||||
3160 | /// MergeFunctionDecl - We just parsed a function 'New' from | ||||||
3161 | /// declarator D which has the same name and scope as a previous | ||||||
3162 | /// declaration 'Old'. Figure out how to resolve this situation, | ||||||
3163 | /// merging decls or emitting diagnostics as appropriate. | ||||||
3164 | /// | ||||||
3165 | /// In C++, New and Old must be declarations that are not | ||||||
3166 | /// overloaded. Use IsOverload to determine whether New and Old are | ||||||
3167 | /// overloaded, and to select the Old declaration that New should be | ||||||
3168 | /// merged with. | ||||||
3169 | /// | ||||||
3170 | /// Returns true if there was an error, false otherwise. | ||||||
3171 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | ||||||
3172 | Scope *S, bool MergeTypeWithOld) { | ||||||
3173 | // Verify the old decl was also a function. | ||||||
3174 | FunctionDecl *Old = OldD->getAsFunction(); | ||||||
3175 | if (!Old) { | ||||||
3176 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | ||||||
3177 | if (New->getFriendObjectKind()) { | ||||||
3178 | Diag(New->getLocation(), diag::err_using_decl_friend); | ||||||
3179 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||||
3180 | diag::note_using_decl_target); | ||||||
3181 | Diag(Shadow->getUsingDecl()->getLocation(), | ||||||
3182 | diag::note_using_decl) << 0; | ||||||
3183 | return true; | ||||||
3184 | } | ||||||
3185 | |||||||
3186 | // Check whether the two declarations might declare the same function. | ||||||
3187 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | ||||||
3188 | return true; | ||||||
3189 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | ||||||
3190 | } else { | ||||||
3191 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
3192 | << New->getDeclName(); | ||||||
3193 | notePreviousDefinition(OldD, New->getLocation()); | ||||||
3194 | return true; | ||||||
3195 | } | ||||||
3196 | } | ||||||
3197 | |||||||
3198 | // If the old declaration is invalid, just give up here. | ||||||
3199 | if (Old->isInvalidDecl()) | ||||||
3200 | return true; | ||||||
3201 | |||||||
3202 | // Disallow redeclaration of some builtins. | ||||||
3203 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | ||||||
3204 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | ||||||
3205 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | ||||||
3206 | << Old << Old->getType(); | ||||||
3207 | return true; | ||||||
3208 | } | ||||||
3209 | |||||||
3210 | diag::kind PrevDiag; | ||||||
3211 | SourceLocation OldLocation; | ||||||
3212 | std::tie(PrevDiag, OldLocation) = | ||||||
3213 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
3214 | |||||||
3215 | // Don't complain about this if we're in GNU89 mode and the old function | ||||||
3216 | // is an extern inline function. | ||||||
3217 | // Don't complain about specializations. They are not supposed to have | ||||||
3218 | // storage classes. | ||||||
3219 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | ||||||
3220 | New->getStorageClass() == SC_Static && | ||||||
3221 | Old->hasExternalFormalLinkage() && | ||||||
3222 | !New->getTemplateSpecializationInfo() && | ||||||
3223 | !canRedefineFunction(Old, getLangOpts())) { | ||||||
3224 | if (getLangOpts().MicrosoftExt) { | ||||||
3225 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | ||||||
3226 | Diag(OldLocation, PrevDiag); | ||||||
3227 | } else { | ||||||
3228 | Diag(New->getLocation(), diag::err_static_non_static) << New; | ||||||
3229 | Diag(OldLocation, PrevDiag); | ||||||
3230 | return true; | ||||||
3231 | } | ||||||
3232 | } | ||||||
3233 | |||||||
3234 | if (New->hasAttr<InternalLinkageAttr>() && | ||||||
3235 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||||
3236 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||||
3237 | << New->getDeclName(); | ||||||
3238 | notePreviousDefinition(Old, New->getLocation()); | ||||||
3239 | New->dropAttr<InternalLinkageAttr>(); | ||||||
3240 | } | ||||||
3241 | |||||||
3242 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||||
3243 | return true; | ||||||
3244 | |||||||
3245 | if (!getLangOpts().CPlusPlus) { | ||||||
3246 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | ||||||
3247 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | ||||||
3248 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | ||||||
3249 | << New << OldOvl; | ||||||
3250 | |||||||
3251 | // Try our best to find a decl that actually has the overloadable | ||||||
3252 | // attribute for the note. In most cases (e.g. programs with only one | ||||||
3253 | // broken declaration/definition), this won't matter. | ||||||
3254 | // | ||||||
3255 | // FIXME: We could do this if we juggled some extra state in | ||||||
3256 | // OverloadableAttr, rather than just removing it. | ||||||
3257 | const Decl *DiagOld = Old; | ||||||
3258 | if (OldOvl) { | ||||||
3259 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | ||||||
3260 | const auto *A = D->getAttr<OverloadableAttr>(); | ||||||
3261 | return A && !A->isImplicit(); | ||||||
3262 | }); | ||||||
3263 | // If we've implicitly added *all* of the overloadable attrs to this | ||||||
3264 | // chain, emitting a "previous redecl" note is pointless. | ||||||
3265 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | ||||||
3266 | } | ||||||
3267 | |||||||
3268 | if (DiagOld) | ||||||
3269 | Diag(DiagOld->getLocation(), | ||||||
3270 | diag::note_attribute_overloadable_prev_overload) | ||||||
3271 | << OldOvl; | ||||||
3272 | |||||||
3273 | if (OldOvl) | ||||||
3274 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||||
3275 | else | ||||||
3276 | New->dropAttr<OverloadableAttr>(); | ||||||
3277 | } | ||||||
3278 | } | ||||||
3279 | |||||||
3280 | // If a function is first declared with a calling convention, but is later | ||||||
3281 | // declared or defined without one, all following decls assume the calling | ||||||
3282 | // convention of the first. | ||||||
3283 | // | ||||||
3284 | // It's OK if a function is first declared without a calling convention, | ||||||
3285 | // but is later declared or defined with the default calling convention. | ||||||
3286 | // | ||||||
3287 | // To test if either decl has an explicit calling convention, we look for | ||||||
3288 | // AttributedType sugar nodes on the type as written. If they are missing or | ||||||
3289 | // were canonicalized away, we assume the calling convention was implicit. | ||||||
3290 | // | ||||||
3291 | // Note also that we DO NOT return at this point, because we still have | ||||||
3292 | // other tests to run. | ||||||
3293 | QualType OldQType = Context.getCanonicalType(Old->getType()); | ||||||
3294 | QualType NewQType = Context.getCanonicalType(New->getType()); | ||||||
3295 | const FunctionType *OldType = cast<FunctionType>(OldQType); | ||||||
3296 | const FunctionType *NewType = cast<FunctionType>(NewQType); | ||||||
3297 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||||
3298 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||||
3299 | bool RequiresAdjustment = false; | ||||||
3300 | |||||||
3301 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | ||||||
3302 | FunctionDecl *First = Old->getFirstDecl(); | ||||||
3303 | const FunctionType *FT = | ||||||
3304 | First->getType().getCanonicalType()->castAs<FunctionType>(); | ||||||
3305 | FunctionType::ExtInfo FI = FT->getExtInfo(); | ||||||
3306 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | ||||||
3307 | if (!NewCCExplicit) { | ||||||
3308 | // Inherit the CC from the previous declaration if it was specified | ||||||
3309 | // there but not here. | ||||||
3310 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||||
3311 | RequiresAdjustment = true; | ||||||
3312 | } else if (New->getBuiltinID()) { | ||||||
3313 | // Calling Conventions on a Builtin aren't really useful and setting a | ||||||
3314 | // default calling convention and cdecl'ing some builtin redeclarations is | ||||||
3315 | // common, so warn and ignore the calling convention on the redeclaration. | ||||||
3316 | Diag(New->getLocation(), diag::warn_cconv_unsupported) | ||||||
3317 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||||
3318 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | ||||||
3319 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||||
3320 | RequiresAdjustment = true; | ||||||
3321 | } else { | ||||||
3322 | // Calling conventions aren't compatible, so complain. | ||||||
3323 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | ||||||
3324 | Diag(New->getLocation(), diag::err_cconv_change) | ||||||
3325 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||||
3326 | << !FirstCCExplicit | ||||||
3327 | << (!FirstCCExplicit ? "" : | ||||||
3328 | FunctionType::getNameForCallConv(FI.getCC())); | ||||||
3329 | |||||||
3330 | // Put the note on the first decl, since it is the one that matters. | ||||||
3331 | Diag(First->getLocation(), diag::note_previous_declaration); | ||||||
3332 | return true; | ||||||
3333 | } | ||||||
3334 | } | ||||||
3335 | |||||||
3336 | // FIXME: diagnose the other way around? | ||||||
3337 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | ||||||
3338 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | ||||||
3339 | RequiresAdjustment = true; | ||||||
3340 | } | ||||||
3341 | |||||||
3342 | // Merge regparm attribute. | ||||||
3343 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | ||||||
3344 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | ||||||
3345 | if (NewTypeInfo.getHasRegParm()) { | ||||||
3346 | Diag(New->getLocation(), diag::err_regparm_mismatch) | ||||||
3347 | << NewType->getRegParmType() | ||||||
3348 | << OldType->getRegParmType(); | ||||||
3349 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3350 | return true; | ||||||
3351 | } | ||||||
3352 | |||||||
3353 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | ||||||
3354 | RequiresAdjustment = true; | ||||||
3355 | } | ||||||
3356 | |||||||
3357 | // Merge ns_returns_retained attribute. | ||||||
3358 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | ||||||
3359 | if (NewTypeInfo.getProducesResult()) { | ||||||
3360 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | ||||||
3361 | << "'ns_returns_retained'"; | ||||||
3362 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3363 | return true; | ||||||
3364 | } | ||||||
3365 | |||||||
3366 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | ||||||
3367 | RequiresAdjustment = true; | ||||||
3368 | } | ||||||
3369 | |||||||
3370 | if (OldTypeInfo.getNoCallerSavedRegs() != | ||||||
3371 | NewTypeInfo.getNoCallerSavedRegs()) { | ||||||
3372 | if (NewTypeInfo.getNoCallerSavedRegs()) { | ||||||
3373 | AnyX86NoCallerSavedRegistersAttr *Attr = | ||||||
3374 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | ||||||
3375 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | ||||||
3376 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3377 | return true; | ||||||
3378 | } | ||||||
3379 | |||||||
3380 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | ||||||
3381 | RequiresAdjustment = true; | ||||||
3382 | } | ||||||
3383 | |||||||
3384 | if (RequiresAdjustment) { | ||||||
3385 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | ||||||
3386 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | ||||||
3387 | New->setType(QualType(AdjustedType, 0)); | ||||||
3388 | NewQType = Context.getCanonicalType(New->getType()); | ||||||
3389 | } | ||||||
3390 | |||||||
3391 | // If this redeclaration makes the function inline, we may need to add it to | ||||||
3392 | // UndefinedButUsed. | ||||||
3393 | if (!Old->isInlined() && New->isInlined() && | ||||||
3394 | !New->hasAttr<GNUInlineAttr>() && | ||||||
3395 | !getLangOpts().GNUInline && | ||||||
3396 | Old->isUsed(false) && | ||||||
3397 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | ||||||
3398 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||||
3399 | SourceLocation())); | ||||||
3400 | |||||||
3401 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | ||||||
3402 | // about it. | ||||||
3403 | if (New->hasAttr<GNUInlineAttr>() && | ||||||
3404 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | ||||||
3405 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | ||||||
3406 | } | ||||||
3407 | |||||||
3408 | // If pass_object_size params don't match up perfectly, this isn't a valid | ||||||
3409 | // redeclaration. | ||||||
3410 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | ||||||
3411 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | ||||||
3412 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | ||||||
3413 | << New->getDeclName(); | ||||||
3414 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3415 | return true; | ||||||
3416 | } | ||||||
3417 | |||||||
3418 | if (getLangOpts().CPlusPlus) { | ||||||
3419 | // C++1z [over.load]p2 | ||||||
3420 | // Certain function declarations cannot be overloaded: | ||||||
3421 | // -- Function declarations that differ only in the return type, | ||||||
3422 | // the exception specification, or both cannot be overloaded. | ||||||
3423 | |||||||
3424 | // Check the exception specifications match. This may recompute the type of | ||||||
3425 | // both Old and New if it resolved exception specifications, so grab the | ||||||
3426 | // types again after this. Because this updates the type, we do this before | ||||||
3427 | // any of the other checks below, which may update the "de facto" NewQType | ||||||
3428 | // but do not necessarily update the type of New. | ||||||
3429 | if (CheckEquivalentExceptionSpec(Old, New)) | ||||||
3430 | return true; | ||||||
3431 | OldQType = Context.getCanonicalType(Old->getType()); | ||||||
3432 | NewQType = Context.getCanonicalType(New->getType()); | ||||||
3433 | |||||||
3434 | // Go back to the type source info to compare the declared return types, | ||||||
3435 | // per C++1y [dcl.type.auto]p13: | ||||||
3436 | // Redeclarations or specializations of a function or function template | ||||||
3437 | // with a declared return type that uses a placeholder type shall also | ||||||
3438 | // use that placeholder, not a deduced type. | ||||||
3439 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | ||||||
3440 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | ||||||
3441 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | ||||||
3442 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | ||||||
3443 | OldDeclaredReturnType)) { | ||||||
3444 | QualType ResQT; | ||||||
3445 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | ||||||
3446 | OldDeclaredReturnType->isObjCObjectPointerType()) | ||||||
3447 | // FIXME: This does the wrong thing for a deduced return type. | ||||||
3448 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | ||||||
3449 | if (ResQT.isNull()) { | ||||||
3450 | if (New->isCXXClassMember() && New->isOutOfLine()) | ||||||
3451 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | ||||||
3452 | << New << New->getReturnTypeSourceRange(); | ||||||
3453 | else | ||||||
3454 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | ||||||
3455 | << New->getReturnTypeSourceRange(); | ||||||
3456 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | ||||||
3457 | << Old->getReturnTypeSourceRange(); | ||||||
3458 | return true; | ||||||
3459 | } | ||||||
3460 | else | ||||||
3461 | NewQType = ResQT; | ||||||
3462 | } | ||||||
3463 | |||||||
3464 | QualType OldReturnType = OldType->getReturnType(); | ||||||
3465 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | ||||||
3466 | if (OldReturnType != NewReturnType) { | ||||||
3467 | // If this function has a deduced return type and has already been | ||||||
3468 | // defined, copy the deduced value from the old declaration. | ||||||
3469 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | ||||||
3470 | if (OldAT && OldAT->isDeduced()) { | ||||||
3471 | New->setType( | ||||||
3472 | SubstAutoType(New->getType(), | ||||||
3473 | OldAT->isDependentType() ? Context.DependentTy | ||||||
3474 | : OldAT->getDeducedType())); | ||||||
3475 | NewQType = Context.getCanonicalType( | ||||||
3476 | SubstAutoType(NewQType, | ||||||
3477 | OldAT->isDependentType() ? Context.DependentTy | ||||||
3478 | : OldAT->getDeducedType())); | ||||||
3479 | } | ||||||
3480 | } | ||||||
3481 | |||||||
3482 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | ||||||
3483 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | ||||||
3484 | if (OldMethod && NewMethod) { | ||||||
3485 | // Preserve triviality. | ||||||
3486 | NewMethod->setTrivial(OldMethod->isTrivial()); | ||||||
3487 | |||||||
3488 | // MSVC allows explicit template specialization at class scope: | ||||||
3489 | // 2 CXXMethodDecls referring to the same function will be injected. | ||||||
3490 | // We don't want a redeclaration error. | ||||||
3491 | bool IsClassScopeExplicitSpecialization = | ||||||
3492 | OldMethod->isFunctionTemplateSpecialization() && | ||||||
3493 | NewMethod->isFunctionTemplateSpecialization(); | ||||||
3494 | bool isFriend = NewMethod->getFriendObjectKind(); | ||||||
3495 | |||||||
3496 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | ||||||
3497 | !IsClassScopeExplicitSpecialization) { | ||||||
3498 | // -- Member function declarations with the same name and the | ||||||
3499 | // same parameter types cannot be overloaded if any of them | ||||||
3500 | // is a static member function declaration. | ||||||
3501 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | ||||||
3502 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | ||||||
3503 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3504 | return true; | ||||||
3505 | } | ||||||
3506 | |||||||
3507 | // C++ [class.mem]p1: | ||||||
3508 | // [...] A member shall not be declared twice in the | ||||||
3509 | // member-specification, except that a nested class or member | ||||||
3510 | // class template can be declared and then later defined. | ||||||
3511 | if (!inTemplateInstantiation()) { | ||||||
3512 | unsigned NewDiag; | ||||||
3513 | if (isa<CXXConstructorDecl>(OldMethod)) | ||||||
3514 | NewDiag = diag::err_constructor_redeclared; | ||||||
3515 | else if (isa<CXXDestructorDecl>(NewMethod)) | ||||||
3516 | NewDiag = diag::err_destructor_redeclared; | ||||||
3517 | else if (isa<CXXConversionDecl>(NewMethod)) | ||||||
3518 | NewDiag = diag::err_conv_function_redeclared; | ||||||
3519 | else | ||||||
3520 | NewDiag = diag::err_member_redeclared; | ||||||
3521 | |||||||
3522 | Diag(New->getLocation(), NewDiag); | ||||||
3523 | } else { | ||||||
3524 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | ||||||
3525 | << New << New->getType(); | ||||||
3526 | } | ||||||
3527 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3528 | return true; | ||||||
3529 | |||||||
3530 | // Complain if this is an explicit declaration of a special | ||||||
3531 | // member that was initially declared implicitly. | ||||||
3532 | // | ||||||
3533 | // As an exception, it's okay to befriend such methods in order | ||||||
3534 | // to permit the implicit constructor/destructor/operator calls. | ||||||
3535 | } else if (OldMethod->isImplicit()) { | ||||||
3536 | if (isFriend) { | ||||||
3537 | NewMethod->setImplicit(); | ||||||
3538 | } else { | ||||||
3539 | Diag(NewMethod->getLocation(), | ||||||
3540 | diag::err_definition_of_implicitly_declared_member) | ||||||
3541 | << New << getSpecialMember(OldMethod); | ||||||
3542 | return true; | ||||||
3543 | } | ||||||
3544 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | ||||||
3545 | Diag(NewMethod->getLocation(), | ||||||
3546 | diag::err_definition_of_explicitly_defaulted_member) | ||||||
3547 | << getSpecialMember(OldMethod); | ||||||
3548 | return true; | ||||||
3549 | } | ||||||
3550 | } | ||||||
3551 | |||||||
3552 | // C++11 [dcl.attr.noreturn]p1: | ||||||
3553 | // The first declaration of a function shall specify the noreturn | ||||||
3554 | // attribute if any declaration of that function specifies the noreturn | ||||||
3555 | // attribute. | ||||||
3556 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); | ||||||
3557 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { | ||||||
3558 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); | ||||||
3559 | Diag(Old->getFirstDecl()->getLocation(), | ||||||
3560 | diag::note_noreturn_missing_first_decl); | ||||||
3561 | } | ||||||
3562 | |||||||
3563 | // C++11 [dcl.attr.depend]p2: | ||||||
3564 | // The first declaration of a function shall specify the | ||||||
3565 | // carries_dependency attribute for its declarator-id if any declaration | ||||||
3566 | // of the function specifies the carries_dependency attribute. | ||||||
3567 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | ||||||
3568 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | ||||||
3569 | Diag(CDA->getLocation(), | ||||||
3570 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | ||||||
3571 | Diag(Old->getFirstDecl()->getLocation(), | ||||||
3572 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | ||||||
3573 | } | ||||||
3574 | |||||||
3575 | // (C++98 8.3.5p3): | ||||||
3576 | // All declarations for a function shall agree exactly in both the | ||||||
3577 | // return type and the parameter-type-list. | ||||||
3578 | // We also want to respect all the extended bits except noreturn. | ||||||
3579 | |||||||
3580 | // noreturn should now match unless the old type info didn't have it. | ||||||
3581 | QualType OldQTypeForComparison = OldQType; | ||||||
3582 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | ||||||
3583 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | ||||||
3584 | const FunctionType *OldTypeForComparison | ||||||
3585 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | ||||||
3586 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | ||||||
3587 | assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void> (0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3587, __PRETTY_FUNCTION__)); | ||||||
3588 | } | ||||||
3589 | |||||||
3590 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||||
3591 | // As a special case, retain the language linkage from previous | ||||||
3592 | // declarations of a friend function as an extension. | ||||||
3593 | // | ||||||
3594 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | ||||||
3595 | // and is useful because there's otherwise no way to specify language | ||||||
3596 | // linkage within class scope. | ||||||
3597 | // | ||||||
3598 | // Check cautiously as the friend object kind isn't yet complete. | ||||||
3599 | if (New->getFriendObjectKind() != Decl::FOK_None) { | ||||||
3600 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | ||||||
3601 | Diag(OldLocation, PrevDiag); | ||||||
3602 | } else { | ||||||
3603 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||||
3604 | Diag(OldLocation, PrevDiag); | ||||||
3605 | return true; | ||||||
3606 | } | ||||||
3607 | } | ||||||
3608 | |||||||
3609 | // If the function types are compatible, merge the declarations. Ignore the | ||||||
3610 | // exception specifier because it was already checked above in | ||||||
3611 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics | ||||||
3612 | // about incompatible types under -fms-compatibility. | ||||||
3613 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, | ||||||
3614 | NewQType)) | ||||||
3615 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3616 | |||||||
3617 | // If the types are imprecise (due to dependent constructs in friends or | ||||||
3618 | // local extern declarations), it's OK if they differ. We'll check again | ||||||
3619 | // during instantiation. | ||||||
3620 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | ||||||
3621 | return false; | ||||||
3622 | |||||||
3623 | // Fall through for conflicting redeclarations and redefinitions. | ||||||
3624 | } | ||||||
3625 | |||||||
3626 | // C: Function types need to be compatible, not identical. This handles | ||||||
3627 | // duplicate function decls like "void f(int); void f(enum X);" properly. | ||||||
3628 | if (!getLangOpts().CPlusPlus && | ||||||
3629 | Context.typesAreCompatible(OldQType, NewQType)) { | ||||||
3630 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | ||||||
3631 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | ||||||
3632 | const FunctionProtoType *OldProto = nullptr; | ||||||
3633 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | ||||||
3634 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | ||||||
3635 | // The old declaration provided a function prototype, but the | ||||||
3636 | // new declaration does not. Merge in the prototype. | ||||||
3637 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C" ) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3637, __PRETTY_FUNCTION__)); | ||||||
3638 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | ||||||
3639 | NewQType = | ||||||
3640 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | ||||||
3641 | OldProto->getExtProtoInfo()); | ||||||
3642 | New->setType(NewQType); | ||||||
3643 | New->setHasInheritedPrototype(); | ||||||
3644 | |||||||
3645 | // Synthesize parameters with the same types. | ||||||
3646 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
3647 | for (const auto &ParamType : OldProto->param_types()) { | ||||||
3648 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | ||||||
3649 | SourceLocation(), nullptr, | ||||||
3650 | ParamType, /*TInfo=*/nullptr, | ||||||
3651 | SC_None, nullptr); | ||||||
3652 | Param->setScopeInfo(0, Params.size()); | ||||||
3653 | Param->setImplicit(); | ||||||
3654 | Params.push_back(Param); | ||||||
3655 | } | ||||||
3656 | |||||||
3657 | New->setParams(Params); | ||||||
3658 | } | ||||||
3659 | |||||||
3660 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3661 | } | ||||||
3662 | |||||||
3663 | // Check if the function types are compatible when pointer size address | ||||||
3664 | // spaces are ignored. | ||||||
3665 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) | ||||||
3666 | return false; | ||||||
3667 | |||||||
3668 | // GNU C permits a K&R definition to follow a prototype declaration | ||||||
3669 | // if the declared types of the parameters in the K&R definition | ||||||
3670 | // match the types in the prototype declaration, even when the | ||||||
3671 | // promoted types of the parameters from the K&R definition differ | ||||||
3672 | // from the types in the prototype. GCC then keeps the types from | ||||||
3673 | // the prototype. | ||||||
3674 | // | ||||||
3675 | // If a variadic prototype is followed by a non-variadic K&R definition, | ||||||
3676 | // the K&R definition becomes variadic. This is sort of an edge case, but | ||||||
3677 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | ||||||
3678 | // C99 6.9.1p8. | ||||||
3679 | if (!getLangOpts().CPlusPlus && | ||||||
3680 | Old->hasPrototype() && !New->hasPrototype() && | ||||||
3681 | New->getType()->getAs<FunctionProtoType>() && | ||||||
3682 | Old->getNumParams() == New->getNumParams()) { | ||||||
3683 | SmallVector<QualType, 16> ArgTypes; | ||||||
3684 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | ||||||
3685 | const FunctionProtoType *OldProto | ||||||
3686 | = Old->getType()->getAs<FunctionProtoType>(); | ||||||
3687 | const FunctionProtoType *NewProto | ||||||
3688 | = New->getType()->getAs<FunctionProtoType>(); | ||||||
3689 | |||||||
3690 | // Determine whether this is the GNU C extension. | ||||||
3691 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | ||||||
3692 | NewProto->getReturnType()); | ||||||
3693 | bool LooseCompatible = !MergedReturn.isNull(); | ||||||
3694 | for (unsigned Idx = 0, End = Old->getNumParams(); | ||||||
3695 | LooseCompatible && Idx != End; ++Idx) { | ||||||
3696 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | ||||||
3697 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | ||||||
3698 | if (Context.typesAreCompatible(OldParm->getType(), | ||||||
3699 | NewProto->getParamType(Idx))) { | ||||||
3700 | ArgTypes.push_back(NewParm->getType()); | ||||||
3701 | } else if (Context.typesAreCompatible(OldParm->getType(), | ||||||
3702 | NewParm->getType(), | ||||||
3703 | /*CompareUnqualified=*/true)) { | ||||||
3704 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | ||||||
3705 | NewProto->getParamType(Idx) }; | ||||||
3706 | Warnings.push_back(Warn); | ||||||
3707 | ArgTypes.push_back(NewParm->getType()); | ||||||
3708 | } else | ||||||
3709 | LooseCompatible = false; | ||||||
3710 | } | ||||||
3711 | |||||||
3712 | if (LooseCompatible) { | ||||||
3713 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | ||||||
3714 | Diag(Warnings[Warn].NewParm->getLocation(), | ||||||
3715 | diag::ext_param_promoted_not_compatible_with_prototype) | ||||||
3716 | << Warnings[Warn].PromotedType | ||||||
3717 | << Warnings[Warn].OldParm->getType(); | ||||||
3718 | if (Warnings[Warn].OldParm->getLocation().isValid()) | ||||||
3719 | Diag(Warnings[Warn].OldParm->getLocation(), | ||||||
3720 | diag::note_previous_declaration); | ||||||
3721 | } | ||||||
3722 | |||||||
3723 | if (MergeTypeWithOld) | ||||||
3724 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | ||||||
3725 | OldProto->getExtProtoInfo())); | ||||||
3726 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3727 | } | ||||||
3728 | |||||||
3729 | // Fall through to diagnose conflicting types. | ||||||
3730 | } | ||||||
3731 | |||||||
3732 | // A function that has already been declared has been redeclared or | ||||||
3733 | // defined with a different type; show an appropriate diagnostic. | ||||||
3734 | |||||||
3735 | // If the previous declaration was an implicitly-generated builtin | ||||||
3736 | // declaration, then at the very least we should use a specialized note. | ||||||
3737 | unsigned BuiltinID; | ||||||
3738 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | ||||||
3739 | // If it's actually a library-defined builtin function like 'malloc' | ||||||
3740 | // or 'printf', just warn about the incompatible redeclaration. | ||||||
3741 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | ||||||
3742 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | ||||||
3743 | Diag(OldLocation, diag::note_previous_builtin_declaration) | ||||||
3744 | << Old << Old->getType(); | ||||||
3745 | |||||||
3746 | // If this is a global redeclaration, just forget hereafter | ||||||
3747 | // about the "builtin-ness" of the function. | ||||||
3748 | // | ||||||
3749 | // Doing this for local extern declarations is problematic. If | ||||||
3750 | // the builtin declaration remains visible, a second invalid | ||||||
3751 | // local declaration will produce a hard error; if it doesn't | ||||||
3752 | // remain visible, a single bogus local redeclaration (which is | ||||||
3753 | // actually only a warning) could break all the downstream code. | ||||||
3754 | if (!New->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
3755 | New->getIdentifier()->revertBuiltin(); | ||||||
3756 | |||||||
3757 | return false; | ||||||
3758 | } | ||||||
3759 | |||||||
3760 | PrevDiag = diag::note_previous_builtin_declaration; | ||||||
3761 | } | ||||||
3762 | |||||||
3763 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | ||||||
3764 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3765 | return true; | ||||||
3766 | } | ||||||
3767 | |||||||
3768 | /// Completes the merge of two function declarations that are | ||||||
3769 | /// known to be compatible. | ||||||
3770 | /// | ||||||
3771 | /// This routine handles the merging of attributes and other | ||||||
3772 | /// properties of function declarations from the old declaration to | ||||||
3773 | /// the new declaration, once we know that New is in fact a | ||||||
3774 | /// redeclaration of Old. | ||||||
3775 | /// | ||||||
3776 | /// \returns false | ||||||
3777 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | ||||||
3778 | Scope *S, bool MergeTypeWithOld) { | ||||||
3779 | // Merge the attributes | ||||||
3780 | mergeDeclAttributes(New, Old); | ||||||
3781 | |||||||
3782 | // Merge "pure" flag. | ||||||
3783 | if (Old->isPure()) | ||||||
3784 | New->setPure(); | ||||||
3785 | |||||||
3786 | // Merge "used" flag. | ||||||
3787 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||||
3788 | New->setIsUsed(); | ||||||
3789 | |||||||
3790 | // Merge attributes from the parameters. These can mismatch with K&R | ||||||
3791 | // declarations. | ||||||
3792 | if (New->getNumParams() == Old->getNumParams()) | ||||||
3793 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | ||||||
3794 | ParmVarDecl *NewParam = New->getParamDecl(i); | ||||||
3795 | ParmVarDecl *OldParam = Old->getParamDecl(i); | ||||||
3796 | mergeParamDeclAttributes(NewParam, OldParam, *this); | ||||||
3797 | mergeParamDeclTypes(NewParam, OldParam, *this); | ||||||
3798 | } | ||||||
3799 | |||||||
3800 | if (getLangOpts().CPlusPlus) | ||||||
3801 | return MergeCXXFunctionDecl(New, Old, S); | ||||||
3802 | |||||||
3803 | // Merge the function types so the we get the composite types for the return | ||||||
3804 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | ||||||
3805 | // was visible. | ||||||
3806 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | ||||||
3807 | if (!Merged.isNull() && MergeTypeWithOld) | ||||||
3808 | New->setType(Merged); | ||||||
3809 | |||||||
3810 | return false; | ||||||
3811 | } | ||||||
3812 | |||||||
3813 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | ||||||
3814 | ObjCMethodDecl *oldMethod) { | ||||||
3815 | // Merge the attributes, including deprecated/unavailable | ||||||
3816 | AvailabilityMergeKind MergeKind = | ||||||
3817 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | ||||||
3818 | ? AMK_ProtocolImplementation | ||||||
3819 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | ||||||
3820 | : AMK_Override; | ||||||
3821 | |||||||
3822 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | ||||||
3823 | |||||||
3824 | // Merge attributes from the parameters. | ||||||
3825 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | ||||||
3826 | oe = oldMethod->param_end(); | ||||||
3827 | for (ObjCMethodDecl::param_iterator | ||||||
3828 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | ||||||
3829 | ni != ne && oi != oe; ++ni, ++oi) | ||||||
3830 | mergeParamDeclAttributes(*ni, *oi, *this); | ||||||
3831 | |||||||
3832 | CheckObjCMethodOverride(newMethod, oldMethod); | ||||||
3833 | } | ||||||
3834 | |||||||
3835 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | ||||||
3836 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType() )) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 3836, __PRETTY_FUNCTION__)); | ||||||
3837 | |||||||
3838 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | ||||||
3839 | ? diag::err_redefinition_different_type | ||||||
3840 | : diag::err_redeclaration_different_type) | ||||||
3841 | << New->getDeclName() << New->getType() << Old->getType(); | ||||||
3842 | |||||||
3843 | diag::kind PrevDiag; | ||||||
3844 | SourceLocation OldLocation; | ||||||
3845 | std::tie(PrevDiag, OldLocation) | ||||||
3846 | = getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
3847 | S.Diag(OldLocation, PrevDiag); | ||||||
3848 | New->setInvalidDecl(); | ||||||
3849 | } | ||||||
3850 | |||||||
3851 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | ||||||
3852 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | ||||||
3853 | /// emitting diagnostics as appropriate. | ||||||
3854 | /// | ||||||
3855 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | ||||||
3856 | /// to here in AddInitializerToDecl. We can't check them before the initializer | ||||||
3857 | /// is attached. | ||||||
3858 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | ||||||
3859 | bool MergeTypeWithOld) { | ||||||
3860 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | ||||||
3861 | return; | ||||||
3862 | |||||||
3863 | QualType MergedT; | ||||||
3864 | if (getLangOpts().CPlusPlus) { | ||||||
3865 | if (New->getType()->isUndeducedType()) { | ||||||
3866 | // We don't know what the new type is until the initializer is attached. | ||||||
3867 | return; | ||||||
3868 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | ||||||
3869 | // These could still be something that needs exception specs checked. | ||||||
3870 | return MergeVarDeclExceptionSpecs(New, Old); | ||||||
3871 | } | ||||||
3872 | // C++ [basic.link]p10: | ||||||
3873 | // [...] the types specified by all declarations referring to a given | ||||||
3874 | // object or function shall be identical, except that declarations for an | ||||||
3875 | // array object can specify array types that differ by the presence or | ||||||
3876 | // absence of a major array bound (8.3.4). | ||||||
3877 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | ||||||
3878 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | ||||||
3879 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | ||||||
3880 | |||||||
3881 | // We are merging a variable declaration New into Old. If it has an array | ||||||
3882 | // bound, and that bound differs from Old's bound, we should diagnose the | ||||||
3883 | // mismatch. | ||||||
3884 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | ||||||
3885 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | ||||||
3886 | PrevVD = PrevVD->getPreviousDecl()) { | ||||||
3887 | const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); | ||||||
3888 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | ||||||
3889 | continue; | ||||||
3890 | |||||||
3891 | if (!Context.hasSameType(NewArray, PrevVDTy)) | ||||||
3892 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | ||||||
3893 | } | ||||||
3894 | } | ||||||
3895 | |||||||
3896 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | ||||||
3897 | if (Context.hasSameType(OldArray->getElementType(), | ||||||
3898 | NewArray->getElementType())) | ||||||
3899 | MergedT = New->getType(); | ||||||
3900 | } | ||||||
3901 | // FIXME: Check visibility. New is hidden but has a complete type. If New | ||||||
3902 | // has no array bound, it should not inherit one from Old, if Old is not | ||||||
3903 | // visible. | ||||||
3904 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | ||||||
3905 | if (Context.hasSameType(OldArray->getElementType(), | ||||||
3906 | NewArray->getElementType())) | ||||||
3907 | MergedT = Old->getType(); | ||||||
3908 | } | ||||||
3909 | } | ||||||
3910 | else if (New->getType()->isObjCObjectPointerType() && | ||||||
3911 | Old->getType()->isObjCObjectPointerType()) { | ||||||
3912 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | ||||||
3913 | Old->getType()); | ||||||
3914 | } | ||||||
3915 | } else { | ||||||
3916 | // C 6.2.7p2: | ||||||
3917 | // All declarations that refer to the same object or function shall have | ||||||
3918 | // compatible type. | ||||||
3919 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | ||||||
3920 | } | ||||||
3921 | if (MergedT.isNull()) { | ||||||
3922 | // It's OK if we couldn't merge types if either type is dependent, for a | ||||||
3923 | // block-scope variable. In other cases (static data members of class | ||||||
3924 | // templates, variable templates, ...), we require the types to be | ||||||
3925 | // equivalent. | ||||||
3926 | // FIXME: The C++ standard doesn't say anything about this. | ||||||
3927 | if ((New->getType()->isDependentType() || | ||||||
3928 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | ||||||
3929 | // If the old type was dependent, we can't merge with it, so the new type | ||||||
3930 | // becomes dependent for now. We'll reproduce the original type when we | ||||||
3931 | // instantiate the TypeSourceInfo for the variable. | ||||||
3932 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | ||||||
3933 | New->setType(Context.DependentTy); | ||||||
3934 | return; | ||||||
3935 | } | ||||||
3936 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | ||||||
3937 | } | ||||||
3938 | |||||||
3939 | // Don't actually update the type on the new declaration if the old | ||||||
3940 | // declaration was an extern declaration in a different scope. | ||||||
3941 | if (MergeTypeWithOld) | ||||||
3942 | New->setType(MergedT); | ||||||
3943 | } | ||||||
3944 | |||||||
3945 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | ||||||
3946 | LookupResult &Previous) { | ||||||
3947 | // C11 6.2.7p4: | ||||||
3948 | // For an identifier with internal or external linkage declared | ||||||
3949 | // in a scope in which a prior declaration of that identifier is | ||||||
3950 | // visible, if the prior declaration specifies internal or | ||||||
3951 | // external linkage, the type of the identifier at the later | ||||||
3952 | // declaration becomes the composite type. | ||||||
3953 | // | ||||||
3954 | // If the variable isn't visible, we do not merge with its type. | ||||||
3955 | if (Previous.isShadowed()) | ||||||
3956 | return false; | ||||||
3957 | |||||||
3958 | if (S.getLangOpts().CPlusPlus) { | ||||||
3959 | // C++11 [dcl.array]p3: | ||||||
3960 | // If there is a preceding declaration of the entity in the same | ||||||
3961 | // scope in which the bound was specified, an omitted array bound | ||||||
3962 | // is taken to be the same as in that earlier declaration. | ||||||
3963 | return NewVD->isPreviousDeclInSameBlockScope() || | ||||||
3964 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | ||||||
3965 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | ||||||
3966 | } else { | ||||||
3967 | // If the old declaration was function-local, don't merge with its | ||||||
3968 | // type unless we're in the same function. | ||||||
3969 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | ||||||
3970 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | ||||||
3971 | } | ||||||
3972 | } | ||||||
3973 | |||||||
3974 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | ||||||
3975 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | ||||||
3976 | /// situation, merging decls or emitting diagnostics as appropriate. | ||||||
3977 | /// | ||||||
3978 | /// Tentative definition rules (C99 6.9.2p2) are checked by | ||||||
3979 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | ||||||
3980 | /// definitions here, since the initializer hasn't been attached. | ||||||
3981 | /// | ||||||
3982 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | ||||||
3983 | // If the new decl is already invalid, don't do any other checking. | ||||||
3984 | if (New->isInvalidDecl()) | ||||||
3985 | return; | ||||||
3986 | |||||||
3987 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | ||||||
3988 | return; | ||||||
3989 | |||||||
3990 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | ||||||
3991 | |||||||
3992 | // Verify the old decl was also a variable or variable template. | ||||||
3993 | VarDecl *Old = nullptr; | ||||||
3994 | VarTemplateDecl *OldTemplate = nullptr; | ||||||
3995 | if (Previous.isSingleResult()) { | ||||||
3996 | if (NewTemplate) { | ||||||
3997 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | ||||||
3998 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | ||||||
3999 | |||||||
4000 | if (auto *Shadow = | ||||||
4001 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||||
4002 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | ||||||
4003 | return New->setInvalidDecl(); | ||||||
4004 | } else { | ||||||
4005 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | ||||||
4006 | |||||||
4007 | if (auto *Shadow = | ||||||
4008 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||||
4009 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | ||||||
4010 | return New->setInvalidDecl(); | ||||||
4011 | } | ||||||
4012 | } | ||||||
4013 | if (!Old) { | ||||||
4014 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
4015 | << New->getDeclName(); | ||||||
4016 | notePreviousDefinition(Previous.getRepresentativeDecl(), | ||||||
4017 | New->getLocation()); | ||||||
4018 | return New->setInvalidDecl(); | ||||||
4019 | } | ||||||
4020 | |||||||
4021 | // Ensure the template parameters are compatible. | ||||||
4022 | if (NewTemplate && | ||||||
4023 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | ||||||
4024 | OldTemplate->getTemplateParameters(), | ||||||
4025 | /*Complain=*/true, TPL_TemplateMatch)) | ||||||
4026 | return New->setInvalidDecl(); | ||||||
4027 | |||||||
4028 | // C++ [class.mem]p1: | ||||||
4029 | // A member shall not be declared twice in the member-specification [...] | ||||||
4030 | // | ||||||
4031 | // Here, we need only consider static data members. | ||||||
4032 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | ||||||
4033 | Diag(New->getLocation(), diag::err_duplicate_member) | ||||||
4034 | << New->getIdentifier(); | ||||||
4035 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
4036 | New->setInvalidDecl(); | ||||||
4037 | } | ||||||
4038 | |||||||
4039 | mergeDeclAttributes(New, Old); | ||||||
4040 | // Warn if an already-declared variable is made a weak_import in a subsequent | ||||||
4041 | // declaration | ||||||
4042 | if (New->hasAttr<WeakImportAttr>() && | ||||||
4043 | Old->getStorageClass() == SC_None && | ||||||
4044 | !Old->hasAttr<WeakImportAttr>()) { | ||||||
4045 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | ||||||
4046 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4047 | // Remove weak_import attribute on new declaration. | ||||||
4048 | New->dropAttr<WeakImportAttr>(); | ||||||
4049 | } | ||||||
4050 | |||||||
4051 | if (New->hasAttr<InternalLinkageAttr>() && | ||||||
4052 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||||
4053 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||||
4054 | << New->getDeclName(); | ||||||
4055 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4056 | New->dropAttr<InternalLinkageAttr>(); | ||||||
4057 | } | ||||||
4058 | |||||||
4059 | // Merge the types. | ||||||
4060 | VarDecl *MostRecent = Old->getMostRecentDecl(); | ||||||
4061 | if (MostRecent != Old) { | ||||||
4062 | MergeVarDeclTypes(New, MostRecent, | ||||||
4063 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | ||||||
4064 | if (New->isInvalidDecl()) | ||||||
4065 | return; | ||||||
4066 | } | ||||||
4067 | |||||||
4068 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | ||||||
4069 | if (New->isInvalidDecl()) | ||||||
4070 | return; | ||||||
4071 | |||||||
4072 | diag::kind PrevDiag; | ||||||
4073 | SourceLocation OldLocation; | ||||||
4074 | std::tie(PrevDiag, OldLocation) = | ||||||
4075 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
4076 | |||||||
4077 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | ||||||
4078 | if (New->getStorageClass() == SC_Static && | ||||||
4079 | !New->isStaticDataMember() && | ||||||
4080 | Old->hasExternalFormalLinkage()) { | ||||||
4081 | if (getLangOpts().MicrosoftExt) { | ||||||
4082 | Diag(New->getLocation(), diag::ext_static_non_static) | ||||||
4083 | << New->getDeclName(); | ||||||
4084 | Diag(OldLocation, PrevDiag); | ||||||
4085 | } else { | ||||||
4086 | Diag(New->getLocation(), diag::err_static_non_static) | ||||||
4087 | << New->getDeclName(); | ||||||
4088 | Diag(OldLocation, PrevDiag); | ||||||
4089 | return New->setInvalidDecl(); | ||||||
4090 | } | ||||||
4091 | } | ||||||
4092 | // C99 6.2.2p4: | ||||||
4093 | // For an identifier declared with the storage-class specifier | ||||||
4094 | // extern in a scope in which a prior declaration of that | ||||||
4095 | // identifier is visible,23) if the prior declaration specifies | ||||||
4096 | // internal or external linkage, the linkage of the identifier at | ||||||
4097 | // the later declaration is the same as the linkage specified at | ||||||
4098 | // the prior declaration. If no prior declaration is visible, or | ||||||
4099 | // if the prior declaration specifies no linkage, then the | ||||||
4100 | // identifier has external linkage. | ||||||
4101 | if (New->hasExternalStorage() && Old->hasLinkage()) | ||||||
4102 | /* Okay */; | ||||||
4103 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | ||||||
4104 | !New->isStaticDataMember() && | ||||||
4105 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | ||||||
4106 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | ||||||
4107 | Diag(OldLocation, PrevDiag); | ||||||
4108 | return New->setInvalidDecl(); | ||||||
4109 | } | ||||||
4110 | |||||||
4111 | // Check if extern is followed by non-extern and vice-versa. | ||||||
4112 | if (New->hasExternalStorage() && | ||||||
4113 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | ||||||
4114 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | ||||||
4115 | Diag(OldLocation, PrevDiag); | ||||||
4116 | return New->setInvalidDecl(); | ||||||
4117 | } | ||||||
4118 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | ||||||
4119 | !New->hasExternalStorage()) { | ||||||
4120 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | ||||||
4121 | Diag(OldLocation, PrevDiag); | ||||||
4122 | return New->setInvalidDecl(); | ||||||
4123 | } | ||||||
4124 | |||||||
4125 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||||
4126 | return; | ||||||
4127 | |||||||
4128 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | ||||||
4129 | |||||||
4130 | // FIXME: The test for external storage here seems wrong? We still | ||||||
4131 | // need to check for mismatches. | ||||||
4132 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | ||||||
4133 | // Don't complain about out-of-line definitions of static members. | ||||||
4134 | !(Old->getLexicalDeclContext()->isRecord() && | ||||||
4135 | !New->getLexicalDeclContext()->isRecord())) { | ||||||
4136 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | ||||||
4137 | Diag(OldLocation, PrevDiag); | ||||||
4138 | return New->setInvalidDecl(); | ||||||
4139 | } | ||||||
4140 | |||||||
4141 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | ||||||
4142 | if (VarDecl *Def = Old->getDefinition()) { | ||||||
4143 | // C++1z [dcl.fcn.spec]p4: | ||||||
4144 | // If the definition of a variable appears in a translation unit before | ||||||
4145 | // its first declaration as inline, the program is ill-formed. | ||||||
4146 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | ||||||
4147 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
4148 | } | ||||||
4149 | } | ||||||
4150 | |||||||
4151 | // If this redeclaration makes the variable inline, we may need to add it to | ||||||
4152 | // UndefinedButUsed. | ||||||
4153 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | ||||||
4154 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | ||||||
4155 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||||
4156 | SourceLocation())); | ||||||
4157 | |||||||
4158 | if (New->getTLSKind() != Old->getTLSKind()) { | ||||||
4159 | if (!Old->getTLSKind()) { | ||||||
4160 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | ||||||
4161 | Diag(OldLocation, PrevDiag); | ||||||
4162 | } else if (!New->getTLSKind()) { | ||||||
4163 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | ||||||
4164 | Diag(OldLocation, PrevDiag); | ||||||
4165 | } else { | ||||||
4166 | // Do not allow redeclaration to change the variable between requiring | ||||||
4167 | // static and dynamic initialization. | ||||||
4168 | // FIXME: GCC allows this, but uses the TLS keyword on the first | ||||||
4169 | // declaration to determine the kind. Do we need to be compatible here? | ||||||
4170 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | ||||||
4171 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | ||||||
4172 | Diag(OldLocation, PrevDiag); | ||||||
4173 | } | ||||||
4174 | } | ||||||
4175 | |||||||
4176 | // C++ doesn't have tentative definitions, so go right ahead and check here. | ||||||
4177 | if (getLangOpts().CPlusPlus && | ||||||
4178 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | ||||||
4179 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | ||||||
4180 | Old->getCanonicalDecl()->isConstexpr()) { | ||||||
4181 | // This definition won't be a definition any more once it's been merged. | ||||||
4182 | Diag(New->getLocation(), | ||||||
4183 | diag::warn_deprecated_redundant_constexpr_static_def); | ||||||
4184 | } else if (VarDecl *Def = Old->getDefinition()) { | ||||||
4185 | if (checkVarDeclRedefinition(Def, New)) | ||||||
4186 | return; | ||||||
4187 | } | ||||||
4188 | } | ||||||
4189 | |||||||
4190 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||||
4191 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||||
4192 | Diag(OldLocation, PrevDiag); | ||||||
4193 | New->setInvalidDecl(); | ||||||
4194 | return; | ||||||
4195 | } | ||||||
4196 | |||||||
4197 | // Merge "used" flag. | ||||||
4198 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||||
4199 | New->setIsUsed(); | ||||||
4200 | |||||||
4201 | // Keep a chain of previous declarations. | ||||||
4202 | New->setPreviousDecl(Old); | ||||||
4203 | if (NewTemplate) | ||||||
4204 | NewTemplate->setPreviousDecl(OldTemplate); | ||||||
4205 | adjustDeclContextForDeclaratorDecl(New, Old); | ||||||
4206 | |||||||
4207 | // Inherit access appropriately. | ||||||
4208 | New->setAccess(Old->getAccess()); | ||||||
4209 | if (NewTemplate) | ||||||
4210 | NewTemplate->setAccess(New->getAccess()); | ||||||
4211 | |||||||
4212 | if (Old->isInline()) | ||||||
4213 | New->setImplicitlyInline(); | ||||||
4214 | } | ||||||
4215 | |||||||
4216 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | ||||||
4217 | SourceManager &SrcMgr = getSourceManager(); | ||||||
4218 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | ||||||
4219 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | ||||||
4220 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | ||||||
4221 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | ||||||
4222 | auto &HSI = PP.getHeaderSearchInfo(); | ||||||
4223 | StringRef HdrFilename = | ||||||
4224 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | ||||||
4225 | |||||||
4226 | auto noteFromModuleOrInclude = [&](Module *Mod, | ||||||
4227 | SourceLocation IncLoc) -> bool { | ||||||
4228 | // Redefinition errors with modules are common with non modular mapped | ||||||
4229 | // headers, example: a non-modular header H in module A that also gets | ||||||
4230 | // included directly in a TU. Pointing twice to the same header/definition | ||||||
4231 | // is confusing, try to get better diagnostics when modules is on. | ||||||
4232 | if (IncLoc.isValid()) { | ||||||
4233 | if (Mod) { | ||||||
4234 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | ||||||
4235 | << HdrFilename.str() << Mod->getFullModuleName(); | ||||||
4236 | if (!Mod->DefinitionLoc.isInvalid()) | ||||||
4237 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | ||||||
4238 | << Mod->getFullModuleName(); | ||||||
4239 | } else { | ||||||
4240 | Diag(IncLoc, diag::note_redefinition_include_same_file) | ||||||
4241 | << HdrFilename.str(); | ||||||
4242 | } | ||||||
4243 | return true; | ||||||
4244 | } | ||||||
4245 | |||||||
4246 | return false; | ||||||
4247 | }; | ||||||
4248 | |||||||
4249 | // Is it the same file and same offset? Provide more information on why | ||||||
4250 | // this leads to a redefinition error. | ||||||
4251 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | ||||||
4252 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | ||||||
4253 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | ||||||
4254 | bool EmittedDiag = | ||||||
4255 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | ||||||
4256 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | ||||||
4257 | |||||||
4258 | // If the header has no guards, emit a note suggesting one. | ||||||
4259 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | ||||||
4260 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | ||||||
4261 | |||||||
4262 | if (EmittedDiag) | ||||||
4263 | return; | ||||||
4264 | } | ||||||
4265 | |||||||
4266 | // Redefinition coming from different files or couldn't do better above. | ||||||
4267 | if (Old->getLocation().isValid()) | ||||||
4268 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||||
4269 | } | ||||||
4270 | |||||||
4271 | /// We've just determined that \p Old and \p New both appear to be definitions | ||||||
4272 | /// of the same variable. Either diagnose or fix the problem. | ||||||
4273 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | ||||||
4274 | if (!hasVisibleDefinition(Old) && | ||||||
4275 | (New->getFormalLinkage() == InternalLinkage || | ||||||
4276 | New->isInline() || | ||||||
4277 | New->getDescribedVarTemplate() || | ||||||
4278 | New->getNumTemplateParameterLists() || | ||||||
4279 | New->getDeclContext()->isDependentContext())) { | ||||||
4280 | // The previous definition is hidden, and multiple definitions are | ||||||
4281 | // permitted (in separate TUs). Demote this to a declaration. | ||||||
4282 | New->demoteThisDefinitionToDeclaration(); | ||||||
4283 | |||||||
4284 | // Make the canonical definition visible. | ||||||
4285 | if (auto *OldTD = Old->getDescribedVarTemplate()) | ||||||
4286 | makeMergedDefinitionVisible(OldTD); | ||||||
4287 | makeMergedDefinitionVisible(Old); | ||||||
4288 | return false; | ||||||
4289 | } else { | ||||||
4290 | Diag(New->getLocation(), diag::err_redefinition) << New; | ||||||
4291 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4292 | New->setInvalidDecl(); | ||||||
4293 | return true; | ||||||
4294 | } | ||||||
4295 | } | ||||||
4296 | |||||||
4297 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||||
4298 | /// no declarator (e.g. "struct foo;") is parsed. | ||||||
4299 | Decl * | ||||||
4300 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||||
4301 | RecordDecl *&AnonRecord) { | ||||||
4302 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | ||||||
4303 | AnonRecord); | ||||||
4304 | } | ||||||
4305 | |||||||
4306 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | ||||||
4307 | // disambiguate entities defined in different scopes. | ||||||
4308 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | ||||||
4309 | // compatibility. | ||||||
4310 | // We will pick our mangling number depending on which version of MSVC is being | ||||||
4311 | // targeted. | ||||||
4312 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | ||||||
4313 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | ||||||
4314 | ? S->getMSCurManglingNumber() | ||||||
4315 | : S->getMSLastManglingNumber(); | ||||||
4316 | } | ||||||
4317 | |||||||
4318 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | ||||||
4319 | if (!Context.getLangOpts().CPlusPlus) | ||||||
4320 | return; | ||||||
4321 | |||||||
4322 | if (isa<CXXRecordDecl>(Tag->getParent())) { | ||||||
4323 | // If this tag is the direct child of a class, number it if | ||||||
4324 | // it is anonymous. | ||||||
4325 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | ||||||
4326 | return; | ||||||
4327 | MangleNumberingContext &MCtx = | ||||||
4328 | Context.getManglingNumberContext(Tag->getParent()); | ||||||
4329 | Context.setManglingNumber( | ||||||
4330 | Tag, MCtx.getManglingNumber( | ||||||
4331 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||||
4332 | return; | ||||||
4333 | } | ||||||
4334 | |||||||
4335 | // If this tag isn't a direct child of a class, number it if it is local. | ||||||
4336 | MangleNumberingContext *MCtx; | ||||||
4337 | Decl *ManglingContextDecl; | ||||||
4338 | std::tie(MCtx, ManglingContextDecl) = | ||||||
4339 | getCurrentMangleNumberContext(Tag->getDeclContext()); | ||||||
4340 | if (MCtx) { | ||||||
4341 | Context.setManglingNumber( | ||||||
4342 | Tag, MCtx->getManglingNumber( | ||||||
4343 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||||
4344 | } | ||||||
4345 | } | ||||||
4346 | |||||||
4347 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | ||||||
4348 | TypedefNameDecl *NewTD) { | ||||||
4349 | if (TagFromDeclSpec->isInvalidDecl()) | ||||||
4350 | return; | ||||||
4351 | |||||||
4352 | // Do nothing if the tag already has a name for linkage purposes. | ||||||
4353 | if (TagFromDeclSpec->hasNameForLinkage()) | ||||||
4354 | return; | ||||||
4355 | |||||||
4356 | // A well-formed anonymous tag must always be a TUK_Definition. | ||||||
4357 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast <void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4357, __PRETTY_FUNCTION__)); | ||||||
4358 | |||||||
4359 | // The type must match the tag exactly; no qualifiers allowed. | ||||||
4360 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | ||||||
4361 | Context.getTagDeclType(TagFromDeclSpec))) { | ||||||
4362 | if (getLangOpts().CPlusPlus) | ||||||
4363 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | ||||||
4364 | return; | ||||||
4365 | } | ||||||
4366 | |||||||
4367 | // If we've already computed linkage for the anonymous tag, then | ||||||
4368 | // adding a typedef name for the anonymous decl can change that | ||||||
4369 | // linkage, which might be a serious problem. Diagnose this as | ||||||
4370 | // unsupported and ignore the typedef name. TODO: we should | ||||||
4371 | // pursue this as a language defect and establish a formal rule | ||||||
4372 | // for how to handle it. | ||||||
4373 | if (TagFromDeclSpec->hasLinkageBeenComputed()) { | ||||||
4374 | Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); | ||||||
4375 | |||||||
4376 | SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); | ||||||
4377 | tagLoc = getLocForEndOfToken(tagLoc); | ||||||
4378 | |||||||
4379 | llvm::SmallString<40> textToInsert; | ||||||
4380 | textToInsert += ' '; | ||||||
4381 | textToInsert += NewTD->getIdentifier()->getName(); | ||||||
4382 | Diag(tagLoc, diag::note_typedef_changes_linkage) | ||||||
4383 | << FixItHint::CreateInsertion(tagLoc, textToInsert); | ||||||
4384 | return; | ||||||
4385 | } | ||||||
4386 | |||||||
4387 | // Otherwise, set this is the anon-decl typedef for the tag. | ||||||
4388 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | ||||||
4389 | } | ||||||
4390 | |||||||
4391 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | ||||||
4392 | switch (T) { | ||||||
4393 | case DeclSpec::TST_class: | ||||||
4394 | return 0; | ||||||
4395 | case DeclSpec::TST_struct: | ||||||
4396 | return 1; | ||||||
4397 | case DeclSpec::TST_interface: | ||||||
4398 | return 2; | ||||||
4399 | case DeclSpec::TST_union: | ||||||
4400 | return 3; | ||||||
4401 | case DeclSpec::TST_enum: | ||||||
4402 | return 4; | ||||||
4403 | default: | ||||||
4404 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4404); | ||||||
4405 | } | ||||||
4406 | } | ||||||
4407 | |||||||
4408 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||||
4409 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | ||||||
4410 | /// parameters to cope with template friend declarations. | ||||||
4411 | Decl * | ||||||
4412 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||||
4413 | MultiTemplateParamsArg TemplateParams, | ||||||
4414 | bool IsExplicitInstantiation, | ||||||
4415 | RecordDecl *&AnonRecord) { | ||||||
4416 | Decl *TagD = nullptr; | ||||||
4417 | TagDecl *Tag = nullptr; | ||||||
4418 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | ||||||
4419 | DS.getTypeSpecType() == DeclSpec::TST_struct || | ||||||
4420 | DS.getTypeSpecType() == DeclSpec::TST_interface || | ||||||
4421 | DS.getTypeSpecType() == DeclSpec::TST_union || | ||||||
4422 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | ||||||
4423 | TagD = DS.getRepAsDecl(); | ||||||
4424 | |||||||
4425 | if (!TagD) // We probably had an error | ||||||
4426 | return nullptr; | ||||||
4427 | |||||||
4428 | // Note that the above type specs guarantee that the | ||||||
4429 | // type rep is a Decl, whereas in many of the others | ||||||
4430 | // it's a Type. | ||||||
4431 | if (isa<TagDecl>(TagD)) | ||||||
4432 | Tag = cast<TagDecl>(TagD); | ||||||
4433 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | ||||||
4434 | Tag = CTD->getTemplatedDecl(); | ||||||
4435 | } | ||||||
4436 | |||||||
4437 | if (Tag) { | ||||||
4438 | handleTagNumbering(Tag, S); | ||||||
4439 | Tag->setFreeStanding(); | ||||||
4440 | if (Tag->isInvalidDecl()) | ||||||
4441 | return Tag; | ||||||
4442 | } | ||||||
4443 | |||||||
4444 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | ||||||
4445 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | ||||||
4446 | // or incomplete types shall not be restrict-qualified." | ||||||
4447 | if (TypeQuals & DeclSpec::TQ_restrict) | ||||||
4448 | Diag(DS.getRestrictSpecLoc(), | ||||||
4449 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | ||||||
4450 | << DS.getSourceRange(); | ||||||
4451 | } | ||||||
4452 | |||||||
4453 | if (DS.isInlineSpecified()) | ||||||
4454 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
4455 | << getLangOpts().CPlusPlus17; | ||||||
4456 | |||||||
4457 | if (DS.hasConstexprSpecifier()) { | ||||||
4458 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | ||||||
4459 | // and definitions of functions and variables. | ||||||
4460 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to | ||||||
4461 | // the declaration of a function or function template | ||||||
4462 | if (Tag) | ||||||
4463 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | ||||||
4464 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) | ||||||
4465 | << DS.getConstexprSpecifier(); | ||||||
4466 | else | ||||||
4467 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) | ||||||
4468 | << DS.getConstexprSpecifier(); | ||||||
4469 | // Don't emit warnings after this error. | ||||||
4470 | return TagD; | ||||||
4471 | } | ||||||
4472 | |||||||
4473 | DiagnoseFunctionSpecifiers(DS); | ||||||
4474 | |||||||
4475 | if (DS.isFriendSpecified()) { | ||||||
4476 | // If we're dealing with a decl but not a TagDecl, assume that | ||||||
4477 | // whatever routines created it handled the friendship aspect. | ||||||
4478 | if (TagD && !Tag) | ||||||
4479 | return nullptr; | ||||||
4480 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | ||||||
4481 | } | ||||||
4482 | |||||||
4483 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | ||||||
4484 | bool IsExplicitSpecialization = | ||||||
4485 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | ||||||
4486 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | ||||||
4487 | !IsExplicitInstantiation && !IsExplicitSpecialization && | ||||||
4488 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | ||||||
4489 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | ||||||
4490 | // nested-name-specifier unless it is an explicit instantiation | ||||||
4491 | // or an explicit specialization. | ||||||
4492 | // | ||||||
4493 | // FIXME: We allow class template partial specializations here too, per the | ||||||
4494 | // obvious intent of DR1819. | ||||||
4495 | // | ||||||
4496 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | ||||||
4497 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | ||||||
4498 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | ||||||
4499 | return nullptr; | ||||||
4500 | } | ||||||
4501 | |||||||
4502 | // Track whether this decl-specifier declares anything. | ||||||
4503 | bool DeclaresAnything = true; | ||||||
4504 | |||||||
4505 | // Handle anonymous struct definitions. | ||||||
4506 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | ||||||
4507 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | ||||||
4508 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | ||||||
4509 | if (getLangOpts().CPlusPlus || | ||||||
4510 | Record->getDeclContext()->isRecord()) { | ||||||
4511 | // If CurContext is a DeclContext that can contain statements, | ||||||
4512 | // RecursiveASTVisitor won't visit the decls that | ||||||
4513 | // BuildAnonymousStructOrUnion() will put into CurContext. | ||||||
4514 | // Also store them here so that they can be part of the | ||||||
4515 | // DeclStmt that gets created in this case. | ||||||
4516 | // FIXME: Also return the IndirectFieldDecls created by | ||||||
4517 | // BuildAnonymousStructOr union, for the same reason? | ||||||
4518 | if (CurContext->isFunctionOrMethod()) | ||||||
4519 | AnonRecord = Record; | ||||||
4520 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | ||||||
4521 | Context.getPrintingPolicy()); | ||||||
4522 | } | ||||||
4523 | |||||||
4524 | DeclaresAnything = false; | ||||||
4525 | } | ||||||
4526 | } | ||||||
4527 | |||||||
4528 | // C11 6.7.2.1p2: | ||||||
4529 | // A struct-declaration that does not declare an anonymous structure or | ||||||
4530 | // anonymous union shall contain a struct-declarator-list. | ||||||
4531 | // | ||||||
4532 | // This rule also existed in C89 and C99; the grammar for struct-declaration | ||||||
4533 | // did not permit a struct-declaration without a struct-declarator-list. | ||||||
4534 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | ||||||
4535 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | ||||||
4536 | // Check for Microsoft C extension: anonymous struct/union member. | ||||||
4537 | // Handle 2 kinds of anonymous struct/union: | ||||||
4538 | // struct STRUCT; | ||||||
4539 | // union UNION; | ||||||
4540 | // and | ||||||
4541 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | ||||||
4542 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | ||||||
4543 | if ((Tag && Tag->getDeclName()) || | ||||||
4544 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | ||||||
4545 | RecordDecl *Record = nullptr; | ||||||
4546 | if (Tag) | ||||||
4547 | Record = dyn_cast<RecordDecl>(Tag); | ||||||
4548 | else if (const RecordType *RT = | ||||||
4549 | DS.getRepAsType().get()->getAsStructureType()) | ||||||
4550 | Record = RT->getDecl(); | ||||||
4551 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | ||||||
4552 | Record = UT->getDecl(); | ||||||
4553 | |||||||
4554 | if (Record && getLangOpts().MicrosoftExt) { | ||||||
4555 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | ||||||
4556 | << Record->isUnion() << DS.getSourceRange(); | ||||||
4557 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | ||||||
4558 | } | ||||||
4559 | |||||||
4560 | DeclaresAnything = false; | ||||||
4561 | } | ||||||
4562 | } | ||||||
4563 | |||||||
4564 | // Skip all the checks below if we have a type error. | ||||||
4565 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | ||||||
4566 | (TagD && TagD->isInvalidDecl())) | ||||||
4567 | return TagD; | ||||||
4568 | |||||||
4569 | if (getLangOpts().CPlusPlus && | ||||||
4570 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | ||||||
4571 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | ||||||
4572 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | ||||||
4573 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | ||||||
4574 | DeclaresAnything = false; | ||||||
4575 | |||||||
4576 | if (!DS.isMissingDeclaratorOk()) { | ||||||
4577 | // Customize diagnostic for a typedef missing a name. | ||||||
4578 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||||
4579 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | ||||||
4580 | << DS.getSourceRange(); | ||||||
4581 | else | ||||||
4582 | DeclaresAnything = false; | ||||||
4583 | } | ||||||
4584 | |||||||
4585 | if (DS.isModulePrivateSpecified() && | ||||||
4586 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | ||||||
4587 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | ||||||
4588 | << Tag->getTagKind() | ||||||
4589 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | ||||||
4590 | |||||||
4591 | ActOnDocumentableDecl(TagD); | ||||||
4592 | |||||||
4593 | // C 6.7/2: | ||||||
4594 | // A declaration [...] shall declare at least a declarator [...], a tag, | ||||||
4595 | // or the members of an enumeration. | ||||||
4596 | // C++ [dcl.dcl]p3: | ||||||
4597 | // [If there are no declarators], and except for the declaration of an | ||||||
4598 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||||
4599 | // names into the program, or shall redeclare a name introduced by a | ||||||
4600 | // previous declaration. | ||||||
4601 | if (!DeclaresAnything) { | ||||||
4602 | // In C, we allow this as a (popular) extension / bug. Don't bother | ||||||
4603 | // producing further diagnostics for redundant qualifiers after this. | ||||||
4604 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||||
4605 | return TagD; | ||||||
4606 | } | ||||||
4607 | |||||||
4608 | // C++ [dcl.stc]p1: | ||||||
4609 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | ||||||
4610 | // init-declarator-list of the declaration shall not be empty. | ||||||
4611 | // C++ [dcl.fct.spec]p1: | ||||||
4612 | // If a cv-qualifier appears in a decl-specifier-seq, the | ||||||
4613 | // init-declarator-list of the declaration shall not be empty. | ||||||
4614 | // | ||||||
4615 | // Spurious qualifiers here appear to be valid in C. | ||||||
4616 | unsigned DiagID = diag::warn_standalone_specifier; | ||||||
4617 | if (getLangOpts().CPlusPlus) | ||||||
4618 | DiagID = diag::ext_standalone_specifier; | ||||||
4619 | |||||||
4620 | // Note that a linkage-specification sets a storage class, but | ||||||
4621 | // 'extern "C" struct foo;' is actually valid and not theoretically | ||||||
4622 | // useless. | ||||||
4623 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | ||||||
4624 | if (SCS == DeclSpec::SCS_mutable) | ||||||
4625 | // Since mutable is not a viable storage class specifier in C, there is | ||||||
4626 | // no reason to treat it as an extension. Instead, diagnose as an error. | ||||||
4627 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | ||||||
4628 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | ||||||
4629 | Diag(DS.getStorageClassSpecLoc(), DiagID) | ||||||
4630 | << DeclSpec::getSpecifierName(SCS); | ||||||
4631 | } | ||||||
4632 | |||||||
4633 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||||
4634 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | ||||||
4635 | << DeclSpec::getSpecifierName(TSCS); | ||||||
4636 | if (DS.getTypeQualifiers()) { | ||||||
4637 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||||
4638 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | ||||||
4639 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||||
4640 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | ||||||
4641 | // Restrict is covered above. | ||||||
4642 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||||
4643 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | ||||||
4644 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||||
4645 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | ||||||
4646 | } | ||||||
4647 | |||||||
4648 | // Warn about ignored type attributes, for example: | ||||||
4649 | // __attribute__((aligned)) struct A; | ||||||
4650 | // Attributes should be placed after tag to apply to type declaration. | ||||||
4651 | if (!DS.getAttributes().empty()) { | ||||||
4652 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | ||||||
4653 | if (TypeSpecType == DeclSpec::TST_class || | ||||||
4654 | TypeSpecType == DeclSpec::TST_struct || | ||||||
4655 | TypeSpecType == DeclSpec::TST_interface || | ||||||
4656 | TypeSpecType == DeclSpec::TST_union || | ||||||
4657 | TypeSpecType == DeclSpec::TST_enum) { | ||||||
4658 | for (const ParsedAttr &AL : DS.getAttributes()) | ||||||
4659 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | ||||||
4660 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); | ||||||
4661 | } | ||||||
4662 | } | ||||||
4663 | |||||||
4664 | return TagD; | ||||||
4665 | } | ||||||
4666 | |||||||
4667 | /// We are trying to inject an anonymous member into the given scope; | ||||||
4668 | /// check if there's an existing declaration that can't be overloaded. | ||||||
4669 | /// | ||||||
4670 | /// \return true if this is a forbidden redeclaration | ||||||
4671 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | ||||||
4672 | Scope *S, | ||||||
4673 | DeclContext *Owner, | ||||||
4674 | DeclarationName Name, | ||||||
4675 | SourceLocation NameLoc, | ||||||
4676 | bool IsUnion) { | ||||||
4677 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | ||||||
4678 | Sema::ForVisibleRedeclaration); | ||||||
4679 | if (!SemaRef.LookupName(R, S)) return false; | ||||||
4680 | |||||||
4681 | // Pick a representative declaration. | ||||||
4682 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | ||||||
4683 | assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast <void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4683, __PRETTY_FUNCTION__)); | ||||||
4684 | |||||||
4685 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | ||||||
4686 | return false; | ||||||
4687 | |||||||
4688 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | ||||||
4689 | << IsUnion << Name; | ||||||
4690 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
4691 | |||||||
4692 | return true; | ||||||
4693 | } | ||||||
4694 | |||||||
4695 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | ||||||
4696 | /// anonymous struct or union AnonRecord into the owning context Owner | ||||||
4697 | /// and scope S. This routine will be invoked just after we realize | ||||||
4698 | /// that an unnamed union or struct is actually an anonymous union or | ||||||
4699 | /// struct, e.g., | ||||||
4700 | /// | ||||||
4701 | /// @code | ||||||
4702 | /// union { | ||||||
4703 | /// int i; | ||||||
4704 | /// float f; | ||||||
4705 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | ||||||
4706 | /// // f into the surrounding scope.x | ||||||
4707 | /// @endcode | ||||||
4708 | /// | ||||||
4709 | /// This routine is recursive, injecting the names of nested anonymous | ||||||
4710 | /// structs/unions into the owning context and scope as well. | ||||||
4711 | static bool | ||||||
4712 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | ||||||
4713 | RecordDecl *AnonRecord, AccessSpecifier AS, | ||||||
4714 | SmallVectorImpl<NamedDecl *> &Chaining) { | ||||||
4715 | bool Invalid = false; | ||||||
4716 | |||||||
4717 | // Look every FieldDecl and IndirectFieldDecl with a name. | ||||||
4718 | for (auto *D : AnonRecord->decls()) { | ||||||
4719 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | ||||||
4720 | cast<NamedDecl>(D)->getDeclName()) { | ||||||
4721 | ValueDecl *VD = cast<ValueDecl>(D); | ||||||
4722 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | ||||||
4723 | VD->getLocation(), | ||||||
4724 | AnonRecord->isUnion())) { | ||||||
4725 | // C++ [class.union]p2: | ||||||
4726 | // The names of the members of an anonymous union shall be | ||||||
4727 | // distinct from the names of any other entity in the | ||||||
4728 | // scope in which the anonymous union is declared. | ||||||
4729 | Invalid = true; | ||||||
4730 | } else { | ||||||
4731 | // C++ [class.union]p2: | ||||||
4732 | // For the purpose of name lookup, after the anonymous union | ||||||
4733 | // definition, the members of the anonymous union are | ||||||
4734 | // considered to have been defined in the scope in which the | ||||||
4735 | // anonymous union is declared. | ||||||
4736 | unsigned OldChainingSize = Chaining.size(); | ||||||
4737 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | ||||||
4738 | Chaining.append(IF->chain_begin(), IF->chain_end()); | ||||||
4739 | else | ||||||
4740 | Chaining.push_back(VD); | ||||||
4741 | |||||||
4742 | assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4742, __PRETTY_FUNCTION__)); | ||||||
4743 | NamedDecl **NamedChain = | ||||||
4744 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | ||||||
4745 | for (unsigned i = 0; i < Chaining.size(); i++) | ||||||
4746 | NamedChain[i] = Chaining[i]; | ||||||
4747 | |||||||
4748 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | ||||||
4749 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | ||||||
4750 | VD->getType(), {NamedChain, Chaining.size()}); | ||||||
4751 | |||||||
4752 | for (const auto *Attr : VD->attrs()) | ||||||
4753 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | ||||||
4754 | |||||||
4755 | IndirectField->setAccess(AS); | ||||||
4756 | IndirectField->setImplicit(); | ||||||
4757 | SemaRef.PushOnScopeChains(IndirectField, S); | ||||||
4758 | |||||||
4759 | // That includes picking up the appropriate access specifier. | ||||||
4760 | if (AS != AS_none) IndirectField->setAccess(AS); | ||||||
4761 | |||||||
4762 | Chaining.resize(OldChainingSize); | ||||||
4763 | } | ||||||
4764 | } | ||||||
4765 | } | ||||||
4766 | |||||||
4767 | return Invalid; | ||||||
4768 | } | ||||||
4769 | |||||||
4770 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | ||||||
4771 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | ||||||
4772 | /// illegal input values are mapped to SC_None. | ||||||
4773 | static StorageClass | ||||||
4774 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | ||||||
4775 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | ||||||
4776 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4777, __PRETTY_FUNCTION__)) | ||||||
4777 | "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4777, __PRETTY_FUNCTION__)); | ||||||
4778 | switch (StorageClassSpec) { | ||||||
4779 | case DeclSpec::SCS_unspecified: return SC_None; | ||||||
4780 | case DeclSpec::SCS_extern: | ||||||
4781 | if (DS.isExternInLinkageSpec()) | ||||||
4782 | return SC_None; | ||||||
4783 | return SC_Extern; | ||||||
4784 | case DeclSpec::SCS_static: return SC_Static; | ||||||
4785 | case DeclSpec::SCS_auto: return SC_Auto; | ||||||
4786 | case DeclSpec::SCS_register: return SC_Register; | ||||||
4787 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||||
4788 | // Illegal SCSs map to None: error reporting is up to the caller. | ||||||
4789 | case DeclSpec::SCS_mutable: // Fall through. | ||||||
4790 | case DeclSpec::SCS_typedef: return SC_None; | ||||||
4791 | } | ||||||
4792 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4792); | ||||||
4793 | } | ||||||
4794 | |||||||
4795 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | ||||||
4796 | assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4796, __PRETTY_FUNCTION__)); | ||||||
4797 | |||||||
4798 | for (const auto *I : Record->decls()) { | ||||||
4799 | const auto *FD = dyn_cast<FieldDecl>(I); | ||||||
4800 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||||
4801 | FD = IFD->getAnonField(); | ||||||
4802 | if (FD && FD->hasInClassInitializer()) | ||||||
4803 | return FD->getLocation(); | ||||||
4804 | } | ||||||
4805 | |||||||
4806 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4806); | ||||||
4807 | } | ||||||
4808 | |||||||
4809 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||||
4810 | SourceLocation DefaultInitLoc) { | ||||||
4811 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||||
4812 | return; | ||||||
4813 | |||||||
4814 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | ||||||
4815 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | ||||||
4816 | } | ||||||
4817 | |||||||
4818 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||||
4819 | CXXRecordDecl *AnonUnion) { | ||||||
4820 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||||
4821 | return; | ||||||
4822 | |||||||
4823 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | ||||||
4824 | } | ||||||
4825 | |||||||
4826 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | ||||||
4827 | /// anonymous structure or union. Anonymous unions are a C++ feature | ||||||
4828 | /// (C++ [class.union]) and a C11 feature; anonymous structures | ||||||
4829 | /// are a C11 feature and GNU C++ extension. | ||||||
4830 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | ||||||
4831 | AccessSpecifier AS, | ||||||
4832 | RecordDecl *Record, | ||||||
4833 | const PrintingPolicy &Policy) { | ||||||
4834 | DeclContext *Owner = Record->getDeclContext(); | ||||||
4835 | |||||||
4836 | // Diagnose whether this anonymous struct/union is an extension. | ||||||
4837 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | ||||||
4838 | Diag(Record->getLocation(), diag::ext_anonymous_union); | ||||||
4839 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | ||||||
4840 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | ||||||
4841 | else if (!Record->isUnion() && !getLangOpts().C11) | ||||||
4842 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | ||||||
4843 | |||||||
4844 | // C and C++ require different kinds of checks for anonymous | ||||||
4845 | // structs/unions. | ||||||
4846 | bool Invalid = false; | ||||||
4847 | if (getLangOpts().CPlusPlus) { | ||||||
4848 | const char *PrevSpec = nullptr; | ||||||
4849 | if (Record->isUnion()) { | ||||||
4850 | // C++ [class.union]p6: | ||||||
4851 | // C++17 [class.union.anon]p2: | ||||||
4852 | // Anonymous unions declared in a named namespace or in the | ||||||
4853 | // global namespace shall be declared static. | ||||||
4854 | unsigned DiagID; | ||||||
4855 | DeclContext *OwnerScope = Owner->getRedeclContext(); | ||||||
4856 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | ||||||
4857 | (OwnerScope->isTranslationUnit() || | ||||||
4858 | (OwnerScope->isNamespace() && | ||||||
4859 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | ||||||
4860 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | ||||||
4861 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | ||||||
4862 | |||||||
4863 | // Recover by adding 'static'. | ||||||
4864 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | ||||||
4865 | PrevSpec, DiagID, Policy); | ||||||
4866 | } | ||||||
4867 | // C++ [class.union]p6: | ||||||
4868 | // A storage class is not allowed in a declaration of an | ||||||
4869 | // anonymous union in a class scope. | ||||||
4870 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | ||||||
4871 | isa<RecordDecl>(Owner)) { | ||||||
4872 | Diag(DS.getStorageClassSpecLoc(), | ||||||
4873 | diag::err_anonymous_union_with_storage_spec) | ||||||
4874 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
4875 | |||||||
4876 | // Recover by removing the storage specifier. | ||||||
4877 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | ||||||
4878 | SourceLocation(), | ||||||
4879 | PrevSpec, DiagID, Context.getPrintingPolicy()); | ||||||
4880 | } | ||||||
4881 | } | ||||||
4882 | |||||||
4883 | // Ignore const/volatile/restrict qualifiers. | ||||||
4884 | if (DS.getTypeQualifiers()) { | ||||||
4885 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||||
4886 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | ||||||
4887 | << Record->isUnion() << "const" | ||||||
4888 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | ||||||
4889 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||||
4890 | Diag(DS.getVolatileSpecLoc(), | ||||||
4891 | diag::ext_anonymous_struct_union_qualified) | ||||||
4892 | << Record->isUnion() << "volatile" | ||||||
4893 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | ||||||
4894 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | ||||||
4895 | Diag(DS.getRestrictSpecLoc(), | ||||||
4896 | diag::ext_anonymous_struct_union_qualified) | ||||||
4897 | << Record->isUnion() << "restrict" | ||||||
4898 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | ||||||
4899 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||||
4900 | Diag(DS.getAtomicSpecLoc(), | ||||||
4901 | diag::ext_anonymous_struct_union_qualified) | ||||||
4902 | << Record->isUnion() << "_Atomic" | ||||||
4903 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | ||||||
4904 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||||
4905 | Diag(DS.getUnalignedSpecLoc(), | ||||||
4906 | diag::ext_anonymous_struct_union_qualified) | ||||||
4907 | << Record->isUnion() << "__unaligned" | ||||||
4908 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | ||||||
4909 | |||||||
4910 | DS.ClearTypeQualifiers(); | ||||||
4911 | } | ||||||
4912 | |||||||
4913 | // C++ [class.union]p2: | ||||||
4914 | // The member-specification of an anonymous union shall only | ||||||
4915 | // define non-static data members. [Note: nested types and | ||||||
4916 | // functions cannot be declared within an anonymous union. ] | ||||||
4917 | for (auto *Mem : Record->decls()) { | ||||||
4918 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | ||||||
4919 | // C++ [class.union]p3: | ||||||
4920 | // An anonymous union shall not have private or protected | ||||||
4921 | // members (clause 11). | ||||||
4922 | assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0 ) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 4922, __PRETTY_FUNCTION__)); | ||||||
4923 | if (FD->getAccess() != AS_public) { | ||||||
4924 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | ||||||
4925 | << Record->isUnion() << (FD->getAccess() == AS_protected); | ||||||
4926 | Invalid = true; | ||||||
4927 | } | ||||||
4928 | |||||||
4929 | // C++ [class.union]p1 | ||||||
4930 | // An object of a class with a non-trivial constructor, a non-trivial | ||||||
4931 | // copy constructor, a non-trivial destructor, or a non-trivial copy | ||||||
4932 | // assignment operator cannot be a member of a union, nor can an | ||||||
4933 | // array of such objects. | ||||||
4934 | if (CheckNontrivialField(FD)) | ||||||
4935 | Invalid = true; | ||||||
4936 | } else if (Mem->isImplicit()) { | ||||||
4937 | // Any implicit members are fine. | ||||||
4938 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | ||||||
4939 | // This is a type that showed up in an | ||||||
4940 | // elaborated-type-specifier inside the anonymous struct or | ||||||
4941 | // union, but which actually declares a type outside of the | ||||||
4942 | // anonymous struct or union. It's okay. | ||||||
4943 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | ||||||
4944 | if (!MemRecord->isAnonymousStructOrUnion() && | ||||||
4945 | MemRecord->getDeclName()) { | ||||||
4946 | // Visual C++ allows type definition in anonymous struct or union. | ||||||
4947 | if (getLangOpts().MicrosoftExt) | ||||||
4948 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | ||||||
4949 | << Record->isUnion(); | ||||||
4950 | else { | ||||||
4951 | // This is a nested type declaration. | ||||||
4952 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | ||||||
4953 | << Record->isUnion(); | ||||||
4954 | Invalid = true; | ||||||
4955 | } | ||||||
4956 | } else { | ||||||
4957 | // This is an anonymous type definition within another anonymous type. | ||||||
4958 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | ||||||
4959 | // not part of standard C++. | ||||||
4960 | Diag(MemRecord->getLocation(), | ||||||
4961 | diag::ext_anonymous_record_with_anonymous_type) | ||||||
4962 | << Record->isUnion(); | ||||||
4963 | } | ||||||
4964 | } else if (isa<AccessSpecDecl>(Mem)) { | ||||||
4965 | // Any access specifier is fine. | ||||||
4966 | } else if (isa<StaticAssertDecl>(Mem)) { | ||||||
4967 | // In C++1z, static_assert declarations are also fine. | ||||||
4968 | } else { | ||||||
4969 | // We have something that isn't a non-static data | ||||||
4970 | // member. Complain about it. | ||||||
4971 | unsigned DK = diag::err_anonymous_record_bad_member; | ||||||
4972 | if (isa<TypeDecl>(Mem)) | ||||||
4973 | DK = diag::err_anonymous_record_with_type; | ||||||
4974 | else if (isa<FunctionDecl>(Mem)) | ||||||
4975 | DK = diag::err_anonymous_record_with_function; | ||||||
4976 | else if (isa<VarDecl>(Mem)) | ||||||
4977 | DK = diag::err_anonymous_record_with_static; | ||||||
4978 | |||||||
4979 | // Visual C++ allows type definition in anonymous struct or union. | ||||||
4980 | if (getLangOpts().MicrosoftExt && | ||||||
4981 | DK == diag::err_anonymous_record_with_type) | ||||||
4982 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | ||||||
4983 | << Record->isUnion(); | ||||||
4984 | else { | ||||||
4985 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | ||||||
4986 | Invalid = true; | ||||||
4987 | } | ||||||
4988 | } | ||||||
4989 | } | ||||||
4990 | |||||||
4991 | // C++11 [class.union]p8 (DR1460): | ||||||
4992 | // At most one variant member of a union may have a | ||||||
4993 | // brace-or-equal-initializer. | ||||||
4994 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | ||||||
4995 | Owner->isRecord()) | ||||||
4996 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | ||||||
4997 | cast<CXXRecordDecl>(Record)); | ||||||
4998 | } | ||||||
4999 | |||||||
5000 | if (!Record->isUnion() && !Owner->isRecord()) { | ||||||
5001 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | ||||||
5002 | << getLangOpts().CPlusPlus; | ||||||
5003 | Invalid = true; | ||||||
5004 | } | ||||||
5005 | |||||||
5006 | // C++ [dcl.dcl]p3: | ||||||
5007 | // [If there are no declarators], and except for the declaration of an | ||||||
5008 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||||
5009 | // names into the program | ||||||
5010 | // C++ [class.mem]p2: | ||||||
5011 | // each such member-declaration shall either declare at least one member | ||||||
5012 | // name of the class or declare at least one unnamed bit-field | ||||||
5013 | // | ||||||
5014 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | ||||||
5015 | if (getLangOpts().CPlusPlus && Record->field_empty()) | ||||||
5016 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||||
5017 | |||||||
5018 | // Mock up a declarator. | ||||||
5019 | Declarator Dc(DS, DeclaratorContext::MemberContext); | ||||||
5020 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||||
5021 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 5021, __PRETTY_FUNCTION__)); | ||||||
5022 | |||||||
5023 | // Create a declaration for this anonymous struct/union. | ||||||
5024 | NamedDecl *Anon = nullptr; | ||||||
5025 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | ||||||
5026 | Anon = FieldDecl::Create( | ||||||
5027 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | ||||||
5028 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | ||||||
5029 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||||
5030 | /*InitStyle=*/ICIS_NoInit); | ||||||
5031 | Anon->setAccess(AS); | ||||||
5032 | ProcessDeclAttributes(S, Anon, Dc); | ||||||
5033 | |||||||
5034 | if (getLangOpts().CPlusPlus) | ||||||
5035 | FieldCollector->Add(cast<FieldDecl>(Anon)); | ||||||
5036 | } else { | ||||||
5037 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | ||||||
5038 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | ||||||
5039 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||||
5040 | // mutable can only appear on non-static class members, so it's always | ||||||
5041 | // an error here | ||||||
5042 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | ||||||
5043 | Invalid = true; | ||||||
5044 | SC = SC_None; | ||||||
5045 | } | ||||||
5046 | |||||||
5047 | assert(DS.getAttributes().empty() && "No attribute expected")((DS.getAttributes().empty() && "No attribute expected" ) ? static_cast<void> (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 5047, __PRETTY_FUNCTION__)); | ||||||
5048 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | ||||||
5049 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | ||||||
5050 | Context.getTypeDeclType(Record), TInfo, SC); | ||||||
5051 | |||||||
5052 | // Default-initialize the implicit variable. This initialization will be | ||||||
5053 | // trivial in almost all cases, except if a union member has an in-class | ||||||
5054 | // initializer: | ||||||
5055 | // union { int n = 0; }; | ||||||
5056 | ActOnUninitializedDecl(Anon); | ||||||
5057 | } | ||||||
5058 | Anon->setImplicit(); | ||||||
5059 | |||||||
5060 | // Mark this as an anonymous struct/union type. | ||||||
5061 | Record->setAnonymousStructOrUnion(true); | ||||||
5062 | |||||||
5063 | // Add the anonymous struct/union object to the current | ||||||
5064 | // context. We'll be referencing this object when we refer to one of | ||||||
5065 | // its members. | ||||||
5066 | Owner->addDecl(Anon); | ||||||
5067 | |||||||
5068 | // Inject the members of the anonymous struct/union into the owning | ||||||
5069 | // context and into the identifier resolver chain for name lookup | ||||||
5070 | // purposes. | ||||||
5071 | SmallVector<NamedDecl*, 2> Chain; | ||||||
5072 | Chain.push_back(Anon); | ||||||
5073 | |||||||
5074 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | ||||||
5075 | Invalid = true; | ||||||
5076 | |||||||
5077 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | ||||||
5078 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||||
5079 | MangleNumberingContext *MCtx; | ||||||
5080 | Decl *ManglingContextDecl; | ||||||
5081 | std::tie(MCtx, ManglingContextDecl) = | ||||||
5082 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||||
5083 | if (MCtx) { | ||||||
5084 | Context.setManglingNumber( | ||||||
5085 | NewVD, MCtx->getManglingNumber( | ||||||
5086 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||||
5087 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||||
5088 | } | ||||||
5089 | } | ||||||
5090 | } | ||||||
5091 | |||||||
5092 | if (Invalid) | ||||||
5093 | Anon->setInvalidDecl(); | ||||||
5094 | |||||||
5095 | return Anon; | ||||||
5096 | } | ||||||
5097 | |||||||
5098 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | ||||||
5099 | /// Microsoft C anonymous structure. | ||||||
5100 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | ||||||
5101 | /// Example: | ||||||
5102 | /// | ||||||
5103 | /// struct A { int a; }; | ||||||
5104 | /// struct B { struct A; int b; }; | ||||||
5105 | /// | ||||||
5106 | /// void foo() { | ||||||
5107 | /// B var; | ||||||
5108 | /// var.a = 3; | ||||||
5109 | /// } | ||||||
5110 | /// | ||||||
5111 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | ||||||
5112 | RecordDecl *Record) { | ||||||
5113 | assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void > (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 5113, __PRETTY_FUNCTION__)); | ||||||
5114 | |||||||
5115 | // Mock up a declarator. | ||||||
5116 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); | ||||||
5117 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||||
5118 | assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 5118, __PRETTY_FUNCTION__)); | ||||||
5119 | |||||||
5120 | auto *ParentDecl = cast<RecordDecl>(CurContext); | ||||||
5121 | QualType RecTy = Context.getTypeDeclType(Record); | ||||||
5122 | |||||||
5123 | // Create a declaration for this anonymous struct. | ||||||
5124 | NamedDecl *Anon = | ||||||
5125 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | ||||||
5126 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | ||||||
5127 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||||
5128 | /*InitStyle=*/ICIS_NoInit); | ||||||
5129 | Anon->setImplicit(); | ||||||
5130 | |||||||
5131 | // Add the anonymous struct object to the current context. | ||||||
5132 | CurContext->addDecl(Anon); | ||||||
5133 | |||||||
5134 | // Inject the members of the anonymous struct into the current | ||||||
5135 | // context and into the identifier resolver chain for name lookup | ||||||
5136 | // purposes. | ||||||
5137 | SmallVector<NamedDecl*, 2> Chain; | ||||||
5138 | Chain.push_back(Anon); | ||||||
5139 | |||||||
5140 | RecordDecl *RecordDef = Record->getDefinition(); | ||||||
5141 | if (RequireCompleteType(Anon->getLocation(), RecTy, | ||||||
5142 | diag::err_field_incomplete) || | ||||||
5143 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | ||||||
5144 | AS_none, Chain)) { | ||||||
5145 | Anon->setInvalidDecl(); | ||||||
5146 | ParentDecl->setInvalidDecl(); | ||||||
5147 | } | ||||||
5148 | |||||||
5149 | return Anon; | ||||||
5150 | } | ||||||
5151 | |||||||
5152 | /// GetNameForDeclarator - Determine the full declaration name for the | ||||||
5153 | /// given Declarator. | ||||||
5154 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | ||||||
5155 | return GetNameFromUnqualifiedId(D.getName()); | ||||||
5156 | } | ||||||
5157 | |||||||
5158 | /// Retrieves the declaration name from a parsed unqualified-id. | ||||||
5159 | DeclarationNameInfo | ||||||
5160 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | ||||||
5161 | DeclarationNameInfo NameInfo; | ||||||
5162 | NameInfo.setLoc(Name.StartLocation); | ||||||
5163 | |||||||
5164 | switch (Name.getKind()) { | ||||||
5165 | |||||||
5166 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||||
5167 | case UnqualifiedIdKind::IK_Identifier: | ||||||
5168 | NameInfo.setName(Name.Identifier); | ||||||
5169 | return NameInfo; | ||||||
5170 | |||||||
5171 | case UnqualifiedIdKind::IK_DeductionGuideName: { | ||||||
5172 | // C++ [temp.deduct.guide]p3: | ||||||
5173 | // The simple-template-id shall name a class template specialization. | ||||||
5174 | // The template-name shall be the same identifier as the template-name | ||||||
5175 | // of the simple-template-id. | ||||||
5176 | // These together intend to imply that the template-name shall name a | ||||||
5177 | // class template. | ||||||
5178 | // FIXME: template<typename T> struct X {}; | ||||||
5179 | // template<typename T> using Y = X<T>; | ||||||
5180 | // Y(int) -> Y<int>; | ||||||
5181 | // satisfies these rules but does not name a class template. | ||||||
5182 | TemplateName TN = Name.TemplateName.get().get(); | ||||||
5183 | auto *Template = TN.getAsTemplateDecl(); | ||||||
5184 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | ||||||
5185 | Diag(Name.StartLocation, | ||||||
5186 | diag::err_deduction_guide_name_not_class_template) | ||||||
5187 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | ||||||
5188 | if (Template) | ||||||
5189 | Diag(Template->getLocation(), diag::note_template_decl_here); | ||||||
5190 | return DeclarationNameInfo(); | ||||||
5191 | } | ||||||
5192 | |||||||
5193 | NameInfo.setName( | ||||||
5194 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | ||||||
5195 | return NameInfo; | ||||||
5196 | } | ||||||
5197 | |||||||
5198 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||||
5199 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | ||||||
5200 | Name.OperatorFunctionId.Operator)); | ||||||
5201 | NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc | ||||||
5202 | = Name.OperatorFunctionId.SymbolLocations[0]; | ||||||
5203 | NameInfo.getInfo().CXXOperatorName.EndOpNameLoc | ||||||
5204 | = Name.EndLocation.getRawEncoding(); | ||||||
5205 | return NameInfo; | ||||||
5206 | |||||||
5207 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||||
5208 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | ||||||
5209 | Name.Identifier)); | ||||||
5210 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | ||||||
5211 | return NameInfo; | ||||||
5212 | |||||||
5213 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | ||||||
5214 | TypeSourceInfo *TInfo; | ||||||
5215 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | ||||||
5216 | if (Ty.isNull()) | ||||||
5217 | return DeclarationNameInfo(); | ||||||
5218 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | ||||||
5219 | Context.getCanonicalType(Ty))); | ||||||
5220 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5221 | return NameInfo; | ||||||
5222 | } | ||||||
5223 | |||||||
5224 | case UnqualifiedIdKind::IK_ConstructorName: { | ||||||
5225 | TypeSourceInfo *TInfo; | ||||||
5226 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | ||||||
5227 | if (Ty.isNull()) | ||||||
5228 | return DeclarationNameInfo(); | ||||||
5229 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||||
5230 | Context.getCanonicalType(Ty))); | ||||||
5231 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5232 | return NameInfo; | ||||||
5233 | } | ||||||
5234 | |||||||
5235 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | ||||||
5236 | // In well-formed code, we can only have a constructor | ||||||
5237 | // template-id that refers to the current context, so go there | ||||||
5238 | // to find the actual type being constructed. | ||||||
5239 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | ||||||
5240 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | ||||||
5241 | return DeclarationNameInfo(); | ||||||
5242 | |||||||
5243 | // Determine the type of the class being constructed. | ||||||
5244 | QualType CurClassType = Context.getTypeDeclType(CurClass); | ||||||
5245 | |||||||
5246 | // FIXME: Check two things: that the template-id names the same type as | ||||||
5247 | // CurClassType, and that the template-id does not occur when the name | ||||||
5248 | // was qualified. | ||||||
5249 | |||||||
5250 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||||
5251 | Context.getCanonicalType(CurClassType))); | ||||||
5252 | // FIXME: should we retrieve TypeSourceInfo? | ||||||
5253 | NameInfo.setNamedTypeInfo(nullptr); | ||||||
5254 | return NameInfo; | ||||||
5255 | } | ||||||
5256 | |||||||
5257 | case UnqualifiedIdKind::IK_DestructorName: { | ||||||
5258 | TypeSourceInfo *TInfo; | ||||||
5259 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | ||||||
5260 | if (Ty.isNull()) | ||||||
5261 | return DeclarationNameInfo(); | ||||||
5262 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | ||||||
5263 | Context.getCanonicalType(Ty))); | ||||||
5264 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5265 | return NameInfo; | ||||||
5266 | } | ||||||
5267 | |||||||
5268 | case UnqualifiedIdKind::IK_TemplateId: { | ||||||
5269 | TemplateName TName = Name.TemplateId->Template.get(); | ||||||
5270 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | ||||||
5271 | return Context.getNameForTemplate(TName, TNameLoc); | ||||||
5272 | } | ||||||
5273 | |||||||
5274 | } // switch (Name.getKind()) | ||||||
5275 | |||||||
5276 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 5276); | ||||||
5277 | } | ||||||
5278 | |||||||
5279 | static QualType getCoreType(QualType Ty) { | ||||||
5280 | do { | ||||||
5281 | if (Ty->isPointerType() || Ty->isReferenceType()) | ||||||
5282 | Ty = Ty->getPointeeType(); | ||||||
5283 | else if (Ty->isArrayType()) | ||||||
5284 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | ||||||
5285 | else | ||||||
5286 | return Ty.withoutLocalFastQualifiers(); | ||||||
5287 | } while (true); | ||||||
5288 | } | ||||||
5289 | |||||||
5290 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | ||||||
5291 | /// and Definition have "nearly" matching parameters. This heuristic is | ||||||
5292 | /// used to improve diagnostics in the case where an out-of-line function | ||||||
5293 | /// definition doesn't match any declaration within the class or namespace. | ||||||
5294 | /// Also sets Params to the list of indices to the parameters that differ | ||||||
5295 | /// between the declaration and the definition. If hasSimilarParameters | ||||||
5296 | /// returns true and Params is empty, then all of the parameters match. | ||||||
5297 | static bool hasSimilarParameters(ASTContext &Context, | ||||||
5298 | FunctionDecl *Declaration, | ||||||
5299 | FunctionDecl *Definition, | ||||||
5300 | SmallVectorImpl<unsigned> &Params) { | ||||||
5301 | Params.clear(); | ||||||
5302 | if (Declaration->param_size() != Definition->param_size()) | ||||||
5303 | return false; | ||||||
5304 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | ||||||
5305 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | ||||||
5306 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | ||||||
5307 | |||||||
5308 | // The parameter types are identical | ||||||
5309 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | ||||||
5310 | continue; | ||||||
5311 | |||||||
5312 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | ||||||
5313 | QualType DefParamBaseTy = getCoreType(DefParamTy); | ||||||
5314 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | ||||||
5315 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | ||||||
5316 | |||||||
5317 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | ||||||
5318 | (DeclTyName && DeclTyName == DefTyName)) | ||||||
5319 | Params.push_back(Idx); | ||||||
5320 | else // The two parameters aren't even close | ||||||
5321 | return false; | ||||||
5322 | } | ||||||
5323 | |||||||
5324 | return true; | ||||||
5325 | } | ||||||
5326 | |||||||
5327 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | ||||||
5328 | /// declarator needs to be rebuilt in the current instantiation. | ||||||
5329 | /// Any bits of declarator which appear before the name are valid for | ||||||
5330 | /// consideration here. That's specifically the type in the decl spec | ||||||
5331 | /// and the base type in any member-pointer chunks. | ||||||
5332 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | ||||||
5333 | DeclarationName Name) { | ||||||
5334 | // The types we specifically need to rebuild are: | ||||||
5335 | // - typenames, typeofs, and decltypes | ||||||
5336 | // - types which will become injected class names | ||||||
5337 | // Of course, we also need to rebuild any type referencing such a | ||||||
5338 | // type. It's safest to just say "dependent", but we call out a | ||||||
5339 | // few cases here. | ||||||
5340 | |||||||
5341 | DeclSpec &DS = D.getMutableDeclSpec(); | ||||||
5342 | switch (DS.getTypeSpecType()) { | ||||||
5343 | case DeclSpec::TST_typename: | ||||||
5344 | case DeclSpec::TST_typeofType: | ||||||
5345 | case DeclSpec::TST_underlyingType: | ||||||
5346 | case DeclSpec::TST_atomic: { | ||||||
5347 | // Grab the type from the parser. | ||||||
5348 | TypeSourceInfo *TSI = nullptr; | ||||||
5349 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | ||||||
5350 | if (T.isNull() || !T->isDependentType()) break; | ||||||
5351 | |||||||
5352 | // Make sure there's a type source info. This isn't really much | ||||||
5353 | // of a waste; most dependent types should have type source info | ||||||
5354 | // attached already. | ||||||
5355 | if (!TSI) | ||||||
5356 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | ||||||
5357 | |||||||
5358 | // Rebuild the type in the current instantiation. | ||||||
5359 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | ||||||
5360 | if (!TSI) return true; | ||||||
5361 | |||||||
5362 | // Store the new type back in the decl spec. | ||||||
5363 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | ||||||
5364 | DS.UpdateTypeRep(LocType); | ||||||
5365 | break; | ||||||
5366 | } | ||||||
5367 | |||||||
5368 | case DeclSpec::TST_decltype: | ||||||
5369 | case DeclSpec::TST_typeofExpr: { | ||||||
5370 | Expr *E = DS.getRepAsExpr(); | ||||||
5371 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | ||||||
5372 | if (Result.isInvalid()) return true; | ||||||
5373 | DS.UpdateExprRep(Result.get()); | ||||||
5374 | break; | ||||||
5375 | } | ||||||
5376 | |||||||
5377 | default: | ||||||
5378 | // Nothing to do for these decl specs. | ||||||
5379 | break; | ||||||
5380 | } | ||||||
5381 | |||||||
5382 | // It doesn't matter what order we do this in. | ||||||
5383 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | ||||||
5384 | DeclaratorChunk &Chunk = D.getTypeObject(I); | ||||||
5385 | |||||||
5386 | // The only type information in the declarator which can come | ||||||
5387 | // before the declaration name is the base type of a member | ||||||
5388 | // pointer. | ||||||
5389 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | ||||||
5390 | continue; | ||||||
5391 | |||||||
5392 | // Rebuild the scope specifier in-place. | ||||||
5393 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | ||||||
5394 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | ||||||
5395 | return true; | ||||||
5396 | } | ||||||
5397 | |||||||
5398 | return false; | ||||||
5399 | } | ||||||
5400 | |||||||
5401 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | ||||||
5402 | D.setFunctionDefinitionKind(FDK_Declaration); | ||||||
5403 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | ||||||
5404 | |||||||
5405 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | ||||||
5406 | Dcl && Dcl->getDeclContext()->isFileContext()) | ||||||
5407 | Dcl->setTopLevelDeclInObjCContainer(); | ||||||
5408 | |||||||
5409 | if (getLangOpts().OpenCL) | ||||||
5410 | setCurrentOpenCLExtensionForDecl(Dcl); | ||||||
5411 | |||||||
5412 | return Dcl; | ||||||
5413 | } | ||||||
5414 | |||||||
5415 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | ||||||
5416 | /// If T is the name of a class, then each of the following shall have a | ||||||
5417 | /// name different from T: | ||||||
5418 | /// - every static data member of class T; | ||||||
5419 | /// - every member function of class T | ||||||
5420 | /// - every member of class T that is itself a type; | ||||||
5421 | /// \returns true if the declaration name violates these rules. | ||||||
5422 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | ||||||
5423 | DeclarationNameInfo NameInfo) { | ||||||
5424 | DeclarationName Name = NameInfo.getName(); | ||||||
5425 | |||||||
5426 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | ||||||
5427 | while (Record && Record->isAnonymousStructOrUnion()) | ||||||
5428 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | ||||||
5429 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | ||||||
5430 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | ||||||
5431 | return true; | ||||||
5432 | } | ||||||
5433 | |||||||
5434 | return false; | ||||||
5435 | } | ||||||
5436 | |||||||
5437 | /// Diagnose a declaration whose declarator-id has the given | ||||||
5438 | /// nested-name-specifier. | ||||||
5439 | /// | ||||||
5440 | /// \param SS The nested-name-specifier of the declarator-id. | ||||||
5441 | /// | ||||||
5442 | /// \param DC The declaration context to which the nested-name-specifier | ||||||
5443 | /// resolves. | ||||||
5444 | /// | ||||||
5445 | /// \param Name The name of the entity being declared. | ||||||
5446 | /// | ||||||
5447 | /// \param Loc The location of the name of the entity being declared. | ||||||
5448 | /// | ||||||
5449 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | ||||||
5450 | /// we're declaring an explicit / partial specialization / instantiation. | ||||||
5451 | /// | ||||||
5452 | /// \returns true if we cannot safely recover from this error, false otherwise. | ||||||
5453 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | ||||||
5454 | DeclarationName Name, | ||||||
5455 | SourceLocation Loc, bool IsTemplateId) { | ||||||
5456 | DeclContext *Cur = CurContext; | ||||||
5457 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | ||||||
5458 | Cur = Cur->getParent(); | ||||||
5459 | |||||||
5460 | // If the user provided a superfluous scope specifier that refers back to the | ||||||
5461 | // class in which the entity is already declared, diagnose and ignore it. | ||||||
5462 | // | ||||||
5463 | // class X { | ||||||
5464 | // void X::f(); | ||||||
5465 | // }; | ||||||
5466 | // | ||||||
5467 | // Note, it was once ill-formed to give redundant qualification in all | ||||||
5468 | // contexts, but that rule was removed by DR482. | ||||||
5469 | if (Cur->Equals(DC)) { | ||||||
5470 | if (Cur->isRecord()) { | ||||||
5471 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | ||||||
5472 | : diag::err_member_extra_qualification) | ||||||
5473 | << Name << FixItHint::CreateRemoval(SS.getRange()); | ||||||
5474 | SS.clear(); | ||||||
5475 | } else { | ||||||
5476 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | ||||||
5477 | } | ||||||
5478 | return false; | ||||||
5479 | } | ||||||
5480 | |||||||
5481 | // Check whether the qualifying scope encloses the scope of the original | ||||||
5482 | // declaration. For a template-id, we perform the checks in | ||||||
5483 | // CheckTemplateSpecializationScope. | ||||||
5484 | if (!Cur->Encloses(DC) && !IsTemplateId) { | ||||||
5485 | if (Cur->isRecord()) | ||||||
5486 | Diag(Loc, diag::err_member_qualification) | ||||||
5487 | << Name << SS.getRange(); | ||||||
5488 | else if (isa<TranslationUnitDecl>(DC)) | ||||||
5489 | Diag(Loc, diag::err_invalid_declarator_global_scope) | ||||||
5490 | << Name << SS.getRange(); | ||||||
5491 | else if (isa<FunctionDecl>(Cur)) | ||||||
5492 | Diag(Loc, diag::err_invalid_declarator_in_function) | ||||||
5493 | << Name << SS.getRange(); | ||||||
5494 | else if (isa<BlockDecl>(Cur)) | ||||||
5495 | Diag(Loc, diag::err_invalid_declarator_in_block) | ||||||
5496 | << Name << SS.getRange(); | ||||||
5497 | else | ||||||
5498 | Diag(Loc, diag::err_invalid_declarator_scope) | ||||||
5499 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | ||||||
5500 | |||||||
5501 | return true; | ||||||
5502 | } | ||||||
5503 | |||||||
5504 | if (Cur->isRecord()) { | ||||||
5505 | // Cannot qualify members within a class. | ||||||
5506 | Diag(Loc, diag::err_member_qualification) | ||||||
5507 | << Name << SS.getRange(); | ||||||
5508 | SS.clear(); | ||||||
5509 | |||||||
5510 | // C++ constructors and destructors with incorrect scopes can break | ||||||
5511 | // our AST invariants by having the wrong underlying types. If | ||||||
5512 | // that's the case, then drop this declaration entirely. | ||||||
5513 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | ||||||
5514 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | ||||||
5515 | !Context.hasSameType(Name.getCXXNameType(), | ||||||
5516 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | ||||||
5517 | return true; | ||||||
5518 | |||||||
5519 | return false; | ||||||
5520 | } | ||||||
5521 | |||||||
5522 | // C++11 [dcl.meaning]p1: | ||||||
5523 | // [...] "The nested-name-specifier of the qualified declarator-id shall | ||||||
5524 | // not begin with a decltype-specifer" | ||||||
5525 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | ||||||
5526 | while (SpecLoc.getPrefix()) | ||||||
5527 | SpecLoc = SpecLoc.getPrefix(); | ||||||
5528 | if (dyn_cast_or_null<DecltypeType>( | ||||||
5529 | SpecLoc.getNestedNameSpecifier()->getAsType())) | ||||||
5530 | Diag(Loc, diag::err_decltype_in_declarator) | ||||||
5531 | << SpecLoc.getTypeLoc().getSourceRange(); | ||||||
5532 | |||||||
5533 | return false; | ||||||
5534 | } | ||||||
5535 | |||||||
5536 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | ||||||
5537 | MultiTemplateParamsArg TemplateParamLists) { | ||||||
5538 | // TODO: consider using NameInfo for diagnostic. | ||||||
5539 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||||
5540 | DeclarationName Name = NameInfo.getName(); | ||||||
5541 | |||||||
5542 | // All of these full declarators require an identifier. If it doesn't have | ||||||
5543 | // one, the ParsedFreeStandingDeclSpec action should be used. | ||||||
5544 | if (D.isDecompositionDeclarator()) { | ||||||
5545 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | ||||||
5546 | } else if (!Name) { | ||||||
5547 | if (!D.isInvalidType()) // Reject this if we think it is valid. | ||||||
5548 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | ||||||
5549 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | ||||||
5550 | return nullptr; | ||||||
5551 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | ||||||
5552 | return nullptr; | ||||||
5553 | |||||||
5554 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||||
5555 | // we find one that is. | ||||||
5556 | while ((S->getFlags() & Scope::DeclScope) == 0 || | ||||||
5557 | (S->getFlags() & Scope::TemplateParamScope) != 0) | ||||||
5558 | S = S->getParent(); | ||||||
5559 | |||||||
5560 | DeclContext *DC = CurContext; | ||||||
5561 | if (D.getCXXScopeSpec().isInvalid()) | ||||||
5562 | D.setInvalidType(); | ||||||
5563 | else if (D.getCXXScopeSpec().isSet()) { | ||||||
5564 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | ||||||
5565 | UPPC_DeclarationQualifier)) | ||||||
5566 | return nullptr; | ||||||
5567 | |||||||
5568 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | ||||||
5569 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | ||||||
5570 | if (!DC || isa<EnumDecl>(DC)) { | ||||||
5571 | // If we could not compute the declaration context, it's because the | ||||||
5572 | // declaration context is dependent but does not refer to a class, | ||||||
5573 | // class template, or class template partial specialization. Complain | ||||||
5574 | // and return early, to avoid the coming semantic disaster. | ||||||
5575 | Diag(D.getIdentifierLoc(), | ||||||
5576 | diag::err_template_qualified_declarator_no_match) | ||||||
5577 | << D.getCXXScopeSpec().getScopeRep() | ||||||
5578 | << D.getCXXScopeSpec().getRange(); | ||||||
5579 | return nullptr; | ||||||
5580 | } | ||||||
5581 | bool IsDependentContext = DC->isDependentContext(); | ||||||
5582 | |||||||
5583 | if (!IsDependentContext && | ||||||
5584 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | ||||||
5585 | return nullptr; | ||||||
5586 | |||||||
5587 | // If a class is incomplete, do not parse entities inside it. | ||||||
5588 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | ||||||
5589 | Diag(D.getIdentifierLoc(), | ||||||
5590 | diag::err_member_def_undefined_record) | ||||||
5591 | << Name << DC << D.getCXXScopeSpec().getRange(); | ||||||
5592 | return nullptr; | ||||||
5593 | } | ||||||
5594 | if (!D.getDeclSpec().isFriendSpecified()) { | ||||||
5595 | if (diagnoseQualifiedDeclaration( | ||||||
5596 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | ||||||
5597 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | ||||||
5598 | if (DC->isRecord()) | ||||||
5599 | return nullptr; | ||||||
5600 | |||||||
5601 | D.setInvalidType(); | ||||||
5602 | } | ||||||
5603 | } | ||||||
5604 | |||||||
5605 | // Check whether we need to rebuild the type of the given | ||||||
5606 | // declaration in the current instantiation. | ||||||
5607 | if (EnteringContext && IsDependentContext && | ||||||
5608 | TemplateParamLists.size() != 0) { | ||||||
5609 | ContextRAII SavedContext(*this, DC); | ||||||
5610 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | ||||||
5611 | D.setInvalidType(); | ||||||
5612 | } | ||||||
5613 | } | ||||||
5614 | |||||||
5615 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
5616 | QualType R = TInfo->getType(); | ||||||
5617 | |||||||
5618 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||||
5619 | UPPC_DeclarationType)) | ||||||
5620 | D.setInvalidType(); | ||||||
5621 | |||||||
5622 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||||
5623 | forRedeclarationInCurContext()); | ||||||
5624 | |||||||
5625 | // See if this is a redefinition of a variable in the same scope. | ||||||
5626 | if (!D.getCXXScopeSpec().isSet()) { | ||||||
5627 | bool IsLinkageLookup = false; | ||||||
5628 | bool CreateBuiltins = false; | ||||||
5629 | |||||||
5630 | // If the declaration we're planning to build will be a function | ||||||
5631 | // or object with linkage, then look for another declaration with | ||||||
5632 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | ||||||
5633 | // | ||||||
5634 | // If the declaration we're planning to build will be declared with | ||||||
5635 | // external linkage in the translation unit, create any builtin with | ||||||
5636 | // the same name. | ||||||
5637 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||||
5638 | /* Do nothing*/; | ||||||
5639 | else if (CurContext->isFunctionOrMethod() && | ||||||
5640 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | ||||||
5641 | R->isFunctionType())) { | ||||||
5642 | IsLinkageLookup = true; | ||||||
5643 | CreateBuiltins = | ||||||
5644 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | ||||||
5645 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | ||||||
5646 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | ||||||
5647 | CreateBuiltins = true; | ||||||
5648 | |||||||
5649 | if (IsLinkageLookup) { | ||||||
5650 | Previous.clear(LookupRedeclarationWithLinkage); | ||||||
5651 | Previous.setRedeclarationKind(ForExternalRedeclaration); | ||||||
5652 | } | ||||||
5653 | |||||||
5654 | LookupName(Previous, S, CreateBuiltins); | ||||||
5655 | } else { // Something like "int foo::x;" | ||||||
5656 | LookupQualifiedName(Previous, DC); | ||||||
5657 | |||||||
5658 | // C++ [dcl.meaning]p1: | ||||||
5659 | // When the declarator-id is qualified, the declaration shall refer to a | ||||||
5660 | // previously declared member of the class or namespace to which the | ||||||
5661 | // qualifier refers (or, in the case of a namespace, of an element of the | ||||||
5662 | // inline namespace set of that namespace (7.3.1)) or to a specialization | ||||||
5663 | // thereof; [...] | ||||||
5664 | // | ||||||
5665 | // Note that we already checked the context above, and that we do not have | ||||||
5666 | // enough information to make sure that Previous contains the declaration | ||||||
5667 | // we want to match. For example, given: | ||||||
5668 | // | ||||||
5669 | // class X { | ||||||
5670 | // void f(); | ||||||
5671 | // void f(float); | ||||||
5672 | // }; | ||||||
5673 | // | ||||||
5674 | // void X::f(int) { } // ill-formed | ||||||
5675 | // | ||||||
5676 | // In this case, Previous will point to the overload set | ||||||
5677 | // containing the two f's declared in X, but neither of them | ||||||
5678 | // matches. | ||||||
5679 | |||||||
5680 | // C++ [dcl.meaning]p1: | ||||||
5681 | // [...] the member shall not merely have been introduced by a | ||||||
5682 | // using-declaration in the scope of the class or namespace nominated by | ||||||
5683 | // the nested-name-specifier of the declarator-id. | ||||||
5684 | RemoveUsingDecls(Previous); | ||||||
5685 | } | ||||||
5686 | |||||||
5687 | if (Previous.isSingleResult() && | ||||||
5688 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||||
5689 | // Maybe we will complain about the shadowed template parameter. | ||||||
5690 | if (!D.isInvalidType()) | ||||||
5691 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | ||||||
5692 | Previous.getFoundDecl()); | ||||||
5693 | |||||||
5694 | // Just pretend that we didn't see the previous declaration. | ||||||
5695 | Previous.clear(); | ||||||
5696 | } | ||||||
5697 | |||||||
5698 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | ||||||
5699 | // Forget that the previous declaration is the injected-class-name. | ||||||
5700 | Previous.clear(); | ||||||
5701 | |||||||
5702 | // In C++, the previous declaration we find might be a tag type | ||||||
5703 | // (class or enum). In this case, the new declaration will hide the | ||||||
5704 | // tag type. Note that this applies to functions, function templates, and | ||||||
5705 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | ||||||
5706 | if (Previous.isSingleTagDecl() && | ||||||
5707 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | ||||||
5708 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | ||||||
5709 | Previous.clear(); | ||||||
5710 | |||||||
5711 | // Check that there are no default arguments other than in the parameters | ||||||
5712 | // of a function declaration (C++ only). | ||||||
5713 | if (getLangOpts().CPlusPlus) | ||||||
5714 | CheckExtraCXXDefaultArguments(D); | ||||||
5715 | |||||||
5716 | NamedDecl *New; | ||||||
5717 | |||||||
5718 | bool AddToScope = true; | ||||||
5719 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | ||||||
5720 | if (TemplateParamLists.size()) { | ||||||
5721 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | ||||||
5722 | return nullptr; | ||||||
5723 | } | ||||||
5724 | |||||||
5725 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | ||||||
5726 | } else if (R->isFunctionType()) { | ||||||
5727 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | ||||||
5728 | TemplateParamLists, | ||||||
5729 | AddToScope); | ||||||
5730 | } else { | ||||||
5731 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | ||||||
5732 | AddToScope); | ||||||
5733 | } | ||||||
5734 | |||||||
5735 | if (!New) | ||||||
5736 | return nullptr; | ||||||
5737 | |||||||
5738 | // If this has an identifier and is not a function template specialization, | ||||||
5739 | // add it to the scope stack. | ||||||
5740 | if (New->getDeclName() && AddToScope) | ||||||
5741 | PushOnScopeChains(New, S); | ||||||
5742 | |||||||
5743 | if (isInOpenMPDeclareTargetContext()) | ||||||
5744 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | ||||||
5745 | |||||||
5746 | return New; | ||||||
5747 | } | ||||||
5748 | |||||||
5749 | /// Helper method to turn variable array types into constant array | ||||||
5750 | /// types in certain situations which would otherwise be errors (for | ||||||
5751 | /// GCC compatibility). | ||||||
5752 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | ||||||
5753 | ASTContext &Context, | ||||||
5754 | bool &SizeIsNegative, | ||||||
5755 | llvm::APSInt &Oversized) { | ||||||
5756 | // This method tries to turn a variable array into a constant | ||||||
5757 | // array even when the size isn't an ICE. This is necessary | ||||||
5758 | // for compatibility with code that depends on gcc's buggy | ||||||
5759 | // constant expression folding, like struct {char x[(int)(char*)2];} | ||||||
5760 | SizeIsNegative = false; | ||||||
5761 | Oversized = 0; | ||||||
5762 | |||||||
5763 | if (T->isDependentType()) | ||||||
5764 | return QualType(); | ||||||
5765 | |||||||
5766 | QualifierCollector Qs; | ||||||
5767 | const Type *Ty = Qs.strip(T); | ||||||
5768 | |||||||
5769 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | ||||||
5770 | QualType Pointee = PTy->getPointeeType(); | ||||||
5771 | QualType FixedType = | ||||||
5772 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | ||||||
5773 | Oversized); | ||||||
5774 | if (FixedType.isNull()) return FixedType; | ||||||
5775 | FixedType = Context.getPointerType(FixedType); | ||||||
5776 | return Qs.apply(Context, FixedType); | ||||||
5777 | } | ||||||
5778 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | ||||||
5779 | QualType Inner = PTy->getInnerType(); | ||||||
5780 | QualType FixedType = | ||||||
5781 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | ||||||
5782 | Oversized); | ||||||
5783 | if (FixedType.isNull()) return FixedType; | ||||||
5784 | FixedType = Context.getParenType(FixedType); | ||||||
5785 | return Qs.apply(Context, FixedType); | ||||||
5786 | } | ||||||
5787 | |||||||
5788 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | ||||||
5789 | if (!VLATy) | ||||||
5790 | return QualType(); | ||||||
5791 | // FIXME: We should probably handle this case | ||||||
5792 | if (VLATy->getElementType()->isVariablyModifiedType()) | ||||||
5793 | return QualType(); | ||||||
5794 | |||||||
5795 | Expr::EvalResult Result; | ||||||
5796 | if (!VLATy->getSizeExpr() || | ||||||
5797 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | ||||||
5798 | return QualType(); | ||||||
5799 | |||||||
5800 | llvm::APSInt Res = Result.Val.getInt(); | ||||||
5801 | |||||||
5802 | // Check whether the array size is negative. | ||||||
5803 | if (Res.isSigned() && Res.isNegative()) { | ||||||
5804 | SizeIsNegative = true; | ||||||
5805 | return QualType(); | ||||||
5806 | } | ||||||
5807 | |||||||
5808 | // Check whether the array is too large to be addressed. | ||||||
5809 | unsigned ActiveSizeBits | ||||||
5810 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), | ||||||
5811 | Res); | ||||||
5812 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | ||||||
5813 | Oversized = Res; | ||||||
5814 | return QualType(); | ||||||
5815 | } | ||||||
5816 | |||||||
5817 | return Context.getConstantArrayType( | ||||||
5818 | VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); | ||||||
5819 | } | ||||||
5820 | |||||||
5821 | static void | ||||||
5822 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | ||||||
5823 | SrcTL = SrcTL.getUnqualifiedLoc(); | ||||||
5824 | DstTL = DstTL.getUnqualifiedLoc(); | ||||||
5825 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | ||||||
5826 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | ||||||
5827 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | ||||||
5828 | DstPTL.getPointeeLoc()); | ||||||
5829 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | ||||||
5830 | return; | ||||||
5831 | } | ||||||
5832 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | ||||||
5833 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | ||||||
5834 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | ||||||
5835 | DstPTL.getInnerLoc()); | ||||||
5836 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | ||||||
5837 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | ||||||
5838 | return; | ||||||
5839 | } | ||||||
5840 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | ||||||
5841 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | ||||||
5842 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | ||||||
5843 | TypeLoc DstElemTL = DstATL.getElementLoc(); | ||||||
5844 | DstElemTL.initializeFullCopy(SrcElemTL); | ||||||
5845 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | ||||||
5846 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | ||||||
5847 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | ||||||
5848 | } | ||||||
5849 | |||||||
5850 | /// Helper method to turn variable array types into constant array | ||||||
5851 | /// types in certain situations which would otherwise be errors (for | ||||||
5852 | /// GCC compatibility). | ||||||
5853 | static TypeSourceInfo* | ||||||
5854 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | ||||||
5855 | ASTContext &Context, | ||||||
5856 | bool &SizeIsNegative, | ||||||
5857 | llvm::APSInt &Oversized) { | ||||||
5858 | QualType FixedTy | ||||||
5859 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | ||||||
5860 | SizeIsNegative, Oversized); | ||||||
5861 | if (FixedTy.isNull()) | ||||||
5862 | return nullptr; | ||||||
5863 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | ||||||
5864 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | ||||||
5865 | FixedTInfo->getTypeLoc()); | ||||||
5866 | return FixedTInfo; | ||||||
5867 | } | ||||||
5868 | |||||||
5869 | /// Register the given locally-scoped extern "C" declaration so | ||||||
5870 | /// that it can be found later for redeclarations. We include any extern "C" | ||||||
5871 | /// declaration that is not visible in the translation unit here, not just | ||||||
5872 | /// function-scope declarations. | ||||||
5873 | void | ||||||
5874 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | ||||||
5875 | if (!getLangOpts().CPlusPlus && | ||||||
5876 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||||
5877 | // Don't need to track declarations in the TU in C. | ||||||
5878 | return; | ||||||
5879 | |||||||
5880 | // Note that we have a locally-scoped external with this name. | ||||||
5881 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | ||||||
5882 | } | ||||||
5883 | |||||||
5884 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | ||||||
5885 | // FIXME: We can have multiple results via __attribute__((overloadable)). | ||||||
5886 | auto Result = Context.getExternCContextDecl()->lookup(Name); | ||||||
5887 | return Result.empty() ? nullptr : *Result.begin(); | ||||||
5888 | } | ||||||
5889 | |||||||
5890 | /// Diagnose function specifiers on a declaration of an identifier that | ||||||
5891 | /// does not identify a function. | ||||||
5892 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | ||||||
5893 | // FIXME: We should probably indicate the identifier in question to avoid | ||||||
5894 | // confusion for constructs like "virtual int a(), b;" | ||||||
5895 | if (DS.isVirtualSpecified()) | ||||||
5896 | Diag(DS.getVirtualSpecLoc(), | ||||||
5897 | diag::err_virtual_non_function); | ||||||
5898 | |||||||
5899 | if (DS.hasExplicitSpecifier()) | ||||||
5900 | Diag(DS.getExplicitSpecLoc(), | ||||||
5901 | diag::err_explicit_non_function); | ||||||
5902 | |||||||
5903 | if (DS.isNoreturnSpecified()) | ||||||
5904 | Diag(DS.getNoreturnSpecLoc(), | ||||||
5905 | diag::err_noreturn_non_function); | ||||||
5906 | } | ||||||
5907 | |||||||
5908 | NamedDecl* | ||||||
5909 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | ||||||
5910 | TypeSourceInfo *TInfo, LookupResult &Previous) { | ||||||
5911 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||||
5912 | if (D.getCXXScopeSpec().isSet()) { | ||||||
5913 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | ||||||
5914 | << D.getCXXScopeSpec().getRange(); | ||||||
5915 | D.setInvalidType(); | ||||||
5916 | // Pretend we didn't see the scope specifier. | ||||||
5917 | DC = CurContext; | ||||||
5918 | Previous.clear(); | ||||||
5919 | } | ||||||
5920 | |||||||
5921 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
5922 | |||||||
5923 | if (D.getDeclSpec().isInlineSpecified()) | ||||||
5924 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
5925 | << getLangOpts().CPlusPlus17; | ||||||
5926 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||||
5927 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||||
5928 | << 1 << D.getDeclSpec().getConstexprSpecifier(); | ||||||
5929 | |||||||
5930 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | ||||||
5931 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | ||||||
5932 | Diag(D.getName().StartLocation, | ||||||
5933 | diag::err_deduction_guide_invalid_specifier) | ||||||
5934 | << "typedef"; | ||||||
5935 | else | ||||||
5936 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | ||||||
5937 | << D.getName().getSourceRange(); | ||||||
5938 | return nullptr; | ||||||
5939 | } | ||||||
5940 | |||||||
5941 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | ||||||
5942 | if (!NewTD) return nullptr; | ||||||
5943 | |||||||
5944 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||||
5945 | ProcessDeclAttributes(S, NewTD, D); | ||||||
5946 | |||||||
5947 | CheckTypedefForVariablyModifiedType(S, NewTD); | ||||||
5948 | |||||||
5949 | bool Redeclaration = D.isRedeclaration(); | ||||||
5950 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | ||||||
5951 | D.setRedeclaration(Redeclaration); | ||||||
5952 | return ND; | ||||||
5953 | } | ||||||
5954 | |||||||
5955 | void | ||||||
5956 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | ||||||
5957 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | ||||||
5958 | // then it shall have block scope. | ||||||
5959 | // Note that variably modified types must be fixed before merging the decl so | ||||||
5960 | // that redeclarations will match. | ||||||
5961 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | ||||||
5962 | QualType T = TInfo->getType(); | ||||||
5963 | if (T->isVariablyModifiedType()) { | ||||||
5964 | setFunctionHasBranchProtectedScope(); | ||||||
5965 | |||||||
5966 | if (S->getFnParent() == nullptr) { | ||||||
5967 | bool SizeIsNegative; | ||||||
5968 | llvm::APSInt Oversized; | ||||||
5969 | TypeSourceInfo *FixedTInfo = | ||||||
5970 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||||
5971 | SizeIsNegative, | ||||||
5972 | Oversized); | ||||||
5973 | if (FixedTInfo) { | ||||||
5974 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); | ||||||
5975 | NewTD->setTypeSourceInfo(FixedTInfo); | ||||||
5976 | } else { | ||||||
5977 | if (SizeIsNegative) | ||||||
5978 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | ||||||
5979 | else if (T->isVariableArrayType()) | ||||||
5980 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | ||||||
5981 | else if (Oversized.getBoolValue()) | ||||||
5982 | Diag(NewTD->getLocation(), diag::err_array_too_large) | ||||||
5983 | << Oversized.toString(10); | ||||||
5984 | else | ||||||
5985 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||||
5986 | NewTD->setInvalidDecl(); | ||||||
5987 | } | ||||||
5988 | } | ||||||
5989 | } | ||||||
5990 | } | ||||||
5991 | |||||||
5992 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | ||||||
5993 | /// declares a typedef-name, either using the 'typedef' type specifier or via | ||||||
5994 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | ||||||
5995 | NamedDecl* | ||||||
5996 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | ||||||
5997 | LookupResult &Previous, bool &Redeclaration) { | ||||||
5998 | |||||||
5999 | // Find the shadowed declaration before filtering for scope. | ||||||
6000 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | ||||||
6001 | |||||||
6002 | // Merge the decl with the existing one if appropriate. If the decl is | ||||||
6003 | // in an outer scope, it isn't the same thing. | ||||||
6004 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | ||||||
6005 | /*AllowInlineNamespace*/false); | ||||||
6006 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | ||||||
6007 | if (!Previous.empty()) { | ||||||
6008 | Redeclaration = true; | ||||||
6009 | MergeTypedefNameDecl(S, NewTD, Previous); | ||||||
6010 | } else { | ||||||
6011 | inferGslPointerAttribute(NewTD); | ||||||
6012 | } | ||||||
6013 | |||||||
6014 | if (ShadowedDecl && !Redeclaration) | ||||||
6015 | CheckShadow(NewTD, ShadowedDecl, Previous); | ||||||
6016 | |||||||
6017 | // If this is the C FILE type, notify the AST context. | ||||||
6018 | if (IdentifierInfo *II = NewTD->getIdentifier()) | ||||||
6019 | if (!NewTD->isInvalidDecl() && | ||||||
6020 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
6021 | if (II->isStr("FILE")) | ||||||
6022 | Context.setFILEDecl(NewTD); | ||||||
6023 | else if (II->isStr("jmp_buf")) | ||||||
6024 | Context.setjmp_bufDecl(NewTD); | ||||||
6025 | else if (II->isStr("sigjmp_buf")) | ||||||
6026 | Context.setsigjmp_bufDecl(NewTD); | ||||||
6027 | else if (II->isStr("ucontext_t")) | ||||||
6028 | Context.setucontext_tDecl(NewTD); | ||||||
6029 | } | ||||||
6030 | |||||||
6031 | return NewTD; | ||||||
6032 | } | ||||||
6033 | |||||||
6034 | /// Determines whether the given declaration is an out-of-scope | ||||||
6035 | /// previous declaration. | ||||||
6036 | /// | ||||||
6037 | /// This routine should be invoked when name lookup has found a | ||||||
6038 | /// previous declaration (PrevDecl) that is not in the scope where a | ||||||
6039 | /// new declaration by the same name is being introduced. If the new | ||||||
6040 | /// declaration occurs in a local scope, previous declarations with | ||||||
6041 | /// linkage may still be considered previous declarations (C99 | ||||||
6042 | /// 6.2.2p4-5, C++ [basic.link]p6). | ||||||
6043 | /// | ||||||
6044 | /// \param PrevDecl the previous declaration found by name | ||||||
6045 | /// lookup | ||||||
6046 | /// | ||||||
6047 | /// \param DC the context in which the new declaration is being | ||||||
6048 | /// declared. | ||||||
6049 | /// | ||||||
6050 | /// \returns true if PrevDecl is an out-of-scope previous declaration | ||||||
6051 | /// for a new delcaration with the same name. | ||||||
6052 | static bool | ||||||
6053 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | ||||||
6054 | ASTContext &Context) { | ||||||
6055 | if (!PrevDecl) | ||||||
6056 | return false; | ||||||
6057 | |||||||
6058 | if (!PrevDecl->hasLinkage()) | ||||||
6059 | return false; | ||||||
6060 | |||||||
6061 | if (Context.getLangOpts().CPlusPlus) { | ||||||
6062 | // C++ [basic.link]p6: | ||||||
6063 | // If there is a visible declaration of an entity with linkage | ||||||
6064 | // having the same name and type, ignoring entities declared | ||||||
6065 | // outside the innermost enclosing namespace scope, the block | ||||||
6066 | // scope declaration declares that same entity and receives the | ||||||
6067 | // linkage of the previous declaration. | ||||||
6068 | DeclContext *OuterContext = DC->getRedeclContext(); | ||||||
6069 | if (!OuterContext->isFunctionOrMethod()) | ||||||
6070 | // This rule only applies to block-scope declarations. | ||||||
6071 | return false; | ||||||
6072 | |||||||
6073 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | ||||||
6074 | if (PrevOuterContext->isRecord()) | ||||||
6075 | // We found a member function: ignore it. | ||||||
6076 | return false; | ||||||
6077 | |||||||
6078 | // Find the innermost enclosing namespace for the new and | ||||||
6079 | // previous declarations. | ||||||
6080 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | ||||||
6081 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | ||||||
6082 | |||||||
6083 | // The previous declaration is in a different namespace, so it | ||||||
6084 | // isn't the same function. | ||||||
6085 | if (!OuterContext->Equals(PrevOuterContext)) | ||||||
6086 | return false; | ||||||
6087 | } | ||||||
6088 | |||||||
6089 | return true; | ||||||
6090 | } | ||||||
6091 | |||||||
6092 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | ||||||
6093 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||||
6094 | if (!SS.isSet()) return; | ||||||
6095 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | ||||||
6096 | } | ||||||
6097 | |||||||
6098 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | ||||||
6099 | QualType type = decl->getType(); | ||||||
6100 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | ||||||
6101 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | ||||||
6102 | // Various kinds of declaration aren't allowed to be __autoreleasing. | ||||||
6103 | unsigned kind = -1U; | ||||||
6104 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||||
6105 | if (var->hasAttr<BlocksAttr>()) | ||||||
6106 | kind = 0; // __block | ||||||
6107 | else if (!var->hasLocalStorage()) | ||||||
6108 | kind = 1; // global | ||||||
6109 | } else if (isa<ObjCIvarDecl>(decl)) { | ||||||
6110 | kind = 3; // ivar | ||||||
6111 | } else if (isa<FieldDecl>(decl)) { | ||||||
6112 | kind = 2; // field | ||||||
6113 | } | ||||||
6114 | |||||||
6115 | if (kind != -1U) { | ||||||
6116 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | ||||||
6117 | << kind; | ||||||
6118 | } | ||||||
6119 | } else if (lifetime == Qualifiers::OCL_None) { | ||||||
6120 | // Try to infer lifetime. | ||||||
6121 | if (!type->isObjCLifetimeType()) | ||||||
6122 | return false; | ||||||
6123 | |||||||
6124 | lifetime = type->getObjCARCImplicitLifetime(); | ||||||
6125 | type = Context.getLifetimeQualifiedType(type, lifetime); | ||||||
6126 | decl->setType(type); | ||||||
6127 | } | ||||||
6128 | |||||||
6129 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||||
6130 | // Thread-local variables cannot have lifetime. | ||||||
6131 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | ||||||
6132 | var->getTLSKind()) { | ||||||
6133 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | ||||||
6134 | << var->getType(); | ||||||
6135 | return true; | ||||||
6136 | } | ||||||
6137 | } | ||||||
6138 | |||||||
6139 | return false; | ||||||
6140 | } | ||||||
6141 | |||||||
6142 | void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { | ||||||
6143 | if (Decl->getType().hasAddressSpace()) | ||||||
6144 | return; | ||||||
6145 | if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { | ||||||
6146 | QualType Type = Var->getType(); | ||||||
6147 | if (Type->isSamplerT() || Type->isVoidType()) | ||||||
6148 | return; | ||||||
6149 | LangAS ImplAS = LangAS::opencl_private; | ||||||
6150 | if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && | ||||||
6151 | Var->hasGlobalStorage()) | ||||||
6152 | ImplAS = LangAS::opencl_global; | ||||||
6153 | // If the original type from a decayed type is an array type and that array | ||||||
6154 | // type has no address space yet, deduce it now. | ||||||
6155 | if (auto DT = dyn_cast<DecayedType>(Type)) { | ||||||
6156 | auto OrigTy = DT->getOriginalType(); | ||||||
6157 | if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { | ||||||
6158 | // Add the address space to the original array type and then propagate | ||||||
6159 | // that to the element type through `getAsArrayType`. | ||||||
6160 | OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); | ||||||
6161 | OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); | ||||||
6162 | // Re-generate the decayed type. | ||||||
6163 | Type = Context.getDecayedType(OrigTy); | ||||||
6164 | } | ||||||
6165 | } | ||||||
6166 | Type = Context.getAddrSpaceQualType(Type, ImplAS); | ||||||
6167 | // Apply any qualifiers (including address space) from the array type to | ||||||
6168 | // the element type. This implements C99 6.7.3p8: "If the specification of | ||||||
6169 | // an array type includes any type qualifiers, the element type is so | ||||||
6170 | // qualified, not the array type." | ||||||
6171 | if (Type->isArrayType()) | ||||||
6172 | Type = QualType(Context.getAsArrayType(Type), 0); | ||||||
6173 | Decl->setType(Type); | ||||||
6174 | } | ||||||
6175 | } | ||||||
6176 | |||||||
6177 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | ||||||
6178 | // Ensure that an auto decl is deduced otherwise the checks below might cache | ||||||
6179 | // the wrong linkage. | ||||||
6180 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast <void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6180, __PRETTY_FUNCTION__)); | ||||||
6181 | |||||||
6182 | // 'weak' only applies to declarations with external linkage. | ||||||
6183 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | ||||||
6184 | if (!ND.isExternallyVisible()) { | ||||||
6185 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | ||||||
6186 | ND.dropAttr<WeakAttr>(); | ||||||
6187 | } | ||||||
6188 | } | ||||||
6189 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | ||||||
6190 | if (ND.isExternallyVisible()) { | ||||||
6191 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | ||||||
6192 | ND.dropAttr<WeakRefAttr>(); | ||||||
6193 | ND.dropAttr<AliasAttr>(); | ||||||
6194 | } | ||||||
6195 | } | ||||||
6196 | |||||||
6197 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | ||||||
6198 | if (VD->hasInit()) { | ||||||
6199 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | ||||||
6200 | assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6201, __PRETTY_FUNCTION__)) | ||||||
6201 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6201, __PRETTY_FUNCTION__)); | ||||||
6202 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | ||||||
6203 | VD->dropAttr<AliasAttr>(); | ||||||
6204 | } | ||||||
6205 | } | ||||||
6206 | } | ||||||
6207 | |||||||
6208 | // 'selectany' only applies to externally visible variable declarations. | ||||||
6209 | // It does not apply to functions. | ||||||
6210 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | ||||||
6211 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | ||||||
6212 | S.Diag(Attr->getLocation(), | ||||||
6213 | diag::err_attribute_selectany_non_extern_data); | ||||||
6214 | ND.dropAttr<SelectAnyAttr>(); | ||||||
6215 | } | ||||||
6216 | } | ||||||
6217 | |||||||
6218 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | ||||||
6219 | auto *VD = dyn_cast<VarDecl>(&ND); | ||||||
6220 | bool IsAnonymousNS = false; | ||||||
6221 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||||
6222 | if (VD) { | ||||||
6223 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | ||||||
6224 | while (NS && !IsAnonymousNS) { | ||||||
6225 | IsAnonymousNS = NS->isAnonymousNamespace(); | ||||||
6226 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | ||||||
6227 | } | ||||||
6228 | } | ||||||
6229 | // dll attributes require external linkage. Static locals may have external | ||||||
6230 | // linkage but still cannot be explicitly imported or exported. | ||||||
6231 | // In Microsoft mode, a variable defined in anonymous namespace must have | ||||||
6232 | // external linkage in order to be exported. | ||||||
6233 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | ||||||
6234 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | ||||||
6235 | (!AnonNSInMicrosoftMode && | ||||||
6236 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | ||||||
6237 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | ||||||
6238 | << &ND << Attr; | ||||||
6239 | ND.setInvalidDecl(); | ||||||
6240 | } | ||||||
6241 | } | ||||||
6242 | |||||||
6243 | // Virtual functions cannot be marked as 'notail'. | ||||||
6244 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) | ||||||
6245 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) | ||||||
6246 | if (MD->isVirtual()) { | ||||||
6247 | S.Diag(ND.getLocation(), | ||||||
6248 | diag::err_invalid_attribute_on_virtual_function) | ||||||
6249 | << Attr; | ||||||
6250 | ND.dropAttr<NotTailCalledAttr>(); | ||||||
6251 | } | ||||||
6252 | |||||||
6253 | // Check the attributes on the function type, if any. | ||||||
6254 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | ||||||
6255 | // Don't declare this variable in the second operand of the for-statement; | ||||||
6256 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||||
6257 | // third operand. See gcc.gnu.org/PR86769. | ||||||
6258 | AttributedTypeLoc ATL; | ||||||
6259 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | ||||||
6260 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||||
6261 | TL = ATL.getModifiedLoc()) { | ||||||
6262 | // The [[lifetimebound]] attribute can be applied to the implicit object | ||||||
6263 | // parameter of a non-static member function (other than a ctor or dtor) | ||||||
6264 | // by applying it to the function type. | ||||||
6265 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | ||||||
6266 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
6267 | if (!MD || MD->isStatic()) { | ||||||
6268 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | ||||||
6269 | << !MD << A->getRange(); | ||||||
6270 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | ||||||
6271 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | ||||||
6272 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | ||||||
6273 | } | ||||||
6274 | } | ||||||
6275 | } | ||||||
6276 | } | ||||||
6277 | } | ||||||
6278 | |||||||
6279 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | ||||||
6280 | NamedDecl *NewDecl, | ||||||
6281 | bool IsSpecialization, | ||||||
6282 | bool IsDefinition) { | ||||||
6283 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | ||||||
6284 | return; | ||||||
6285 | |||||||
6286 | bool IsTemplate = false; | ||||||
6287 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | ||||||
6288 | OldDecl = OldTD->getTemplatedDecl(); | ||||||
6289 | IsTemplate = true; | ||||||
6290 | if (!IsSpecialization) | ||||||
6291 | IsDefinition = false; | ||||||
6292 | } | ||||||
6293 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | ||||||
6294 | NewDecl = NewTD->getTemplatedDecl(); | ||||||
6295 | IsTemplate = true; | ||||||
6296 | } | ||||||
6297 | |||||||
6298 | if (!OldDecl || !NewDecl) | ||||||
6299 | return; | ||||||
6300 | |||||||
6301 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | ||||||
6302 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | ||||||
6303 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | ||||||
6304 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | ||||||
6305 | |||||||
6306 | // dllimport and dllexport are inheritable attributes so we have to exclude | ||||||
6307 | // inherited attribute instances. | ||||||
6308 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | ||||||
6309 | (NewExportAttr && !NewExportAttr->isInherited()); | ||||||
6310 | |||||||
6311 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | ||||||
6312 | // the only exception being explicit specializations. | ||||||
6313 | // Implicitly generated declarations are also excluded for now because there | ||||||
6314 | // is no other way to switch these to use dllimport or dllexport. | ||||||
6315 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | ||||||
6316 | |||||||
6317 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | ||||||
6318 | // Allow with a warning for free functions and global variables. | ||||||
6319 | bool JustWarn = false; | ||||||
6320 | if (!OldDecl->isCXXClassMember()) { | ||||||
6321 | auto *VD = dyn_cast<VarDecl>(OldDecl); | ||||||
6322 | if (VD && !VD->getDescribedVarTemplate()) | ||||||
6323 | JustWarn = true; | ||||||
6324 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | ||||||
6325 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | ||||||
6326 | JustWarn = true; | ||||||
6327 | } | ||||||
6328 | |||||||
6329 | // We cannot change a declaration that's been used because IR has already | ||||||
6330 | // been emitted. Dllimported functions will still work though (modulo | ||||||
6331 | // address equality) as they can use the thunk. | ||||||
6332 | if (OldDecl->isUsed()) | ||||||
6333 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | ||||||
6334 | JustWarn = false; | ||||||
6335 | |||||||
6336 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | ||||||
6337 | : diag::err_attribute_dll_redeclaration; | ||||||
6338 | S.Diag(NewDecl->getLocation(), DiagID) | ||||||
6339 | << NewDecl | ||||||
6340 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | ||||||
6341 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6342 | if (!JustWarn) { | ||||||
6343 | NewDecl->setInvalidDecl(); | ||||||
6344 | return; | ||||||
6345 | } | ||||||
6346 | } | ||||||
6347 | |||||||
6348 | // A redeclaration is not allowed to drop a dllimport attribute, the only | ||||||
6349 | // exceptions being inline function definitions (except for function | ||||||
6350 | // templates), local extern declarations, qualified friend declarations or | ||||||
6351 | // special MSVC extension: in the last case, the declaration is treated as if | ||||||
6352 | // it were marked dllexport. | ||||||
6353 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | ||||||
6354 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||||
6355 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | ||||||
6356 | // Ignore static data because out-of-line definitions are diagnosed | ||||||
6357 | // separately. | ||||||
6358 | IsStaticDataMember = VD->isStaticDataMember(); | ||||||
6359 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | ||||||
6360 | VarDecl::DeclarationOnly; | ||||||
6361 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | ||||||
6362 | IsInline = FD->isInlined(); | ||||||
6363 | IsQualifiedFriend = FD->getQualifier() && | ||||||
6364 | FD->getFriendObjectKind() == Decl::FOK_Declared; | ||||||
6365 | } | ||||||
6366 | |||||||
6367 | if (OldImportAttr && !HasNewAttr && | ||||||
6368 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && | ||||||
6369 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | ||||||
6370 | if (IsMicrosoft && IsDefinition) { | ||||||
6371 | S.Diag(NewDecl->getLocation(), | ||||||
6372 | diag::warn_redeclaration_without_import_attribute) | ||||||
6373 | << NewDecl; | ||||||
6374 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6375 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6376 | NewDecl->addAttr( | ||||||
6377 | DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); | ||||||
6378 | } else { | ||||||
6379 | S.Diag(NewDecl->getLocation(), | ||||||
6380 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | ||||||
6381 | << NewDecl << OldImportAttr; | ||||||
6382 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6383 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | ||||||
6384 | OldDecl->dropAttr<DLLImportAttr>(); | ||||||
6385 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6386 | } | ||||||
6387 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { | ||||||
6388 | // In MinGW, seeing a function declared inline drops the dllimport | ||||||
6389 | // attribute. | ||||||
6390 | OldDecl->dropAttr<DLLImportAttr>(); | ||||||
6391 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6392 | S.Diag(NewDecl->getLocation(), | ||||||
6393 | diag::warn_dllimport_dropped_from_inline_function) | ||||||
6394 | << NewDecl << OldImportAttr; | ||||||
6395 | } | ||||||
6396 | |||||||
6397 | // A specialization of a class template member function is processed here | ||||||
6398 | // since it's a redeclaration. If the parent class is dllexport, the | ||||||
6399 | // specialization inherits that attribute. This doesn't happen automatically | ||||||
6400 | // since the parent class isn't instantiated until later. | ||||||
6401 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | ||||||
6402 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | ||||||
6403 | !NewImportAttr && !NewExportAttr) { | ||||||
6404 | if (const DLLExportAttr *ParentExportAttr = | ||||||
6405 | MD->getParent()->getAttr<DLLExportAttr>()) { | ||||||
6406 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | ||||||
6407 | NewAttr->setInherited(true); | ||||||
6408 | NewDecl->addAttr(NewAttr); | ||||||
6409 | } | ||||||
6410 | } | ||||||
6411 | } | ||||||
6412 | } | ||||||
6413 | |||||||
6414 | /// Given that we are within the definition of the given function, | ||||||
6415 | /// will that definition behave like C99's 'inline', where the | ||||||
6416 | /// definition is discarded except for optimization purposes? | ||||||
6417 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | ||||||
6418 | // Try to avoid calling GetGVALinkageForFunction. | ||||||
6419 | |||||||
6420 | // All cases of this require the 'inline' keyword. | ||||||
6421 | if (!FD->isInlined()) return false; | ||||||
6422 | |||||||
6423 | // This is only possible in C++ with the gnu_inline attribute. | ||||||
6424 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | ||||||
6425 | return false; | ||||||
6426 | |||||||
6427 | // Okay, go ahead and call the relatively-more-expensive function. | ||||||
6428 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | ||||||
6429 | } | ||||||
6430 | |||||||
6431 | /// Determine whether a variable is extern "C" prior to attaching | ||||||
6432 | /// an initializer. We can't just call isExternC() here, because that | ||||||
6433 | /// will also compute and cache whether the declaration is externally | ||||||
6434 | /// visible, which might change when we attach the initializer. | ||||||
6435 | /// | ||||||
6436 | /// This can only be used if the declaration is known to not be a | ||||||
6437 | /// redeclaration of an internal linkage declaration. | ||||||
6438 | /// | ||||||
6439 | /// For instance: | ||||||
6440 | /// | ||||||
6441 | /// auto x = []{}; | ||||||
6442 | /// | ||||||
6443 | /// Attaching the initializer here makes this declaration not externally | ||||||
6444 | /// visible, because its type has internal linkage. | ||||||
6445 | /// | ||||||
6446 | /// FIXME: This is a hack. | ||||||
6447 | template<typename T> | ||||||
6448 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | ||||||
6449 | if (S.getLangOpts().CPlusPlus) { | ||||||
6450 | // In C++, the overloadable attribute negates the effects of extern "C". | ||||||
6451 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | ||||||
6452 | return false; | ||||||
6453 | |||||||
6454 | // So do CUDA's host/device attributes. | ||||||
6455 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | ||||||
6456 | D->template hasAttr<CUDAHostAttr>())) | ||||||
6457 | return false; | ||||||
6458 | } | ||||||
6459 | return D->isExternC(); | ||||||
6460 | } | ||||||
6461 | |||||||
6462 | static bool shouldConsiderLinkage(const VarDecl *VD) { | ||||||
6463 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | ||||||
6464 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | ||||||
6465 | isa<OMPDeclareMapperDecl>(DC)) | ||||||
6466 | return VD->hasExternalStorage(); | ||||||
6467 | if (DC->isFileContext()) | ||||||
6468 | return true; | ||||||
6469 | if (DC->isRecord()) | ||||||
6470 | return false; | ||||||
6471 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6471); | ||||||
6472 | } | ||||||
6473 | |||||||
6474 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | ||||||
6475 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | ||||||
6476 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | ||||||
6477 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | ||||||
6478 | return true; | ||||||
6479 | if (DC->isRecord()) | ||||||
6480 | return false; | ||||||
6481 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6481); | ||||||
6482 | } | ||||||
6483 | |||||||
6484 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | ||||||
6485 | ParsedAttr::Kind Kind) { | ||||||
6486 | // Check decl attributes on the DeclSpec. | ||||||
6487 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | ||||||
6488 | return true; | ||||||
6489 | |||||||
6490 | // Walk the declarator structure, checking decl attributes that were in a type | ||||||
6491 | // position to the decl itself. | ||||||
6492 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | ||||||
6493 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | ||||||
6494 | return true; | ||||||
6495 | } | ||||||
6496 | |||||||
6497 | // Finally, check attributes on the decl itself. | ||||||
6498 | return PD.getAttributes().hasAttribute(Kind); | ||||||
6499 | } | ||||||
6500 | |||||||
6501 | /// Adjust the \c DeclContext for a function or variable that might be a | ||||||
6502 | /// function-local external declaration. | ||||||
6503 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | ||||||
6504 | if (!DC->isFunctionOrMethod()) | ||||||
6505 | return false; | ||||||
6506 | |||||||
6507 | // If this is a local extern function or variable declared within a function | ||||||
6508 | // template, don't add it into the enclosing namespace scope until it is | ||||||
6509 | // instantiated; it might have a dependent type right now. | ||||||
6510 | if (DC->isDependentContext()) | ||||||
6511 | return true; | ||||||
6512 | |||||||
6513 | // C++11 [basic.link]p7: | ||||||
6514 | // When a block scope declaration of an entity with linkage is not found to | ||||||
6515 | // refer to some other declaration, then that entity is a member of the | ||||||
6516 | // innermost enclosing namespace. | ||||||
6517 | // | ||||||
6518 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | ||||||
6519 | // semantically-enclosing namespace, not a lexically-enclosing one. | ||||||
6520 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | ||||||
6521 | DC = DC->getParent(); | ||||||
6522 | return true; | ||||||
6523 | } | ||||||
6524 | |||||||
6525 | /// Returns true if given declaration has external C language linkage. | ||||||
6526 | static bool isDeclExternC(const Decl *D) { | ||||||
6527 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | ||||||
6528 | return FD->isExternC(); | ||||||
6529 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||||
6530 | return VD->isExternC(); | ||||||
6531 | |||||||
6532 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6532); | ||||||
6533 | } | ||||||
6534 | /// Returns true if there hasn't been any invalid type diagnosed. | ||||||
6535 | static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, | ||||||
6536 | DeclContext *DC, QualType R) { | ||||||
6537 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | ||||||
6538 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | ||||||
6539 | // argument. | ||||||
6540 | if (R->isImageType() || R->isPipeType()) { | ||||||
6541 | Se.Diag(D.getIdentifierLoc(), | ||||||
6542 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | ||||||
6543 | << R; | ||||||
6544 | D.setInvalidType(); | ||||||
6545 | return false; | ||||||
6546 | } | ||||||
6547 | |||||||
6548 | // OpenCL v1.2 s6.9.r: | ||||||
6549 | // The event type cannot be used to declare a program scope variable. | ||||||
6550 | // OpenCL v2.0 s6.9.q: | ||||||
6551 | // The clk_event_t and reserve_id_t types cannot be declared in program | ||||||
6552 | // scope. | ||||||
6553 | if (NULL__null == S->getParent()) { | ||||||
6554 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | ||||||
6555 | Se.Diag(D.getIdentifierLoc(), | ||||||
6556 | diag::err_invalid_type_for_program_scope_var) | ||||||
6557 | << R; | ||||||
6558 | D.setInvalidType(); | ||||||
6559 | return false; | ||||||
6560 | } | ||||||
6561 | } | ||||||
6562 | |||||||
6563 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | ||||||
6564 | QualType NR = R; | ||||||
6565 | while (NR->isPointerType()) { | ||||||
6566 | if (NR->isFunctionPointerType()) { | ||||||
6567 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); | ||||||
6568 | D.setInvalidType(); | ||||||
6569 | return false; | ||||||
6570 | } | ||||||
6571 | NR = NR->getPointeeType(); | ||||||
6572 | } | ||||||
6573 | |||||||
6574 | if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | ||||||
6575 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | ||||||
6576 | // half array type (unless the cl_khr_fp16 extension is enabled). | ||||||
6577 | if (Se.Context.getBaseElementType(R)->isHalfType()) { | ||||||
6578 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; | ||||||
6579 | D.setInvalidType(); | ||||||
6580 | return false; | ||||||
6581 | } | ||||||
6582 | } | ||||||
6583 | |||||||
6584 | // OpenCL v1.2 s6.9.r: | ||||||
6585 | // The event type cannot be used with the __local, __constant and __global | ||||||
6586 | // address space qualifiers. | ||||||
6587 | if (R->isEventT()) { | ||||||
6588 | if (R.getAddressSpace() != LangAS::opencl_private) { | ||||||
6589 | Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); | ||||||
6590 | D.setInvalidType(); | ||||||
6591 | return false; | ||||||
6592 | } | ||||||
6593 | } | ||||||
6594 | |||||||
6595 | // C++ for OpenCL does not allow the thread_local storage qualifier. | ||||||
6596 | // OpenCL C does not support thread_local either, and | ||||||
6597 | // also reject all other thread storage class specifiers. | ||||||
6598 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | ||||||
6599 | if (TSC != TSCS_unspecified) { | ||||||
6600 | bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; | ||||||
6601 | Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6602 | diag::err_opencl_unknown_type_specifier) | ||||||
6603 | << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() | ||||||
6604 | << DeclSpec::getSpecifierName(TSC) << 1; | ||||||
6605 | D.setInvalidType(); | ||||||
6606 | return false; | ||||||
6607 | } | ||||||
6608 | |||||||
6609 | if (R->isSamplerT()) { | ||||||
6610 | // OpenCL v1.2 s6.9.b p4: | ||||||
6611 | // The sampler type cannot be used with the __local and __global address | ||||||
6612 | // space qualifiers. | ||||||
6613 | if (R.getAddressSpace() == LangAS::opencl_local || | ||||||
6614 | R.getAddressSpace() == LangAS::opencl_global) { | ||||||
6615 | Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); | ||||||
6616 | D.setInvalidType(); | ||||||
6617 | } | ||||||
6618 | |||||||
6619 | // OpenCL v1.2 s6.12.14.1: | ||||||
6620 | // A global sampler must be declared with either the constant address | ||||||
6621 | // space qualifier or with the const qualifier. | ||||||
6622 | if (DC->isTranslationUnit() && | ||||||
6623 | !(R.getAddressSpace() == LangAS::opencl_constant || | ||||||
6624 | R.isConstQualified())) { | ||||||
6625 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); | ||||||
6626 | D.setInvalidType(); | ||||||
6627 | } | ||||||
6628 | if (D.isInvalidType()) | ||||||
6629 | return false; | ||||||
6630 | } | ||||||
6631 | return true; | ||||||
6632 | } | ||||||
6633 | |||||||
6634 | NamedDecl *Sema::ActOnVariableDeclarator( | ||||||
6635 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | ||||||
6636 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | ||||||
6637 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | ||||||
6638 | QualType R = TInfo->getType(); | ||||||
6639 | DeclarationName Name = GetNameForDeclarator(D).getName(); | ||||||
6640 | |||||||
6641 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||
6642 | |||||||
6643 | if (D.isDecompositionDeclarator()) { | ||||||
6644 | // Take the name of the first declarator as our name for diagnostic | ||||||
6645 | // purposes. | ||||||
6646 | auto &Decomp = D.getDecompositionDeclarator(); | ||||||
6647 | if (!Decomp.bindings().empty()) { | ||||||
6648 | II = Decomp.bindings()[0].Name; | ||||||
6649 | Name = II; | ||||||
6650 | } | ||||||
6651 | } else if (!II) { | ||||||
6652 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | ||||||
6653 | return nullptr; | ||||||
6654 | } | ||||||
6655 | |||||||
6656 | |||||||
6657 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | ||||||
6658 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | ||||||
6659 | |||||||
6660 | // dllimport globals without explicit storage class are treated as extern. We | ||||||
6661 | // have to change the storage class this early to get the right DeclContext. | ||||||
6662 | if (SC == SC_None && !DC->isRecord() && | ||||||
6663 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | ||||||
6664 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | ||||||
6665 | SC = SC_Extern; | ||||||
6666 | |||||||
6667 | DeclContext *OriginalDC = DC; | ||||||
6668 | bool IsLocalExternDecl = SC == SC_Extern && | ||||||
6669 | adjustContextForLocalExternDecl(DC); | ||||||
6670 | |||||||
6671 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||||
6672 | // mutable can only appear on non-static class members, so it's always | ||||||
6673 | // an error here | ||||||
6674 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | ||||||
6675 | D.setInvalidType(); | ||||||
6676 | SC = SC_None; | ||||||
6677 | } | ||||||
6678 | |||||||
6679 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | ||||||
6680 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | ||||||
6681 | D.getDeclSpec().getStorageClassSpecLoc())) { | ||||||
6682 | // In C++11, the 'register' storage class specifier is deprecated. | ||||||
6683 | // Suppress the warning in system macros, it's used in macros in some | ||||||
6684 | // popular C system headers, such as in glibc's htonl() macro. | ||||||
6685 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6686 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||||
6687 | : diag::warn_deprecated_register) | ||||||
6688 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6689 | } | ||||||
6690 | |||||||
6691 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
6692 | |||||||
6693 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | ||||||
6694 | // C99 6.9p2: The storage-class specifiers auto and register shall not | ||||||
6695 | // appear in the declaration specifiers in an external declaration. | ||||||
6696 | // Global Register+Asm is a GNU extension we support. | ||||||
6697 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | ||||||
6698 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | ||||||
6699 | D.setInvalidType(); | ||||||
6700 | } | ||||||
6701 | } | ||||||
6702 | |||||||
6703 | bool IsMemberSpecialization = false; | ||||||
6704 | bool IsVariableTemplateSpecialization = false; | ||||||
6705 | bool IsPartialSpecialization = false; | ||||||
6706 | bool IsVariableTemplate = false; | ||||||
6707 | VarDecl *NewVD = nullptr; | ||||||
6708 | VarTemplateDecl *NewTemplate = nullptr; | ||||||
6709 | TemplateParameterList *TemplateParams = nullptr; | ||||||
6710 | if (!getLangOpts().CPlusPlus) { | ||||||
6711 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | ||||||
6712 | II, R, TInfo, SC); | ||||||
6713 | |||||||
6714 | if (R->getContainedDeducedType()) | ||||||
6715 | ParsingInitForAutoVars.insert(NewVD); | ||||||
6716 | |||||||
6717 | if (D.isInvalidType()) | ||||||
6718 | NewVD->setInvalidDecl(); | ||||||
6719 | |||||||
6720 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && | ||||||
6721 | NewVD->hasLocalStorage()) | ||||||
6722 | checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), | ||||||
6723 | NTCUC_AutoVar, NTCUK_Destruct); | ||||||
6724 | } else { | ||||||
6725 | bool Invalid = false; | ||||||
6726 | |||||||
6727 | if (DC->isRecord() && !CurContext->isRecord()) { | ||||||
6728 | // This is an out-of-line definition of a static data member. | ||||||
6729 | switch (SC) { | ||||||
6730 | case SC_None: | ||||||
6731 | break; | ||||||
6732 | case SC_Static: | ||||||
6733 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6734 | diag::err_static_out_of_line) | ||||||
6735 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6736 | break; | ||||||
6737 | case SC_Auto: | ||||||
6738 | case SC_Register: | ||||||
6739 | case SC_Extern: | ||||||
6740 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | ||||||
6741 | // to names of variables declared in a block or to function parameters. | ||||||
6742 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | ||||||
6743 | // of class members | ||||||
6744 | |||||||
6745 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6746 | diag::err_storage_class_for_static_member) | ||||||
6747 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6748 | break; | ||||||
6749 | case SC_PrivateExtern: | ||||||
6750 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6750); | ||||||
6751 | } | ||||||
6752 | } | ||||||
6753 | |||||||
6754 | if (SC == SC_Static && CurContext->isRecord()) { | ||||||
6755 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | ||||||
6756 | if (RD->isLocalClass()) | ||||||
6757 | Diag(D.getIdentifierLoc(), | ||||||
6758 | diag::err_static_data_member_not_allowed_in_local_class) | ||||||
6759 | << Name << RD->getDeclName(); | ||||||
6760 | |||||||
6761 | // C++98 [class.union]p1: If a union contains a static data member, | ||||||
6762 | // the program is ill-formed. C++11 drops this restriction. | ||||||
6763 | if (RD->isUnion()) | ||||||
6764 | Diag(D.getIdentifierLoc(), | ||||||
6765 | getLangOpts().CPlusPlus11 | ||||||
6766 | ? diag::warn_cxx98_compat_static_data_member_in_union | ||||||
6767 | : diag::ext_static_data_member_in_union) << Name; | ||||||
6768 | // We conservatively disallow static data members in anonymous structs. | ||||||
6769 | else if (!RD->getDeclName()) | ||||||
6770 | Diag(D.getIdentifierLoc(), | ||||||
6771 | diag::err_static_data_member_not_allowed_in_anon_struct) | ||||||
6772 | << Name << RD->isUnion(); | ||||||
6773 | } | ||||||
6774 | } | ||||||
6775 | |||||||
6776 | // Match up the template parameter lists with the scope specifier, then | ||||||
6777 | // determine whether we have a template or a template specialization. | ||||||
6778 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | ||||||
6779 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||||
6780 | D.getCXXScopeSpec(), | ||||||
6781 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||||
6782 | ? D.getName().TemplateId | ||||||
6783 | : nullptr, | ||||||
6784 | TemplateParamLists, | ||||||
6785 | /*never a friend*/ false, IsMemberSpecialization, Invalid); | ||||||
6786 | |||||||
6787 | if (TemplateParams) { | ||||||
6788 | if (!TemplateParams->size() && | ||||||
6789 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||||
6790 | // There is an extraneous 'template<>' for this variable. Complain | ||||||
6791 | // about it, but allow the declaration of the variable. | ||||||
6792 | Diag(TemplateParams->getTemplateLoc(), | ||||||
6793 | diag::err_template_variable_noparams) | ||||||
6794 | << II | ||||||
6795 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||||
6796 | TemplateParams->getRAngleLoc()); | ||||||
6797 | TemplateParams = nullptr; | ||||||
6798 | } else { | ||||||
6799 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||
6800 | // This is an explicit specialization or a partial specialization. | ||||||
6801 | // FIXME: Check that we can declare a specialization here. | ||||||
6802 | IsVariableTemplateSpecialization = true; | ||||||
6803 | IsPartialSpecialization = TemplateParams->size() > 0; | ||||||
6804 | } else { // if (TemplateParams->size() > 0) | ||||||
6805 | // This is a template declaration. | ||||||
6806 | IsVariableTemplate = true; | ||||||
6807 | |||||||
6808 | // Check that we can declare a template here. | ||||||
6809 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||||
6810 | return nullptr; | ||||||
6811 | |||||||
6812 | // Only C++1y supports variable templates (N3651). | ||||||
6813 | Diag(D.getIdentifierLoc(), | ||||||
6814 | getLangOpts().CPlusPlus14 | ||||||
6815 | ? diag::warn_cxx11_compat_variable_template | ||||||
6816 | : diag::ext_variable_template); | ||||||
6817 | } | ||||||
6818 | } | ||||||
6819 | } else { | ||||||
6820 | assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6822, __PRETTY_FUNCTION__)) | ||||||
6821 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6822, __PRETTY_FUNCTION__)) | ||||||
6822 | "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 6822, __PRETTY_FUNCTION__)); | ||||||
6823 | } | ||||||
6824 | |||||||
6825 | if (IsVariableTemplateSpecialization) { | ||||||
6826 | SourceLocation TemplateKWLoc = | ||||||
6827 | TemplateParamLists.size() > 0 | ||||||
6828 | ? TemplateParamLists[0]->getTemplateLoc() | ||||||
6829 | : SourceLocation(); | ||||||
6830 | DeclResult Res = ActOnVarTemplateSpecialization( | ||||||
6831 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | ||||||
6832 | IsPartialSpecialization); | ||||||
6833 | if (Res.isInvalid()) | ||||||
6834 | return nullptr; | ||||||
6835 | NewVD = cast<VarDecl>(Res.get()); | ||||||
6836 | AddToScope = false; | ||||||
6837 | } else if (D.isDecompositionDeclarator()) { | ||||||
6838 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | ||||||
6839 | D.getIdentifierLoc(), R, TInfo, SC, | ||||||
6840 | Bindings); | ||||||
6841 | } else | ||||||
6842 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | ||||||
6843 | D.getIdentifierLoc(), II, R, TInfo, SC); | ||||||
6844 | |||||||
6845 | // If this is supposed to be a variable template, create it as such. | ||||||
6846 | if (IsVariableTemplate) { | ||||||
6847 | NewTemplate = | ||||||
6848 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | ||||||
6849 | TemplateParams, NewVD); | ||||||
6850 | NewVD->setDescribedVarTemplate(NewTemplate); | ||||||
6851 | } | ||||||
6852 | |||||||
6853 | // If this decl has an auto type in need of deduction, make a note of the | ||||||
6854 | // Decl so we can diagnose uses of it in its own initializer. | ||||||
6855 | if (R->getContainedDeducedType()) | ||||||
6856 | ParsingInitForAutoVars.insert(NewVD); | ||||||
6857 | |||||||
6858 | if (D.isInvalidType() || Invalid) { | ||||||
6859 | NewVD->setInvalidDecl(); | ||||||
6860 | if (NewTemplate) | ||||||
6861 | NewTemplate->setInvalidDecl(); | ||||||
6862 | } | ||||||
6863 | |||||||
6864 | SetNestedNameSpecifier(*this, NewVD, D); | ||||||
6865 | |||||||
6866 | // If we have any template parameter lists that don't directly belong to | ||||||
6867 | // the variable (matching the scope specifier), store them. | ||||||
6868 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | ||||||
6869 | if (TemplateParamLists.size() > VDTemplateParamLists) | ||||||
6870 | NewVD->setTemplateParameterListsInfo( | ||||||
6871 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | ||||||
6872 | } | ||||||
6873 | |||||||
6874 | if (D.getDeclSpec().isInlineSpecified()) { | ||||||
6875 | if (!getLangOpts().CPlusPlus) { | ||||||
6876 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
6877 | << 0; | ||||||
6878 | } else if (CurContext->isFunctionOrMethod()) { | ||||||
6879 | // 'inline' is not allowed on block scope variable declaration. | ||||||
6880 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
6881 | diag::err_inline_declaration_block_scope) << Name | ||||||
6882 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||||
6883 | } else { | ||||||
6884 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
6885 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | ||||||
6886 | : diag::ext_inline_variable); | ||||||
6887 | NewVD->setInlineSpecified(); | ||||||
6888 | } | ||||||
6889 | } | ||||||
6890 | |||||||
6891 | // Set the lexical context. If the declarator has a C++ scope specifier, the | ||||||
6892 | // lexical context will be different from the semantic context. | ||||||
6893 | NewVD->setLexicalDeclContext(CurContext); | ||||||
6894 | if (NewTemplate) | ||||||
6895 | NewTemplate->setLexicalDeclContext(CurContext); | ||||||
6896 | |||||||
6897 | if (IsLocalExternDecl) { | ||||||
6898 | if (D.isDecompositionDeclarator()) | ||||||
6899 | for (auto *B : Bindings) | ||||||
6900 | B->setLocalExternDecl(); | ||||||
6901 | else | ||||||
6902 | NewVD->setLocalExternDecl(); | ||||||
6903 | } | ||||||
6904 | |||||||
6905 | bool EmitTLSUnsupportedError = false; | ||||||
6906 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | ||||||
6907 | // C++11 [dcl.stc]p4: | ||||||
6908 | // When thread_local is applied to a variable of block scope the | ||||||
6909 | // storage-class-specifier static is implied if it does not appear | ||||||
6910 | // explicitly. | ||||||
6911 | // Core issue: 'static' is not implied if the variable is declared | ||||||
6912 | // 'extern'. | ||||||
6913 | if (NewVD->hasLocalStorage() && | ||||||
6914 | (SCSpec != DeclSpec::SCS_unspecified || | ||||||
6915 | TSCS != DeclSpec::TSCS_thread_local || | ||||||
6916 | !DC->isFunctionOrMethod())) | ||||||
6917 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6918 | diag::err_thread_non_global) | ||||||
6919 | << DeclSpec::getSpecifierName(TSCS); | ||||||
6920 | else if (!Context.getTargetInfo().isTLSSupported()) { | ||||||
6921 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | ||||||
6922 | // Postpone error emission until we've collected attributes required to | ||||||
6923 | // figure out whether it's a host or device variable and whether the | ||||||
6924 | // error should be ignored. | ||||||
6925 | EmitTLSUnsupportedError = true; | ||||||
6926 | // We still need to mark the variable as TLS so it shows up in AST with | ||||||
6927 | // proper storage class for other tools to use even if we're not going | ||||||
6928 | // to emit any code for it. | ||||||
6929 | NewVD->setTSCSpec(TSCS); | ||||||
6930 | } else | ||||||
6931 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6932 | diag::err_thread_unsupported); | ||||||
6933 | } else | ||||||
6934 | NewVD->setTSCSpec(TSCS); | ||||||
6935 | } | ||||||
6936 | |||||||
6937 | switch (D.getDeclSpec().getConstexprSpecifier()) { | ||||||
6938 | case CSK_unspecified: | ||||||
6939 | break; | ||||||
6940 | |||||||
6941 | case CSK_consteval: | ||||||
6942 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
6943 | diag::err_constexpr_wrong_decl_kind) | ||||||
6944 | << D.getDeclSpec().getConstexprSpecifier(); | ||||||
6945 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
6946 | |||||||
6947 | case CSK_constexpr: | ||||||
6948 | NewVD->setConstexpr(true); | ||||||
6949 | // C++1z [dcl.spec.constexpr]p1: | ||||||
6950 | // A static data member declared with the constexpr specifier is | ||||||
6951 | // implicitly an inline variable. | ||||||
6952 | if (NewVD->isStaticDataMember() && | ||||||
6953 | (getLangOpts().CPlusPlus17 || | ||||||
6954 | Context.getTargetInfo().getCXXABI().isMicrosoft())) | ||||||
6955 | NewVD->setImplicitlyInline(); | ||||||
6956 | break; | ||||||
6957 | |||||||
6958 | case CSK_constinit: | ||||||
6959 | if (!NewVD->hasGlobalStorage()) | ||||||
6960 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
6961 | diag::err_constinit_local_variable); | ||||||
6962 | else | ||||||
6963 | NewVD->addAttr(ConstInitAttr::Create( | ||||||
6964 | Context, D.getDeclSpec().getConstexprSpecLoc(), | ||||||
6965 | AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); | ||||||
6966 | break; | ||||||
6967 | } | ||||||
6968 | |||||||
6969 | // C99 6.7.4p3 | ||||||
6970 | // An inline definition of a function with external linkage shall | ||||||
6971 | // not contain a definition of a modifiable object with static or | ||||||
6972 | // thread storage duration... | ||||||
6973 | // We only apply this when the function is required to be defined | ||||||
6974 | // elsewhere, i.e. when the function is not 'extern inline'. Note | ||||||
6975 | // that a local variable with thread storage duration still has to | ||||||
6976 | // be marked 'static'. Also note that it's possible to get these | ||||||
6977 | // semantics in C++ using __attribute__((gnu_inline)). | ||||||
6978 | if (SC == SC_Static && S->getFnParent() != nullptr && | ||||||
6979 | !NewVD->getType().isConstQualified()) { | ||||||
6980 | FunctionDecl *CurFD = getCurFunctionDecl(); | ||||||
6981 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | ||||||
6982 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6983 | diag::warn_static_local_in_extern_inline); | ||||||
6984 | MaybeSuggestAddingStaticToDecl(CurFD); | ||||||
6985 | } | ||||||
6986 | } | ||||||
6987 | |||||||
6988 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
6989 | if (IsVariableTemplateSpecialization) | ||||||
6990 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||||
6991 | << (IsPartialSpecialization ? 1 : 0) | ||||||
6992 | << FixItHint::CreateRemoval( | ||||||
6993 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
6994 | else if (IsMemberSpecialization) | ||||||
6995 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||||
6996 | << 2 | ||||||
6997 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
6998 | else if (NewVD->hasLocalStorage()) | ||||||
6999 | Diag(NewVD->getLocation(), diag::err_module_private_local) | ||||||
7000 | << 0 << NewVD->getDeclName() | ||||||
7001 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
7002 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
7003 | else { | ||||||
7004 | NewVD->setModulePrivate(); | ||||||
7005 | if (NewTemplate) | ||||||
7006 | NewTemplate->setModulePrivate(); | ||||||
7007 | for (auto *B : Bindings) | ||||||
7008 | B->setModulePrivate(); | ||||||
7009 | } | ||||||
7010 | } | ||||||
7011 | |||||||
7012 | if (getLangOpts().OpenCL) { | ||||||
7013 | |||||||
7014 | deduceOpenCLAddressSpace(NewVD); | ||||||
7015 | |||||||
7016 | diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); | ||||||
7017 | } | ||||||
7018 | |||||||
7019 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||||
7020 | ProcessDeclAttributes(S, NewVD, D); | ||||||
7021 | |||||||
7022 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | ||||||
7023 | if (EmitTLSUnsupportedError && | ||||||
7024 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | ||||||
7025 | (getLangOpts().OpenMPIsDevice && | ||||||
7026 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) | ||||||
7027 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
7028 | diag::err_thread_unsupported); | ||||||
7029 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | ||||||
7030 | // storage [duration]." | ||||||
7031 | if (SC == SC_None && S->getFnParent() != nullptr && | ||||||
7032 | (NewVD->hasAttr<CUDASharedAttr>() || | ||||||
7033 | NewVD->hasAttr<CUDAConstantAttr>())) { | ||||||
7034 | NewVD->setStorageClass(SC_Static); | ||||||
7035 | } | ||||||
7036 | } | ||||||
7037 | |||||||
7038 | // Ensure that dllimport globals without explicit storage class are treated as | ||||||
7039 | // extern. The storage class is set above using parsed attributes. Now we can | ||||||
7040 | // check the VarDecl itself. | ||||||
7041 | assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 7043, __PRETTY_FUNCTION__)) | ||||||
7042 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 7043, __PRETTY_FUNCTION__)) | ||||||
7043 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 7043, __PRETTY_FUNCTION__)); | ||||||
7044 | |||||||
7045 | // In auto-retain/release, infer strong retension for variables of | ||||||
7046 | // retainable type. | ||||||
7047 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | ||||||
7048 | NewVD->setInvalidDecl(); | ||||||
7049 | |||||||
7050 | // Handle GNU asm-label extension (encoded as an attribute). | ||||||
7051 | if (Expr *E = (Expr*)D.getAsmLabel()) { | ||||||
7052 | // The parser guarantees this is a string. | ||||||
7053 | StringLiteral *SE = cast<StringLiteral>(E); | ||||||
7054 | StringRef Label = SE->getString(); | ||||||
7055 | if (S->getFnParent() != nullptr) { | ||||||
7056 | switch (SC) { | ||||||
7057 | case SC_None: | ||||||
7058 | case SC_Auto: | ||||||
7059 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | ||||||
7060 | break; | ||||||
7061 | case SC_Register: | ||||||
7062 | // Local Named register | ||||||
7063 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | ||||||
7064 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | ||||||
7065 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||||
7066 | break; | ||||||
7067 | case SC_Static: | ||||||
7068 | case SC_Extern: | ||||||
7069 | case SC_PrivateExtern: | ||||||
7070 | break; | ||||||
7071 | } | ||||||
7072 | } else if (SC == SC_Register) { | ||||||
7073 | // Global Named register | ||||||
7074 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | ||||||
7075 | const auto &TI = Context.getTargetInfo(); | ||||||
7076 | bool HasSizeMismatch; | ||||||
7077 | |||||||
7078 | if (!TI.isValidGCCRegisterName(Label)) | ||||||
7079 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||||
7080 | else if (!TI.validateGlobalRegisterVariable(Label, | ||||||
7081 | Context.getTypeSize(R), | ||||||
7082 | HasSizeMismatch)) | ||||||
7083 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | ||||||
7084 | else if (HasSizeMismatch) | ||||||
7085 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | ||||||
7086 | } | ||||||
7087 | |||||||
7088 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | ||||||
7089 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | ||||||
7090 | NewVD->setInvalidDecl(true); | ||||||
7091 | } | ||||||
7092 | } | ||||||
7093 | |||||||
7094 | NewVD->addAttr(AsmLabelAttr::Create(Context, Label, | ||||||
7095 | /*IsLiteralLabel=*/true, | ||||||
7096 | SE->getStrTokenLoc(0))); | ||||||
7097 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||||
7098 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||||
7099 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | ||||||
7100 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||||
7101 | if (isDeclExternC(NewVD)) { | ||||||
7102 | NewVD->addAttr(I->second); | ||||||
7103 | ExtnameUndeclaredIdentifiers.erase(I); | ||||||
7104 | } else | ||||||
7105 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
7106 | << /*Variable*/1 << NewVD; | ||||||
7107 | } | ||||||
7108 | } | ||||||
7109 | |||||||
7110 | // Find the shadowed declaration before filtering for scope. | ||||||
7111 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | ||||||
7112 | ? getShadowedDeclaration(NewVD, Previous) | ||||||
7113 | : nullptr; | ||||||
7114 | |||||||
7115 | // Don't consider existing declarations that are in a different | ||||||
7116 | // scope and are out-of-semantic-context declarations (if the new | ||||||
7117 | // declaration has linkage). | ||||||
7118 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | ||||||
7119 | D.getCXXScopeSpec().isNotEmpty() || | ||||||
7120 | IsMemberSpecialization || | ||||||
7121 | IsVariableTemplateSpecialization); | ||||||
7122 | |||||||
7123 | // Check whether the previous declaration is in the same block scope. This | ||||||
7124 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | ||||||
7125 | if (getLangOpts().CPlusPlus && | ||||||
7126 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | ||||||
7127 | NewVD->setPreviousDeclInSameBlockScope( | ||||||
7128 | Previous.isSingleResult() && !Previous.isShadowed() && | ||||||
7129 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | ||||||
7130 | |||||||
7131 | if (!getLangOpts().CPlusPlus) { | ||||||
7132 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||||
7133 | } else { | ||||||
7134 | // If this is an explicit specialization of a static data member, check it. | ||||||
7135 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | ||||||
7136 | CheckMemberSpecialization(NewVD, Previous)) | ||||||
7137 | NewVD->setInvalidDecl(); | ||||||
7138 | |||||||
7139 | // Merge the decl with the existing one if appropriate. | ||||||
7140 | if (!Previous.empty()) { | ||||||
7141 | if (Previous.isSingleResult() && | ||||||
7142 | isa<FieldDecl>(Previous.getFoundDecl()) && | ||||||
7143 | D.getCXXScopeSpec().isSet()) { | ||||||
7144 | // The user tried to define a non-static data member | ||||||
7145 | // out-of-line (C++ [dcl.meaning]p1). | ||||||
7146 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | ||||||
7147 | << D.getCXXScopeSpec().getRange(); | ||||||
7148 | Previous.clear(); | ||||||
7149 | NewVD->setInvalidDecl(); | ||||||
7150 | } | ||||||
7151 | } else if (D.getCXXScopeSpec().isSet()) { | ||||||
7152 | // No previous declaration in the qualifying scope. | ||||||
7153 | Diag(D.getIdentifierLoc(), diag::err_no_member) | ||||||
7154 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | ||||||
7155 | << D.getCXXScopeSpec().getRange(); | ||||||
7156 | NewVD->setInvalidDecl(); | ||||||
7157 | } | ||||||
7158 | |||||||
7159 | if (!IsVariableTemplateSpecialization) | ||||||
7160 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||||
7161 | |||||||
7162 | if (NewTemplate) { | ||||||
7163 | VarTemplateDecl *PrevVarTemplate = | ||||||
7164 | NewVD->getPreviousDecl() | ||||||
7165 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | ||||||
7166 | : nullptr; | ||||||
7167 | |||||||
7168 | // Check the template parameter list of this declaration, possibly | ||||||
7169 | // merging in the template parameter list from the previous variable | ||||||
7170 | // template declaration. | ||||||
7171 | if (CheckTemplateParameterList( | ||||||
7172 | TemplateParams, | ||||||
7173 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | ||||||
7174 | : nullptr, | ||||||
7175 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | ||||||
7176 | DC->isDependentContext()) | ||||||
7177 | ? TPC_ClassTemplateMember | ||||||
7178 | : TPC_VarTemplate)) | ||||||
7179 | NewVD->setInvalidDecl(); | ||||||
7180 | |||||||
7181 | // If we are providing an explicit specialization of a static variable | ||||||
7182 | // template, make a note of that. | ||||||
7183 | if (PrevVarTemplate && | ||||||
7184 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | ||||||
7185 | PrevVarTemplate->setMemberSpecialization(); | ||||||
7186 | } | ||||||
7187 | } | ||||||
7188 | |||||||
7189 | // Diagnose shadowed variables iff this isn't a redeclaration. | ||||||
7190 | if (ShadowedDecl && !D.isRedeclaration()) | ||||||
7191 | CheckShadow(NewVD, ShadowedDecl, Previous); | ||||||
7192 | |||||||
7193 | ProcessPragmaWeak(S, NewVD); | ||||||
7194 | |||||||
7195 | // If this is the first declaration of an extern C variable, update | ||||||
7196 | // the map of such variables. | ||||||
7197 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | ||||||
7198 | isIncompleteDeclExternC(*this, NewVD)) | ||||||
7199 | RegisterLocallyScopedExternCDecl(NewVD, S); | ||||||
7200 | |||||||
7201 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||||
7202 | MangleNumberingContext *MCtx; | ||||||
7203 | Decl *ManglingContextDecl; | ||||||
7204 | std::tie(MCtx, ManglingContextDecl) = | ||||||
7205 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||||
7206 | if (MCtx) { | ||||||
7207 | Context.setManglingNumber( | ||||||
7208 | NewVD, MCtx->getManglingNumber( | ||||||
7209 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||||
7210 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||||
7211 | } | ||||||
7212 | } | ||||||
7213 | |||||||
7214 | // Special handling of variable named 'main'. | ||||||
7215 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | ||||||
7216 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||||
7217 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | ||||||
7218 | |||||||
7219 | // C++ [basic.start.main]p3 | ||||||
7220 | // A program that declares a variable main at global scope is ill-formed. | ||||||
7221 | if (getLangOpts().CPlusPlus) | ||||||
7222 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | ||||||
7223 | |||||||
7224 | // In C, and external-linkage variable named main results in undefined | ||||||
7225 | // behavior. | ||||||
7226 | else if (NewVD->hasExternalFormalLinkage()) | ||||||
7227 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | ||||||
7228 | } | ||||||
7229 | |||||||
7230 | if (D.isRedeclaration() && !Previous.empty()) { | ||||||
7231 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||||
7232 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | ||||||
7233 | D.isFunctionDefinition()); | ||||||
7234 | } | ||||||
7235 | |||||||
7236 | if (NewTemplate) { | ||||||
7237 | if (NewVD->isInvalidDecl()) | ||||||
7238 | NewTemplate->setInvalidDecl(); | ||||||
7239 | ActOnDocumentableDecl(NewTemplate); | ||||||
7240 | return NewTemplate; | ||||||
7241 | } | ||||||
7242 | |||||||
7243 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | ||||||
7244 | CompleteMemberSpecialization(NewVD, Previous); | ||||||
7245 | |||||||
7246 | return NewVD; | ||||||
7247 | } | ||||||
7248 | |||||||
7249 | /// Enum describing the %select options in diag::warn_decl_shadow. | ||||||
7250 | enum ShadowedDeclKind { | ||||||
7251 | SDK_Local, | ||||||
7252 | SDK_Global, | ||||||
7253 | SDK_StaticMember, | ||||||
7254 | SDK_Field, | ||||||
7255 | SDK_Typedef, | ||||||
7256 | SDK_Using | ||||||
7257 | }; | ||||||
7258 | |||||||
7259 | /// Determine what kind of declaration we're shadowing. | ||||||
7260 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | ||||||
7261 | const DeclContext *OldDC) { | ||||||
7262 | if (isa<TypeAliasDecl>(ShadowedDecl)) | ||||||
7263 | return SDK_Using; | ||||||
7264 | else if (isa<TypedefDecl>(ShadowedDecl)) | ||||||
7265 | return SDK_Typedef; | ||||||
7266 | else if (isa<RecordDecl>(OldDC)) | ||||||
7267 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | ||||||
7268 | |||||||
7269 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | ||||||
7270 | } | ||||||
7271 | |||||||
7272 | /// Return the location of the capture if the given lambda captures the given | ||||||
7273 | /// variable \p VD, or an invalid source location otherwise. | ||||||
7274 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | ||||||
7275 | const VarDecl *VD) { | ||||||
7276 | for (const Capture &Capture : LSI->Captures) { | ||||||
7277 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | ||||||
7278 | return Capture.getLocation(); | ||||||
7279 | } | ||||||
7280 | return SourceLocation(); | ||||||
7281 | } | ||||||
7282 | |||||||
7283 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | ||||||
7284 | const LookupResult &R) { | ||||||
7285 | // Only diagnose if we're shadowing an unambiguous field or variable. | ||||||
7286 | if (R.getResultKind() != LookupResult::Found) | ||||||
7287 | return false; | ||||||
7288 | |||||||
7289 | // Return false if warning is ignored. | ||||||
7290 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | ||||||
7291 | } | ||||||
7292 | |||||||
7293 | /// Return the declaration shadowed by the given variable \p D, or null | ||||||
7294 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||||
7295 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | ||||||
7296 | const LookupResult &R) { | ||||||
7297 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||||
7298 | return nullptr; | ||||||
7299 | |||||||
7300 | // Don't diagnose declarations at file scope. | ||||||
7301 | if (D->hasGlobalStorage()) | ||||||
7302 | return nullptr; | ||||||
7303 | |||||||
7304 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||||
7305 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) | ||||||
7306 | ? ShadowedDecl | ||||||
7307 | : nullptr; | ||||||
7308 | } | ||||||
7309 | |||||||
7310 | /// Return the declaration shadowed by the given typedef \p D, or null | ||||||
7311 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||||
7312 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | ||||||
7313 | const LookupResult &R) { | ||||||
7314 | // Don't warn if typedef declaration is part of a class | ||||||
7315 | if (D->getDeclContext()->isRecord()) | ||||||
7316 | return nullptr; | ||||||
7317 | |||||||
7318 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||||
7319 | return nullptr; | ||||||
7320 | |||||||
7321 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||||
7322 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | ||||||
7323 | } | ||||||
7324 | |||||||
7325 | /// Diagnose variable or built-in function shadowing. Implements | ||||||
7326 | /// -Wshadow. | ||||||
7327 | /// | ||||||
7328 | /// This method is called whenever a VarDecl is added to a "useful" | ||||||
7329 | /// scope. | ||||||
7330 | /// | ||||||
7331 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | ||||||
7332 | /// \param R the lookup of the name | ||||||
7333 | /// | ||||||
7334 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | ||||||
7335 | const LookupResult &R) { | ||||||
7336 | DeclContext *NewDC = D->getDeclContext(); | ||||||
7337 | |||||||
7338 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | ||||||
7339 | // Fields are not shadowed by variables in C++ static methods. | ||||||
7340 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | ||||||
7341 | if (MD->isStatic()) | ||||||
7342 | return; | ||||||
7343 | |||||||
7344 | // Fields shadowed by constructor parameters are a special case. Usually | ||||||
7345 | // the constructor initializes the field with the parameter. | ||||||
7346 | if (isa<CXXConstructorDecl>(NewDC)) | ||||||
7347 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | ||||||
7348 | // Remember that this was shadowed so we can either warn about its | ||||||
7349 | // modification or its existence depending on warning settings. | ||||||
7350 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | ||||||
7351 | return; | ||||||
7352 | } | ||||||
7353 | } | ||||||
7354 | |||||||
7355 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | ||||||
7356 | if (shadowedVar->isExternC()) { | ||||||
7357 | // For shadowing external vars, make sure that we point to the global | ||||||
7358 | // declaration, not a locally scoped extern declaration. | ||||||
7359 | for (auto I : shadowedVar->redecls()) | ||||||
7360 | if (I->isFileVarDecl()) { | ||||||
7361 | ShadowedDecl = I; | ||||||
7362 | break; | ||||||
7363 | } | ||||||
7364 | } | ||||||
7365 | |||||||
7366 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | ||||||
7367 | |||||||
7368 | unsigned WarningDiag = diag::warn_decl_shadow; | ||||||
7369 | SourceLocation CaptureLoc; | ||||||
7370 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | ||||||
7371 | isa<CXXMethodDecl>(NewDC)) { | ||||||
7372 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | ||||||
7373 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | ||||||
7374 | if (RD->getLambdaCaptureDefault() == LCD_None) { | ||||||
7375 | // Try to avoid warnings for lambdas with an explicit capture list. | ||||||
7376 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | ||||||
7377 | // Warn only when the lambda captures the shadowed decl explicitly. | ||||||
7378 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | ||||||
7379 | if (CaptureLoc.isInvalid()) | ||||||
7380 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | ||||||
7381 | } else { | ||||||
7382 | // Remember that this was shadowed so we can avoid the warning if the | ||||||
7383 | // shadowed decl isn't captured and the warning settings allow it. | ||||||
7384 | cast<LambdaScopeInfo>(getCurFunction()) | ||||||
7385 | ->ShadowingDecls.push_back( | ||||||
7386 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | ||||||
7387 | return; | ||||||
7388 | } | ||||||
7389 | } | ||||||
7390 | |||||||
7391 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | ||||||
7392 | // A variable can't shadow a local variable in an enclosing scope, if | ||||||
7393 | // they are separated by a non-capturing declaration context. | ||||||
7394 | for (DeclContext *ParentDC = NewDC; | ||||||
7395 | ParentDC && !ParentDC->Equals(OldDC); | ||||||
7396 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | ||||||
7397 | // Only block literals, captured statements, and lambda expressions | ||||||
7398 | // can capture; other scopes don't. | ||||||
7399 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | ||||||
7400 | !isLambdaCallOperator(ParentDC)) { | ||||||
7401 | return; | ||||||
7402 | } | ||||||
7403 | } | ||||||
7404 | } | ||||||
7405 | } | ||||||
7406 | } | ||||||
7407 | |||||||
7408 | // Only warn about certain kinds of shadowing for class members. | ||||||
7409 | if (NewDC && NewDC->isRecord()) { | ||||||
7410 | // In particular, don't warn about shadowing non-class members. | ||||||
7411 | if (!OldDC->isRecord()) | ||||||
7412 | return; | ||||||
7413 | |||||||
7414 | // TODO: should we warn about static data members shadowing | ||||||
7415 | // static data members from base classes? | ||||||
7416 | |||||||
7417 | // TODO: don't diagnose for inaccessible shadowed members. | ||||||
7418 | // This is hard to do perfectly because we might friend the | ||||||
7419 | // shadowing context, but that's just a false negative. | ||||||
7420 | } | ||||||
7421 | |||||||
7422 | |||||||
7423 | DeclarationName Name = R.getLookupName(); | ||||||
7424 | |||||||
7425 | // Emit warning and note. | ||||||
7426 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | ||||||
7427 | return; | ||||||
7428 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | ||||||
7429 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | ||||||
7430 | if (!CaptureLoc.isInvalid()) | ||||||
7431 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||||
7432 | << Name << /*explicitly*/ 1; | ||||||
7433 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7434 | } | ||||||
7435 | |||||||
7436 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | ||||||
7437 | /// when these variables are captured by the lambda. | ||||||
7438 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | ||||||
7439 | for (const auto &Shadow : LSI->ShadowingDecls) { | ||||||
7440 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | ||||||
7441 | // Try to avoid the warning when the shadowed decl isn't captured. | ||||||
7442 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | ||||||
7443 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||||
7444 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | ||||||
7445 | ? diag::warn_decl_shadow_uncaptured_local | ||||||
7446 | : diag::warn_decl_shadow) | ||||||
7447 | << Shadow.VD->getDeclName() | ||||||
7448 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | ||||||
7449 | if (!CaptureLoc.isInvalid()) | ||||||
7450 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||||
7451 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | ||||||
7452 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7453 | } | ||||||
7454 | } | ||||||
7455 | |||||||
7456 | /// Check -Wshadow without the advantage of a previous lookup. | ||||||
7457 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | ||||||
7458 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | ||||||
7459 | return; | ||||||
7460 | |||||||
7461 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | ||||||
7462 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | ||||||
7463 | LookupName(R, S); | ||||||
7464 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | ||||||
7465 | CheckShadow(D, ShadowedDecl, R); | ||||||
7466 | } | ||||||
7467 | |||||||
7468 | /// Check if 'E', which is an expression that is about to be modified, refers | ||||||
7469 | /// to a constructor parameter that shadows a field. | ||||||
7470 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | ||||||
7471 | // Quickly ignore expressions that can't be shadowing ctor parameters. | ||||||
7472 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | ||||||
7473 | return; | ||||||
7474 | E = E->IgnoreParenImpCasts(); | ||||||
7475 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||||
7476 | if (!DRE) | ||||||
7477 | return; | ||||||
7478 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | ||||||
7479 | auto I = ShadowingDecls.find(D); | ||||||
7480 | if (I == ShadowingDecls.end()) | ||||||
7481 | return; | ||||||
7482 | const NamedDecl *ShadowedDecl = I->second; | ||||||
7483 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||||
7484 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | ||||||
7485 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | ||||||
7486 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7487 | |||||||
7488 | // Avoid issuing multiple warnings about the same decl. | ||||||
7489 | ShadowingDecls.erase(I); | ||||||
7490 | } | ||||||
7491 | |||||||
7492 | /// Check for conflict between this global or extern "C" declaration and | ||||||
7493 | /// previous global or extern "C" declarations. This is only used in C++. | ||||||
7494 | template<typename T> | ||||||
7495 | static bool checkGlobalOrExternCConflict( | ||||||
7496 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | ||||||
7497 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 7497, __PRETTY_FUNCTION__)); | ||||||
7498 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | ||||||
7499 | |||||||
7500 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | ||||||
7501 | // The common case: this global doesn't conflict with any extern "C" | ||||||
7502 | // declaration. | ||||||
7503 | return false; | ||||||
7504 | } | ||||||
7505 | |||||||
7506 | if (Prev) { | ||||||
7507 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | ||||||
7508 | // Both the old and new declarations have C language linkage. This is a | ||||||
7509 | // redeclaration. | ||||||
7510 | Previous.clear(); | ||||||
7511 | Previous.addDecl(Prev); | ||||||
7512 | return true; | ||||||
7513 | } | ||||||
7514 | |||||||
7515 | // This is a global, non-extern "C" declaration, and there is a previous | ||||||
7516 | // non-global extern "C" declaration. Diagnose if this is a variable | ||||||
7517 | // declaration. | ||||||
7518 | if (!isa<VarDecl>(ND)) | ||||||
7519 | return false; | ||||||
7520 | } else { | ||||||
7521 | // The declaration is extern "C". Check for any declaration in the | ||||||
7522 | // translation unit which might conflict. | ||||||
7523 | if (IsGlobal) { | ||||||
7524 | // We have already performed the lookup into the translation unit. | ||||||
7525 | IsGlobal = false; | ||||||
7526 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||||
7527 | I != E; ++I) { | ||||||
7528 | if (isa<VarDecl>(*I)) { | ||||||
7529 | Prev = *I; | ||||||
7530 | break; | ||||||
7531 | } | ||||||
7532 | } | ||||||
7533 | } else { | ||||||
7534 | DeclContext::lookup_result R = | ||||||
7535 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | ||||||
7536 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | ||||||
7537 | I != E; ++I) { | ||||||
7538 | if (isa<VarDecl>(*I)) { | ||||||
7539 | Prev = *I; | ||||||
7540 | break; | ||||||
7541 | } | ||||||
7542 | // FIXME: If we have any other entity with this name in global scope, | ||||||
7543 | // the declaration is ill-formed, but that is a defect: it breaks the | ||||||
7544 | // 'stat' hack, for instance. Only variables can have mangled name | ||||||
7545 | // clashes with extern "C" declarations, so only they deserve a | ||||||
7546 | // diagnostic. | ||||||
7547 | } | ||||||
7548 | } | ||||||
7549 | |||||||
7550 | if (!Prev) | ||||||
7551 | return false; | ||||||
7552 | } | ||||||
7553 | |||||||
7554 | // Use the first declaration's location to ensure we point at something which | ||||||
7555 | // is lexically inside an extern "C" linkage-spec. | ||||||
7556 | assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 7556, __PRETTY_FUNCTION__)); | ||||||
7557 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | ||||||
7558 | Prev = FD->getFirstDecl(); | ||||||
7559 | else | ||||||
7560 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | ||||||
7561 | |||||||
7562 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | ||||||
7563 | << IsGlobal << ND; | ||||||
7564 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | ||||||
7565 | << IsGlobal; | ||||||
7566 | return false; | ||||||
7567 | } | ||||||
7568 | |||||||
7569 | /// Apply special rules for handling extern "C" declarations. Returns \c true | ||||||
7570 | /// if we have found that this is a redeclaration of some prior entity. | ||||||
7571 | /// | ||||||
7572 | /// Per C++ [dcl.link]p6: | ||||||
7573 | /// Two declarations [for a function or variable] with C language linkage | ||||||
7574 | /// with the same name that appear in different scopes refer to the same | ||||||
7575 | /// [entity]. An entity with C language linkage shall not be declared with | ||||||
7576 | /// the same name as an entity in global scope. | ||||||
7577 | template<typename T> | ||||||
7578 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | ||||||
7579 | LookupResult &Previous) { | ||||||
7580 | if (!S.getLangOpts().CPlusPlus) { | ||||||
7581 | // In C, when declaring a global variable, look for a corresponding 'extern' | ||||||
7582 | // variable declared in function scope. We don't need this in C++, because | ||||||
7583 | // we find local extern decls in the surrounding file-scope DeclContext. | ||||||
7584 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
7585 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | ||||||
7586 | Previous.clear(); | ||||||
7587 | Previous.addDecl(Prev); | ||||||
7588 | return true; | ||||||
7589 | } | ||||||
7590 | } | ||||||
7591 | return false; | ||||||
7592 | } | ||||||
7593 | |||||||
7594 | // A declaration in the translation unit can conflict with an extern "C" | ||||||
7595 | // declaration. | ||||||
7596 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||||
7597 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | ||||||
7598 | |||||||
7599 | // An extern "C" declaration can conflict with a declaration in the | ||||||
7600 | // translation unit or can be a redeclaration of an extern "C" declaration | ||||||
7601 | // in another scope. | ||||||
7602 | if (isIncompleteDeclExternC(S,ND)) | ||||||
7603 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | ||||||
7604 | |||||||
7605 | // Neither global nor extern "C": nothing to do. | ||||||
7606 | return false; | ||||||
7607 | } | ||||||
7608 | |||||||
7609 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | ||||||
7610 | // If the decl is already known invalid, don't check it. | ||||||
7611 | if (NewVD->isInvalidDecl()) | ||||||
7612 | return; | ||||||
7613 | |||||||
7614 | QualType T = NewVD->getType(); | ||||||
7615 | |||||||
7616 | // Defer checking an 'auto' type until its initializer is attached. | ||||||
7617 | if (T->isUndeducedType()) | ||||||
7618 | return; | ||||||
7619 | |||||||
7620 | if (NewVD->hasAttrs()) | ||||||
7621 | CheckAlignasUnderalignment(NewVD); | ||||||
7622 | |||||||
7623 | if (T->isObjCObjectType()) { | ||||||
7624 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | ||||||
7625 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | ||||||
7626 | T = Context.getObjCObjectPointerType(T); | ||||||
7627 | NewVD->setType(T); | ||||||
7628 | } | ||||||
7629 | |||||||
7630 | // Emit an error if an address space was applied to decl with local storage. | ||||||
7631 | // This includes arrays of objects with address space qualifiers, but not | ||||||
7632 | // automatic variables that point to other address spaces. | ||||||
7633 | // ISO/IEC TR 18037 S5.1.2 | ||||||
7634 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | ||||||
7635 | T.getAddressSpace() != LangAS::Default) { | ||||||
7636 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | ||||||
7637 | NewVD->setInvalidDecl(); | ||||||
7638 | return; | ||||||
7639 | } | ||||||
7640 | |||||||
7641 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | ||||||
7642 | // scope. | ||||||
7643 | if (getLangOpts().OpenCLVersion == 120 && | ||||||
7644 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && | ||||||
7645 | NewVD->isStaticLocal()) { | ||||||
7646 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | ||||||
7647 | NewVD->setInvalidDecl(); | ||||||
7648 | return; | ||||||
7649 | } | ||||||
7650 | |||||||
7651 | if (getLangOpts().OpenCL) { | ||||||
7652 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | ||||||
7653 | if (NewVD->hasAttr<BlocksAttr>()) { | ||||||
7654 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | ||||||
7655 | return; | ||||||
7656 | } | ||||||
7657 | |||||||
7658 | if (T->isBlockPointerType()) { | ||||||
7659 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | ||||||
7660 | // can't use 'extern' storage class. | ||||||
7661 | if (!T.isConstQualified()) { | ||||||
7662 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||||
7663 | << 0 /*const*/; | ||||||
7664 | NewVD->setInvalidDecl(); | ||||||
7665 | return; | ||||||
7666 | } | ||||||
7667 | if (NewVD->hasExternalStorage()) { | ||||||
7668 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | ||||||
7669 | NewVD->setInvalidDecl(); | ||||||
7670 | return; | ||||||
7671 | } | ||||||
7672 | } | ||||||
7673 | // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the | ||||||
7674 | // __constant address space. | ||||||
7675 | // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static | ||||||
7676 | // variables inside a function can also be declared in the global | ||||||
7677 | // address space. | ||||||
7678 | // C++ for OpenCL inherits rule from OpenCL C v2.0. | ||||||
7679 | // FIXME: Adding local AS in C++ for OpenCL might make sense. | ||||||
7680 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | ||||||
7681 | NewVD->hasExternalStorage()) { | ||||||
7682 | if (!T->isSamplerT() && | ||||||
7683 | !(T.getAddressSpace() == LangAS::opencl_constant || | ||||||
7684 | (T.getAddressSpace() == LangAS::opencl_global && | ||||||
7685 | (getLangOpts().OpenCLVersion == 200 || | ||||||
7686 | getLangOpts().OpenCLCPlusPlus)))) { | ||||||
7687 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | ||||||
7688 | if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) | ||||||
7689 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||||
7690 | << Scope << "global or constant"; | ||||||
7691 | else | ||||||
7692 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||||
7693 | << Scope << "constant"; | ||||||
7694 | NewVD->setInvalidDecl(); | ||||||
7695 | return; | ||||||
7696 | } | ||||||
7697 | } else { | ||||||
7698 | if (T.getAddressSpace() == LangAS::opencl_global) { | ||||||
7699 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7700 | << 1 /*is any function*/ << "global"; | ||||||
7701 | NewVD->setInvalidDecl(); | ||||||
7702 | return; | ||||||
7703 | } | ||||||
7704 | if (T.getAddressSpace() == LangAS::opencl_constant || | ||||||
7705 | T.getAddressSpace() == LangAS::opencl_local) { | ||||||
7706 | FunctionDecl *FD = getCurFunctionDecl(); | ||||||
7707 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | ||||||
7708 | // in functions. | ||||||
7709 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | ||||||
7710 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||||
7711 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7712 | << 0 /*non-kernel only*/ << "constant"; | ||||||
7713 | else | ||||||
7714 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7715 | << 0 /*non-kernel only*/ << "local"; | ||||||
7716 | NewVD->setInvalidDecl(); | ||||||
7717 | return; | ||||||
7718 | } | ||||||
7719 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | ||||||
7720 | // in the outermost scope of a kernel function. | ||||||
7721 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | ||||||
7722 | if (!getCurScope()->isFunctionScope()) { | ||||||
7723 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||||
7724 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||||
7725 | << "constant"; | ||||||
7726 | else | ||||||
7727 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||||
7728 | << "local"; | ||||||
7729 | NewVD->setInvalidDecl(); | ||||||
7730 | return; | ||||||
7731 | } | ||||||
7732 | } | ||||||
7733 | } else if (T.getAddressSpace() != LangAS::opencl_private && | ||||||
7734 | // If we are parsing a template we didn't deduce an addr | ||||||
7735 | // space yet. | ||||||
7736 | T.getAddressSpace() != LangAS::Default) { | ||||||
7737 | // Do not allow other address spaces on automatic variable. | ||||||
7738 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | ||||||
7739 | NewVD->setInvalidDecl(); | ||||||
7740 | return; | ||||||
7741 | } | ||||||
7742 | } | ||||||
7743 | } | ||||||
7744 | |||||||
7745 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | ||||||
7746 | && !NewVD->hasAttr<BlocksAttr>()) { | ||||||
7747 | if (getLangOpts().getGC() != LangOptions::NonGC) | ||||||
7748 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | ||||||
7749 | else { | ||||||
7750 | assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> ( 0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 7750, __PRETTY_FUNCTION__)); | ||||||
7751 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | ||||||
7752 | } | ||||||
7753 | } | ||||||
7754 | |||||||
7755 | bool isVM = T->isVariablyModifiedType(); | ||||||
7756 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | ||||||
7757 | NewVD->hasAttr<BlocksAttr>()) | ||||||
7758 | setFunctionHasBranchProtectedScope(); | ||||||
7759 | |||||||
7760 | if ((isVM && NewVD->hasLinkage()) || | ||||||
7761 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | ||||||
7762 | bool SizeIsNegative; | ||||||
7763 | llvm::APSInt Oversized; | ||||||
7764 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | ||||||
7765 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | ||||||
7766 | QualType FixedT; | ||||||
7767 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | ||||||
7768 | FixedT = FixedTInfo->getType(); | ||||||
7769 | else if (FixedTInfo) { | ||||||
7770 | // Type and type-as-written are canonically different. We need to fix up | ||||||
7771 | // both types separately. | ||||||
7772 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | ||||||
7773 | Oversized); | ||||||
7774 | } | ||||||
7775 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | ||||||
7776 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | ||||||
7777 | // FIXME: This won't give the correct result for | ||||||
7778 | // int a[10][n]; | ||||||
7779 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | ||||||
7780 | |||||||
7781 | if (NewVD->isFileVarDecl()) | ||||||
7782 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | ||||||
7783 | << SizeRange; | ||||||
7784 | else if (NewVD->isStaticLocal()) | ||||||
7785 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | ||||||
7786 | << SizeRange; | ||||||
7787 | else | ||||||
7788 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | ||||||
7789 | << SizeRange; | ||||||
7790 | NewVD->setInvalidDecl(); | ||||||
7791 | return; | ||||||
7792 | } | ||||||
7793 | |||||||
7794 | if (!FixedTInfo) { | ||||||
7795 | if (NewVD->isFileVarDecl()) | ||||||
7796 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||||
7797 | else | ||||||
7798 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | ||||||
7799 | NewVD->setInvalidDecl(); | ||||||
7800 | return; | ||||||
7801 | } | ||||||
7802 | |||||||
7803 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); | ||||||
7804 | NewVD->setType(FixedT); | ||||||
7805 | NewVD->setTypeSourceInfo(FixedTInfo); | ||||||
7806 | } | ||||||
7807 | |||||||
7808 | if (T->isVoidType()) { | ||||||
7809 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | ||||||
7810 | // of objects and functions. | ||||||
7811 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | ||||||
7812 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | ||||||
7813 | << T; | ||||||
7814 | NewVD->setInvalidDecl(); | ||||||
7815 | return; | ||||||
7816 | } | ||||||
7817 | } | ||||||
7818 | |||||||
7819 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | ||||||
7820 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | ||||||
7821 | NewVD->setInvalidDecl(); | ||||||
7822 | return; | ||||||
7823 | } | ||||||
7824 | |||||||
7825 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | ||||||
7826 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | ||||||
7827 | NewVD->setInvalidDecl(); | ||||||
7828 | return; | ||||||
7829 | } | ||||||
7830 | |||||||
7831 | if (NewVD->isConstexpr() && !T->isDependentType() && | ||||||
7832 | RequireLiteralType(NewVD->getLocation(), T, | ||||||
7833 | diag::err_constexpr_var_non_literal)) { | ||||||
7834 | NewVD->setInvalidDecl(); | ||||||
7835 | return; | ||||||
7836 | } | ||||||
7837 | } | ||||||
7838 | |||||||
7839 | /// Perform semantic checking on a newly-created variable | ||||||
7840 | /// declaration. | ||||||
7841 | /// | ||||||
7842 | /// This routine performs all of the type-checking required for a | ||||||
7843 | /// variable declaration once it has been built. It is used both to | ||||||
7844 | /// check variables after they have been parsed and their declarators | ||||||
7845 | /// have been translated into a declaration, and to check variables | ||||||
7846 | /// that have been instantiated from a template. | ||||||
7847 | /// | ||||||
7848 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | ||||||
7849 | /// | ||||||
7850 | /// Returns true if the variable declaration is a redeclaration. | ||||||
7851 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | ||||||
7852 | CheckVariableDeclarationType(NewVD); | ||||||
7853 | |||||||
7854 | // If the decl is already known invalid, don't check it. | ||||||
7855 | if (NewVD->isInvalidDecl()) | ||||||
7856 | return false; | ||||||
7857 | |||||||
7858 | // If we did not find anything by this name, look for a non-visible | ||||||
7859 | // extern "C" declaration with the same name. | ||||||
7860 | if (Previous.empty() && | ||||||
7861 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | ||||||
7862 | Previous.setShadowed(); | ||||||
7863 | |||||||
7864 | if (!Previous.empty()) { | ||||||
7865 | MergeVarDecl(NewVD, Previous); | ||||||
7866 | return true; | ||||||
7867 | } | ||||||
7868 | return false; | ||||||
7869 | } | ||||||
7870 | |||||||
7871 | namespace { | ||||||
7872 | struct FindOverriddenMethod { | ||||||
7873 | Sema *S; | ||||||
7874 | CXXMethodDecl *Method; | ||||||
7875 | |||||||
7876 | /// Member lookup function that determines whether a given C++ | ||||||
7877 | /// method overrides a method in a base class, to be used with | ||||||
7878 | /// CXXRecordDecl::lookupInBases(). | ||||||
7879 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | ||||||
7880 | RecordDecl *BaseRecord = | ||||||
7881 | Specifier->getType()->castAs<RecordType>()->getDecl(); | ||||||
7882 | |||||||
7883 | DeclarationName Name = Method->getDeclName(); | ||||||
7884 | |||||||
7885 | // FIXME: Do we care about other names here too? | ||||||
7886 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
7887 | // We really want to find the base class destructor here. | ||||||
7888 | QualType T = S->Context.getTypeDeclType(BaseRecord); | ||||||
7889 | CanQualType CT = S->Context.getCanonicalType(T); | ||||||
7890 | |||||||
7891 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); | ||||||
7892 | } | ||||||
7893 | |||||||
7894 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | ||||||
7895 | Path.Decls = Path.Decls.slice(1)) { | ||||||
7896 | NamedDecl *D = Path.Decls.front(); | ||||||
7897 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||||
7898 | if (MD->isVirtual() && | ||||||
7899 | !S->IsOverload( | ||||||
7900 | Method, MD, /*UseMemberUsingDeclRules=*/false, | ||||||
7901 | /*ConsiderCudaAttrs=*/true, | ||||||
7902 | // C++2a [class.virtual]p2 does not consider requires clauses | ||||||
7903 | // when overriding. | ||||||
7904 | /*ConsiderRequiresClauses=*/false)) | ||||||
7905 | return true; | ||||||
7906 | } | ||||||
7907 | } | ||||||
7908 | |||||||
7909 | return false; | ||||||
7910 | } | ||||||
7911 | }; | ||||||
7912 | |||||||
7913 | enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; | ||||||
7914 | } // end anonymous namespace | ||||||
7915 | |||||||
7916 | /// Report an error regarding overriding, along with any relevant | ||||||
7917 | /// overridden methods. | ||||||
7918 | /// | ||||||
7919 | /// \param DiagID the primary error to report. | ||||||
7920 | /// \param MD the overriding method. | ||||||
7921 | /// \param OEK which overrides to include as notes. | ||||||
7922 | static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, | ||||||
7923 | OverrideErrorKind OEK = OEK_All) { | ||||||
7924 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | ||||||
7925 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | ||||||
7926 | // This check (& the OEK parameter) could be replaced by a predicate, but | ||||||
7927 | // without lambdas that would be overkill. This is still nicer than writing | ||||||
7928 | // out the diag loop 3 times. | ||||||
7929 | if ((OEK == OEK_All) || | ||||||
7930 | (OEK == OEK_NonDeleted && !O->isDeleted()) || | ||||||
7931 | (OEK == OEK_Deleted && O->isDeleted())) | ||||||
7932 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); | ||||||
7933 | } | ||||||
7934 | } | ||||||
7935 | |||||||
7936 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | ||||||
7937 | /// and if so, check that it's a valid override and remember it. | ||||||
7938 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | ||||||
7939 | // Look for methods in base classes that this method might override. | ||||||
7940 | CXXBasePaths Paths; | ||||||
7941 | FindOverriddenMethod FOM; | ||||||
7942 | FOM.Method = MD; | ||||||
7943 | FOM.S = this; | ||||||
7944 | bool hasDeletedOverridenMethods = false; | ||||||
7945 | bool hasNonDeletedOverridenMethods = false; | ||||||
7946 | bool AddedAny = false; | ||||||
7947 | if (DC->lookupInBases(FOM, Paths)) { | ||||||
7948 | for (auto *I : Paths.found_decls()) { | ||||||
7949 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { | ||||||
7950 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); | ||||||
7951 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && | ||||||
7952 | !CheckOverridingFunctionAttributes(MD, OldMD) && | ||||||
7953 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && | ||||||
7954 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { | ||||||
7955 | hasDeletedOverridenMethods |= OldMD->isDeleted(); | ||||||
7956 | hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); | ||||||
7957 | AddedAny = true; | ||||||
7958 | } | ||||||
7959 | } | ||||||
7960 | } | ||||||
7961 | } | ||||||
7962 | |||||||
7963 | if (hasDeletedOverridenMethods && !MD->isDeleted()) { | ||||||
7964 | ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); | ||||||
7965 | } | ||||||
7966 | if (hasNonDeletedOverridenMethods && MD->isDeleted()) { | ||||||
7967 | ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); | ||||||
7968 | } | ||||||
7969 | |||||||
7970 | return AddedAny; | ||||||
7971 | } | ||||||
7972 | |||||||
7973 | namespace { | ||||||
7974 | // Struct for holding all of the extra arguments needed by | ||||||
7975 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | ||||||
7976 | struct ActOnFDArgs { | ||||||
7977 | Scope *S; | ||||||
7978 | Declarator &D; | ||||||
7979 | MultiTemplateParamsArg TemplateParamLists; | ||||||
7980 | bool AddToScope; | ||||||
7981 | }; | ||||||
7982 | } // end anonymous namespace | ||||||
7983 | |||||||
7984 | namespace { | ||||||
7985 | |||||||
7986 | // Callback to only accept typo corrections that have a non-zero edit distance. | ||||||
7987 | // Also only accept corrections that have the same parent decl. | ||||||
7988 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | ||||||
7989 | public: | ||||||
7990 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | ||||||
7991 | CXXRecordDecl *Parent) | ||||||
7992 | : Context(Context), OriginalFD(TypoFD), | ||||||
7993 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | ||||||
7994 | |||||||
7995 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||
7996 | if (candidate.getEditDistance() == 0) | ||||||
7997 | return false; | ||||||
7998 | |||||||
7999 | SmallVector<unsigned, 1> MismatchedParams; | ||||||
8000 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | ||||||
8001 | CDeclEnd = candidate.end(); | ||||||
8002 | CDecl != CDeclEnd; ++CDecl) { | ||||||
8003 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||||
8004 | |||||||
8005 | if (FD && !FD->hasBody() && | ||||||
8006 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | ||||||
8007 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
8008 | CXXRecordDecl *Parent = MD->getParent(); | ||||||
8009 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | ||||||
8010 | return true; | ||||||
8011 | } else if (!ExpectedParent) { | ||||||
8012 | return true; | ||||||
8013 | } | ||||||
8014 | } | ||||||
8015 | } | ||||||
8016 | |||||||
8017 | return false; | ||||||
8018 | } | ||||||
8019 | |||||||
8020 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||
8021 | return std::make_unique<DifferentNameValidatorCCC>(*this); | ||||||
8022 | } | ||||||
8023 | |||||||
8024 | private: | ||||||
8025 | ASTContext &Context; | ||||||
8026 | FunctionDecl *OriginalFD; | ||||||
8027 | CXXRecordDecl *ExpectedParent; | ||||||
8028 | }; | ||||||
8029 | |||||||
8030 | } // end anonymous namespace | ||||||
8031 | |||||||
8032 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | ||||||
8033 | TypoCorrectedFunctionDefinitions.insert(F); | ||||||
8034 | } | ||||||
8035 | |||||||
8036 | /// Generate diagnostics for an invalid function redeclaration. | ||||||
8037 | /// | ||||||
8038 | /// This routine handles generating the diagnostic messages for an invalid | ||||||
8039 | /// function redeclaration, including finding possible similar declarations | ||||||
8040 | /// or performing typo correction if there are no previous declarations with | ||||||
8041 | /// the same name. | ||||||
8042 | /// | ||||||
8043 | /// Returns a NamedDecl iff typo correction was performed and substituting in | ||||||
8044 | /// the new declaration name does not cause new errors. | ||||||
8045 | static NamedDecl *DiagnoseInvalidRedeclaration( | ||||||
8046 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | ||||||
8047 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | ||||||
8048 | DeclarationName Name = NewFD->getDeclName(); | ||||||
8049 | DeclContext *NewDC = NewFD->getDeclContext(); | ||||||
8050 | SmallVector<unsigned, 1> MismatchedParams; | ||||||
8051 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | ||||||
8052 | TypoCorrection Correction; | ||||||
8053 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | ||||||
8054 | unsigned DiagMsg = | ||||||
8055 | IsLocalFriend ? diag::err_no_matching_local_friend : | ||||||
8056 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | ||||||
8057 | diag::err_member_decl_does_not_match; | ||||||
8058 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | ||||||
8059 | IsLocalFriend ? Sema::LookupLocalFriendName | ||||||
8060 | : Sema::LookupOrdinaryName, | ||||||
8061 | Sema::ForVisibleRedeclaration); | ||||||
8062 | |||||||
8063 | NewFD->setInvalidDecl(); | ||||||
8064 | if (IsLocalFriend) | ||||||
8065 | SemaRef.LookupName(Prev, S); | ||||||
8066 | else | ||||||
8067 | SemaRef.LookupQualifiedName(Prev, NewDC); | ||||||
8068 | assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8069, __PRETTY_FUNCTION__)) | ||||||
8069 | "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8069, __PRETTY_FUNCTION__)); | ||||||
8070 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||||
8071 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | ||||||
8072 | MD ? MD->getParent() : nullptr); | ||||||
8073 | if (!Prev.empty()) { | ||||||
8074 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | ||||||
8075 | Func != FuncEnd; ++Func) { | ||||||
8076 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | ||||||
8077 | if (FD && | ||||||
8078 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||||
8079 | // Add 1 to the index so that 0 can mean the mismatch didn't | ||||||
8080 | // involve a parameter | ||||||
8081 | unsigned ParamNum = | ||||||
8082 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | ||||||
8083 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | ||||||
8084 | } | ||||||
8085 | } | ||||||
8086 | // If the qualified name lookup yielded nothing, try typo correction | ||||||
8087 | } else if ((Correction = SemaRef.CorrectTypo( | ||||||
8088 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | ||||||
8089 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | ||||||
8090 | IsLocalFriend ? nullptr : NewDC))) { | ||||||
8091 | // Set up everything for the call to ActOnFunctionDeclarator | ||||||
8092 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | ||||||
8093 | ExtraArgs.D.getIdentifierLoc()); | ||||||
8094 | Previous.clear(); | ||||||
8095 | Previous.setLookupName(Correction.getCorrection()); | ||||||
8096 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | ||||||
8097 | CDeclEnd = Correction.end(); | ||||||
8098 | CDecl != CDeclEnd; ++CDecl) { | ||||||
8099 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||||
8100 | if (FD && !FD->hasBody() && | ||||||
8101 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||||
8102 | Previous.addDecl(FD); | ||||||
8103 | } | ||||||
8104 | } | ||||||
8105 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | ||||||
8106 | |||||||
8107 | NamedDecl *Result; | ||||||
8108 | // Retry building the function declaration with the new previous | ||||||
8109 | // declarations, and with errors suppressed. | ||||||
8110 | { | ||||||
8111 | // Trap errors. | ||||||
8112 | Sema::SFINAETrap Trap(SemaRef); | ||||||
8113 | |||||||
8114 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | ||||||
8115 | // pieces need to verify the typo-corrected C++ declaration and hopefully | ||||||
8116 | // eliminate the need for the parameter pack ExtraArgs. | ||||||
8117 | Result = SemaRef.ActOnFunctionDeclarator( | ||||||
8118 | ExtraArgs.S, ExtraArgs.D, | ||||||
8119 | Correction.getCorrectionDecl()->getDeclContext(), | ||||||
8120 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | ||||||
8121 | ExtraArgs.AddToScope); | ||||||
8122 | |||||||
8123 | if (Trap.hasErrorOccurred()) | ||||||
8124 | Result = nullptr; | ||||||
8125 | } | ||||||
8126 | |||||||
8127 | if (Result) { | ||||||
8128 | // Determine which correction we picked. | ||||||
8129 | Decl *Canonical = Result->getCanonicalDecl(); | ||||||
8130 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||||
8131 | I != E; ++I) | ||||||
8132 | if ((*I)->getCanonicalDecl() == Canonical) | ||||||
8133 | Correction.setCorrectionDecl(*I); | ||||||
8134 | |||||||
8135 | // Let Sema know about the correction. | ||||||
8136 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | ||||||
8137 | SemaRef.diagnoseTypo( | ||||||
8138 | Correction, | ||||||
8139 | SemaRef.PDiag(IsLocalFriend | ||||||
8140 | ? diag::err_no_matching_local_friend_suggest | ||||||
8141 | : diag::err_member_decl_does_not_match_suggest) | ||||||
8142 | << Name << NewDC << IsDefinition); | ||||||
8143 | return Result; | ||||||
8144 | } | ||||||
8145 | |||||||
8146 | // Pretend the typo correction never occurred | ||||||
8147 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | ||||||
8148 | ExtraArgs.D.getIdentifierLoc()); | ||||||
8149 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | ||||||
8150 | Previous.clear(); | ||||||
8151 | Previous.setLookupName(Name); | ||||||
8152 | } | ||||||
8153 | |||||||
8154 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | ||||||
8155 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | ||||||
8156 | |||||||
8157 | bool NewFDisConst = false; | ||||||
8158 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | ||||||
8159 | NewFDisConst = NewMD->isConst(); | ||||||
8160 | |||||||
8161 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | ||||||
8162 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | ||||||
8163 | NearMatch != NearMatchEnd; ++NearMatch) { | ||||||
8164 | FunctionDecl *FD = NearMatch->first; | ||||||
8165 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
8166 | bool FDisConst = MD && MD->isConst(); | ||||||
8167 | bool IsMember = MD || !IsLocalFriend; | ||||||
8168 | |||||||
8169 | // FIXME: These notes are poorly worded for the local friend case. | ||||||
8170 | if (unsigned Idx = NearMatch->second) { | ||||||
8171 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | ||||||
8172 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | ||||||
8173 | if (Loc.isInvalid()) Loc = FD->getLocation(); | ||||||
8174 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | ||||||
8175 | : diag::note_local_decl_close_param_match) | ||||||
8176 | << Idx << FDParam->getType() | ||||||
8177 | << NewFD->getParamDecl(Idx - 1)->getType(); | ||||||
8178 | } else if (FDisConst != NewFDisConst) { | ||||||
8179 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | ||||||
8180 | << NewFDisConst << FD->getSourceRange().getEnd(); | ||||||
8181 | } else | ||||||
8182 | SemaRef.Diag(FD->getLocation(), | ||||||
8183 | IsMember ? diag::note_member_def_close_match | ||||||
8184 | : diag::note_local_decl_close_match); | ||||||
8185 | } | ||||||
8186 | return nullptr; | ||||||
8187 | } | ||||||
8188 | |||||||
8189 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | ||||||
8190 | switch (D.getDeclSpec().getStorageClassSpec()) { | ||||||
8191 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8191); | ||||||
8192 | case DeclSpec::SCS_auto: | ||||||
8193 | case DeclSpec::SCS_register: | ||||||
8194 | case DeclSpec::SCS_mutable: | ||||||
8195 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8196 | diag::err_typecheck_sclass_func); | ||||||
8197 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||||
8198 | D.setInvalidType(); | ||||||
8199 | break; | ||||||
8200 | case DeclSpec::SCS_unspecified: break; | ||||||
8201 | case DeclSpec::SCS_extern: | ||||||
8202 | if (D.getDeclSpec().isExternInLinkageSpec()) | ||||||
8203 | return SC_None; | ||||||
8204 | return SC_Extern; | ||||||
8205 | case DeclSpec::SCS_static: { | ||||||
8206 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | ||||||
8207 | // C99 6.7.1p5: | ||||||
8208 | // The declaration of an identifier for a function that has | ||||||
8209 | // block scope shall have no explicit storage-class specifier | ||||||
8210 | // other than extern | ||||||
8211 | // See also (C++ [dcl.stc]p4). | ||||||
8212 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8213 | diag::err_static_block_func); | ||||||
8214 | break; | ||||||
8215 | } else | ||||||
8216 | return SC_Static; | ||||||
8217 | } | ||||||
8218 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||||
8219 | } | ||||||
8220 | |||||||
8221 | // No explicit storage class has already been returned | ||||||
8222 | return SC_None; | ||||||
8223 | } | ||||||
8224 | |||||||
8225 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | ||||||
8226 | DeclContext *DC, QualType &R, | ||||||
8227 | TypeSourceInfo *TInfo, | ||||||
8228 | StorageClass SC, | ||||||
8229 | bool &IsVirtualOkay) { | ||||||
8230 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | ||||||
8231 | DeclarationName Name = NameInfo.getName(); | ||||||
8232 | |||||||
8233 | FunctionDecl *NewFD = nullptr; | ||||||
8234 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||||
8235 | |||||||
8236 | if (!SemaRef.getLangOpts().CPlusPlus) { | ||||||
8237 | // Determine whether the function was written with a | ||||||
8238 | // prototype. This true when: | ||||||
8239 | // - there is a prototype in the declarator, or | ||||||
8240 | // - the type R of the function is some kind of typedef or other non- | ||||||
8241 | // attributed reference to a type name (which eventually refers to a | ||||||
8242 | // function type). | ||||||
8243 | bool HasPrototype = | ||||||
8244 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | ||||||
8245 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | ||||||
8246 | |||||||
8247 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||||
8248 | R, TInfo, SC, isInline, HasPrototype, | ||||||
8249 | CSK_unspecified, | ||||||
8250 | /*TrailingRequiresClause=*/nullptr); | ||||||
8251 | if (D.isInvalidType()) | ||||||
8252 | NewFD->setInvalidDecl(); | ||||||
8253 | |||||||
8254 | return NewFD; | ||||||
8255 | } | ||||||
8256 | |||||||
8257 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | ||||||
8258 | |||||||
8259 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | ||||||
8260 | if (ConstexprKind == CSK_constinit) { | ||||||
8261 | SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
8262 | diag::err_constexpr_wrong_decl_kind) | ||||||
8263 | << ConstexprKind; | ||||||
8264 | ConstexprKind = CSK_unspecified; | ||||||
8265 | D.getMutableDeclSpec().ClearConstexprSpec(); | ||||||
8266 | } | ||||||
8267 | Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); | ||||||
8268 | |||||||
8269 | // Check that the return type is not an abstract class type. | ||||||
8270 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||||
8271 | // the class has been completely parsed. | ||||||
8272 | if (!DC->isRecord() && | ||||||
8273 | SemaRef.RequireNonAbstractType( | ||||||
8274 | D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), | ||||||
8275 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | ||||||
8276 | D.setInvalidType(); | ||||||
8277 | |||||||
8278 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | ||||||
8279 | // This is a C++ constructor declaration. | ||||||
8280 | assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8281, __PRETTY_FUNCTION__)) | ||||||
8281 | "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8281, __PRETTY_FUNCTION__)); | ||||||
8282 | |||||||
8283 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | ||||||
8284 | return CXXConstructorDecl::Create( | ||||||
8285 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8286 | TInfo, ExplicitSpecifier, isInline, | ||||||
8287 | /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), | ||||||
8288 | TrailingRequiresClause); | ||||||
8289 | |||||||
8290 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8291 | // This is a C++ destructor declaration. | ||||||
8292 | if (DC->isRecord()) { | ||||||
8293 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | ||||||
8294 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | ||||||
8295 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | ||||||
8296 | SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, | ||||||
8297 | isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, | ||||||
8298 | TrailingRequiresClause); | ||||||
8299 | |||||||
8300 | // If the destructor needs an implicit exception specification, set it | ||||||
8301 | // now. FIXME: It'd be nice to be able to create the right type to start | ||||||
8302 | // with, but the type needs to reference the destructor declaration. | ||||||
8303 | if (SemaRef.getLangOpts().CPlusPlus11) | ||||||
8304 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | ||||||
8305 | |||||||
8306 | IsVirtualOkay = true; | ||||||
8307 | return NewDD; | ||||||
8308 | |||||||
8309 | } else { | ||||||
8310 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | ||||||
8311 | D.setInvalidType(); | ||||||
8312 | |||||||
8313 | // Create a FunctionDecl to satisfy the function definition parsing | ||||||
8314 | // code path. | ||||||
8315 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||||
8316 | D.getIdentifierLoc(), Name, R, TInfo, SC, | ||||||
8317 | isInline, | ||||||
8318 | /*hasPrototype=*/true, ConstexprKind, | ||||||
8319 | TrailingRequiresClause); | ||||||
8320 | } | ||||||
8321 | |||||||
8322 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||||
8323 | if (!DC->isRecord()) { | ||||||
8324 | SemaRef.Diag(D.getIdentifierLoc(), | ||||||
8325 | diag::err_conv_function_not_member); | ||||||
8326 | return nullptr; | ||||||
8327 | } | ||||||
8328 | |||||||
8329 | SemaRef.CheckConversionDeclarator(D, R, SC); | ||||||
8330 | if (D.isInvalidType()) | ||||||
8331 | return nullptr; | ||||||
8332 | |||||||
8333 | IsVirtualOkay = true; | ||||||
8334 | return CXXConversionDecl::Create( | ||||||
8335 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8336 | TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), | ||||||
8337 | TrailingRequiresClause); | ||||||
8338 | |||||||
8339 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | ||||||
8340 | if (TrailingRequiresClause) | ||||||
8341 | SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), | ||||||
8342 | diag::err_trailing_requires_clause_on_deduction_guide) | ||||||
8343 | << TrailingRequiresClause->getSourceRange(); | ||||||
8344 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | ||||||
8345 | |||||||
8346 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||||
8347 | ExplicitSpecifier, NameInfo, R, TInfo, | ||||||
8348 | D.getEndLoc()); | ||||||
8349 | } else if (DC->isRecord()) { | ||||||
8350 | // If the name of the function is the same as the name of the record, | ||||||
8351 | // then this must be an invalid constructor that has a return type. | ||||||
8352 | // (The parser checks for a return type and makes the declarator a | ||||||
8353 | // constructor if it has no return type). | ||||||
8354 | if (Name.getAsIdentifierInfo() && | ||||||
8355 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | ||||||
8356 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | ||||||
8357 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | ||||||
8358 | << SourceRange(D.getIdentifierLoc()); | ||||||
8359 | return nullptr; | ||||||
8360 | } | ||||||
8361 | |||||||
8362 | // This is a C++ method declaration. | ||||||
8363 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | ||||||
8364 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8365 | TInfo, SC, isInline, ConstexprKind, SourceLocation(), | ||||||
8366 | TrailingRequiresClause); | ||||||
8367 | IsVirtualOkay = !Ret->isStatic(); | ||||||
8368 | return Ret; | ||||||
8369 | } else { | ||||||
8370 | bool isFriend = | ||||||
8371 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | ||||||
8372 | if (!isFriend && SemaRef.CurContext->isRecord()) | ||||||
8373 | return nullptr; | ||||||
8374 | |||||||
8375 | // Determine whether the function was written with a | ||||||
8376 | // prototype. This true when: | ||||||
8377 | // - we're in C++ (where every function has a prototype), | ||||||
8378 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||||
8379 | R, TInfo, SC, isInline, true /*HasPrototype*/, | ||||||
8380 | ConstexprKind, TrailingRequiresClause); | ||||||
8381 | } | ||||||
8382 | } | ||||||
8383 | |||||||
8384 | enum OpenCLParamType { | ||||||
8385 | ValidKernelParam, | ||||||
8386 | PtrPtrKernelParam, | ||||||
8387 | PtrKernelParam, | ||||||
8388 | InvalidAddrSpacePtrKernelParam, | ||||||
8389 | InvalidKernelParam, | ||||||
8390 | RecordKernelParam | ||||||
8391 | }; | ||||||
8392 | |||||||
8393 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | ||||||
8394 | // Size dependent types are just typedefs to normal integer types | ||||||
8395 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | ||||||
8396 | // integers other than by their names. | ||||||
8397 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | ||||||
8398 | |||||||
8399 | // Remove typedefs one by one until we reach a typedef | ||||||
8400 | // for a size dependent type. | ||||||
8401 | QualType DesugaredTy = Ty; | ||||||
8402 | do { | ||||||
8403 | ArrayRef<StringRef> Names(SizeTypeNames); | ||||||
8404 | auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); | ||||||
8405 | if (Names.end() != Match) | ||||||
8406 | return true; | ||||||
8407 | |||||||
8408 | Ty = DesugaredTy; | ||||||
8409 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | ||||||
8410 | } while (DesugaredTy != Ty); | ||||||
8411 | |||||||
8412 | return false; | ||||||
8413 | } | ||||||
8414 | |||||||
8415 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | ||||||
8416 | if (PT->isPointerType()) { | ||||||
8417 | QualType PointeeType = PT->getPointeeType(); | ||||||
8418 | if (PointeeType->isPointerType()) | ||||||
8419 | return PtrPtrKernelParam; | ||||||
8420 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | ||||||
8421 | PointeeType.getAddressSpace() == LangAS::opencl_private || | ||||||
8422 | PointeeType.getAddressSpace() == LangAS::Default) | ||||||
8423 | return InvalidAddrSpacePtrKernelParam; | ||||||
8424 | return PtrKernelParam; | ||||||
8425 | } | ||||||
8426 | |||||||
8427 | // OpenCL v1.2 s6.9.k: | ||||||
8428 | // Arguments to kernel functions in a program cannot be declared with the | ||||||
8429 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||||
8430 | // uintptr_t or a struct and/or union that contain fields declared to be one | ||||||
8431 | // of these built-in scalar types. | ||||||
8432 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | ||||||
8433 | return InvalidKernelParam; | ||||||
8434 | |||||||
8435 | if (PT->isImageType()) | ||||||
8436 | return PtrKernelParam; | ||||||
8437 | |||||||
8438 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | ||||||
8439 | return InvalidKernelParam; | ||||||
8440 | |||||||
8441 | // OpenCL extension spec v1.2 s9.5: | ||||||
8442 | // This extension adds support for half scalar and vector types as built-in | ||||||
8443 | // types that can be used for arithmetic operations, conversions etc. | ||||||
8444 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) | ||||||
8445 | return InvalidKernelParam; | ||||||
8446 | |||||||
8447 | if (PT->isRecordType()) | ||||||
8448 | return RecordKernelParam; | ||||||
8449 | |||||||
8450 | // Look into an array argument to check if it has a forbidden type. | ||||||
8451 | if (PT->isArrayType()) { | ||||||
8452 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | ||||||
8453 | // Call ourself to check an underlying type of an array. Since the | ||||||
8454 | // getPointeeOrArrayElementType returns an innermost type which is not an | ||||||
8455 | // array, this recursive call only happens once. | ||||||
8456 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | ||||||
8457 | } | ||||||
8458 | |||||||
8459 | return ValidKernelParam; | ||||||
8460 | } | ||||||
8461 | |||||||
8462 | static void checkIsValidOpenCLKernelParameter( | ||||||
8463 | Sema &S, | ||||||
8464 | Declarator &D, | ||||||
8465 | ParmVarDecl *Param, | ||||||
8466 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | ||||||
8467 | QualType PT = Param->getType(); | ||||||
8468 | |||||||
8469 | // Cache the valid types we encounter to avoid rechecking structs that are | ||||||
8470 | // used again | ||||||
8471 | if (ValidTypes.count(PT.getTypePtr())) | ||||||
8472 | return; | ||||||
8473 | |||||||
8474 | switch (getOpenCLKernelParameterType(S, PT)) { | ||||||
8475 | case PtrPtrKernelParam: | ||||||
8476 | // OpenCL v1.2 s6.9.a: | ||||||
8477 | // A kernel function argument cannot be declared as a | ||||||
8478 | // pointer to a pointer type. | ||||||
8479 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | ||||||
8480 | D.setInvalidType(); | ||||||
8481 | return; | ||||||
8482 | |||||||
8483 | case InvalidAddrSpacePtrKernelParam: | ||||||
8484 | // OpenCL v1.0 s6.5: | ||||||
8485 | // __kernel function arguments declared to be a pointer of a type can point | ||||||
8486 | // to one of the following address spaces only : __global, __local or | ||||||
8487 | // __constant. | ||||||
8488 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | ||||||
8489 | D.setInvalidType(); | ||||||
8490 | return; | ||||||
8491 | |||||||
8492 | // OpenCL v1.2 s6.9.k: | ||||||
8493 | // Arguments to kernel functions in a program cannot be declared with the | ||||||
8494 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||||
8495 | // uintptr_t or a struct and/or union that contain fields declared to be | ||||||
8496 | // one of these built-in scalar types. | ||||||
8497 | |||||||
8498 | case InvalidKernelParam: | ||||||
8499 | // OpenCL v1.2 s6.8 n: | ||||||
8500 | // A kernel function argument cannot be declared | ||||||
8501 | // of event_t type. | ||||||
8502 | // Do not diagnose half type since it is diagnosed as invalid argument | ||||||
8503 | // type for any function elsewhere. | ||||||
8504 | if (!PT->isHalfType()) { | ||||||
8505 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||||
8506 | |||||||
8507 | // Explain what typedefs are involved. | ||||||
8508 | const TypedefType *Typedef = nullptr; | ||||||
8509 | while ((Typedef = PT->getAs<TypedefType>())) { | ||||||
8510 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | ||||||
8511 | // SourceLocation may be invalid for a built-in type. | ||||||
8512 | if (Loc.isValid()) | ||||||
8513 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | ||||||
8514 | PT = Typedef->desugar(); | ||||||
8515 | } | ||||||
8516 | } | ||||||
8517 | |||||||
8518 | D.setInvalidType(); | ||||||
8519 | return; | ||||||
8520 | |||||||
8521 | case PtrKernelParam: | ||||||
8522 | case ValidKernelParam: | ||||||
8523 | ValidTypes.insert(PT.getTypePtr()); | ||||||
8524 | return; | ||||||
8525 | |||||||
8526 | case RecordKernelParam: | ||||||
8527 | break; | ||||||
8528 | } | ||||||
8529 | |||||||
8530 | // Track nested structs we will inspect | ||||||
8531 | SmallVector<const Decl *, 4> VisitStack; | ||||||
8532 | |||||||
8533 | // Track where we are in the nested structs. Items will migrate from | ||||||
8534 | // VisitStack to HistoryStack as we do the DFS for bad field. | ||||||
8535 | SmallVector<const FieldDecl *, 4> HistoryStack; | ||||||
8536 | HistoryStack.push_back(nullptr); | ||||||
8537 | |||||||
8538 | // At this point we already handled everything except of a RecordType or | ||||||
8539 | // an ArrayType of a RecordType. | ||||||
8540 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type." ) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8540, __PRETTY_FUNCTION__)); | ||||||
8541 | const RecordType *RecTy = | ||||||
8542 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | ||||||
8543 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | ||||||
8544 | |||||||
8545 | VisitStack.push_back(RecTy->getDecl()); | ||||||
8546 | assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast <void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8546, __PRETTY_FUNCTION__)); | ||||||
8547 | |||||||
8548 | do { | ||||||
8549 | const Decl *Next = VisitStack.pop_back_val(); | ||||||
8550 | if (!Next) { | ||||||
8551 | assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8551, __PRETTY_FUNCTION__)); | ||||||
8552 | // Found a marker, we have gone up a level | ||||||
8553 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | ||||||
8554 | ValidTypes.insert(Hist->getType().getTypePtr()); | ||||||
8555 | |||||||
8556 | continue; | ||||||
8557 | } | ||||||
8558 | |||||||
8559 | // Adds everything except the original parameter declaration (which is not a | ||||||
8560 | // field itself) to the history stack. | ||||||
8561 | const RecordDecl *RD; | ||||||
8562 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | ||||||
8563 | HistoryStack.push_back(Field); | ||||||
8564 | |||||||
8565 | QualType FieldTy = Field->getType(); | ||||||
8566 | // Other field types (known to be valid or invalid) are handled while we | ||||||
8567 | // walk around RecordDecl::fields(). | ||||||
8568 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8569, __PRETTY_FUNCTION__)) | ||||||
8569 | "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8569, __PRETTY_FUNCTION__)); | ||||||
8570 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | ||||||
8571 | |||||||
8572 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | ||||||
8573 | } else { | ||||||
8574 | RD = cast<RecordDecl>(Next); | ||||||
8575 | } | ||||||
8576 | |||||||
8577 | // Add a null marker so we know when we've gone back up a level | ||||||
8578 | VisitStack.push_back(nullptr); | ||||||
8579 | |||||||
8580 | for (const auto *FD : RD->fields()) { | ||||||
8581 | QualType QT = FD->getType(); | ||||||
8582 | |||||||
8583 | if (ValidTypes.count(QT.getTypePtr())) | ||||||
8584 | continue; | ||||||
8585 | |||||||
8586 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | ||||||
8587 | if (ParamType == ValidKernelParam) | ||||||
8588 | continue; | ||||||
8589 | |||||||
8590 | if (ParamType == RecordKernelParam) { | ||||||
8591 | VisitStack.push_back(FD); | ||||||
8592 | continue; | ||||||
8593 | } | ||||||
8594 | |||||||
8595 | // OpenCL v1.2 s6.9.p: | ||||||
8596 | // Arguments to kernel functions that are declared to be a struct or union | ||||||
8597 | // do not allow OpenCL objects to be passed as elements of the struct or | ||||||
8598 | // union. | ||||||
8599 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | ||||||
8600 | ParamType == InvalidAddrSpacePtrKernelParam) { | ||||||
8601 | S.Diag(Param->getLocation(), | ||||||
8602 | diag::err_record_with_pointers_kernel_param) | ||||||
8603 | << PT->isUnionType() | ||||||
8604 | << PT; | ||||||
8605 | } else { | ||||||
8606 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||||
8607 | } | ||||||
8608 | |||||||
8609 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | ||||||
8610 | << OrigRecDecl->getDeclName(); | ||||||
8611 | |||||||
8612 | // We have an error, now let's go back up through history and show where | ||||||
8613 | // the offending field came from | ||||||
8614 | for (ArrayRef<const FieldDecl *>::const_iterator | ||||||
8615 | I = HistoryStack.begin() + 1, | ||||||
8616 | E = HistoryStack.end(); | ||||||
8617 | I != E; ++I) { | ||||||
8618 | const FieldDecl *OuterField = *I; | ||||||
8619 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | ||||||
8620 | << OuterField->getType(); | ||||||
8621 | } | ||||||
8622 | |||||||
8623 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | ||||||
8624 | << QT->isPointerType() | ||||||
8625 | << QT; | ||||||
8626 | D.setInvalidType(); | ||||||
8627 | return; | ||||||
8628 | } | ||||||
8629 | } while (!VisitStack.empty()); | ||||||
8630 | } | ||||||
8631 | |||||||
8632 | /// Find the DeclContext in which a tag is implicitly declared if we see an | ||||||
8633 | /// elaborated type specifier in the specified context, and lookup finds | ||||||
8634 | /// nothing. | ||||||
8635 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | ||||||
8636 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | ||||||
8637 | DC = DC->getParent(); | ||||||
8638 | return DC; | ||||||
8639 | } | ||||||
8640 | |||||||
8641 | /// Find the Scope in which a tag is implicitly declared if we see an | ||||||
8642 | /// elaborated type specifier in the specified context, and lookup finds | ||||||
8643 | /// nothing. | ||||||
8644 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | ||||||
8645 | while (S->isClassScope() || | ||||||
8646 | (LangOpts.CPlusPlus && | ||||||
8647 | S->isFunctionPrototypeScope()) || | ||||||
8648 | ((S->getFlags() & Scope::DeclScope) == 0) || | ||||||
8649 | (S->getEntity() && S->getEntity()->isTransparentContext())) | ||||||
8650 | S = S->getParent(); | ||||||
8651 | return S; | ||||||
8652 | } | ||||||
8653 | |||||||
8654 | NamedDecl* | ||||||
8655 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | ||||||
8656 | TypeSourceInfo *TInfo, LookupResult &Previous, | ||||||
8657 | MultiTemplateParamsArg TemplateParamLists, | ||||||
8658 | bool &AddToScope) { | ||||||
8659 | QualType R = TInfo->getType(); | ||||||
8660 | |||||||
8661 | assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 8661, __PRETTY_FUNCTION__)); | ||||||
8662 | |||||||
8663 | // TODO: consider using NameInfo for diagnostic. | ||||||
8664 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||||
8665 | DeclarationName Name = NameInfo.getName(); | ||||||
8666 | StorageClass SC = getFunctionStorageClass(*this, D); | ||||||
8667 | |||||||
8668 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||||
8669 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
8670 | diag::err_invalid_thread) | ||||||
8671 | << DeclSpec::getSpecifierName(TSCS); | ||||||
8672 | |||||||
8673 | if (D.isFirstDeclarationOfMember()) | ||||||
8674 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | ||||||
8675 | D.getIdentifierLoc()); | ||||||
8676 | |||||||
8677 | bool isFriend = false; | ||||||
8678 | FunctionTemplateDecl *FunctionTemplate = nullptr; | ||||||
8679 | bool isMemberSpecialization = false; | ||||||
8680 | bool isFunctionTemplateSpecialization = false; | ||||||
8681 | |||||||
8682 | bool isDependentClassScopeExplicitSpecialization = false; | ||||||
8683 | bool HasExplicitTemplateArgs = false; | ||||||
8684 | TemplateArgumentListInfo TemplateArgs; | ||||||
8685 | |||||||
8686 | bool isVirtualOkay = false; | ||||||
8687 | |||||||
8688 | DeclContext *OriginalDC = DC; | ||||||
8689 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | ||||||
8690 | |||||||
8691 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | ||||||
8692 | isVirtualOkay); | ||||||
8693 | if (!NewFD) return nullptr; | ||||||
8694 | |||||||
8695 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | ||||||
8696 | NewFD->setTopLevelDeclInObjCContainer(); | ||||||
8697 | |||||||
8698 | // Set the lexical context. If this is a function-scope declaration, or has a | ||||||
8699 | // C++ scope specifier, or is the object of a friend declaration, the lexical | ||||||
8700 | // context will be different from the semantic context. | ||||||
8701 | NewFD->setLexicalDeclContext(CurContext); | ||||||
8702 | |||||||
8703 | if (IsLocalExternDecl) | ||||||
8704 | NewFD->setLocalExternDecl(); | ||||||
8705 | |||||||
8706 | if (getLangOpts().CPlusPlus) { | ||||||
8707 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||||
8708 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | ||||||
8709 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | ||||||
8710 | isFriend = D.getDeclSpec().isFriendSpecified(); | ||||||
8711 | if (isFriend && !isInline && D.isFunctionDefinition()) { | ||||||
8712 | // C++ [class.friend]p5 | ||||||
8713 | // A function can be defined in a friend declaration of a | ||||||
8714 | // class . . . . Such a function is implicitly inline. | ||||||
8715 | NewFD->setImplicitlyInline(); | ||||||
8716 | } | ||||||
8717 | |||||||
8718 | // If this is a method defined in an __interface, and is not a constructor | ||||||
8719 | // or an overloaded operator, then set the pure flag (isVirtual will already | ||||||
8720 | // return true). | ||||||
8721 | if (const CXXRecordDecl *Parent = | ||||||
8722 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | ||||||
8723 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | ||||||
8724 | NewFD->setPure(true); | ||||||
8725 | |||||||
8726 | // C++ [class.union]p2 | ||||||
8727 | // A union can have member functions, but not virtual functions. | ||||||
8728 | if (isVirtual && Parent->isUnion()) | ||||||
8729 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | ||||||
8730 | } | ||||||
8731 | |||||||
8732 | SetNestedNameSpecifier(*this, NewFD, D); | ||||||
8733 | isMemberSpecialization = false; | ||||||
8734 | isFunctionTemplateSpecialization = false; | ||||||
8735 | if (D.isInvalidType()) | ||||||
8736 | NewFD->setInvalidDecl(); | ||||||
8737 | |||||||
8738 | // Match up the template parameter lists with the scope specifier, then | ||||||
8739 | // determine whether we have a template or a template specialization. | ||||||
8740 | bool Invalid = false; | ||||||
8741 | if (TemplateParameterList *TemplateParams = | ||||||
8742 | MatchTemplateParametersToScopeSpecifier( | ||||||
8743 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||||
8744 | D.getCXXScopeSpec(), | ||||||
8745 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||||
8746 | ? D.getName().TemplateId | ||||||
8747 | : nullptr, | ||||||
8748 | TemplateParamLists, isFriend, isMemberSpecialization, | ||||||
8749 | Invalid)) { | ||||||
8750 | if (TemplateParams->size() > 0) { | ||||||
8751 | // This is a function template | ||||||
8752 | |||||||
8753 | // Check that we can declare a template here. | ||||||
8754 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||||
8755 | NewFD->setInvalidDecl(); | ||||||
8756 | |||||||
8757 | // A destructor cannot be a template. | ||||||
8758 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8759 | Diag(NewFD->getLocation(), diag::err_destructor_template); | ||||||
8760 | NewFD->setInvalidDecl(); | ||||||
8761 | } | ||||||
8762 | |||||||
8763 | // If we're adding a template to a dependent context, we may need to | ||||||
8764 | // rebuilding some of the types used within the template parameter list, | ||||||
8765 | // now that we know what the current instantiation is. | ||||||
8766 | if (DC->isDependentContext()) { | ||||||
8767 | ContextRAII SavedContext(*this, DC); | ||||||
8768 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | ||||||
8769 | Invalid = true; | ||||||
8770 | } | ||||||
8771 | |||||||
8772 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | ||||||
8773 | NewFD->getLocation(), | ||||||
8774 | Name, TemplateParams, | ||||||
8775 | NewFD); | ||||||
8776 | FunctionTemplate->setLexicalDeclContext(CurContext); | ||||||
8777 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | ||||||
8778 | |||||||
8779 | // For source fidelity, store the other template param lists. | ||||||
8780 | if (TemplateParamLists.size() > 1) { | ||||||
8781 | NewFD->setTemplateParameterListsInfo(Context, | ||||||
8782 | TemplateParamLists.drop_back(1)); | ||||||
8783 | } | ||||||
8784 | } else { | ||||||
8785 | // This is a function template specialization. | ||||||
8786 | isFunctionTemplateSpecialization = true; | ||||||
8787 | // For source fidelity, store all the template param lists. | ||||||
8788 | if (TemplateParamLists.size() > 0) | ||||||
8789 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||||
8790 | |||||||
8791 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | ||||||
8792 | if (isFriend) { | ||||||
8793 | // We want to remove the "template<>", found here. | ||||||
8794 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | ||||||
8795 | |||||||
8796 | // If we remove the template<> and the name is not a | ||||||
8797 | // template-id, we're actually silently creating a problem: | ||||||
8798 | // the friend declaration will refer to an untemplated decl, | ||||||
8799 | // and clearly the user wants a template specialization. So | ||||||
8800 | // we need to insert '<>' after the name. | ||||||
8801 | SourceLocation InsertLoc; | ||||||
8802 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||||
8803 | InsertLoc = D.getName().getSourceRange().getEnd(); | ||||||
8804 | InsertLoc = getLocForEndOfToken(InsertLoc); | ||||||
8805 | } | ||||||
8806 | |||||||
8807 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | ||||||
8808 | << Name << RemoveRange | ||||||
8809 | << FixItHint::CreateRemoval(RemoveRange) | ||||||
8810 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | ||||||
8811 | } | ||||||
8812 | } | ||||||
8813 | } else { | ||||||
8814 | // All template param lists were matched against the scope specifier: | ||||||
8815 | // this is NOT (an explicit specialization of) a template. | ||||||
8816 | if (TemplateParamLists.size() > 0) | ||||||
8817 | // For source fidelity, store all the template param lists. | ||||||
8818 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||||
8819 | } | ||||||
8820 | |||||||
8821 | if (Invalid) { | ||||||
8822 | NewFD->setInvalidDecl(); | ||||||
8823 | if (FunctionTemplate) | ||||||
8824 | FunctionTemplate->setInvalidDecl(); | ||||||
8825 | } | ||||||
8826 | |||||||
8827 | // C++ [dcl.fct.spec]p5: | ||||||
8828 | // The virtual specifier shall only be used in declarations of | ||||||
8829 | // nonstatic class member functions that appear within a | ||||||
8830 | // member-specification of a class declaration; see 10.3. | ||||||
8831 | // | ||||||
8832 | if (isVirtual && !NewFD->isInvalidDecl()) { | ||||||
8833 | if (!isVirtualOkay) { | ||||||
8834 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
8835 | diag::err_virtual_non_function); | ||||||
8836 | } else if (!CurContext->isRecord()) { | ||||||
8837 | // 'virtual' was specified outside of the class. | ||||||
8838 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
8839 | diag::err_virtual_out_of_class) | ||||||
8840 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||||
8841 | } else if (NewFD->getDescribedFunctionTemplate()) { | ||||||
8842 | // C++ [temp.mem]p3: | ||||||
8843 | // A member function template shall not be virtual. | ||||||
8844 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
8845 | diag::err_virtual_member_function_template) | ||||||
8846 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||||
8847 | } else { | ||||||
8848 | // Okay: Add virtual to the method. | ||||||
8849 | NewFD->setVirtualAsWritten(true); | ||||||
8850 | } | ||||||
8851 | |||||||
8852 | if (getLangOpts().CPlusPlus14 && | ||||||
8853 | NewFD->getReturnType()->isUndeducedType()) | ||||||
8854 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | ||||||
8855 | } | ||||||
8856 | |||||||
8857 | if (getLangOpts().CPlusPlus14 && | ||||||
8858 | (NewFD->isDependentContext() || | ||||||
8859 | (isFriend && CurContext->isDependentContext())) && | ||||||
8860 | NewFD->getReturnType()->isUndeducedType()) { | ||||||
8861 | // If the function template is referenced directly (for instance, as a | ||||||
8862 | // member of the current instantiation), pretend it has a dependent type. | ||||||
8863 | // This is not really justified by the standard, but is the only sane | ||||||
8864 | // thing to do. | ||||||
8865 | // FIXME: For a friend function, we have not marked the function as being | ||||||
8866 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | ||||||
8867 | const FunctionProtoType *FPT = | ||||||
8868 | NewFD->getType()->castAs<FunctionProtoType>(); | ||||||
8869 | QualType Result = | ||||||
8870 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); | ||||||
8871 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | ||||||
8872 | FPT->getExtProtoInfo())); | ||||||
8873 | } | ||||||
8874 | |||||||
8875 | // C++ [dcl.fct.spec]p3: | ||||||
8876 | // The inline specifier shall not appear on a block scope function | ||||||
8877 | // declaration. | ||||||
8878 | if (isInline && !NewFD->isInvalidDecl()) { | ||||||
8879 | if (CurContext->isFunctionOrMethod()) { | ||||||
8880 | // 'inline' is not allowed on block scope function declaration. | ||||||
8881 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
8882 | diag::err_inline_declaration_block_scope) << Name | ||||||
8883 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||||
8884 | } | ||||||
8885 | } | ||||||
8886 | |||||||
8887 | // C++ [dcl.fct.spec]p6: | ||||||
8888 | // The explicit specifier shall be used only in the declaration of a | ||||||
8889 | // constructor or conversion function within its class definition; | ||||||
8890 | // see 12.3.1 and 12.3.2. | ||||||
8891 | if (hasExplicit && !NewFD->isInvalidDecl() && | ||||||
8892 | !isa<CXXDeductionGuideDecl>(NewFD)) { | ||||||
8893 | if (!CurContext->isRecord()) { | ||||||
8894 | // 'explicit' was specified outside of the class. | ||||||
8895 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||||
8896 | diag::err_explicit_out_of_class) | ||||||
8897 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||||
8898 | } else if (!isa<CXXConstructorDecl>(NewFD) && | ||||||
8899 | !isa<CXXConversionDecl>(NewFD)) { | ||||||
8900 | // 'explicit' was specified on a function that wasn't a constructor | ||||||
8901 | // or conversion function. | ||||||
8902 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||||
8903 | diag::err_explicit_non_ctor_or_conv_function) | ||||||
8904 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||||
8905 | } | ||||||
8906 | } | ||||||
8907 | |||||||
8908 | if (ConstexprSpecKind ConstexprKind = | ||||||
8909 | D.getDeclSpec().getConstexprSpecifier()) { | ||||||
8910 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | ||||||
8911 | // are implicitly inline. | ||||||
8912 | NewFD->setImplicitlyInline(); | ||||||
8913 | |||||||
8914 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | ||||||
8915 | // be either constructors or to return a literal type. Therefore, | ||||||
8916 | // destructors cannot be declared constexpr. | ||||||
8917 | if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) { | ||||||
8918 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) | ||||||
8919 | << ConstexprKind; | ||||||
8920 | } | ||||||
8921 | } | ||||||
8922 | |||||||
8923 | // If __module_private__ was specified, mark the function accordingly. | ||||||
8924 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
8925 | if (isFunctionTemplateSpecialization) { | ||||||
8926 | SourceLocation ModulePrivateLoc | ||||||
8927 | = D.getDeclSpec().getModulePrivateSpecLoc(); | ||||||
8928 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | ||||||
8929 | << 0 | ||||||
8930 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||||
8931 | } else { | ||||||
8932 | NewFD->setModulePrivate(); | ||||||
8933 | if (FunctionTemplate) | ||||||
8934 | FunctionTemplate->setModulePrivate(); | ||||||
8935 | } | ||||||
8936 | } | ||||||
8937 | |||||||
8938 | if (isFriend) { | ||||||
8939 | if (FunctionTemplate) { | ||||||
8940 | FunctionTemplate->setObjectOfFriendDecl(); | ||||||
8941 | FunctionTemplate->setAccess(AS_public); | ||||||
8942 | } | ||||||
8943 | NewFD->setObjectOfFriendDecl(); | ||||||
8944 | NewFD->setAccess(AS_public); | ||||||
8945 | } | ||||||
8946 | |||||||
8947 | // If a function is defined as defaulted or deleted, mark it as such now. | ||||||
8948 | // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function | ||||||
8949 | // definition kind to FDK_Definition. | ||||||
8950 | switch (D.getFunctionDefinitionKind()) { | ||||||
8951 | case FDK_Declaration: | ||||||
8952 | case FDK_Definition: | ||||||
8953 | break; | ||||||
8954 | |||||||
8955 | case FDK_Defaulted: | ||||||
8956 | NewFD->setDefaulted(); | ||||||
8957 | break; | ||||||
8958 | |||||||
8959 | case FDK_Deleted: | ||||||
8960 | NewFD->setDeletedAsWritten(); | ||||||
8961 | break; | ||||||
8962 | } | ||||||
8963 | |||||||
8964 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | ||||||
8965 | D.isFunctionDefinition()) { | ||||||
8966 | // C++ [class.mfct]p2: | ||||||
8967 | // A member function may be defined (8.4) in its class definition, in | ||||||
8968 | // which case it is an inline member function (7.1.2) | ||||||
8969 | NewFD->setImplicitlyInline(); | ||||||
8970 | } | ||||||
8971 | |||||||
8972 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | ||||||
8973 | !CurContext->isRecord()) { | ||||||
8974 | // C++ [class.static]p1: | ||||||
8975 | // A data or function member of a class may be declared static | ||||||
8976 | // in a class definition, in which case it is a static member of | ||||||
8977 | // the class. | ||||||
8978 | |||||||
8979 | // Complain about the 'static' specifier if it's on an out-of-line | ||||||
8980 | // member function definition. | ||||||
8981 | |||||||
8982 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | ||||||
8983 | // member function template declaration and class member template | ||||||
8984 | // declaration (MSVC versions before 2015), warn about this. | ||||||
8985 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8986 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||||
8987 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | ||||||
8988 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | ||||||
8989 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | ||||||
8990 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
8991 | } | ||||||
8992 | |||||||
8993 | // C++11 [except.spec]p15: | ||||||
8994 | // A deallocation function with no exception-specification is treated | ||||||
8995 | // as if it were specified with noexcept(true). | ||||||
8996 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | ||||||
8997 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | ||||||
8998 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | ||||||
8999 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | ||||||
9000 | NewFD->setType(Context.getFunctionType( | ||||||
9001 | FPT->getReturnType(), FPT->getParamTypes(), | ||||||
9002 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | ||||||
9003 | } | ||||||
9004 | |||||||
9005 | // Filter out previous declarations that don't match the scope. | ||||||
9006 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | ||||||
9007 | D.getCXXScopeSpec().isNotEmpty() || | ||||||
9008 | isMemberSpecialization || | ||||||
9009 | isFunctionTemplateSpecialization); | ||||||
9010 | |||||||
9011 | // Handle GNU asm-label extension (encoded as an attribute). | ||||||
9012 | if (Expr *E = (Expr*) D.getAsmLabel()) { | ||||||
9013 | // The parser guarantees this is a string. | ||||||
9014 | StringLiteral *SE = cast<StringLiteral>(E); | ||||||
9015 | NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), | ||||||
9016 | /*IsLiteralLabel=*/true, | ||||||
9017 | SE->getStrTokenLoc(0))); | ||||||
9018 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||||
9019 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||||
9020 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | ||||||
9021 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||||
9022 | if (isDeclExternC(NewFD)) { | ||||||
9023 | NewFD->addAttr(I->second); | ||||||
9024 | ExtnameUndeclaredIdentifiers.erase(I); | ||||||
9025 | } else | ||||||
9026 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
9027 | << /*Variable*/0 << NewFD; | ||||||
9028 | } | ||||||
9029 | } | ||||||
9030 | |||||||
9031 | // Copy the parameter declarations from the declarator D to the function | ||||||
9032 | // declaration NewFD, if they are available. First scavenge them into Params. | ||||||
9033 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
9034 | unsigned FTIIdx; | ||||||
9035 | if (D.isFunctionDeclarator(FTIIdx)) { | ||||||
9036 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | ||||||
9037 | |||||||
9038 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | ||||||
9039 | // function that takes no arguments, not a function that takes a | ||||||
9040 | // single void argument. | ||||||
9041 | // We let through "const void" here because Sema::GetTypeForDeclarator | ||||||
9042 | // already checks for that case. | ||||||
9043 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | ||||||
9044 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | ||||||
9045 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||||
9046 | assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?" ) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9046, __PRETTY_FUNCTION__)); | ||||||
9047 | Param->setDeclContext(NewFD); | ||||||
9048 | Params.push_back(Param); | ||||||
9049 | |||||||
9050 | if (Param->isInvalidDecl()) | ||||||
9051 | NewFD->setInvalidDecl(); | ||||||
9052 | } | ||||||
9053 | } | ||||||
9054 | |||||||
9055 | if (!getLangOpts().CPlusPlus) { | ||||||
9056 | // In C, find all the tag declarations from the prototype and move them | ||||||
9057 | // into the function DeclContext. Remove them from the surrounding tag | ||||||
9058 | // injection context of the function, which is typically but not always | ||||||
9059 | // the TU. | ||||||
9060 | DeclContext *PrototypeTagContext = | ||||||
9061 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | ||||||
9062 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | ||||||
9063 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | ||||||
9064 | |||||||
9065 | // We don't want to reparent enumerators. Look at their parent enum | ||||||
9066 | // instead. | ||||||
9067 | if (!TD) { | ||||||
9068 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | ||||||
9069 | TD = cast<EnumDecl>(ECD->getDeclContext()); | ||||||
9070 | } | ||||||
9071 | if (!TD) | ||||||
9072 | continue; | ||||||
9073 | DeclContext *TagDC = TD->getLexicalDeclContext(); | ||||||
9074 | if (!TagDC->containsDecl(TD)) | ||||||
9075 | continue; | ||||||
9076 | TagDC->removeDecl(TD); | ||||||
9077 | TD->setDeclContext(NewFD); | ||||||
9078 | NewFD->addDecl(TD); | ||||||
9079 | |||||||
9080 | // Preserve the lexical DeclContext if it is not the surrounding tag | ||||||
9081 | // injection context of the FD. In this example, the semantic context of | ||||||
9082 | // E will be f and the lexical context will be S, while both the | ||||||
9083 | // semantic and lexical contexts of S will be f: | ||||||
9084 | // void f(struct S { enum E { a } f; } s); | ||||||
9085 | if (TagDC != PrototypeTagContext) | ||||||
9086 | TD->setLexicalDeclContext(TagDC); | ||||||
9087 | } | ||||||
9088 | } | ||||||
9089 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | ||||||
9090 | // When we're declaring a function with a typedef, typeof, etc as in the | ||||||
9091 | // following example, we'll need to synthesize (unnamed) | ||||||
9092 | // parameters for use in the declaration. | ||||||
9093 | // | ||||||
9094 | // @code | ||||||
9095 | // typedef void fn(int); | ||||||
9096 | // fn f; | ||||||
9097 | // @endcode | ||||||
9098 | |||||||
9099 | // Synthesize a parameter for each argument type. | ||||||
9100 | for (const auto &AI : FT->param_types()) { | ||||||
9101 | ParmVarDecl *Param = | ||||||
9102 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | ||||||
9103 | Param->setScopeInfo(0, Params.size()); | ||||||
9104 | Params.push_back(Param); | ||||||
9105 | } | ||||||
9106 | } else { | ||||||
9107 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9108, __PRETTY_FUNCTION__)) | ||||||
9108 | "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9108, __PRETTY_FUNCTION__)); | ||||||
9109 | } | ||||||
9110 | |||||||
9111 | // Finally, we know we have the right number of parameters, install them. | ||||||
9112 | NewFD->setParams(Params); | ||||||
9113 | |||||||
9114 | if (D.getDeclSpec().isNoreturnSpecified()) | ||||||
9115 | NewFD->addAttr(C11NoReturnAttr::Create(Context, | ||||||
9116 | D.getDeclSpec().getNoreturnSpecLoc(), | ||||||
9117 | AttributeCommonInfo::AS_Keyword)); | ||||||
9118 | |||||||
9119 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | ||||||
9120 | // because all functions have linkage. | ||||||
9121 | if (!NewFD->isInvalidDecl() && | ||||||
9122 | NewFD->getReturnType()->isVariablyModifiedType()) { | ||||||
9123 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | ||||||
9124 | NewFD->setInvalidDecl(); | ||||||
9125 | } | ||||||
9126 | |||||||
9127 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | ||||||
9128 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | ||||||
9129 | !NewFD->hasAttr<SectionAttr>()) | ||||||
9130 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( | ||||||
9131 | Context, PragmaClangTextSection.SectionName, | ||||||
9132 | PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); | ||||||
9133 | |||||||
9134 | // Apply an implicit SectionAttr if #pragma code_seg is active. | ||||||
9135 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | ||||||
9136 | !NewFD->hasAttr<SectionAttr>()) { | ||||||
9137 | NewFD->addAttr(SectionAttr::CreateImplicit( | ||||||
9138 | Context, CodeSegStack.CurrentValue->getString(), | ||||||
9139 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
9140 | SectionAttr::Declspec_allocate)); | ||||||
9141 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | ||||||
9142 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | ||||||
9143 | ASTContext::PSF_Read, | ||||||
9144 | NewFD)) | ||||||
9145 | NewFD->dropAttr<SectionAttr>(); | ||||||
9146 | } | ||||||
9147 | |||||||
9148 | // Apply an implicit CodeSegAttr from class declspec or | ||||||
9149 | // apply an implicit SectionAttr from #pragma code_seg if active. | ||||||
9150 | if (!NewFD->hasAttr<CodeSegAttr>()) { | ||||||
9151 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | ||||||
9152 | D.isFunctionDefinition())) { | ||||||
9153 | NewFD->addAttr(SAttr); | ||||||
9154 | } | ||||||
9155 | } | ||||||
9156 | |||||||
9157 | // Handle attributes. | ||||||
9158 | ProcessDeclAttributes(S, NewFD, D); | ||||||
9159 | |||||||
9160 | if (getLangOpts().OpenCL) { | ||||||
9161 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | ||||||
9162 | // type declaration will generate a compilation error. | ||||||
9163 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | ||||||
9164 | if (AddressSpace != LangAS::Default) { | ||||||
9165 | Diag(NewFD->getLocation(), | ||||||
9166 | diag::err_opencl_return_value_with_address_space); | ||||||
9167 | NewFD->setInvalidDecl(); | ||||||
9168 | } | ||||||
9169 | } | ||||||
9170 | |||||||
9171 | if (!getLangOpts().CPlusPlus) { | ||||||
9172 | // Perform semantic checking on the function declaration. | ||||||
9173 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||||
9174 | CheckMain(NewFD, D.getDeclSpec()); | ||||||
9175 | |||||||
9176 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||||
9177 | CheckMSVCRTEntryPoint(NewFD); | ||||||
9178 | |||||||
9179 | if (!NewFD->isInvalidDecl()) | ||||||
9180 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||||
9181 | isMemberSpecialization)); | ||||||
9182 | else if (!Previous.empty()) | ||||||
9183 | // Recover gracefully from an invalid redeclaration. | ||||||
9184 | D.setRedeclaration(true); | ||||||
9185 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9187, __PRETTY_FUNCTION__)) | ||||||
9186 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9187, __PRETTY_FUNCTION__)) | ||||||
9187 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9187, __PRETTY_FUNCTION__)); | ||||||
9188 | |||||||
9189 | // Diagnose no-prototype function declarations with calling conventions that | ||||||
9190 | // don't support variadic calls. Only do this in C and do it after merging | ||||||
9191 | // possibly prototyped redeclarations. | ||||||
9192 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | ||||||
9193 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | ||||||
9194 | CallingConv CC = FT->getExtInfo().getCC(); | ||||||
9195 | if (!supportsVariadicCall(CC)) { | ||||||
9196 | // Windows system headers sometimes accidentally use stdcall without | ||||||
9197 | // (void) parameters, so we relax this to a warning. | ||||||
9198 | int DiagID = | ||||||
9199 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | ||||||
9200 | Diag(NewFD->getLocation(), DiagID) | ||||||
9201 | << FunctionType::getNameForCallConv(CC); | ||||||
9202 | } | ||||||
9203 | } | ||||||
9204 | |||||||
9205 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||
9206 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
9207 | checkNonTrivialCUnion(NewFD->getReturnType(), | ||||||
9208 | NewFD->getReturnTypeSourceRange().getBegin(), | ||||||
9209 | NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); | ||||||
9210 | } else { | ||||||
9211 | // C++11 [replacement.functions]p3: | ||||||
9212 | // The program's definitions shall not be specified as inline. | ||||||
9213 | // | ||||||
9214 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | ||||||
9215 | // | ||||||
9216 | // Suppress the diagnostic if the function is __attribute__((used)), since | ||||||
9217 | // that forces an external definition to be emitted. | ||||||
9218 | if (D.getDeclSpec().isInlineSpecified() && | ||||||
9219 | NewFD->isReplaceableGlobalAllocationFunction() && | ||||||
9220 | !NewFD->hasAttr<UsedAttr>()) | ||||||
9221 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
9222 | diag::ext_operator_new_delete_declared_inline) | ||||||
9223 | << NewFD->getDeclName(); | ||||||
9224 | |||||||
9225 | // If the declarator is a template-id, translate the parser's template | ||||||
9226 | // argument list into our AST format. | ||||||
9227 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||
9228 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | ||||||
9229 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | ||||||
9230 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | ||||||
9231 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||||
9232 | TemplateId->NumArgs); | ||||||
9233 | translateTemplateArguments(TemplateArgsPtr, | ||||||
9234 | TemplateArgs); | ||||||
9235 | |||||||
9236 | HasExplicitTemplateArgs = true; | ||||||
9237 | |||||||
9238 | if (NewFD->isInvalidDecl()) { | ||||||
9239 | HasExplicitTemplateArgs = false; | ||||||
9240 | } else if (FunctionTemplate) { | ||||||
9241 | // Function template with explicit template arguments. | ||||||
9242 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | ||||||
9243 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | ||||||
9244 | |||||||
9245 | HasExplicitTemplateArgs = false; | ||||||
9246 | } else { | ||||||
9247 | assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9249, __PRETTY_FUNCTION__)) | ||||||
9248 | D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9249, __PRETTY_FUNCTION__)) | ||||||
9249 | "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9249, __PRETTY_FUNCTION__)); | ||||||
9250 | // "friend void foo<>(int);" is an implicit specialization decl. | ||||||
9251 | isFunctionTemplateSpecialization = true; | ||||||
9252 | } | ||||||
9253 | } else if (isFriend && isFunctionTemplateSpecialization) { | ||||||
9254 | // This combination is only possible in a recovery case; the user | ||||||
9255 | // wrote something like: | ||||||
9256 | // template <> friend void foo(int); | ||||||
9257 | // which we're recovering from as if the user had written: | ||||||
9258 | // friend void foo<>(int); | ||||||
9259 | // Go ahead and fake up a template id. | ||||||
9260 | HasExplicitTemplateArgs = true; | ||||||
9261 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | ||||||
9262 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | ||||||
9263 | } | ||||||
9264 | |||||||
9265 | // We do not add HD attributes to specializations here because | ||||||
9266 | // they may have different constexpr-ness compared to their | ||||||
9267 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | ||||||
9268 | // may end up with different effective targets. Instead, a | ||||||
9269 | // specialization inherits its target attributes from its template | ||||||
9270 | // in the CheckFunctionTemplateSpecialization() call below. | ||||||
9271 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) | ||||||
9272 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | ||||||
9273 | |||||||
9274 | // If it's a friend (and only if it's a friend), it's possible | ||||||
9275 | // that either the specialized function type or the specialized | ||||||
9276 | // template is dependent, and therefore matching will fail. In | ||||||
9277 | // this case, don't check the specialization yet. | ||||||
9278 | bool InstantiationDependent = false; | ||||||
9279 | if (isFunctionTemplateSpecialization && isFriend && | ||||||
9280 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | ||||||
9281 | TemplateSpecializationType::anyDependentTemplateArguments( | ||||||
9282 | TemplateArgs, | ||||||
9283 | InstantiationDependent))) { | ||||||
9284 | assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9285, __PRETTY_FUNCTION__)) | ||||||
9285 | "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9285, __PRETTY_FUNCTION__)); | ||||||
9286 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | ||||||
9287 | Previous)) | ||||||
9288 | NewFD->setInvalidDecl(); | ||||||
9289 | } else if (isFunctionTemplateSpecialization) { | ||||||
9290 | if (CurContext->isDependentContext() && CurContext->isRecord() | ||||||
9291 | && !isFriend) { | ||||||
9292 | isDependentClassScopeExplicitSpecialization = true; | ||||||
9293 | } else if (!NewFD->isInvalidDecl() && | ||||||
9294 | CheckFunctionTemplateSpecialization( | ||||||
9295 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | ||||||
9296 | Previous)) | ||||||
9297 | NewFD->setInvalidDecl(); | ||||||
9298 | |||||||
9299 | // C++ [dcl.stc]p1: | ||||||
9300 | // A storage-class-specifier shall not be specified in an explicit | ||||||
9301 | // specialization (14.7.3) | ||||||
9302 | FunctionTemplateSpecializationInfo *Info = | ||||||
9303 | NewFD->getTemplateSpecializationInfo(); | ||||||
9304 | if (Info && SC != SC_None) { | ||||||
9305 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | ||||||
9306 | Diag(NewFD->getLocation(), | ||||||
9307 | diag::err_explicit_specialization_inconsistent_storage_class) | ||||||
9308 | << SC | ||||||
9309 | << FixItHint::CreateRemoval( | ||||||
9310 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9311 | |||||||
9312 | else | ||||||
9313 | Diag(NewFD->getLocation(), | ||||||
9314 | diag::ext_explicit_specialization_storage_class) | ||||||
9315 | << FixItHint::CreateRemoval( | ||||||
9316 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9317 | } | ||||||
9318 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | ||||||
9319 | if (CheckMemberSpecialization(NewFD, Previous)) | ||||||
9320 | NewFD->setInvalidDecl(); | ||||||
9321 | } | ||||||
9322 | |||||||
9323 | // Perform semantic checking on the function declaration. | ||||||
9324 | if (!isDependentClassScopeExplicitSpecialization) { | ||||||
9325 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||||
9326 | CheckMain(NewFD, D.getDeclSpec()); | ||||||
9327 | |||||||
9328 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||||
9329 | CheckMSVCRTEntryPoint(NewFD); | ||||||
9330 | |||||||
9331 | if (!NewFD->isInvalidDecl()) | ||||||
9332 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||||
9333 | isMemberSpecialization)); | ||||||
9334 | else if (!Previous.empty()) | ||||||
9335 | // Recover gracefully from an invalid redeclaration. | ||||||
9336 | D.setRedeclaration(true); | ||||||
9337 | } | ||||||
9338 | |||||||
9339 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9341, __PRETTY_FUNCTION__)) | ||||||
9340 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9341, __PRETTY_FUNCTION__)) | ||||||
9341 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9341, __PRETTY_FUNCTION__)); | ||||||
9342 | |||||||
9343 | NamedDecl *PrincipalDecl = (FunctionTemplate | ||||||
9344 | ? cast<NamedDecl>(FunctionTemplate) | ||||||
9345 | : NewFD); | ||||||
9346 | |||||||
9347 | if (isFriend && NewFD->getPreviousDecl()) { | ||||||
9348 | AccessSpecifier Access = AS_public; | ||||||
9349 | if (!NewFD->isInvalidDecl()) | ||||||
9350 | Access = NewFD->getPreviousDecl()->getAccess(); | ||||||
9351 | |||||||
9352 | NewFD->setAccess(Access); | ||||||
9353 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | ||||||
9354 | } | ||||||
9355 | |||||||
9356 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | ||||||
9357 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | ||||||
9358 | PrincipalDecl->setNonMemberOperator(); | ||||||
9359 | |||||||
9360 | // If we have a function template, check the template parameter | ||||||
9361 | // list. This will check and merge default template arguments. | ||||||
9362 | if (FunctionTemplate) { | ||||||
9363 | FunctionTemplateDecl *PrevTemplate = | ||||||
9364 | FunctionTemplate->getPreviousDecl(); | ||||||
9365 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | ||||||
9366 | PrevTemplate ? PrevTemplate->getTemplateParameters() | ||||||
9367 | : nullptr, | ||||||
9368 | D.getDeclSpec().isFriendSpecified() | ||||||
9369 | ? (D.isFunctionDefinition() | ||||||
9370 | ? TPC_FriendFunctionTemplateDefinition | ||||||
9371 | : TPC_FriendFunctionTemplate) | ||||||
9372 | : (D.getCXXScopeSpec().isSet() && | ||||||
9373 | DC && DC->isRecord() && | ||||||
9374 | DC->isDependentContext()) | ||||||
9375 | ? TPC_ClassTemplateMember | ||||||
9376 | : TPC_FunctionTemplate); | ||||||
9377 | } | ||||||
9378 | |||||||
9379 | if (NewFD->isInvalidDecl()) { | ||||||
9380 | // Ignore all the rest of this. | ||||||
9381 | } else if (!D.isRedeclaration()) { | ||||||
9382 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | ||||||
9383 | AddToScope }; | ||||||
9384 | // Fake up an access specifier if it's supposed to be a class member. | ||||||
9385 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | ||||||
9386 | NewFD->setAccess(AS_public); | ||||||
9387 | |||||||
9388 | // Qualified decls generally require a previous declaration. | ||||||
9389 | if (D.getCXXScopeSpec().isSet()) { | ||||||
9390 | // ...with the major exception of templated-scope or | ||||||
9391 | // dependent-scope friend declarations. | ||||||
9392 | |||||||
9393 | // TODO: we currently also suppress this check in dependent | ||||||
9394 | // contexts because (1) the parameter depth will be off when | ||||||
9395 | // matching friend templates and (2) we might actually be | ||||||
9396 | // selecting a friend based on a dependent factor. But there | ||||||
9397 | // are situations where these conditions don't apply and we | ||||||
9398 | // can actually do this check immediately. | ||||||
9399 | // | ||||||
9400 | // Unless the scope is dependent, it's always an error if qualified | ||||||
9401 | // redeclaration lookup found nothing at all. Diagnose that now; | ||||||
9402 | // nothing will diagnose that error later. | ||||||
9403 | if (isFriend && | ||||||
9404 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || | ||||||
9405 | (!Previous.empty() && CurContext->isDependentContext()))) { | ||||||
9406 | // ignore these | ||||||
9407 | } else { | ||||||
9408 | // The user tried to provide an out-of-line definition for a | ||||||
9409 | // function that is a member of a class or namespace, but there | ||||||
9410 | // was no such member function declared (C++ [class.mfct]p2, | ||||||
9411 | // C++ [namespace.memdef]p2). For example: | ||||||
9412 | // | ||||||
9413 | // class X { | ||||||
9414 | // void f() const; | ||||||
9415 | // }; | ||||||
9416 | // | ||||||
9417 | // void X::f() { } // ill-formed | ||||||
9418 | // | ||||||
9419 | // Complain about this problem, and attempt to suggest close | ||||||
9420 | // matches (e.g., those that differ only in cv-qualifiers and | ||||||
9421 | // whether the parameter types are references). | ||||||
9422 | |||||||
9423 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||||
9424 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | ||||||
9425 | AddToScope = ExtraArgs.AddToScope; | ||||||
9426 | return Result; | ||||||
9427 | } | ||||||
9428 | } | ||||||
9429 | |||||||
9430 | // Unqualified local friend declarations are required to resolve | ||||||
9431 | // to something. | ||||||
9432 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | ||||||
9433 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||||
9434 | *this, Previous, NewFD, ExtraArgs, true, S)) { | ||||||
9435 | AddToScope = ExtraArgs.AddToScope; | ||||||
9436 | return Result; | ||||||
9437 | } | ||||||
9438 | } | ||||||
9439 | } else if (!D.isFunctionDefinition() && | ||||||
9440 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | ||||||
9441 | !isFriend && !isFunctionTemplateSpecialization && | ||||||
9442 | !isMemberSpecialization) { | ||||||
9443 | // An out-of-line member function declaration must also be a | ||||||
9444 | // definition (C++ [class.mfct]p2). | ||||||
9445 | // Note that this is not the case for explicit specializations of | ||||||
9446 | // function templates or member functions of class templates, per | ||||||
9447 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | ||||||
9448 | // extension for compatibility with old SWIG code which likes to | ||||||
9449 | // generate them. | ||||||
9450 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | ||||||
9451 | << D.getCXXScopeSpec().getRange(); | ||||||
9452 | } | ||||||
9453 | } | ||||||
9454 | |||||||
9455 | ProcessPragmaWeak(S, NewFD); | ||||||
9456 | checkAttributesAfterMerging(*this, *NewFD); | ||||||
9457 | |||||||
9458 | AddKnownFunctionAttributes(NewFD); | ||||||
9459 | |||||||
9460 | if (NewFD->hasAttr<OverloadableAttr>() && | ||||||
9461 | !NewFD->getType()->getAs<FunctionProtoType>()) { | ||||||
9462 | Diag(NewFD->getLocation(), | ||||||
9463 | diag::err_attribute_overloadable_no_prototype) | ||||||
9464 | << NewFD; | ||||||
9465 | |||||||
9466 | // Turn this into a variadic function with no parameters. | ||||||
9467 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); | ||||||
9468 | FunctionProtoType::ExtProtoInfo EPI( | ||||||
9469 | Context.getDefaultCallingConvention(true, false)); | ||||||
9470 | EPI.Variadic = true; | ||||||
9471 | EPI.ExtInfo = FT->getExtInfo(); | ||||||
9472 | |||||||
9473 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | ||||||
9474 | NewFD->setType(R); | ||||||
9475 | } | ||||||
9476 | |||||||
9477 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||||
9478 | // member, set the visibility of this function. | ||||||
9479 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | ||||||
9480 | AddPushedVisibilityAttribute(NewFD); | ||||||
9481 | |||||||
9482 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | ||||||
9483 | // marking the function. | ||||||
9484 | AddCFAuditedAttribute(NewFD); | ||||||
9485 | |||||||
9486 | // If this is a function definition, check if we have to apply optnone due to | ||||||
9487 | // a pragma. | ||||||
9488 | if(D.isFunctionDefinition()) | ||||||
9489 | AddRangeBasedOptnone(NewFD); | ||||||
9490 | |||||||
9491 | // If this is the first declaration of an extern C variable, update | ||||||
9492 | // the map of such variables. | ||||||
9493 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | ||||||
9494 | isIncompleteDeclExternC(*this, NewFD)) | ||||||
9495 | RegisterLocallyScopedExternCDecl(NewFD, S); | ||||||
9496 | |||||||
9497 | // Set this FunctionDecl's range up to the right paren. | ||||||
9498 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | ||||||
9499 | |||||||
9500 | if (D.isRedeclaration() && !Previous.empty()) { | ||||||
9501 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||||
9502 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | ||||||
9503 | isMemberSpecialization || | ||||||
9504 | isFunctionTemplateSpecialization, | ||||||
9505 | D.isFunctionDefinition()); | ||||||
9506 | } | ||||||
9507 | |||||||
9508 | if (getLangOpts().CUDA) { | ||||||
9509 | IdentifierInfo *II = NewFD->getIdentifier(); | ||||||
9510 | if (II && II->isStr(getCudaConfigureFuncName()) && | ||||||
9511 | !NewFD->isInvalidDecl() && | ||||||
9512 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
9513 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) | ||||||
9514 | Diag(NewFD->getLocation(), diag::err_config_scalar_return) | ||||||
9515 | << getCudaConfigureFuncName(); | ||||||
9516 | Context.setcudaConfigureCallDecl(NewFD); | ||||||
9517 | } | ||||||
9518 | |||||||
9519 | // Variadic functions, other than a *declaration* of printf, are not allowed | ||||||
9520 | // in device-side CUDA code, unless someone passed | ||||||
9521 | // -fcuda-allow-variadic-functions. | ||||||
9522 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | ||||||
9523 | (NewFD->hasAttr<CUDADeviceAttr>() || | ||||||
9524 | NewFD->hasAttr<CUDAGlobalAttr>()) && | ||||||
9525 | !(II && II->isStr("printf") && NewFD->isExternC() && | ||||||
9526 | !D.isFunctionDefinition())) { | ||||||
9527 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | ||||||
9528 | } | ||||||
9529 | } | ||||||
9530 | |||||||
9531 | MarkUnusedFileScopedDecl(NewFD); | ||||||
9532 | |||||||
9533 | |||||||
9534 | |||||||
9535 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { | ||||||
9536 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | ||||||
9537 | if ((getLangOpts().OpenCLVersion >= 120) | ||||||
9538 | && (SC == SC_Static)) { | ||||||
9539 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | ||||||
9540 | D.setInvalidType(); | ||||||
9541 | } | ||||||
9542 | |||||||
9543 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | ||||||
9544 | if (!NewFD->getReturnType()->isVoidType()) { | ||||||
9545 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | ||||||
9546 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | ||||||
9547 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | ||||||
9548 | : FixItHint()); | ||||||
9549 | D.setInvalidType(); | ||||||
9550 | } | ||||||
9551 | |||||||
9552 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | ||||||
9553 | for (auto Param : NewFD->parameters()) | ||||||
9554 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | ||||||
9555 | |||||||
9556 | if (getLangOpts().OpenCLCPlusPlus) { | ||||||
9557 | if (DC->isRecord()) { | ||||||
9558 | Diag(D.getIdentifierLoc(), diag::err_method_kernel); | ||||||
9559 | D.setInvalidType(); | ||||||
9560 | } | ||||||
9561 | if (FunctionTemplate) { | ||||||
9562 | Diag(D.getIdentifierLoc(), diag::err_template_kernel); | ||||||
9563 | D.setInvalidType(); | ||||||
9564 | } | ||||||
9565 | } | ||||||
9566 | } | ||||||
9567 | |||||||
9568 | if (getLangOpts().CPlusPlus) { | ||||||
9569 | if (FunctionTemplate) { | ||||||
9570 | if (NewFD->isInvalidDecl()) | ||||||
9571 | FunctionTemplate->setInvalidDecl(); | ||||||
9572 | return FunctionTemplate; | ||||||
9573 | } | ||||||
9574 | |||||||
9575 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | ||||||
9576 | CompleteMemberSpecialization(NewFD, Previous); | ||||||
9577 | } | ||||||
9578 | |||||||
9579 | for (const ParmVarDecl *Param : NewFD->parameters()) { | ||||||
9580 | QualType PT = Param->getType(); | ||||||
9581 | |||||||
9582 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | ||||||
9583 | // types. | ||||||
9584 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||||
9585 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | ||||||
9586 | QualType ElemTy = PipeTy->getElementType(); | ||||||
9587 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | ||||||
9588 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | ||||||
9589 | D.setInvalidType(); | ||||||
9590 | } | ||||||
9591 | } | ||||||
9592 | } | ||||||
9593 | } | ||||||
9594 | |||||||
9595 | // Here we have an function template explicit specialization at class scope. | ||||||
9596 | // The actual specialization will be postponed to template instatiation | ||||||
9597 | // time via the ClassScopeFunctionSpecializationDecl node. | ||||||
9598 | if (isDependentClassScopeExplicitSpecialization) { | ||||||
9599 | ClassScopeFunctionSpecializationDecl *NewSpec = | ||||||
9600 | ClassScopeFunctionSpecializationDecl::Create( | ||||||
9601 | Context, CurContext, NewFD->getLocation(), | ||||||
9602 | cast<CXXMethodDecl>(NewFD), | ||||||
9603 | HasExplicitTemplateArgs, TemplateArgs); | ||||||
9604 | CurContext->addDecl(NewSpec); | ||||||
9605 | AddToScope = false; | ||||||
9606 | } | ||||||
9607 | |||||||
9608 | // Diagnose availability attributes. Availability cannot be used on functions | ||||||
9609 | // that are run during load/unload. | ||||||
9610 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | ||||||
9611 | if (NewFD->hasAttr<ConstructorAttr>()) { | ||||||
9612 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||||
9613 | << 1; | ||||||
9614 | NewFD->dropAttr<AvailabilityAttr>(); | ||||||
9615 | } | ||||||
9616 | if (NewFD->hasAttr<DestructorAttr>()) { | ||||||
9617 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||||
9618 | << 2; | ||||||
9619 | NewFD->dropAttr<AvailabilityAttr>(); | ||||||
9620 | } | ||||||
9621 | } | ||||||
9622 | |||||||
9623 | // Diagnose no_builtin attribute on function declaration that are not a | ||||||
9624 | // definition. | ||||||
9625 | // FIXME: We should really be doing this in | ||||||
9626 | // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to | ||||||
9627 | // the FunctionDecl and at this point of the code | ||||||
9628 | // FunctionDecl::isThisDeclarationADefinition() which always returns `false` | ||||||
9629 | // because Sema::ActOnStartOfFunctionDef has not been called yet. | ||||||
9630 | if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) | ||||||
9631 | switch (D.getFunctionDefinitionKind()) { | ||||||
9632 | case FDK_Defaulted: | ||||||
9633 | case FDK_Deleted: | ||||||
9634 | Diag(NBA->getLocation(), | ||||||
9635 | diag::err_attribute_no_builtin_on_defaulted_deleted_function) | ||||||
9636 | << NBA->getSpelling(); | ||||||
9637 | break; | ||||||
9638 | case FDK_Declaration: | ||||||
9639 | Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) | ||||||
9640 | << NBA->getSpelling(); | ||||||
9641 | break; | ||||||
9642 | case FDK_Definition: | ||||||
9643 | break; | ||||||
9644 | } | ||||||
9645 | |||||||
9646 | return NewFD; | ||||||
9647 | } | ||||||
9648 | |||||||
9649 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | ||||||
9650 | /// when __declspec(code_seg) "is applied to a class, all member functions of | ||||||
9651 | /// the class and nested classes -- this includes compiler-generated special | ||||||
9652 | /// member functions -- are put in the specified segment." | ||||||
9653 | /// The actual behavior is a little more complicated. The Microsoft compiler | ||||||
9654 | /// won't check outer classes if there is an active value from #pragma code_seg. | ||||||
9655 | /// The CodeSeg is always applied from the direct parent but only from outer | ||||||
9656 | /// classes when the #pragma code_seg stack is empty. See: | ||||||
9657 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | ||||||
9658 | /// available since MS has removed the page. | ||||||
9659 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | ||||||
9660 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | ||||||
9661 | if (!Method) | ||||||
9662 | return nullptr; | ||||||
9663 | const CXXRecordDecl *Parent = Method->getParent(); | ||||||
9664 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||||
9665 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||||
9666 | NewAttr->setImplicit(true); | ||||||
9667 | return NewAttr; | ||||||
9668 | } | ||||||
9669 | |||||||
9670 | // The Microsoft compiler won't check outer classes for the CodeSeg | ||||||
9671 | // when the #pragma code_seg stack is active. | ||||||
9672 | if (S.CodeSegStack.CurrentValue) | ||||||
9673 | return nullptr; | ||||||
9674 | |||||||
9675 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | ||||||
9676 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||||
9677 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||||
9678 | NewAttr->setImplicit(true); | ||||||
9679 | return NewAttr; | ||||||
9680 | } | ||||||
9681 | } | ||||||
9682 | return nullptr; | ||||||
9683 | } | ||||||
9684 | |||||||
9685 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | ||||||
9686 | /// containing class. Otherwise it will return implicit SectionAttr if the | ||||||
9687 | /// function is a definition and there is an active value on CodeSegStack | ||||||
9688 | /// (from the current #pragma code-seg value). | ||||||
9689 | /// | ||||||
9690 | /// \param FD Function being declared. | ||||||
9691 | /// \param IsDefinition Whether it is a definition or just a declarartion. | ||||||
9692 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | ||||||
9693 | /// nullptr if no attribute should be added. | ||||||
9694 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | ||||||
9695 | bool IsDefinition) { | ||||||
9696 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | ||||||
9697 | return A; | ||||||
9698 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | ||||||
9699 | CodeSegStack.CurrentValue) | ||||||
9700 | return SectionAttr::CreateImplicit( | ||||||
9701 | getASTContext(), CodeSegStack.CurrentValue->getString(), | ||||||
9702 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
9703 | SectionAttr::Declspec_allocate); | ||||||
9704 | return nullptr; | ||||||
9705 | } | ||||||
9706 | |||||||
9707 | /// Determines if we can perform a correct type check for \p D as a | ||||||
9708 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a | ||||||
9709 | /// best-effort check. | ||||||
9710 | /// | ||||||
9711 | /// \param NewD The new declaration. | ||||||
9712 | /// \param OldD The old declaration. | ||||||
9713 | /// \param NewT The portion of the type of the new declaration to check. | ||||||
9714 | /// \param OldT The portion of the type of the old declaration to check. | ||||||
9715 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | ||||||
9716 | QualType NewT, QualType OldT) { | ||||||
9717 | if (!NewD->getLexicalDeclContext()->isDependentContext()) | ||||||
9718 | return true; | ||||||
9719 | |||||||
9720 | // For dependently-typed local extern declarations and friends, we can't | ||||||
9721 | // perform a correct type check in general until instantiation: | ||||||
9722 | // | ||||||
9723 | // int f(); | ||||||
9724 | // template<typename T> void g() { T f(); } | ||||||
9725 | // | ||||||
9726 | // (valid if g() is only instantiated with T = int). | ||||||
9727 | if (NewT->isDependentType() && | ||||||
9728 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) | ||||||
9729 | return false; | ||||||
9730 | |||||||
9731 | // Similarly, if the previous declaration was a dependent local extern | ||||||
9732 | // declaration, we don't really know its type yet. | ||||||
9733 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) | ||||||
9734 | return false; | ||||||
9735 | |||||||
9736 | return true; | ||||||
9737 | } | ||||||
9738 | |||||||
9739 | /// Checks if the new declaration declared in dependent context must be | ||||||
9740 | /// put in the same redeclaration chain as the specified declaration. | ||||||
9741 | /// | ||||||
9742 | /// \param D Declaration that is checked. | ||||||
9743 | /// \param PrevDecl Previous declaration found with proper lookup method for the | ||||||
9744 | /// same declaration name. | ||||||
9745 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | ||||||
9746 | /// belongs to. | ||||||
9747 | /// | ||||||
9748 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | ||||||
9749 | if (!D->getLexicalDeclContext()->isDependentContext()) | ||||||
9750 | return true; | ||||||
9751 | |||||||
9752 | // Don't chain dependent friend function definitions until instantiation, to | ||||||
9753 | // permit cases like | ||||||
9754 | // | ||||||
9755 | // void func(); | ||||||
9756 | // template<typename T> class C1 { friend void func() {} }; | ||||||
9757 | // template<typename T> class C2 { friend void func() {} }; | ||||||
9758 | // | ||||||
9759 | // ... which is valid if only one of C1 and C2 is ever instantiated. | ||||||
9760 | // | ||||||
9761 | // FIXME: This need only apply to function definitions. For now, we proxy | ||||||
9762 | // this by checking for a file-scope function. We do not want this to apply | ||||||
9763 | // to friend declarations nominating member functions, because that gets in | ||||||
9764 | // the way of access checks. | ||||||
9765 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) | ||||||
9766 | return false; | ||||||
9767 | |||||||
9768 | auto *VD = dyn_cast<ValueDecl>(D); | ||||||
9769 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); | ||||||
9770 | return !VD || !PrevVD || | ||||||
9771 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), | ||||||
9772 | PrevVD->getType()); | ||||||
9773 | } | ||||||
9774 | |||||||
9775 | /// Check the target attribute of the function for MultiVersion | ||||||
9776 | /// validity. | ||||||
9777 | /// | ||||||
9778 | /// Returns true if there was an error, false otherwise. | ||||||
9779 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | ||||||
9780 | const auto *TA = FD->getAttr<TargetAttr>(); | ||||||
9781 | assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute" ) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 9781, __PRETTY_FUNCTION__)); | ||||||
9782 | ParsedTargetAttr ParseInfo = TA->parse(); | ||||||
9783 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | ||||||
9784 | enum ErrType { Feature = 0, Architecture = 1 }; | ||||||
9785 | |||||||
9786 | if (!ParseInfo.Architecture.empty() && | ||||||
9787 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | ||||||
9788 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
9789 | << Architecture << ParseInfo.Architecture; | ||||||
9790 | return true; | ||||||
9791 | } | ||||||
9792 | |||||||
9793 | for (const auto &Feat : ParseInfo.Features) { | ||||||
9794 | auto BareFeat = StringRef{Feat}.substr(1); | ||||||
9795 | if (Feat[0] == '-') { | ||||||
9796 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
9797 | << Feature << ("no-" + BareFeat).str(); | ||||||
9798 | return true; | ||||||
9799 | } | ||||||
9800 | |||||||
9801 | if (!TargetInfo.validateCpuSupports(BareFeat) || | ||||||
9802 | !TargetInfo.isValidFeatureName(BareFeat)) { | ||||||
9803 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
9804 | << Feature << BareFeat; | ||||||
9805 | return true; | ||||||
9806 | } | ||||||
9807 | } | ||||||
9808 | return false; | ||||||
9809 | } | ||||||
9810 | |||||||
9811 | static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, | ||||||
9812 | MultiVersionKind MVType) { | ||||||
9813 | for (const Attr *A : FD->attrs()) { | ||||||
9814 | switch (A->getKind()) { | ||||||
9815 | case attr::CPUDispatch: | ||||||
9816 | case attr::CPUSpecific: | ||||||
9817 | if (MVType != MultiVersionKind::CPUDispatch && | ||||||
9818 | MVType != MultiVersionKind::CPUSpecific) | ||||||
9819 | return true; | ||||||
9820 | break; | ||||||
9821 | case attr::Target: | ||||||
9822 | if (MVType != MultiVersionKind::Target) | ||||||
9823 | return true; | ||||||
9824 | break; | ||||||
9825 | default: | ||||||
9826 | return true; | ||||||
9827 | } | ||||||
9828 | } | ||||||
9829 | return false; | ||||||
9830 | } | ||||||
9831 | |||||||
9832 | bool Sema::areMultiversionVariantFunctionsCompatible( | ||||||
9833 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, | ||||||
9834 | const PartialDiagnostic &NoProtoDiagID, | ||||||
9835 | const PartialDiagnosticAt &NoteCausedDiagIDAt, | ||||||
9836 | const PartialDiagnosticAt &NoSupportDiagIDAt, | ||||||
9837 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, | ||||||
9838 | bool ConstexprSupported, bool CLinkageMayDiffer) { | ||||||
9839 | enum DoesntSupport { | ||||||
9840 | FuncTemplates = 0, | ||||||
9841 | VirtFuncs = 1, | ||||||
9842 | DeducedReturn = 2, | ||||||
9843 | Constructors = 3, | ||||||
9844 | Destructors = 4, | ||||||
9845 | DeletedFuncs = 5, | ||||||
9846 | DefaultedFuncs = 6, | ||||||
9847 | ConstexprFuncs = 7, | ||||||
9848 | ConstevalFuncs = 8, | ||||||
9849 | }; | ||||||
9850 | enum Different { | ||||||
9851 | CallingConv = 0, | ||||||
9852 | ReturnType = 1, | ||||||
9853 | ConstexprSpec = 2, | ||||||
9854 | InlineSpec = 3, | ||||||
9855 | StorageClass = 4, | ||||||
9856 | Linkage = 5, | ||||||
9857 | }; | ||||||
9858 | |||||||
9859 | if (NoProtoDiagID.getDiagID() != 0 && OldFD && | ||||||
9860 | !OldFD->getType()->getAs<FunctionProtoType>()) { | ||||||
9861 | Diag(OldFD->getLocation(), NoProtoDiagID); | ||||||
9862 | Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); | ||||||
9863 | return true; | ||||||
9864 | } | ||||||
9865 | |||||||
9866 | if (NoProtoDiagID.getDiagID() != 0 && | ||||||
9867 | !NewFD->getType()->getAs<FunctionProtoType>()) | ||||||
9868 | return Diag(NewFD->getLocation(), NoProtoDiagID); | ||||||
9869 | |||||||
9870 | if (!TemplatesSupported && | ||||||
9871 | NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | ||||||
9872 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9873 | << FuncTemplates; | ||||||
9874 | |||||||
9875 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||||
9876 | if (NewCXXFD->isVirtual()) | ||||||
9877 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9878 | << VirtFuncs; | ||||||
9879 | |||||||
9880 | if (isa<CXXConstructorDecl>(NewCXXFD)) | ||||||
9881 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9882 | << Constructors; | ||||||
9883 | |||||||
9884 | if (isa<CXXDestructorDecl>(NewCXXFD)) | ||||||
9885 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9886 | << Destructors; | ||||||
9887 | } | ||||||
9888 | |||||||
9889 | if (NewFD->isDeleted()) | ||||||
9890 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9891 | << DeletedFuncs; | ||||||
9892 | |||||||
9893 | if (NewFD->isDefaulted()) | ||||||
9894 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9895 | << DefaultedFuncs; | ||||||
9896 | |||||||
9897 | if (!ConstexprSupported && NewFD->isConstexpr()) | ||||||
9898 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9899 | << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); | ||||||
9900 | |||||||
9901 | QualType NewQType = Context.getCanonicalType(NewFD->getType()); | ||||||
9902 | const auto *NewType = cast<FunctionType>(NewQType); | ||||||
9903 | QualType NewReturnType = NewType->getReturnType(); | ||||||
9904 | |||||||
9905 | if (NewReturnType->isUndeducedType()) | ||||||
9906 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9907 | << DeducedReturn; | ||||||
9908 | |||||||
9909 | // Ensure the return type is identical. | ||||||
9910 | if (OldFD) { | ||||||
9911 | QualType OldQType = Context.getCanonicalType(OldFD->getType()); | ||||||
9912 | const auto *OldType = cast<FunctionType>(OldQType); | ||||||
9913 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||||
9914 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||||
9915 | |||||||
9916 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | ||||||
9917 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; | ||||||
9918 | |||||||
9919 | QualType OldReturnType = OldType->getReturnType(); | ||||||
9920 | |||||||
9921 | if (OldReturnType != NewReturnType) | ||||||
9922 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; | ||||||
9923 | |||||||
9924 | if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) | ||||||
9925 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; | ||||||
9926 | |||||||
9927 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | ||||||
9928 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; | ||||||
9929 | |||||||
9930 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) | ||||||
9931 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; | ||||||
9932 | |||||||
9933 | if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) | ||||||
9934 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; | ||||||
9935 | |||||||
9936 | if (CheckEquivalentExceptionSpec( | ||||||
9937 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | ||||||
9938 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | ||||||
9939 | return true; | ||||||
9940 | } | ||||||
9941 | return false; | ||||||
9942 | } | ||||||
9943 | |||||||
9944 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | ||||||
9945 | const FunctionDecl *NewFD, | ||||||
9946 | bool CausesMV, | ||||||
9947 | MultiVersionKind MVType) { | ||||||
9948 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||||
9949 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||||
9950 | if (OldFD) | ||||||
9951 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
9952 | return true; | ||||||
9953 | } | ||||||
9954 | |||||||
9955 | bool IsCPUSpecificCPUDispatchMVType = | ||||||
9956 | MVType == MultiVersionKind::CPUDispatch || | ||||||
9957 | MVType == MultiVersionKind::CPUSpecific; | ||||||
9958 | |||||||
9959 | // For now, disallow all other attributes. These should be opt-in, but | ||||||
9960 | // an analysis of all of them is a future FIXME. | ||||||
9961 | if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { | ||||||
9962 | S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) | ||||||
9963 | << IsCPUSpecificCPUDispatchMVType; | ||||||
9964 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
9965 | return true; | ||||||
9966 | } | ||||||
9967 | |||||||
9968 | if (HasNonMultiVersionAttributes(NewFD, MVType)) | ||||||
9969 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) | ||||||
9970 | << IsCPUSpecificCPUDispatchMVType; | ||||||
9971 | |||||||
9972 | // Only allow transition to MultiVersion if it hasn't been used. | ||||||
9973 | if (OldFD && CausesMV && OldFD->isUsed(false)) | ||||||
9974 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | ||||||
9975 | |||||||
9976 | return S.areMultiversionVariantFunctionsCompatible( | ||||||
9977 | OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), | ||||||
9978 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
9979 | S.PDiag(diag::note_multiversioning_caused_here)), | ||||||
9980 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
9981 | S.PDiag(diag::err_multiversion_doesnt_support) | ||||||
9982 | << IsCPUSpecificCPUDispatchMVType), | ||||||
9983 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
9984 | S.PDiag(diag::err_multiversion_diff)), | ||||||
9985 | /*TemplatesSupported=*/false, | ||||||
9986 | /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, | ||||||
9987 | /*CLinkageMayDiffer=*/false); | ||||||
9988 | } | ||||||
9989 | |||||||
9990 | /// Check the validity of a multiversion function declaration that is the | ||||||
9991 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | ||||||
9992 | /// | ||||||
9993 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
9994 | /// | ||||||
9995 | /// Returns true if there was an error, false otherwise. | ||||||
9996 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | ||||||
9997 | MultiVersionKind MVType, | ||||||
9998 | const TargetAttr *TA) { | ||||||
9999 | assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10000, __PRETTY_FUNCTION__)) | ||||||
10000 | "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10000, __PRETTY_FUNCTION__)); | ||||||
10001 | |||||||
10002 | // Target only causes MV if it is default, otherwise this is a normal | ||||||
10003 | // function. | ||||||
10004 | if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) | ||||||
10005 | return false; | ||||||
10006 | |||||||
10007 | if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { | ||||||
10008 | FD->setInvalidDecl(); | ||||||
10009 | return true; | ||||||
10010 | } | ||||||
10011 | |||||||
10012 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { | ||||||
10013 | FD->setInvalidDecl(); | ||||||
10014 | return true; | ||||||
10015 | } | ||||||
10016 | |||||||
10017 | FD->setIsMultiVersion(); | ||||||
10018 | return false; | ||||||
10019 | } | ||||||
10020 | |||||||
10021 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { | ||||||
10022 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { | ||||||
10023 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) | ||||||
10024 | return true; | ||||||
10025 | } | ||||||
10026 | |||||||
10027 | return false; | ||||||
10028 | } | ||||||
10029 | |||||||
10030 | static bool CheckTargetCausesMultiVersioning( | ||||||
10031 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | ||||||
10032 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||||
10033 | LookupResult &Previous) { | ||||||
10034 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | ||||||
10035 | ParsedTargetAttr NewParsed = NewTA->parse(); | ||||||
10036 | // Sort order doesn't matter, it just needs to be consistent. | ||||||
10037 | llvm::sort(NewParsed.Features); | ||||||
10038 | |||||||
10039 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | ||||||
10040 | // to change, this is a simple redeclaration. | ||||||
10041 | if (!NewTA->isDefaultVersion() && | ||||||
10042 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) | ||||||
10043 | return false; | ||||||
10044 | |||||||
10045 | // Otherwise, this decl causes MultiVersioning. | ||||||
10046 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||||
10047 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||||
10048 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10049 | NewFD->setInvalidDecl(); | ||||||
10050 | return true; | ||||||
10051 | } | ||||||
10052 | |||||||
10053 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | ||||||
10054 | MultiVersionKind::Target)) { | ||||||
10055 | NewFD->setInvalidDecl(); | ||||||
10056 | return true; | ||||||
10057 | } | ||||||
10058 | |||||||
10059 | if (CheckMultiVersionValue(S, NewFD)) { | ||||||
10060 | NewFD->setInvalidDecl(); | ||||||
10061 | return true; | ||||||
10062 | } | ||||||
10063 | |||||||
10064 | // If this is 'default', permit the forward declaration. | ||||||
10065 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { | ||||||
10066 | Redeclaration = true; | ||||||
10067 | OldDecl = OldFD; | ||||||
10068 | OldFD->setIsMultiVersion(); | ||||||
10069 | NewFD->setIsMultiVersion(); | ||||||
10070 | return false; | ||||||
10071 | } | ||||||
10072 | |||||||
10073 | if (CheckMultiVersionValue(S, OldFD)) { | ||||||
10074 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10075 | NewFD->setInvalidDecl(); | ||||||
10076 | return true; | ||||||
10077 | } | ||||||
10078 | |||||||
10079 | ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); | ||||||
10080 | |||||||
10081 | if (OldParsed == NewParsed) { | ||||||
10082 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||||
10083 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10084 | NewFD->setInvalidDecl(); | ||||||
10085 | return true; | ||||||
10086 | } | ||||||
10087 | |||||||
10088 | for (const auto *FD : OldFD->redecls()) { | ||||||
10089 | const auto *CurTA = FD->getAttr<TargetAttr>(); | ||||||
10090 | // We allow forward declarations before ANY multiversioning attributes, but | ||||||
10091 | // nothing after the fact. | ||||||
10092 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && | ||||||
10093 | (!CurTA || CurTA->isInherited())) { | ||||||
10094 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||||
10095 | << 0; | ||||||
10096 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10097 | NewFD->setInvalidDecl(); | ||||||
10098 | return true; | ||||||
10099 | } | ||||||
10100 | } | ||||||
10101 | |||||||
10102 | OldFD->setIsMultiVersion(); | ||||||
10103 | NewFD->setIsMultiVersion(); | ||||||
10104 | Redeclaration = false; | ||||||
10105 | MergeTypeWithPrevious = false; | ||||||
10106 | OldDecl = nullptr; | ||||||
10107 | Previous.clear(); | ||||||
10108 | return false; | ||||||
10109 | } | ||||||
10110 | |||||||
10111 | /// Check the validity of a new function declaration being added to an existing | ||||||
10112 | /// multiversioned declaration collection. | ||||||
10113 | static bool CheckMultiVersionAdditionalDecl( | ||||||
10114 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | ||||||
10115 | MultiVersionKind NewMVType, const TargetAttr *NewTA, | ||||||
10116 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | ||||||
10117 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||||
10118 | LookupResult &Previous) { | ||||||
10119 | |||||||
10120 | MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); | ||||||
10121 | // Disallow mixing of multiversioning types. | ||||||
10122 | if ((OldMVType == MultiVersionKind::Target && | ||||||
10123 | NewMVType != MultiVersionKind::Target) || | ||||||
10124 | (NewMVType == MultiVersionKind::Target && | ||||||
10125 | OldMVType != MultiVersionKind::Target)) { | ||||||
10126 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||||
10127 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10128 | NewFD->setInvalidDecl(); | ||||||
10129 | return true; | ||||||
10130 | } | ||||||
10131 | |||||||
10132 | ParsedTargetAttr NewParsed; | ||||||
10133 | if (NewTA) { | ||||||
10134 | NewParsed = NewTA->parse(); | ||||||
10135 | llvm::sort(NewParsed.Features); | ||||||
10136 | } | ||||||
10137 | |||||||
10138 | bool UseMemberUsingDeclRules = | ||||||
10139 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | ||||||
10140 | |||||||
10141 | // Next, check ALL non-overloads to see if this is a redeclaration of a | ||||||
10142 | // previous member of the MultiVersion set. | ||||||
10143 | for (NamedDecl *ND : Previous) { | ||||||
10144 | FunctionDecl *CurFD = ND->getAsFunction(); | ||||||
10145 | if (!CurFD) | ||||||
10146 | continue; | ||||||
10147 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | ||||||
10148 | continue; | ||||||
10149 | |||||||
10150 | if (NewMVType == MultiVersionKind::Target) { | ||||||
10151 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | ||||||
10152 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | ||||||
10153 | NewFD->setIsMultiVersion(); | ||||||
10154 | Redeclaration = true; | ||||||
10155 | OldDecl = ND; | ||||||
10156 | return false; | ||||||
10157 | } | ||||||
10158 | |||||||
10159 | ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); | ||||||
10160 | if (CurParsed == NewParsed) { | ||||||
10161 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||||
10162 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10163 | NewFD->setInvalidDecl(); | ||||||
10164 | return true; | ||||||
10165 | } | ||||||
10166 | } else { | ||||||
10167 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | ||||||
10168 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | ||||||
10169 | // Handle CPUDispatch/CPUSpecific versions. | ||||||
10170 | // Only 1 CPUDispatch function is allowed, this will make it go through | ||||||
10171 | // the redeclaration errors. | ||||||
10172 | if (NewMVType == MultiVersionKind::CPUDispatch && | ||||||
10173 | CurFD->hasAttr<CPUDispatchAttr>()) { | ||||||
10174 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | ||||||
10175 | std::equal( | ||||||
10176 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | ||||||
10177 | NewCPUDisp->cpus_begin(), | ||||||
10178 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||||
10179 | return Cur->getName() == New->getName(); | ||||||
10180 | })) { | ||||||
10181 | NewFD->setIsMultiVersion(); | ||||||
10182 | Redeclaration = true; | ||||||
10183 | OldDecl = ND; | ||||||
10184 | return false; | ||||||
10185 | } | ||||||
10186 | |||||||
10187 | // If the declarations don't match, this is an error condition. | ||||||
10188 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | ||||||
10189 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10190 | NewFD->setInvalidDecl(); | ||||||
10191 | return true; | ||||||
10192 | } | ||||||
10193 | if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { | ||||||
10194 | |||||||
10195 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | ||||||
10196 | std::equal( | ||||||
10197 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | ||||||
10198 | NewCPUSpec->cpus_begin(), | ||||||
10199 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||||
10200 | return Cur->getName() == New->getName(); | ||||||
10201 | })) { | ||||||
10202 | NewFD->setIsMultiVersion(); | ||||||
10203 | Redeclaration = true; | ||||||
10204 | OldDecl = ND; | ||||||
10205 | return false; | ||||||
10206 | } | ||||||
10207 | |||||||
10208 | // Only 1 version of CPUSpecific is allowed for each CPU. | ||||||
10209 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | ||||||
10210 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | ||||||
10211 | if (CurII == NewII) { | ||||||
10212 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | ||||||
10213 | << NewII; | ||||||
10214 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10215 | NewFD->setInvalidDecl(); | ||||||
10216 | return true; | ||||||
10217 | } | ||||||
10218 | } | ||||||
10219 | } | ||||||
10220 | } | ||||||
10221 | // If the two decls aren't the same MVType, there is no possible error | ||||||
10222 | // condition. | ||||||
10223 | } | ||||||
10224 | } | ||||||
10225 | |||||||
10226 | // Else, this is simply a non-redecl case. Checking the 'value' is only | ||||||
10227 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | ||||||
10228 | // handled in the attribute adding step. | ||||||
10229 | if (NewMVType == MultiVersionKind::Target && | ||||||
10230 | CheckMultiVersionValue(S, NewFD)) { | ||||||
10231 | NewFD->setInvalidDecl(); | ||||||
10232 | return true; | ||||||
10233 | } | ||||||
10234 | |||||||
10235 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, | ||||||
10236 | !OldFD->isMultiVersion(), NewMVType)) { | ||||||
10237 | NewFD->setInvalidDecl(); | ||||||
10238 | return true; | ||||||
10239 | } | ||||||
10240 | |||||||
10241 | // Permit forward declarations in the case where these two are compatible. | ||||||
10242 | if (!OldFD->isMultiVersion()) { | ||||||
10243 | OldFD->setIsMultiVersion(); | ||||||
10244 | NewFD->setIsMultiVersion(); | ||||||
10245 | Redeclaration = true; | ||||||
10246 | OldDecl = OldFD; | ||||||
10247 | return false; | ||||||
10248 | } | ||||||
10249 | |||||||
10250 | NewFD->setIsMultiVersion(); | ||||||
10251 | Redeclaration = false; | ||||||
10252 | MergeTypeWithPrevious = false; | ||||||
10253 | OldDecl = nullptr; | ||||||
10254 | Previous.clear(); | ||||||
10255 | return false; | ||||||
10256 | } | ||||||
10257 | |||||||
10258 | |||||||
10259 | /// Check the validity of a mulitversion function declaration. | ||||||
10260 | /// Also sets the multiversion'ness' of the function itself. | ||||||
10261 | /// | ||||||
10262 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10263 | /// | ||||||
10264 | /// Returns true if there was an error, false otherwise. | ||||||
10265 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | ||||||
10266 | bool &Redeclaration, NamedDecl *&OldDecl, | ||||||
10267 | bool &MergeTypeWithPrevious, | ||||||
10268 | LookupResult &Previous) { | ||||||
10269 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | ||||||
10270 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | ||||||
10271 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | ||||||
10272 | |||||||
10273 | // Mixing Multiversioning types is prohibited. | ||||||
10274 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || | ||||||
10275 | (NewCPUDisp && NewCPUSpec)) { | ||||||
10276 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||||
10277 | NewFD->setInvalidDecl(); | ||||||
10278 | return true; | ||||||
10279 | } | ||||||
10280 | |||||||
10281 | MultiVersionKind MVType = NewFD->getMultiVersionKind(); | ||||||
10282 | |||||||
10283 | // Main isn't allowed to become a multiversion function, however it IS | ||||||
10284 | // permitted to have 'main' be marked with the 'target' optimization hint. | ||||||
10285 | if (NewFD->isMain()) { | ||||||
10286 | if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || | ||||||
10287 | MVType == MultiVersionKind::CPUDispatch || | ||||||
10288 | MVType == MultiVersionKind::CPUSpecific) { | ||||||
10289 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | ||||||
10290 | NewFD->setInvalidDecl(); | ||||||
10291 | return true; | ||||||
10292 | } | ||||||
10293 | return false; | ||||||
10294 | } | ||||||
10295 | |||||||
10296 | if (!OldDecl || !OldDecl->getAsFunction() || | ||||||
10297 | OldDecl->getDeclContext()->getRedeclContext() != | ||||||
10298 | NewFD->getDeclContext()->getRedeclContext()) { | ||||||
10299 | // If there's no previous declaration, AND this isn't attempting to cause | ||||||
10300 | // multiversioning, this isn't an error condition. | ||||||
10301 | if (MVType == MultiVersionKind::None) | ||||||
10302 | return false; | ||||||
10303 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); | ||||||
10304 | } | ||||||
10305 | |||||||
10306 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | ||||||
10307 | |||||||
10308 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) | ||||||
10309 | return false; | ||||||
10310 | |||||||
10311 | if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { | ||||||
10312 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||||
10313 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); | ||||||
10314 | NewFD->setInvalidDecl(); | ||||||
10315 | return true; | ||||||
10316 | } | ||||||
10317 | |||||||
10318 | // Handle the target potentially causes multiversioning case. | ||||||
10319 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) | ||||||
10320 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | ||||||
10321 | Redeclaration, OldDecl, | ||||||
10322 | MergeTypeWithPrevious, Previous); | ||||||
10323 | |||||||
10324 | // At this point, we have a multiversion function decl (in OldFD) AND an | ||||||
10325 | // appropriate attribute in the current function decl. Resolve that these are | ||||||
10326 | // still compatible with previous declarations. | ||||||
10327 | return CheckMultiVersionAdditionalDecl( | ||||||
10328 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, | ||||||
10329 | OldDecl, MergeTypeWithPrevious, Previous); | ||||||
10330 | } | ||||||
10331 | |||||||
10332 | /// Perform semantic checking of a new function declaration. | ||||||
10333 | /// | ||||||
10334 | /// Performs semantic analysis of the new function declaration | ||||||
10335 | /// NewFD. This routine performs all semantic checking that does not | ||||||
10336 | /// require the actual declarator involved in the declaration, and is | ||||||
10337 | /// used both for the declaration of functions as they are parsed | ||||||
10338 | /// (called via ActOnDeclarator) and for the declaration of functions | ||||||
10339 | /// that have been instantiated via C++ template instantiation (called | ||||||
10340 | /// via InstantiateDecl). | ||||||
10341 | /// | ||||||
10342 | /// \param IsMemberSpecialization whether this new function declaration is | ||||||
10343 | /// a member specialization (that replaces any definition provided by the | ||||||
10344 | /// previous declaration). | ||||||
10345 | /// | ||||||
10346 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10347 | /// | ||||||
10348 | /// \returns true if the function declaration is a redeclaration. | ||||||
10349 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | ||||||
10350 | LookupResult &Previous, | ||||||
10351 | bool IsMemberSpecialization) { | ||||||
10352 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10353, __PRETTY_FUNCTION__)) | ||||||
10353 | "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10353, __PRETTY_FUNCTION__)); | ||||||
10354 | |||||||
10355 | // Determine whether the type of this function should be merged with | ||||||
10356 | // a previous visible declaration. This never happens for functions in C++, | ||||||
10357 | // and always happens in C if the previous declaration was visible. | ||||||
10358 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | ||||||
10359 | !Previous.isShadowed(); | ||||||
10360 | |||||||
10361 | bool Redeclaration = false; | ||||||
10362 | NamedDecl *OldDecl = nullptr; | ||||||
10363 | bool MayNeedOverloadableChecks = false; | ||||||
10364 | |||||||
10365 | // Merge or overload the declaration with an existing declaration of | ||||||
10366 | // the same name, if appropriate. | ||||||
10367 | if (!Previous.empty()) { | ||||||
10368 | // Determine whether NewFD is an overload of PrevDecl or | ||||||
10369 | // a declaration that requires merging. If it's an overload, | ||||||
10370 | // there's no more work to do here; we'll just add the new | ||||||
10371 | // function to the scope. | ||||||
10372 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | ||||||
10373 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | ||||||
10374 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | ||||||
10375 | Redeclaration = true; | ||||||
10376 | OldDecl = Candidate; | ||||||
10377 | } | ||||||
10378 | } else { | ||||||
10379 | MayNeedOverloadableChecks = true; | ||||||
10380 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | ||||||
10381 | /*NewIsUsingDecl*/ false)) { | ||||||
10382 | case Ovl_Match: | ||||||
10383 | Redeclaration = true; | ||||||
10384 | break; | ||||||
10385 | |||||||
10386 | case Ovl_NonFunction: | ||||||
10387 | Redeclaration = true; | ||||||
10388 | break; | ||||||
10389 | |||||||
10390 | case Ovl_Overload: | ||||||
10391 | Redeclaration = false; | ||||||
10392 | break; | ||||||
10393 | } | ||||||
10394 | } | ||||||
10395 | } | ||||||
10396 | |||||||
10397 | // Check for a previous extern "C" declaration with this name. | ||||||
10398 | if (!Redeclaration && | ||||||
10399 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | ||||||
10400 | if (!Previous.empty()) { | ||||||
10401 | // This is an extern "C" declaration with the same name as a previous | ||||||
10402 | // declaration, and thus redeclares that entity... | ||||||
10403 | Redeclaration = true; | ||||||
10404 | OldDecl = Previous.getFoundDecl(); | ||||||
10405 | MergeTypeWithPrevious = false; | ||||||
10406 | |||||||
10407 | // ... except in the presence of __attribute__((overloadable)). | ||||||
10408 | if (OldDecl->hasAttr<OverloadableAttr>() || | ||||||
10409 | NewFD->hasAttr<OverloadableAttr>()) { | ||||||
10410 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | ||||||
10411 | MayNeedOverloadableChecks = true; | ||||||
10412 | Redeclaration = false; | ||||||
10413 | OldDecl = nullptr; | ||||||
10414 | } | ||||||
10415 | } | ||||||
10416 | } | ||||||
10417 | } | ||||||
10418 | |||||||
10419 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, | ||||||
10420 | MergeTypeWithPrevious, Previous)) | ||||||
10421 | return Redeclaration; | ||||||
10422 | |||||||
10423 | // C++11 [dcl.constexpr]p8: | ||||||
10424 | // A constexpr specifier for a non-static member function that is not | ||||||
10425 | // a constructor declares that member function to be const. | ||||||
10426 | // | ||||||
10427 | // This needs to be delayed until we know whether this is an out-of-line | ||||||
10428 | // definition of a static member function. | ||||||
10429 | // | ||||||
10430 | // This rule is not present in C++1y, so we produce a backwards | ||||||
10431 | // compatibility warning whenever it happens in C++11. | ||||||
10432 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||||
10433 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | ||||||
10434 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | ||||||
10435 | !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { | ||||||
10436 | CXXMethodDecl *OldMD = nullptr; | ||||||
10437 | if (OldDecl) | ||||||
10438 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | ||||||
10439 | if (!OldMD || !OldMD->isStatic()) { | ||||||
10440 | const FunctionProtoType *FPT = | ||||||
10441 | MD->getType()->castAs<FunctionProtoType>(); | ||||||
10442 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||||
10443 | EPI.TypeQuals.addConst(); | ||||||
10444 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | ||||||
10445 | FPT->getParamTypes(), EPI)); | ||||||
10446 | |||||||
10447 | // Warn that we did this, if we're not performing template instantiation. | ||||||
10448 | // In that case, we'll have warned already when the template was defined. | ||||||
10449 | if (!inTemplateInstantiation()) { | ||||||
10450 | SourceLocation AddConstLoc; | ||||||
10451 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | ||||||
10452 | .IgnoreParens().getAs<FunctionTypeLoc>()) | ||||||
10453 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | ||||||
10454 | |||||||
10455 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | ||||||
10456 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | ||||||
10457 | } | ||||||
10458 | } | ||||||
10459 | } | ||||||
10460 | |||||||
10461 | if (Redeclaration) { | ||||||
10462 | // NewFD and OldDecl represent declarations that need to be | ||||||
10463 | // merged. | ||||||
10464 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { | ||||||
10465 | NewFD->setInvalidDecl(); | ||||||
10466 | return Redeclaration; | ||||||
10467 | } | ||||||
10468 | |||||||
10469 | Previous.clear(); | ||||||
10470 | Previous.addDecl(OldDecl); | ||||||
10471 | |||||||
10472 | if (FunctionTemplateDecl *OldTemplateDecl = | ||||||
10473 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | ||||||
10474 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | ||||||
10475 | FunctionTemplateDecl *NewTemplateDecl | ||||||
10476 | = NewFD->getDescribedFunctionTemplate(); | ||||||
10477 | assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch" ) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10477, __PRETTY_FUNCTION__)); | ||||||
10478 | |||||||
10479 | // The call to MergeFunctionDecl above may have created some state in | ||||||
10480 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we | ||||||
10481 | // can add it as a redeclaration. | ||||||
10482 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); | ||||||
10483 | |||||||
10484 | NewFD->setPreviousDeclaration(OldFD); | ||||||
10485 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||||
10486 | if (NewFD->isCXXClassMember()) { | ||||||
10487 | NewFD->setAccess(OldTemplateDecl->getAccess()); | ||||||
10488 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | ||||||
10489 | } | ||||||
10490 | |||||||
10491 | // If this is an explicit specialization of a member that is a function | ||||||
10492 | // template, mark it as a member specialization. | ||||||
10493 | if (IsMemberSpecialization && | ||||||
10494 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | ||||||
10495 | NewTemplateDecl->setMemberSpecialization(); | ||||||
10496 | assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast <void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10496, __PRETTY_FUNCTION__)); | ||||||
10497 | // Explicit specializations of a member template do not inherit deleted | ||||||
10498 | // status from the parent member template that they are specializing. | ||||||
10499 | if (OldFD->isDeleted()) { | ||||||
10500 | // FIXME: This assert will not hold in the presence of modules. | ||||||
10501 | assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void > (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10501, __PRETTY_FUNCTION__)); | ||||||
10502 | // FIXME: We need an update record for this AST mutation. | ||||||
10503 | OldFD->setDeletedAsWritten(false); | ||||||
10504 | } | ||||||
10505 | } | ||||||
10506 | |||||||
10507 | } else { | ||||||
10508 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | ||||||
10509 | auto *OldFD = cast<FunctionDecl>(OldDecl); | ||||||
10510 | // This needs to happen first so that 'inline' propagates. | ||||||
10511 | NewFD->setPreviousDeclaration(OldFD); | ||||||
10512 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||||
10513 | if (NewFD->isCXXClassMember()) | ||||||
10514 | NewFD->setAccess(OldFD->getAccess()); | ||||||
10515 | } | ||||||
10516 | } | ||||||
10517 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | ||||||
10518 | !NewFD->getAttr<OverloadableAttr>()) { | ||||||
10519 | assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10520 | llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10521 | [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10522 | return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10523 | })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10524 | "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)); | ||||||
10525 | |||||||
10526 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | ||||||
10527 | const auto *FD = dyn_cast<FunctionDecl>(ND); | ||||||
10528 | return FD && !FD->hasAttr<OverloadableAttr>(); | ||||||
10529 | }); | ||||||
10530 | |||||||
10531 | if (OtherUnmarkedIter != Previous.end()) { | ||||||
10532 | Diag(NewFD->getLocation(), | ||||||
10533 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | ||||||
10534 | Diag((*OtherUnmarkedIter)->getLocation(), | ||||||
10535 | diag::note_attribute_overloadable_prev_overload) | ||||||
10536 | << false; | ||||||
10537 | |||||||
10538 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||||
10539 | } | ||||||
10540 | } | ||||||
10541 | |||||||
10542 | // Semantic checking for this function declaration (in isolation). | ||||||
10543 | |||||||
10544 | if (getLangOpts().CPlusPlus) { | ||||||
10545 | // C++-specific checks. | ||||||
10546 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | ||||||
10547 | CheckConstructor(Constructor); | ||||||
10548 | } else if (CXXDestructorDecl *Destructor = | ||||||
10549 | dyn_cast<CXXDestructorDecl>(NewFD)) { | ||||||
10550 | CXXRecordDecl *Record = Destructor->getParent(); | ||||||
10551 | QualType ClassType = Context.getTypeDeclType(Record); | ||||||
10552 | |||||||
10553 | // FIXME: Shouldn't we be able to perform this check even when the class | ||||||
10554 | // type is dependent? Both gcc and edg can handle that. | ||||||
10555 | if (!ClassType->isDependentType()) { | ||||||
10556 | DeclarationName Name | ||||||
10557 | = Context.DeclarationNames.getCXXDestructorName( | ||||||
10558 | Context.getCanonicalType(ClassType)); | ||||||
10559 | if (NewFD->getDeclName() != Name) { | ||||||
10560 | Diag(NewFD->getLocation(), diag::err_destructor_name); | ||||||
10561 | NewFD->setInvalidDecl(); | ||||||
10562 | return Redeclaration; | ||||||
10563 | } | ||||||
10564 | } | ||||||
10565 | } else if (CXXConversionDecl *Conversion | ||||||
10566 | = dyn_cast<CXXConversionDecl>(NewFD)) { | ||||||
10567 | ActOnConversionDeclarator(Conversion); | ||||||
10568 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | ||||||
10569 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | ||||||
10570 | CheckDeductionGuideTemplate(TD); | ||||||
10571 | |||||||
10572 | // A deduction guide is not on the list of entities that can be | ||||||
10573 | // explicitly specialized. | ||||||
10574 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | ||||||
10575 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) | ||||||
10576 | << /*explicit specialization*/ 1; | ||||||
10577 | } | ||||||
10578 | |||||||
10579 | // Find any virtual functions that this function overrides. | ||||||
10580 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||||
10581 | if (!Method->isFunctionTemplateSpecialization() && | ||||||
10582 | !Method->getDescribedFunctionTemplate() && | ||||||
10583 | Method->isCanonicalDecl()) { | ||||||
10584 | if (AddOverriddenMethods(Method->getParent(), Method)) { | ||||||
10585 | // If the function was marked as "static", we have a problem. | ||||||
10586 | if (NewFD->getStorageClass() == SC_Static) { | ||||||
10587 | ReportOverrides(*this, diag::err_static_overrides_virtual, Method); | ||||||
10588 | } | ||||||
10589 | } | ||||||
10590 | } | ||||||
10591 | if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) | ||||||
10592 | // C++2a [class.virtual]p6 | ||||||
10593 | // A virtual method shall not have a requires-clause. | ||||||
10594 | Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), | ||||||
10595 | diag::err_constrained_virtual_method); | ||||||
10596 | |||||||
10597 | if (Method->isStatic()) | ||||||
10598 | checkThisInStaticMemberFunctionType(Method); | ||||||
10599 | } | ||||||
10600 | |||||||
10601 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | ||||||
10602 | if (NewFD->isOverloadedOperator() && | ||||||
10603 | CheckOverloadedOperatorDeclaration(NewFD)) { | ||||||
10604 | NewFD->setInvalidDecl(); | ||||||
10605 | return Redeclaration; | ||||||
10606 | } | ||||||
10607 | |||||||
10608 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | ||||||
10609 | if (NewFD->getLiteralIdentifier() && | ||||||
10610 | CheckLiteralOperatorDeclaration(NewFD)) { | ||||||
10611 | NewFD->setInvalidDecl(); | ||||||
10612 | return Redeclaration; | ||||||
10613 | } | ||||||
10614 | |||||||
10615 | // In C++, check default arguments now that we have merged decls. Unless | ||||||
10616 | // the lexical context is the class, because in this case this is done | ||||||
10617 | // during delayed parsing anyway. | ||||||
10618 | if (!CurContext->isRecord()) | ||||||
10619 | CheckCXXDefaultArguments(NewFD); | ||||||
10620 | |||||||
10621 | // If this function declares a builtin function, check the type of this | ||||||
10622 | // declaration against the expected type for the builtin. | ||||||
10623 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { | ||||||
10624 | ASTContext::GetBuiltinTypeError Error; | ||||||
10625 | LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); | ||||||
10626 | QualType T = Context.GetBuiltinType(BuiltinID, Error); | ||||||
10627 | // If the type of the builtin differs only in its exception | ||||||
10628 | // specification, that's OK. | ||||||
10629 | // FIXME: If the types do differ in this way, it would be better to | ||||||
10630 | // retain the 'noexcept' form of the type. | ||||||
10631 | if (!T.isNull() && | ||||||
10632 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, | ||||||
10633 | NewFD->getType())) | ||||||
10634 | // The type of this function differs from the type of the builtin, | ||||||
10635 | // so forget about the builtin entirely. | ||||||
10636 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); | ||||||
10637 | } | ||||||
10638 | |||||||
10639 | // If this function is declared as being extern "C", then check to see if | ||||||
10640 | // the function returns a UDT (class, struct, or union type) that is not C | ||||||
10641 | // compatible, and if it does, warn the user. | ||||||
10642 | // But, issue any diagnostic on the first declaration only. | ||||||
10643 | if (Previous.empty() && NewFD->isExternC()) { | ||||||
10644 | QualType R = NewFD->getReturnType(); | ||||||
10645 | if (R->isIncompleteType() && !R->isVoidType()) | ||||||
10646 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | ||||||
10647 | << NewFD << R; | ||||||
10648 | else if (!R.isPODType(Context) && !R->isVoidType() && | ||||||
10649 | !R->isObjCObjectPointerType()) | ||||||
10650 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | ||||||
10651 | } | ||||||
10652 | |||||||
10653 | // C++1z [dcl.fct]p6: | ||||||
10654 | // [...] whether the function has a non-throwing exception-specification | ||||||
10655 | // [is] part of the function type | ||||||
10656 | // | ||||||
10657 | // This results in an ABI break between C++14 and C++17 for functions whose | ||||||
10658 | // declared type includes an exception-specification in a parameter or | ||||||
10659 | // return type. (Exception specifications on the function itself are OK in | ||||||
10660 | // most cases, and exception specifications are not permitted in most other | ||||||
10661 | // contexts where they could make it into a mangling.) | ||||||
10662 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | ||||||
10663 | auto HasNoexcept = [&](QualType T) -> bool { | ||||||
10664 | // Strip off declarator chunks that could be between us and a function | ||||||
10665 | // type. We don't need to look far, exception specifications are very | ||||||
10666 | // restricted prior to C++17. | ||||||
10667 | if (auto *RT = T->getAs<ReferenceType>()) | ||||||
10668 | T = RT->getPointeeType(); | ||||||
10669 | else if (T->isAnyPointerType()) | ||||||
10670 | T = T->getPointeeType(); | ||||||
10671 | else if (auto *MPT = T->getAs<MemberPointerType>()) | ||||||
10672 | T = MPT->getPointeeType(); | ||||||
10673 | if (auto *FPT = T->getAs<FunctionProtoType>()) | ||||||
10674 | if (FPT->isNothrow()) | ||||||
10675 | return true; | ||||||
10676 | return false; | ||||||
10677 | }; | ||||||
10678 | |||||||
10679 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | ||||||
10680 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | ||||||
10681 | for (QualType T : FPT->param_types()) | ||||||
10682 | AnyNoexcept |= HasNoexcept(T); | ||||||
10683 | if (AnyNoexcept) | ||||||
10684 | Diag(NewFD->getLocation(), | ||||||
10685 | diag::warn_cxx17_compat_exception_spec_in_signature) | ||||||
10686 | << NewFD; | ||||||
10687 | } | ||||||
10688 | |||||||
10689 | if (!Redeclaration && LangOpts.CUDA) | ||||||
10690 | checkCUDATargetOverload(NewFD, Previous); | ||||||
10691 | } | ||||||
10692 | return Redeclaration; | ||||||
10693 | } | ||||||
10694 | |||||||
10695 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | ||||||
10696 | // C++11 [basic.start.main]p3: | ||||||
10697 | // A program that [...] declares main to be inline, static or | ||||||
10698 | // constexpr is ill-formed. | ||||||
10699 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | ||||||
10700 | // appear in a declaration of main. | ||||||
10701 | // static main is not an error under C99, but we should warn about it. | ||||||
10702 | // We accept _Noreturn main as an extension. | ||||||
10703 | if (FD->getStorageClass() == SC_Static) | ||||||
10704 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | ||||||
10705 | ? diag::err_static_main : diag::warn_static_main) | ||||||
10706 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
10707 | if (FD->isInlineSpecified()) | ||||||
10708 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | ||||||
10709 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | ||||||
10710 | if (DS.isNoreturnSpecified()) { | ||||||
10711 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | ||||||
10712 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | ||||||
10713 | Diag(NoreturnLoc, diag::ext_noreturn_main); | ||||||
10714 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | ||||||
10715 | << FixItHint::CreateRemoval(NoreturnRange); | ||||||
10716 | } | ||||||
10717 | if (FD->isConstexpr()) { | ||||||
10718 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | ||||||
10719 | << FD->isConsteval() | ||||||
10720 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | ||||||
10721 | FD->setConstexprKind(CSK_unspecified); | ||||||
10722 | } | ||||||
10723 | |||||||
10724 | if (getLangOpts().OpenCL) { | ||||||
10725 | Diag(FD->getLocation(), diag::err_opencl_no_main) | ||||||
10726 | << FD->hasAttr<OpenCLKernelAttr>(); | ||||||
10727 | FD->setInvalidDecl(); | ||||||
10728 | return; | ||||||
10729 | } | ||||||
10730 | |||||||
10731 | QualType T = FD->getType(); | ||||||
10732 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10732, __PRETTY_FUNCTION__)); | ||||||
10733 | const FunctionType* FT = T->castAs<FunctionType>(); | ||||||
10734 | |||||||
10735 | // Set default calling convention for main() | ||||||
10736 | if (FT->getCallConv() != CC_C) { | ||||||
10737 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | ||||||
10738 | FD->setType(QualType(FT, 0)); | ||||||
10739 | T = Context.getCanonicalType(FD->getType()); | ||||||
10740 | } | ||||||
10741 | |||||||
10742 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | ||||||
10743 | // In C with GNU extensions we allow main() to have non-integer return | ||||||
10744 | // type, but we should warn about the extension, and we disable the | ||||||
10745 | // implicit-return-zero rule. | ||||||
10746 | |||||||
10747 | // GCC in C mode accepts qualified 'int'. | ||||||
10748 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | ||||||
10749 | FD->setHasImplicitReturnZero(true); | ||||||
10750 | else { | ||||||
10751 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | ||||||
10752 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||||
10753 | if (RTRange.isValid()) | ||||||
10754 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | ||||||
10755 | << FixItHint::CreateReplacement(RTRange, "int"); | ||||||
10756 | } | ||||||
10757 | } else { | ||||||
10758 | // In C and C++, main magically returns 0 if you fall off the end; | ||||||
10759 | // set the flag which tells us that. | ||||||
10760 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | ||||||
10761 | |||||||
10762 | // All the standards say that main() should return 'int'. | ||||||
10763 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | ||||||
10764 | FD->setHasImplicitReturnZero(true); | ||||||
10765 | else { | ||||||
10766 | // Otherwise, this is just a flat-out error. | ||||||
10767 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||||
10768 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | ||||||
10769 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | ||||||
10770 | : FixItHint()); | ||||||
10771 | FD->setInvalidDecl(true); | ||||||
10772 | } | ||||||
10773 | } | ||||||
10774 | |||||||
10775 | // Treat protoless main() as nullary. | ||||||
10776 | if (isa<FunctionNoProtoType>(FT)) return; | ||||||
10777 | |||||||
10778 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | ||||||
10779 | unsigned nparams = FTP->getNumParams(); | ||||||
10780 | assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10780, __PRETTY_FUNCTION__)); | ||||||
10781 | |||||||
10782 | bool HasExtraParameters = (nparams > 3); | ||||||
10783 | |||||||
10784 | if (FTP->isVariadic()) { | ||||||
10785 | Diag(FD->getLocation(), diag::ext_variadic_main); | ||||||
10786 | // FIXME: if we had information about the location of the ellipsis, we | ||||||
10787 | // could add a FixIt hint to remove it as a parameter. | ||||||
10788 | } | ||||||
10789 | |||||||
10790 | // Darwin passes an undocumented fourth argument of type char**. If | ||||||
10791 | // other platforms start sprouting these, the logic below will start | ||||||
10792 | // getting shifty. | ||||||
10793 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | ||||||
10794 | HasExtraParameters = false; | ||||||
10795 | |||||||
10796 | if (HasExtraParameters) { | ||||||
10797 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | ||||||
10798 | FD->setInvalidDecl(true); | ||||||
10799 | nparams = 3; | ||||||
10800 | } | ||||||
10801 | |||||||
10802 | // FIXME: a lot of the following diagnostics would be improved | ||||||
10803 | // if we had some location information about types. | ||||||
10804 | |||||||
10805 | QualType CharPP = | ||||||
10806 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | ||||||
10807 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | ||||||
10808 | |||||||
10809 | for (unsigned i = 0; i < nparams; ++i) { | ||||||
10810 | QualType AT = FTP->getParamType(i); | ||||||
10811 | |||||||
10812 | bool mismatch = true; | ||||||
10813 | |||||||
10814 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | ||||||
10815 | mismatch = false; | ||||||
10816 | else if (Expected[i] == CharPP) { | ||||||
10817 | // As an extension, the following forms are okay: | ||||||
10818 | // char const ** | ||||||
10819 | // char const * const * | ||||||
10820 | // char * const * | ||||||
10821 | |||||||
10822 | QualifierCollector qs; | ||||||
10823 | const PointerType* PT; | ||||||
10824 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | ||||||
10825 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | ||||||
10826 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | ||||||
10827 | Context.CharTy)) { | ||||||
10828 | qs.removeConst(); | ||||||
10829 | mismatch = !qs.empty(); | ||||||
10830 | } | ||||||
10831 | } | ||||||
10832 | |||||||
10833 | if (mismatch) { | ||||||
10834 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | ||||||
10835 | // TODO: suggest replacing given type with expected type | ||||||
10836 | FD->setInvalidDecl(true); | ||||||
10837 | } | ||||||
10838 | } | ||||||
10839 | |||||||
10840 | if (nparams == 1 && !FD->isInvalidDecl()) { | ||||||
10841 | Diag(FD->getLocation(), diag::warn_main_one_arg); | ||||||
10842 | } | ||||||
10843 | |||||||
10844 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||||
10845 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||||
10846 | FD->setInvalidDecl(); | ||||||
10847 | } | ||||||
10848 | } | ||||||
10849 | |||||||
10850 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | ||||||
10851 | QualType T = FD->getType(); | ||||||
10852 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 10852, __PRETTY_FUNCTION__)); | ||||||
10853 | const FunctionType *FT = T->castAs<FunctionType>(); | ||||||
10854 | |||||||
10855 | // Set an implicit return of 'zero' if the function can return some integral, | ||||||
10856 | // enumeration, pointer or nullptr type. | ||||||
10857 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | ||||||
10858 | FT->getReturnType()->isAnyPointerType() || | ||||||
10859 | FT->getReturnType()->isNullPtrType()) | ||||||
10860 | // DllMain is exempt because a return value of zero means it failed. | ||||||
10861 | if (FD->getName() != "DllMain") | ||||||
10862 | FD->setHasImplicitReturnZero(true); | ||||||
10863 | |||||||
10864 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||||
10865 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||||
10866 | FD->setInvalidDecl(); | ||||||
10867 | } | ||||||
10868 | } | ||||||
10869 | |||||||
10870 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | ||||||
10871 | // FIXME: Need strict checking. In C89, we need to check for | ||||||
10872 | // any assignment, increment, decrement, function-calls, or | ||||||
10873 | // commas outside of a sizeof. In C99, it's the same list, | ||||||
10874 | // except that the aforementioned are allowed in unevaluated | ||||||
10875 | // expressions. Everything else falls under the | ||||||
10876 | // "may accept other forms of constant expressions" exception. | ||||||
10877 | // (We never end up here for C++, so the constant expression | ||||||
10878 | // rules there don't matter.) | ||||||
10879 | const Expr *Culprit; | ||||||
10880 | if (Init->isConstantInitializer(Context, false, &Culprit)) | ||||||
10881 | return false; | ||||||
10882 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | ||||||
10883 | << Culprit->getSourceRange(); | ||||||
10884 | return true; | ||||||
10885 | } | ||||||
10886 | |||||||
10887 | namespace { | ||||||
10888 | // Visits an initialization expression to see if OrigDecl is evaluated in | ||||||
10889 | // its own initialization and throws a warning if it does. | ||||||
10890 | class SelfReferenceChecker | ||||||
10891 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | ||||||
10892 | Sema &S; | ||||||
10893 | Decl *OrigDecl; | ||||||
10894 | bool isRecordType; | ||||||
10895 | bool isPODType; | ||||||
10896 | bool isReferenceType; | ||||||
10897 | |||||||
10898 | bool isInitList; | ||||||
10899 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | ||||||
10900 | |||||||
10901 | public: | ||||||
10902 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | ||||||
10903 | |||||||
10904 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | ||||||
10905 | S(S), OrigDecl(OrigDecl) { | ||||||
10906 | isPODType = false; | ||||||
10907 | isRecordType = false; | ||||||
10908 | isReferenceType = false; | ||||||
10909 | isInitList = false; | ||||||
10910 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | ||||||
10911 | isPODType = VD->getType().isPODType(S.Context); | ||||||
10912 | isRecordType = VD->getType()->isRecordType(); | ||||||
10913 | isReferenceType = VD->getType()->isReferenceType(); | ||||||
10914 | } | ||||||
10915 | } | ||||||
10916 | |||||||
10917 | // For most expressions, just call the visitor. For initializer lists, | ||||||
10918 | // track the index of the field being initialized since fields are | ||||||
10919 | // initialized in order allowing use of previously initialized fields. | ||||||
10920 | void CheckExpr(Expr *E) { | ||||||
10921 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | ||||||
10922 | if (!InitList) { | ||||||
10923 | Visit(E); | ||||||
10924 | return; | ||||||
10925 | } | ||||||
10926 | |||||||
10927 | // Track and increment the index here. | ||||||
10928 | isInitList = true; | ||||||
10929 | InitFieldIndex.push_back(0); | ||||||
10930 | for (auto Child : InitList->children()) { | ||||||
10931 | CheckExpr(cast<Expr>(Child)); | ||||||
10932 | ++InitFieldIndex.back(); | ||||||
10933 | } | ||||||
10934 | InitFieldIndex.pop_back(); | ||||||
10935 | } | ||||||
10936 | |||||||
10937 | // Returns true if MemberExpr is checked and no further checking is needed. | ||||||
10938 | // Returns false if additional checking is required. | ||||||
10939 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | ||||||
10940 | llvm::SmallVector<FieldDecl*, 4> Fields; | ||||||
10941 | Expr *Base = E; | ||||||
10942 | bool ReferenceField = false; | ||||||
10943 | |||||||
10944 | // Get the field members used. | ||||||
10945 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
10946 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||||
10947 | if (!FD) | ||||||
10948 | return false; | ||||||
10949 | Fields.push_back(FD); | ||||||
10950 | if (FD->getType()->isReferenceType()) | ||||||
10951 | ReferenceField = true; | ||||||
10952 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
10953 | } | ||||||
10954 | |||||||
10955 | // Keep checking only if the base Decl is the same. | ||||||
10956 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | ||||||
10957 | if (!DRE || DRE->getDecl() != OrigDecl) | ||||||
10958 | return false; | ||||||
10959 | |||||||
10960 | // A reference field can be bound to an unininitialized field. | ||||||
10961 | if (CheckReference && !ReferenceField) | ||||||
10962 | return true; | ||||||
10963 | |||||||
10964 | // Convert FieldDecls to their index number. | ||||||
10965 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | ||||||
10966 | for (const FieldDecl *I : llvm::reverse(Fields)) | ||||||
10967 | UsedFieldIndex.push_back(I->getFieldIndex()); | ||||||
10968 | |||||||
10969 | // See if a warning is needed by checking the first difference in index | ||||||
10970 | // numbers. If field being used has index less than the field being | ||||||
10971 | // initialized, then the use is safe. | ||||||
10972 | for (auto UsedIter = UsedFieldIndex.begin(), | ||||||
10973 | UsedEnd = UsedFieldIndex.end(), | ||||||
10974 | OrigIter = InitFieldIndex.begin(), | ||||||
10975 | OrigEnd = InitFieldIndex.end(); | ||||||
10976 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | ||||||
10977 | if (*UsedIter < *OrigIter) | ||||||
10978 | return true; | ||||||
10979 | if (*UsedIter > *OrigIter) | ||||||
10980 | break; | ||||||
10981 | } | ||||||
10982 | |||||||
10983 | // TODO: Add a different warning which will print the field names. | ||||||
10984 | HandleDeclRefExpr(DRE); | ||||||
10985 | return true; | ||||||
10986 | } | ||||||
10987 | |||||||
10988 | // For most expressions, the cast is directly above the DeclRefExpr. | ||||||
10989 | // For conditional operators, the cast can be outside the conditional | ||||||
10990 | // operator if both expressions are DeclRefExpr's. | ||||||
10991 | void HandleValue(Expr *E) { | ||||||
10992 | E = E->IgnoreParens(); | ||||||
10993 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | ||||||
10994 | HandleDeclRefExpr(DRE); | ||||||
10995 | return; | ||||||
10996 | } | ||||||
10997 | |||||||
10998 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | ||||||
10999 | Visit(CO->getCond()); | ||||||
11000 | HandleValue(CO->getTrueExpr()); | ||||||
11001 | HandleValue(CO->getFalseExpr()); | ||||||
11002 | return; | ||||||
11003 | } | ||||||
11004 | |||||||
11005 | if (BinaryConditionalOperator *BCO = | ||||||
11006 | dyn_cast<BinaryConditionalOperator>(E)) { | ||||||
11007 | Visit(BCO->getCond()); | ||||||
11008 | HandleValue(BCO->getFalseExpr()); | ||||||
11009 | return; | ||||||
11010 | } | ||||||
11011 | |||||||
11012 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | ||||||
11013 | HandleValue(OVE->getSourceExpr()); | ||||||
11014 | return; | ||||||
11015 | } | ||||||
11016 | |||||||
11017 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | ||||||
11018 | if (BO->getOpcode() == BO_Comma) { | ||||||
11019 | Visit(BO->getLHS()); | ||||||
11020 | HandleValue(BO->getRHS()); | ||||||
11021 | return; | ||||||
11022 | } | ||||||
11023 | } | ||||||
11024 | |||||||
11025 | if (isa<MemberExpr>(E)) { | ||||||
11026 | if (isInitList) { | ||||||
11027 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | ||||||
11028 | false /*CheckReference*/)) | ||||||
11029 | return; | ||||||
11030 | } | ||||||
11031 | |||||||
11032 | Expr *Base = E->IgnoreParenImpCasts(); | ||||||
11033 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11034 | // Check for static member variables and don't warn on them. | ||||||
11035 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||||
11036 | return; | ||||||
11037 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11038 | } | ||||||
11039 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | ||||||
11040 | HandleDeclRefExpr(DRE); | ||||||
11041 | return; | ||||||
11042 | } | ||||||
11043 | |||||||
11044 | Visit(E); | ||||||
11045 | } | ||||||
11046 | |||||||
11047 | // Reference types not handled in HandleValue are handled here since all | ||||||
11048 | // uses of references are bad, not just r-value uses. | ||||||
11049 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||||
11050 | if (isReferenceType) | ||||||
11051 | HandleDeclRefExpr(E); | ||||||
11052 | } | ||||||
11053 | |||||||
11054 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||||
11055 | if (E->getCastKind() == CK_LValueToRValue) { | ||||||
11056 | HandleValue(E->getSubExpr()); | ||||||
11057 | return; | ||||||
11058 | } | ||||||
11059 | |||||||
11060 | Inherited::VisitImplicitCastExpr(E); | ||||||
11061 | } | ||||||
11062 | |||||||
11063 | void VisitMemberExpr(MemberExpr *E) { | ||||||
11064 | if (isInitList) { | ||||||
11065 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | ||||||
11066 | return; | ||||||
11067 | } | ||||||
11068 | |||||||
11069 | // Don't warn on arrays since they can be treated as pointers. | ||||||
11070 | if (E->getType()->canDecayToPointerType()) return; | ||||||
11071 | |||||||
11072 | // Warn when a non-static method call is followed by non-static member | ||||||
11073 | // field accesses, which is followed by a DeclRefExpr. | ||||||
11074 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | ||||||
11075 | bool Warn = (MD && !MD->isStatic()); | ||||||
11076 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | ||||||
11077 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11078 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||||
11079 | Warn = false; | ||||||
11080 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11081 | } | ||||||
11082 | |||||||
11083 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | ||||||
11084 | if (Warn) | ||||||
11085 | HandleDeclRefExpr(DRE); | ||||||
11086 | return; | ||||||
11087 | } | ||||||
11088 | |||||||
11089 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | ||||||
11090 | // Visit that expression. | ||||||
11091 | Visit(Base); | ||||||
11092 | } | ||||||
11093 | |||||||
11094 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||||
11095 | Expr *Callee = E->getCallee(); | ||||||
11096 | |||||||
11097 | if (isa<UnresolvedLookupExpr>(Callee)) | ||||||
11098 | return Inherited::VisitCXXOperatorCallExpr(E); | ||||||
11099 | |||||||
11100 | Visit(Callee); | ||||||
11101 | for (auto Arg: E->arguments()) | ||||||
11102 | HandleValue(Arg->IgnoreParenImpCasts()); | ||||||
11103 | } | ||||||
11104 | |||||||
11105 | void VisitUnaryOperator(UnaryOperator *E) { | ||||||
11106 | // For POD record types, addresses of its own members are well-defined. | ||||||
11107 | if (E->getOpcode() == UO_AddrOf && isRecordType && | ||||||
11108 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | ||||||
11109 | if (!isPODType) | ||||||
11110 | HandleValue(E->getSubExpr()); | ||||||
11111 | return; | ||||||
11112 | } | ||||||
11113 | |||||||
11114 | if (E->isIncrementDecrementOp()) { | ||||||
11115 | HandleValue(E->getSubExpr()); | ||||||
11116 | return; | ||||||
11117 | } | ||||||
11118 | |||||||
11119 | Inherited::VisitUnaryOperator(E); | ||||||
11120 | } | ||||||
11121 | |||||||
11122 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | ||||||
11123 | |||||||
11124 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | ||||||
11125 | if (E->getConstructor()->isCopyConstructor()) { | ||||||
11126 | Expr *ArgExpr = E->getArg(0); | ||||||
11127 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | ||||||
11128 | if (ILE->getNumInits() == 1) | ||||||
11129 | ArgExpr = ILE->getInit(0); | ||||||
11130 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | ||||||
11131 | if (ICE->getCastKind() == CK_NoOp) | ||||||
11132 | ArgExpr = ICE->getSubExpr(); | ||||||
11133 | HandleValue(ArgExpr); | ||||||
11134 | return; | ||||||
11135 | } | ||||||
11136 | Inherited::VisitCXXConstructExpr(E); | ||||||
11137 | } | ||||||
11138 | |||||||
11139 | void VisitCallExpr(CallExpr *E) { | ||||||
11140 | // Treat std::move as a use. | ||||||
11141 | if (E->isCallToStdMove()) { | ||||||
11142 | HandleValue(E->getArg(0)); | ||||||
11143 | return; | ||||||
11144 | } | ||||||
11145 | |||||||
11146 | Inherited::VisitCallExpr(E); | ||||||
11147 | } | ||||||
11148 | |||||||
11149 | void VisitBinaryOperator(BinaryOperator *E) { | ||||||
11150 | if (E->isCompoundAssignmentOp()) { | ||||||
11151 | HandleValue(E->getLHS()); | ||||||
11152 | Visit(E->getRHS()); | ||||||
11153 | return; | ||||||
11154 | } | ||||||
11155 | |||||||
11156 | Inherited::VisitBinaryOperator(E); | ||||||
11157 | } | ||||||
11158 | |||||||
11159 | // A custom visitor for BinaryConditionalOperator is needed because the | ||||||
11160 | // regular visitor would check the condition and true expression separately | ||||||
11161 | // but both point to the same place giving duplicate diagnostics. | ||||||
11162 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | ||||||
11163 | Visit(E->getCond()); | ||||||
11164 | Visit(E->getFalseExpr()); | ||||||
11165 | } | ||||||
11166 | |||||||
11167 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | ||||||
11168 | Decl* ReferenceDecl = DRE->getDecl(); | ||||||
11169 | if (OrigDecl != ReferenceDecl) return; | ||||||
11170 | unsigned diag; | ||||||
11171 | if (isReferenceType) { | ||||||
11172 | diag = diag::warn_uninit_self_reference_in_reference_init; | ||||||
11173 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | ||||||
11174 | diag = diag::warn_static_self_reference_in_init; | ||||||
11175 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | ||||||
11176 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | ||||||
11177 | DRE->getDecl()->getType()->isRecordType()) { | ||||||
11178 | diag = diag::warn_uninit_self_reference_in_init; | ||||||
11179 | } else { | ||||||
11180 | // Local variables will be handled by the CFG analysis. | ||||||
11181 | return; | ||||||
11182 | } | ||||||
11183 | |||||||
11184 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, | ||||||
11185 | S.PDiag(diag) | ||||||
11186 | << DRE->getDecl() << OrigDecl->getLocation() | ||||||
11187 | << DRE->getSourceRange()); | ||||||
11188 | } | ||||||
11189 | }; | ||||||
11190 | |||||||
11191 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | ||||||
11192 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | ||||||
11193 | bool DirectInit) { | ||||||
11194 | // Parameters arguments are occassionially constructed with itself, | ||||||
11195 | // for instance, in recursive functions. Skip them. | ||||||
11196 | if (isa<ParmVarDecl>(OrigDecl)) | ||||||
11197 | return; | ||||||
11198 | |||||||
11199 | E = E->IgnoreParens(); | ||||||
11200 | |||||||
11201 | // Skip checking T a = a where T is not a record or reference type. | ||||||
11202 | // Doing so is a way to silence uninitialized warnings. | ||||||
11203 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | ||||||
11204 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||||
11205 | if (ICE->getCastKind() == CK_LValueToRValue) | ||||||
11206 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | ||||||
11207 | if (DRE->getDecl() == OrigDecl) | ||||||
11208 | return; | ||||||
11209 | |||||||
11210 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | ||||||
11211 | } | ||||||
11212 | } // end anonymous namespace | ||||||
11213 | |||||||
11214 | namespace { | ||||||
11215 | // Simple wrapper to add the name of a variable or (if no variable is | ||||||
11216 | // available) a DeclarationName into a diagnostic. | ||||||
11217 | struct VarDeclOrName { | ||||||
11218 | VarDecl *VDecl; | ||||||
11219 | DeclarationName Name; | ||||||
11220 | |||||||
11221 | friend const Sema::SemaDiagnosticBuilder & | ||||||
11222 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | ||||||
11223 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | ||||||
11224 | } | ||||||
11225 | }; | ||||||
11226 | } // end anonymous namespace | ||||||
11227 | |||||||
11228 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | ||||||
11229 | DeclarationName Name, QualType Type, | ||||||
11230 | TypeSourceInfo *TSI, | ||||||
11231 | SourceRange Range, bool DirectInit, | ||||||
11232 | Expr *Init) { | ||||||
11233 | bool IsInitCapture = !VDecl; | ||||||
11234 | assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11235, __PRETTY_FUNCTION__)) | ||||||
11235 | "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11235, __PRETTY_FUNCTION__)); | ||||||
11236 | |||||||
11237 | VarDeclOrName VN{VDecl, Name}; | ||||||
11238 | |||||||
11239 | DeducedType *Deduced = Type->getContainedDeducedType(); | ||||||
11240 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11240, __PRETTY_FUNCTION__)); | ||||||
11241 | |||||||
11242 | // C++11 [dcl.spec.auto]p3 | ||||||
11243 | if (!Init) { | ||||||
11244 | assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast <void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11244, __PRETTY_FUNCTION__)); | ||||||
11245 | |||||||
11246 | // Except for class argument deduction, and then for an initializing | ||||||
11247 | // declaration only, i.e. no static at class scope or extern. | ||||||
11248 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | ||||||
11249 | VDecl->hasExternalStorage() || | ||||||
11250 | VDecl->isStaticDataMember()) { | ||||||
11251 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | ||||||
11252 | << VDecl->getDeclName() << Type; | ||||||
11253 | return QualType(); | ||||||
11254 | } | ||||||
11255 | } | ||||||
11256 | |||||||
11257 | ArrayRef<Expr*> DeduceInits; | ||||||
11258 | if (Init) | ||||||
11259 | DeduceInits = Init; | ||||||
11260 | |||||||
11261 | if (DirectInit) { | ||||||
11262 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | ||||||
11263 | DeduceInits = PL->exprs(); | ||||||
11264 | } | ||||||
11265 | |||||||
11266 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | ||||||
11267 | assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?" ) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11267, __PRETTY_FUNCTION__)); | ||||||
11268 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||||
11269 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||||
11270 | VDecl->getLocation(), DirectInit, Init); | ||||||
11271 | // FIXME: Initialization should not be taking a mutable list of inits. | ||||||
11272 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | ||||||
11273 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | ||||||
11274 | InitsCopy); | ||||||
11275 | } | ||||||
11276 | |||||||
11277 | if (DirectInit) { | ||||||
11278 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | ||||||
11279 | DeduceInits = IL->inits(); | ||||||
11280 | } | ||||||
11281 | |||||||
11282 | // Deduction only works if we have exactly one source expression. | ||||||
11283 | if (DeduceInits.empty()) { | ||||||
11284 | // It isn't possible to write this directly, but it is possible to | ||||||
11285 | // end up in this situation with "auto x(some_pack...);" | ||||||
11286 | Diag(Init->getBeginLoc(), IsInitCapture | ||||||
11287 | ? diag::err_init_capture_no_expression | ||||||
11288 | : diag::err_auto_var_init_no_expression) | ||||||
11289 | << VN << Type << Range; | ||||||
11290 | return QualType(); | ||||||
11291 | } | ||||||
11292 | |||||||
11293 | if (DeduceInits.size() > 1) { | ||||||
11294 | Diag(DeduceInits[1]->getBeginLoc(), | ||||||
11295 | IsInitCapture ? diag::err_init_capture_multiple_expressions | ||||||
11296 | : diag::err_auto_var_init_multiple_expressions) | ||||||
11297 | << VN << Type << Range; | ||||||
11298 | return QualType(); | ||||||
11299 | } | ||||||
11300 | |||||||
11301 | Expr *DeduceInit = DeduceInits[0]; | ||||||
11302 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | ||||||
11303 | Diag(Init->getBeginLoc(), IsInitCapture | ||||||
11304 | ? diag::err_init_capture_paren_braces | ||||||
11305 | : diag::err_auto_var_init_paren_braces) | ||||||
11306 | << isa<InitListExpr>(Init) << VN << Type << Range; | ||||||
11307 | return QualType(); | ||||||
11308 | } | ||||||
11309 | |||||||
11310 | // Expressions default to 'id' when we're in a debugger. | ||||||
11311 | bool DefaultedAnyToId = false; | ||||||
11312 | if (getLangOpts().DebuggerCastResultToId && | ||||||
11313 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | ||||||
11314 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||||
11315 | if (Result.isInvalid()) { | ||||||
11316 | return QualType(); | ||||||
11317 | } | ||||||
11318 | Init = Result.get(); | ||||||
11319 | DefaultedAnyToId = true; | ||||||
11320 | } | ||||||
11321 | |||||||
11322 | // C++ [dcl.decomp]p1: | ||||||
11323 | // If the assignment-expression [...] has array type A and no ref-qualifier | ||||||
11324 | // is present, e has type cv A | ||||||
11325 | if (VDecl && isa<DecompositionDecl>(VDecl) && | ||||||
11326 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | ||||||
11327 | DeduceInit->getType()->isConstantArrayType()) | ||||||
11328 | return Context.getQualifiedType(DeduceInit->getType(), | ||||||
11329 | Type.getQualifiers()); | ||||||
11330 | |||||||
11331 | QualType DeducedType; | ||||||
11332 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | ||||||
11333 | if (!IsInitCapture) | ||||||
11334 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | ||||||
11335 | else if (isa<InitListExpr>(Init)) | ||||||
11336 | Diag(Range.getBegin(), | ||||||
11337 | diag::err_init_capture_deduction_failure_from_init_list) | ||||||
11338 | << VN | ||||||
11339 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||||
11340 | : DeduceInit->getType()) | ||||||
11341 | << DeduceInit->getSourceRange(); | ||||||
11342 | else | ||||||
11343 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | ||||||
11344 | << VN << TSI->getType() | ||||||
11345 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||||
11346 | : DeduceInit->getType()) | ||||||
11347 | << DeduceInit->getSourceRange(); | ||||||
11348 | } | ||||||
11349 | |||||||
11350 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | ||||||
11351 | // 'id' instead of a specific object type prevents most of our usual | ||||||
11352 | // checks. | ||||||
11353 | // We only want to warn outside of template instantiations, though: | ||||||
11354 | // inside a template, the 'id' could have come from a parameter. | ||||||
11355 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | ||||||
11356 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | ||||||
11357 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | ||||||
11358 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | ||||||
11359 | } | ||||||
11360 | |||||||
11361 | return DeducedType; | ||||||
11362 | } | ||||||
11363 | |||||||
11364 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | ||||||
11365 | Expr *Init) { | ||||||
11366 | QualType DeducedType = deduceVarTypeFromInitializer( | ||||||
11367 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | ||||||
11368 | VDecl->getSourceRange(), DirectInit, Init); | ||||||
11369 | if (DeducedType.isNull()) { | ||||||
11370 | VDecl->setInvalidDecl(); | ||||||
11371 | return true; | ||||||
11372 | } | ||||||
11373 | |||||||
11374 | VDecl->setType(DeducedType); | ||||||
11375 | assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11375, __PRETTY_FUNCTION__)); | ||||||
11376 | |||||||
11377 | // In ARC, infer lifetime. | ||||||
11378 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | ||||||
11379 | VDecl->setInvalidDecl(); | ||||||
11380 | |||||||
11381 | if (getLangOpts().OpenCL) | ||||||
11382 | deduceOpenCLAddressSpace(VDecl); | ||||||
11383 | |||||||
11384 | // If this is a redeclaration, check that the type we just deduced matches | ||||||
11385 | // the previously declared type. | ||||||
11386 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | ||||||
11387 | // We never need to merge the type, because we cannot form an incomplete | ||||||
11388 | // array of auto, nor deduce such a type. | ||||||
11389 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | ||||||
11390 | } | ||||||
11391 | |||||||
11392 | // Check the deduced type is valid for a variable declaration. | ||||||
11393 | CheckVariableDeclarationType(VDecl); | ||||||
11394 | return VDecl->isInvalidDecl(); | ||||||
11395 | } | ||||||
11396 | |||||||
11397 | void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, | ||||||
11398 | SourceLocation Loc) { | ||||||
11399 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||||
11400 | Init = CE->getSubExpr(); | ||||||
11401 | |||||||
11402 | QualType InitType = Init->getType(); | ||||||
11403 | assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11405, __PRETTY_FUNCTION__)) | ||||||
11404 | InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11405, __PRETTY_FUNCTION__)) | ||||||
11405 | "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11405, __PRETTY_FUNCTION__)); | ||||||
11406 | if (auto *ILE = dyn_cast<InitListExpr>(Init)) { | ||||||
11407 | for (auto I : ILE->inits()) { | ||||||
11408 | if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && | ||||||
11409 | !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11410 | continue; | ||||||
11411 | SourceLocation SL = I->getExprLoc(); | ||||||
11412 | checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); | ||||||
11413 | } | ||||||
11414 | return; | ||||||
11415 | } | ||||||
11416 | |||||||
11417 | if (isa<ImplicitValueInitExpr>(Init)) { | ||||||
11418 | if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
11419 | checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, | ||||||
11420 | NTCUK_Init); | ||||||
11421 | } else { | ||||||
11422 | // Assume all other explicit initializers involving copying some existing | ||||||
11423 | // object. | ||||||
11424 | // TODO: ignore any explicit initializers where we can guarantee | ||||||
11425 | // copy-elision. | ||||||
11426 | if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11427 | checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); | ||||||
11428 | } | ||||||
11429 | } | ||||||
11430 | |||||||
11431 | namespace { | ||||||
11432 | |||||||
11433 | bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { | ||||||
11434 | // Ignore unavailable fields. A field can be marked as unavailable explicitly | ||||||
11435 | // in the source code or implicitly by the compiler if it is in a union | ||||||
11436 | // defined in a system header and has non-trivial ObjC ownership | ||||||
11437 | // qualifications. We don't want those fields to participate in determining | ||||||
11438 | // whether the containing union is non-trivial. | ||||||
11439 | return FD->hasAttr<UnavailableAttr>(); | ||||||
11440 | } | ||||||
11441 | |||||||
11442 | struct DiagNonTrivalCUnionDefaultInitializeVisitor | ||||||
11443 | : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||||
11444 | void> { | ||||||
11445 | using Super = | ||||||
11446 | DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||||
11447 | void>; | ||||||
11448 | |||||||
11449 | DiagNonTrivalCUnionDefaultInitializeVisitor( | ||||||
11450 | QualType OrigTy, SourceLocation OrigLoc, | ||||||
11451 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||||
11452 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11453 | |||||||
11454 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, | ||||||
11455 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11456 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11457 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11458 | InNonTrivialUnion); | ||||||
11459 | return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); | ||||||
11460 | } | ||||||
11461 | |||||||
11462 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11463 | bool InNonTrivialUnion) { | ||||||
11464 | if (InNonTrivialUnion) | ||||||
11465 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11466 | << 1 << 0 << QT << FD->getName(); | ||||||
11467 | } | ||||||
11468 | |||||||
11469 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11470 | if (InNonTrivialUnion) | ||||||
11471 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11472 | << 1 << 0 << QT << FD->getName(); | ||||||
11473 | } | ||||||
11474 | |||||||
11475 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11476 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11477 | if (RD->isUnion()) { | ||||||
11478 | if (OrigLoc.isValid()) { | ||||||
11479 | bool IsUnion = false; | ||||||
11480 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11481 | IsUnion = OrigRD->isUnion(); | ||||||
11482 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11483 | << 0 << OrigTy << IsUnion << UseContext; | ||||||
11484 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11485 | OrigLoc = SourceLocation(); | ||||||
11486 | } | ||||||
11487 | InNonTrivialUnion = true; | ||||||
11488 | } | ||||||
11489 | |||||||
11490 | if (InNonTrivialUnion) | ||||||
11491 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11492 | << 0 << 0 << QT.getUnqualifiedType() << ""; | ||||||
11493 | |||||||
11494 | for (const FieldDecl *FD : RD->fields()) | ||||||
11495 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11496 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11497 | } | ||||||
11498 | |||||||
11499 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11500 | |||||||
11501 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11502 | // non-trivial C union. | ||||||
11503 | QualType OrigTy; | ||||||
11504 | SourceLocation OrigLoc; | ||||||
11505 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11506 | Sema &S; | ||||||
11507 | }; | ||||||
11508 | |||||||
11509 | struct DiagNonTrivalCUnionDestructedTypeVisitor | ||||||
11510 | : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { | ||||||
11511 | using Super = | ||||||
11512 | DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; | ||||||
11513 | |||||||
11514 | DiagNonTrivalCUnionDestructedTypeVisitor( | ||||||
11515 | QualType OrigTy, SourceLocation OrigLoc, | ||||||
11516 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||||
11517 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11518 | |||||||
11519 | void visitWithKind(QualType::DestructionKind DK, QualType QT, | ||||||
11520 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11521 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11522 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11523 | InNonTrivialUnion); | ||||||
11524 | return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); | ||||||
11525 | } | ||||||
11526 | |||||||
11527 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11528 | bool InNonTrivialUnion) { | ||||||
11529 | if (InNonTrivialUnion) | ||||||
11530 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11531 | << 1 << 1 << QT << FD->getName(); | ||||||
11532 | } | ||||||
11533 | |||||||
11534 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11535 | if (InNonTrivialUnion) | ||||||
11536 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11537 | << 1 << 1 << QT << FD->getName(); | ||||||
11538 | } | ||||||
11539 | |||||||
11540 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11541 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11542 | if (RD->isUnion()) { | ||||||
11543 | if (OrigLoc.isValid()) { | ||||||
11544 | bool IsUnion = false; | ||||||
11545 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11546 | IsUnion = OrigRD->isUnion(); | ||||||
11547 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11548 | << 1 << OrigTy << IsUnion << UseContext; | ||||||
11549 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11550 | OrigLoc = SourceLocation(); | ||||||
11551 | } | ||||||
11552 | InNonTrivialUnion = true; | ||||||
11553 | } | ||||||
11554 | |||||||
11555 | if (InNonTrivialUnion) | ||||||
11556 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11557 | << 0 << 1 << QT.getUnqualifiedType() << ""; | ||||||
11558 | |||||||
11559 | for (const FieldDecl *FD : RD->fields()) | ||||||
11560 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11561 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11562 | } | ||||||
11563 | |||||||
11564 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11565 | void visitCXXDestructor(QualType QT, const FieldDecl *FD, | ||||||
11566 | bool InNonTrivialUnion) {} | ||||||
11567 | |||||||
11568 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11569 | // non-trivial C union. | ||||||
11570 | QualType OrigTy; | ||||||
11571 | SourceLocation OrigLoc; | ||||||
11572 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11573 | Sema &S; | ||||||
11574 | }; | ||||||
11575 | |||||||
11576 | struct DiagNonTrivalCUnionCopyVisitor | ||||||
11577 | : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { | ||||||
11578 | using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; | ||||||
11579 | |||||||
11580 | DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, | ||||||
11581 | Sema::NonTrivialCUnionContext UseContext, | ||||||
11582 | Sema &S) | ||||||
11583 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11584 | |||||||
11585 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||||
11586 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11587 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11588 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11589 | InNonTrivialUnion); | ||||||
11590 | return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); | ||||||
11591 | } | ||||||
11592 | |||||||
11593 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11594 | bool InNonTrivialUnion) { | ||||||
11595 | if (InNonTrivialUnion) | ||||||
11596 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11597 | << 1 << 2 << QT << FD->getName(); | ||||||
11598 | } | ||||||
11599 | |||||||
11600 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11601 | if (InNonTrivialUnion) | ||||||
11602 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11603 | << 1 << 2 << QT << FD->getName(); | ||||||
11604 | } | ||||||
11605 | |||||||
11606 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11607 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11608 | if (RD->isUnion()) { | ||||||
11609 | if (OrigLoc.isValid()) { | ||||||
11610 | bool IsUnion = false; | ||||||
11611 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11612 | IsUnion = OrigRD->isUnion(); | ||||||
11613 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11614 | << 2 << OrigTy << IsUnion << UseContext; | ||||||
11615 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11616 | OrigLoc = SourceLocation(); | ||||||
11617 | } | ||||||
11618 | InNonTrivialUnion = true; | ||||||
11619 | } | ||||||
11620 | |||||||
11621 | if (InNonTrivialUnion) | ||||||
11622 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11623 | << 0 << 2 << QT.getUnqualifiedType() << ""; | ||||||
11624 | |||||||
11625 | for (const FieldDecl *FD : RD->fields()) | ||||||
11626 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11627 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11628 | } | ||||||
11629 | |||||||
11630 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||||
11631 | const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11632 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11633 | void visitVolatileTrivial(QualType QT, const FieldDecl *FD, | ||||||
11634 | bool InNonTrivialUnion) {} | ||||||
11635 | |||||||
11636 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11637 | // non-trivial C union. | ||||||
11638 | QualType OrigTy; | ||||||
11639 | SourceLocation OrigLoc; | ||||||
11640 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11641 | Sema &S; | ||||||
11642 | }; | ||||||
11643 | |||||||
11644 | } // namespace | ||||||
11645 | |||||||
11646 | void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, | ||||||
11647 | NonTrivialCUnionContext UseContext, | ||||||
11648 | unsigned NonTrivialKind) { | ||||||
11649 | assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)) | ||||||
11650 | QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)) | ||||||
11651 | QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)) | ||||||
11652 | "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)); | ||||||
11653 | |||||||
11654 | if ((NonTrivialKind & NTCUK_Init) && | ||||||
11655 | QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
11656 | DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) | ||||||
11657 | .visit(QT, nullptr, false); | ||||||
11658 | if ((NonTrivialKind & NTCUK_Destruct) && | ||||||
11659 | QT.hasNonTrivialToPrimitiveDestructCUnion()) | ||||||
11660 | DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) | ||||||
11661 | .visit(QT, nullptr, false); | ||||||
11662 | if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11663 | DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) | ||||||
11664 | .visit(QT, nullptr, false); | ||||||
11665 | } | ||||||
11666 | |||||||
11667 | /// AddInitializerToDecl - Adds the initializer Init to the | ||||||
11668 | /// declaration dcl. If DirectInit is true, this is C++ direct | ||||||
11669 | /// initialization rather than copy initialization. | ||||||
11670 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | ||||||
11671 | // If there is no declaration, there was an error parsing it. Just ignore | ||||||
11672 | // the initializer. | ||||||
11673 | if (!RealDecl || RealDecl->isInvalidDecl()) { | ||||||
11674 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | ||||||
11675 | return; | ||||||
11676 | } | ||||||
11677 | |||||||
11678 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | ||||||
11679 | // Pure-specifiers are handled in ActOnPureSpecifier. | ||||||
11680 | Diag(Method->getLocation(), diag::err_member_function_initialization) | ||||||
11681 | << Method->getDeclName() << Init->getSourceRange(); | ||||||
11682 | Method->setInvalidDecl(); | ||||||
11683 | return; | ||||||
11684 | } | ||||||
11685 | |||||||
11686 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | ||||||
11687 | if (!VDecl) { | ||||||
11688 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here" ) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 11688, __PRETTY_FUNCTION__)); | ||||||
11689 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | ||||||
11690 | RealDecl->setInvalidDecl(); | ||||||
11691 | return; | ||||||
11692 | } | ||||||
11693 | |||||||
11694 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | ||||||
11695 | if (VDecl->getType()->isUndeducedType()) { | ||||||
11696 | // Attempt typo correction early so that the type of the init expression can | ||||||
11697 | // be deduced based on the chosen correction if the original init contains a | ||||||
11698 | // TypoExpr. | ||||||
11699 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | ||||||
11700 | if (!Res.isUsable()) { | ||||||
11701 | RealDecl->setInvalidDecl(); | ||||||
11702 | return; | ||||||
11703 | } | ||||||
11704 | Init = Res.get(); | ||||||
11705 | |||||||
11706 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | ||||||
11707 | return; | ||||||
11708 | } | ||||||
11709 | |||||||
11710 | // dllimport cannot be used on variable definitions. | ||||||
11711 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | ||||||
11712 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | ||||||
11713 | VDecl->setInvalidDecl(); | ||||||
11714 | return; | ||||||
11715 | } | ||||||
11716 | |||||||
11717 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | ||||||
11718 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | ||||||
11719 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | ||||||
11720 | VDecl->setInvalidDecl(); | ||||||
11721 | return; | ||||||
11722 | } | ||||||
11723 | |||||||
11724 | if (!VDecl->getType()->isDependentType()) { | ||||||
11725 | // A definition must end up with a complete type, which means it must be | ||||||
11726 | // complete with the restriction that an array type might be completed by | ||||||
11727 | // the initializer; note that later code assumes this restriction. | ||||||
11728 | QualType BaseDeclType = VDecl->getType(); | ||||||
11729 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | ||||||
11730 | BaseDeclType = Array->getElementType(); | ||||||
11731 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | ||||||
11732 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
11733 | RealDecl->setInvalidDecl(); | ||||||
11734 | return; | ||||||
11735 | } | ||||||
11736 | |||||||
11737 | // The variable can not have an abstract class type. | ||||||
11738 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | ||||||
11739 | diag::err_abstract_type_in_decl, | ||||||
11740 | AbstractVariableType)) | ||||||
11741 | VDecl->setInvalidDecl(); | ||||||
11742 | } | ||||||
11743 | |||||||
11744 | // If adding the initializer will turn this declaration into a definition, | ||||||
11745 | // and we already have a definition for this variable, diagnose or otherwise | ||||||
11746 | // handle the situation. | ||||||
11747 | VarDecl *Def; | ||||||
11748 | if ((Def = VDecl->getDefinition()) && Def != VDecl && | ||||||
11749 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | ||||||
11750 | !VDecl->isThisDeclarationADemotedDefinition() && | ||||||
11751 | checkVarDeclRedefinition(Def, VDecl)) | ||||||
11752 | return; | ||||||
11753 | |||||||
11754 | if (getLangOpts().CPlusPlus) { | ||||||
11755 | // C++ [class.static.data]p4 | ||||||
11756 | // If a static data member is of const integral or const | ||||||
11757 | // enumeration type, its declaration in the class definition can | ||||||
11758 | // specify a constant-initializer which shall be an integral | ||||||
11759 | // constant expression (5.19). In that case, the member can appear | ||||||
11760 | // in integral constant expressions. The member shall still be | ||||||
11761 | // defined in a namespace scope if it is used in the program and the | ||||||
11762 | // namespace scope definition shall not contain an initializer. | ||||||
11763 | // | ||||||
11764 | // We already performed a redefinition check above, but for static | ||||||
11765 | // data members we also need to check whether there was an in-class | ||||||
11766 | // declaration with an initializer. | ||||||
11767 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | ||||||
11768 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | ||||||
11769 | << VDecl->getDeclName(); | ||||||
11770 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | ||||||
11771 | diag::note_previous_initializer) | ||||||
11772 | << 0; | ||||||
11773 | return; | ||||||
11774 | } | ||||||
11775 | |||||||
11776 | if (VDecl->hasLocalStorage()) | ||||||
11777 | setFunctionHasBranchProtectedScope(); | ||||||
11778 | |||||||
11779 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | ||||||
11780 | VDecl->setInvalidDecl(); | ||||||
11781 | return; | ||||||
11782 | } | ||||||
11783 | } | ||||||
11784 | |||||||
11785 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | ||||||
11786 | // a kernel function cannot be initialized." | ||||||
11787 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | ||||||
11788 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | ||||||
11789 | VDecl->setInvalidDecl(); | ||||||
11790 | return; | ||||||
11791 | } | ||||||
11792 | |||||||
11793 | // Get the decls type and save a reference for later, since | ||||||
11794 | // CheckInitializerTypes may change it. | ||||||
11795 | QualType DclT = VDecl->getType(), SavT = DclT; | ||||||
11796 | |||||||
11797 | // Expressions default to 'id' when we're in a debugger | ||||||
11798 | // and we are assigning it to a variable of Objective-C pointer type. | ||||||
11799 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | ||||||
11800 | Init->getType() == Context.UnknownAnyTy) { | ||||||
11801 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||||
11802 | if (Result.isInvalid()) { | ||||||
11803 | VDecl->setInvalidDecl(); | ||||||
11804 | return; | ||||||
11805 | } | ||||||
11806 | Init = Result.get(); | ||||||
11807 | } | ||||||
11808 | |||||||
11809 | // Perform the initialization. | ||||||
11810 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | ||||||
11811 | if (!VDecl->isInvalidDecl()) { | ||||||
11812 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||||
11813 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||||
11814 | VDecl->getLocation(), DirectInit, Init); | ||||||
11815 | |||||||
11816 | MultiExprArg Args = Init; | ||||||
11817 | if (CXXDirectInit) | ||||||
11818 | Args = MultiExprArg(CXXDirectInit->getExprs(), | ||||||
11819 | CXXDirectInit->getNumExprs()); | ||||||
11820 | |||||||
11821 | // Try to correct any TypoExprs in the initialization arguments. | ||||||
11822 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | ||||||
11823 | ExprResult Res = CorrectDelayedTyposInExpr( | ||||||
11824 | Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { | ||||||
11825 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | ||||||
11826 | return Init.Failed() ? ExprError() : E; | ||||||
11827 | }); | ||||||
11828 | if (Res.isInvalid()) { | ||||||
11829 | VDecl->setInvalidDecl(); | ||||||
11830 | } else if (Res.get() != Args[Idx]) { | ||||||
11831 | Args[Idx] = Res.get(); | ||||||
11832 | } | ||||||
11833 | } | ||||||
11834 | if (VDecl->isInvalidDecl()) | ||||||
11835 | return; | ||||||
11836 | |||||||
11837 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | ||||||
11838 | /*TopLevelOfInitList=*/false, | ||||||
11839 | /*TreatUnavailableAsInvalid=*/false); | ||||||
11840 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | ||||||
11841 | if (Result.isInvalid()) { | ||||||
11842 | VDecl->setInvalidDecl(); | ||||||
11843 | return; | ||||||
11844 | } | ||||||
11845 | |||||||
11846 | Init = Result.getAs<Expr>(); | ||||||
11847 | } | ||||||
11848 | |||||||
11849 | // Check for self-references within variable initializers. | ||||||
11850 | // Variables declared within a function/method body (except for references) | ||||||
11851 | // are handled by a dataflow analysis. | ||||||
11852 | // This is undefined behavior in C++, but valid in C. | ||||||
11853 | if (getLangOpts().CPlusPlus) { | ||||||
11854 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | ||||||
11855 | VDecl->getType()->isReferenceType()) { | ||||||
11856 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | ||||||
11857 | } | ||||||
11858 | } | ||||||
11859 | |||||||
11860 | // If the type changed, it means we had an incomplete type that was | ||||||
11861 | // completed by the initializer. For example: | ||||||
11862 | // int ary[] = { 1, 3, 5 }; | ||||||
11863 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | ||||||
11864 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | ||||||
11865 | VDecl->setType(DclT); | ||||||
11866 | |||||||
11867 | if (!VDecl->isInvalidDecl()) { | ||||||
11868 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | ||||||
11869 | |||||||
11870 | if (VDecl->hasAttr<BlocksAttr>()) | ||||||
11871 | checkRetainCycles(VDecl, Init); | ||||||
11872 | |||||||
11873 | // It is safe to assign a weak reference into a strong variable. | ||||||
11874 | // Although this code can still have problems: | ||||||
11875 | // id x = self.weakProp; | ||||||
11876 | // id y = self.weakProp; | ||||||
11877 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||||
11878 | // paths through the function. This should be revisited if | ||||||
11879 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||||
11880 | if (FunctionScopeInfo *FSI = getCurFunction()) | ||||||
11881 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | ||||||
11882 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | ||||||
11883 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||||
11884 | Init->getBeginLoc())) | ||||||
11885 | FSI->markSafeWeakUse(Init); | ||||||
11886 | } | ||||||
11887 | |||||||
11888 | // The initialization is usually a full-expression. | ||||||
11889 | // | ||||||
11890 | // FIXME: If this is a braced initialization of an aggregate, it is not | ||||||
11891 | // an expression, and each individual field initializer is a separate | ||||||
11892 | // full-expression. For instance, in: | ||||||
11893 | // | ||||||
11894 | // struct Temp { ~Temp(); }; | ||||||
11895 | // struct S { S(Temp); }; | ||||||
11896 | // struct T { S a, b; } t = { Temp(), Temp() } | ||||||
11897 | // | ||||||
11898 | // we should destroy the first Temp before constructing the second. | ||||||
11899 | ExprResult Result = | ||||||
11900 | ActOnFinishFullExpr(Init, VDecl->getLocation(), | ||||||
11901 | /*DiscardedValue*/ false, VDecl->isConstexpr()); | ||||||
11902 | if (Result.isInvalid()) { | ||||||
11903 | VDecl->setInvalidDecl(); | ||||||
11904 | return; | ||||||
11905 | } | ||||||
11906 | Init = Result.get(); | ||||||
11907 | |||||||
11908 | // Attach the initializer to the decl. | ||||||
11909 | VDecl->setInit(Init); | ||||||
11910 | |||||||
11911 | if (VDecl->isLocalVarDecl()) { | ||||||
11912 | // Don't check the initializer if the declaration is malformed. | ||||||
11913 | if (VDecl->isInvalidDecl()) { | ||||||
11914 | // do nothing | ||||||
11915 | |||||||
11916 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | ||||||
11917 | // This is true even in C++ for OpenCL. | ||||||
11918 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | ||||||
11919 | CheckForConstantInitializer(Init, DclT); | ||||||
11920 | |||||||
11921 | // Otherwise, C++ does not restrict the initializer. | ||||||
11922 | } else if (getLangOpts().CPlusPlus) { | ||||||
11923 | // do nothing | ||||||
11924 | |||||||
11925 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | ||||||
11926 | // static storage duration shall be constant expressions or string literals. | ||||||
11927 | } else if (VDecl->getStorageClass() == SC_Static) { | ||||||
11928 | CheckForConstantInitializer(Init, DclT); | ||||||
11929 | |||||||
11930 | // C89 is stricter than C99 for aggregate initializers. | ||||||
11931 | // C89 6.5.7p3: All the expressions [...] in an initializer list | ||||||
11932 | // for an object that has aggregate or union type shall be | ||||||
11933 | // constant expressions. | ||||||
11934 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | ||||||
11935 | isa<InitListExpr>(Init)) { | ||||||
11936 | const Expr *Culprit; | ||||||
11937 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | ||||||
11938 | Diag(Culprit->getExprLoc(), | ||||||
11939 | diag::ext_aggregate_init_not_constant) | ||||||
11940 | << Culprit->getSourceRange(); | ||||||
11941 | } | ||||||
11942 | } | ||||||
11943 | |||||||
11944 | if (auto *E = dyn_cast<ExprWithCleanups>(Init)) | ||||||
11945 | if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) | ||||||
11946 | if (VDecl->hasLocalStorage()) | ||||||
11947 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||||
11948 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | ||||||
11949 | VDecl->getLexicalDeclContext()->isRecord()) { | ||||||
11950 | // This is an in-class initialization for a static data member, e.g., | ||||||
11951 | // | ||||||
11952 | // struct S { | ||||||
11953 | // static const int value = 17; | ||||||
11954 | // }; | ||||||
11955 | |||||||
11956 | // C++ [class.mem]p4: | ||||||
11957 | // A member-declarator can contain a constant-initializer only | ||||||
11958 | // if it declares a static member (9.4) of const integral or | ||||||
11959 | // const enumeration type, see 9.4.2. | ||||||
11960 | // | ||||||
11961 | // C++11 [class.static.data]p3: | ||||||
11962 | // If a non-volatile non-inline const static data member is of integral | ||||||
11963 | // or enumeration type, its declaration in the class definition can | ||||||
11964 | // specify a brace-or-equal-initializer in which every initializer-clause | ||||||
11965 | // that is an assignment-expression is a constant expression. A static | ||||||
11966 | // data member of literal type can be declared in the class definition | ||||||
11967 | // with the constexpr specifier; if so, its declaration shall specify a | ||||||
11968 | // brace-or-equal-initializer in which every initializer-clause that is | ||||||
11969 | // an assignment-expression is a constant expression. | ||||||
11970 | |||||||
11971 | // Do nothing on dependent types. | ||||||
11972 | if (DclT->isDependentType()) { | ||||||
11973 | |||||||
11974 | // Allow any 'static constexpr' members, whether or not they are of literal | ||||||
11975 | // type. We separately check that every constexpr variable is of literal | ||||||
11976 | // type. | ||||||
11977 | } else if (VDecl->isConstexpr()) { | ||||||
11978 | |||||||
11979 | // Require constness. | ||||||
11980 | } else if (!DclT.isConstQualified()) { | ||||||
11981 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | ||||||
11982 | << Init->getSourceRange(); | ||||||
11983 | VDecl->setInvalidDecl(); | ||||||
11984 | |||||||
11985 | // We allow integer constant expressions in all cases. | ||||||
11986 | } else if (DclT->isIntegralOrEnumerationType()) { | ||||||
11987 | // Check whether the expression is a constant expression. | ||||||
11988 | SourceLocation Loc; | ||||||
11989 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | ||||||
11990 | // In C++11, a non-constexpr const static data member with an | ||||||
11991 | // in-class initializer cannot be volatile. | ||||||
11992 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | ||||||
11993 | else if (Init->isValueDependent()) | ||||||
11994 | ; // Nothing to check. | ||||||
11995 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | ||||||
11996 | ; // Ok, it's an ICE! | ||||||
11997 | else if (Init->getType()->isScopedEnumeralType() && | ||||||
11998 | Init->isCXX11ConstantExpr(Context)) | ||||||
11999 | ; // Ok, it is a scoped-enum constant expression. | ||||||
12000 | else if (Init->isEvaluatable(Context)) { | ||||||
12001 | // If we can constant fold the initializer through heroics, accept it, | ||||||
12002 | // but report this as a use of an extension for -pedantic. | ||||||
12003 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | ||||||
12004 | << Init->getSourceRange(); | ||||||
12005 | } else { | ||||||
12006 | // Otherwise, this is some crazy unknown case. Report the issue at the | ||||||
12007 | // location provided by the isIntegerConstantExpr failed check. | ||||||
12008 | Diag(Loc, diag::err_in_class_initializer_non_constant) | ||||||
12009 | << Init->getSourceRange(); | ||||||
12010 | VDecl->setInvalidDecl(); | ||||||
12011 | } | ||||||
12012 | |||||||
12013 | // We allow foldable floating-point constants as an extension. | ||||||
12014 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | ||||||
12015 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | ||||||
12016 | // it anyway and provide a fixit to add the 'constexpr'. | ||||||
12017 | if (getLangOpts().CPlusPlus11) { | ||||||
12018 | Diag(VDecl->getLocation(), | ||||||
12019 | diag::ext_in_class_initializer_float_type_cxx11) | ||||||
12020 | << DclT << Init->getSourceRange(); | ||||||
12021 | Diag(VDecl->getBeginLoc(), | ||||||
12022 | diag::note_in_class_initializer_float_type_cxx11) | ||||||
12023 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||||
12024 | } else { | ||||||
12025 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | ||||||
12026 | << DclT << Init->getSourceRange(); | ||||||
12027 | |||||||
12028 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | ||||||
12029 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | ||||||
12030 | << Init->getSourceRange(); | ||||||
12031 | VDecl->setInvalidDecl(); | ||||||
12032 | } | ||||||
12033 | } | ||||||
12034 | |||||||
12035 | // Suggest adding 'constexpr' in C++11 for literal types. | ||||||
12036 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | ||||||
12037 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | ||||||
12038 | << DclT << Init->getSourceRange() | ||||||
12039 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||||
12040 | VDecl->setConstexpr(true); | ||||||
12041 | |||||||
12042 | } else { | ||||||
12043 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | ||||||
12044 | << DclT << Init->getSourceRange(); | ||||||
12045 | VDecl->setInvalidDecl(); | ||||||
12046 | } | ||||||
12047 | } else if (VDecl->isFileVarDecl()) { | ||||||
12048 | // In C, extern is typically used to avoid tentative definitions when | ||||||
12049 | // declaring variables in headers, but adding an intializer makes it a | ||||||
12050 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | ||||||
12051 | // In C++, extern is often used to give implictly static const variables | ||||||
12052 | // external linkage, so don't warn in that case. If selectany is present, | ||||||
12053 | // this might be header code intended for C and C++ inclusion, so apply the | ||||||
12054 | // C++ rules. | ||||||
12055 | if (VDecl->getStorageClass() == SC_Extern && | ||||||
12056 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | ||||||
12057 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | ||||||
12058 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | ||||||
12059 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | ||||||
12060 | Diag(VDecl->getLocation(), diag::warn_extern_init); | ||||||
12061 | |||||||
12062 | // In Microsoft C++ mode, a const variable defined in namespace scope has | ||||||
12063 | // external linkage by default if the variable is declared with | ||||||
12064 | // __declspec(dllexport). | ||||||
12065 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||||
12066 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && | ||||||
12067 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) | ||||||
12068 | VDecl->setStorageClass(SC_Extern); | ||||||
12069 | |||||||
12070 | // C99 6.7.8p4. All file scoped initializers need to be constant. | ||||||
12071 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | ||||||
12072 | CheckForConstantInitializer(Init, DclT); | ||||||
12073 | } | ||||||
12074 | |||||||
12075 | QualType InitType = Init->getType(); | ||||||
12076 | if (!InitType.isNull() && | ||||||
12077 | (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||
12078 | InitType.hasNonTrivialToPrimitiveCopyCUnion())) | ||||||
12079 | checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); | ||||||
12080 | |||||||
12081 | // We will represent direct-initialization similarly to copy-initialization: | ||||||
12082 | // int x(1); -as-> int x = 1; | ||||||
12083 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | ||||||
12084 | // | ||||||
12085 | // Clients that want to distinguish between the two forms, can check for | ||||||
12086 | // direct initializer using VarDecl::getInitStyle(). | ||||||
12087 | // A major benefit is that clients that don't particularly care about which | ||||||
12088 | // exactly form was it (like the CodeGen) can handle both cases without | ||||||
12089 | // special case code. | ||||||
12090 | |||||||
12091 | // C++ 8.5p11: | ||||||
12092 | // The form of initialization (using parentheses or '=') is generally | ||||||
12093 | // insignificant, but does matter when the entity being initialized has a | ||||||
12094 | // class type. | ||||||
12095 | if (CXXDirectInit) { | ||||||
12096 | assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init." ) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 12096, __PRETTY_FUNCTION__)); | ||||||
12097 | VDecl->setInitStyle(VarDecl::CallInit); | ||||||
12098 | } else if (DirectInit) { | ||||||
12099 | // This must be list-initialization. No other way is direct-initialization. | ||||||
12100 | VDecl->setInitStyle(VarDecl::ListInit); | ||||||
12101 | } | ||||||
12102 | |||||||
12103 | CheckCompleteVariableDeclaration(VDecl); | ||||||
12104 | } | ||||||
12105 | |||||||
12106 | /// ActOnInitializerError - Given that there was an error parsing an | ||||||
12107 | /// initializer for the given declaration, try to return to some form | ||||||
12108 | /// of sanity. | ||||||
12109 | void Sema::ActOnInitializerError(Decl *D) { | ||||||
12110 | // Our main concern here is re-establishing invariants like "a | ||||||
12111 | // variable's type is either dependent or complete". | ||||||
12112 | if (!D || D->isInvalidDecl()) return; | ||||||
12113 | |||||||
12114 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
12115 | if (!VD) return; | ||||||
12116 | |||||||
12117 | // Bindings are not usable if we can't make sense of the initializer. | ||||||
12118 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | ||||||
12119 | for (auto *BD : DD->bindings()) | ||||||
12120 | BD->setInvalidDecl(); | ||||||
12121 | |||||||
12122 | // Auto types are meaningless if we can't make sense of the initializer. | ||||||
12123 | if (ParsingInitForAutoVars.count(D)) { | ||||||
12124 | D->setInvalidDecl(); | ||||||
12125 | return; | ||||||
12126 | } | ||||||
12127 | |||||||
12128 | QualType Ty = VD->getType(); | ||||||
12129 | if (Ty->isDependentType()) return; | ||||||
12130 | |||||||
12131 | // Require a complete type. | ||||||
12132 | if (RequireCompleteType(VD->getLocation(), | ||||||
12133 | Context.getBaseElementType(Ty), | ||||||
12134 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12135 | VD->setInvalidDecl(); | ||||||
12136 | return; | ||||||
12137 | } | ||||||
12138 | |||||||
12139 | // Require a non-abstract type. | ||||||
12140 | if (RequireNonAbstractType(VD->getLocation(), Ty, | ||||||
12141 | diag::err_abstract_type_in_decl, | ||||||
12142 | AbstractVariableType)) { | ||||||
12143 | VD->setInvalidDecl(); | ||||||
12144 | return; | ||||||
12145 | } | ||||||
12146 | |||||||
12147 | // Don't bother complaining about constructors or destructors, | ||||||
12148 | // though. | ||||||
12149 | } | ||||||
12150 | |||||||
12151 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | ||||||
12152 | // If there is no declaration, there was an error parsing it. Just ignore it. | ||||||
12153 | if (!RealDecl) | ||||||
12154 | return; | ||||||
12155 | |||||||
12156 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | ||||||
12157 | QualType Type = Var->getType(); | ||||||
12158 | |||||||
12159 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | ||||||
12160 | if (isa<DecompositionDecl>(RealDecl)) { | ||||||
12161 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | ||||||
12162 | Var->setInvalidDecl(); | ||||||
12163 | return; | ||||||
12164 | } | ||||||
12165 | |||||||
12166 | if (Type->isUndeducedType() && | ||||||
12167 | DeduceVariableDeclarationType(Var, false, nullptr)) | ||||||
12168 | return; | ||||||
12169 | |||||||
12170 | // C++11 [class.static.data]p3: A static data member can be declared with | ||||||
12171 | // the constexpr specifier; if so, its declaration shall specify | ||||||
12172 | // a brace-or-equal-initializer. | ||||||
12173 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | ||||||
12174 | // the definition of a variable [...] or the declaration of a static data | ||||||
12175 | // member. | ||||||
12176 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | ||||||
12177 | !Var->isThisDeclarationADemotedDefinition()) { | ||||||
12178 | if (Var->isStaticDataMember()) { | ||||||
12179 | // C++1z removes the relevant rule; the in-class declaration is always | ||||||
12180 | // a definition there. | ||||||
12181 | if (!getLangOpts().CPlusPlus17 && | ||||||
12182 | !Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||||
12183 | Diag(Var->getLocation(), | ||||||
12184 | diag::err_constexpr_static_mem_var_requires_init) | ||||||
12185 | << Var->getDeclName(); | ||||||
12186 | Var->setInvalidDecl(); | ||||||
12187 | return; | ||||||
12188 | } | ||||||
12189 | } else { | ||||||
12190 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | ||||||
12191 | Var->setInvalidDecl(); | ||||||
12192 | return; | ||||||
12193 | } | ||||||
12194 | } | ||||||
12195 | |||||||
12196 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | ||||||
12197 | // be initialized. | ||||||
12198 | if (!Var->isInvalidDecl() && | ||||||
12199 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | ||||||
12200 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | ||||||
12201 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | ||||||
12202 | Var->setInvalidDecl(); | ||||||
12203 | return; | ||||||
12204 | } | ||||||
12205 | |||||||
12206 | VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); | ||||||
12207 | if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && | ||||||
12208 | Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
12209 | checkNonTrivialCUnion(Var->getType(), Var->getLocation(), | ||||||
12210 | NTCUC_DefaultInitializedObject, NTCUK_Init); | ||||||
12211 | |||||||
12212 | |||||||
12213 | switch (DefKind) { | ||||||
12214 | case VarDecl::Definition: | ||||||
12215 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | ||||||
12216 | break; | ||||||
12217 | |||||||
12218 | // We have an out-of-line definition of a static data member | ||||||
12219 | // that has an in-class initializer, so we type-check this like | ||||||
12220 | // a declaration. | ||||||
12221 | // | ||||||
12222 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
12223 | |||||||
12224 | case VarDecl::DeclarationOnly: | ||||||
12225 | // It's only a declaration. | ||||||
12226 | |||||||
12227 | // Block scope. C99 6.7p7: If an identifier for an object is | ||||||
12228 | // declared with no linkage (C99 6.2.2p6), the type for the | ||||||
12229 | // object shall be complete. | ||||||
12230 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | ||||||
12231 | !Var->hasLinkage() && !Var->isInvalidDecl() && | ||||||
12232 | RequireCompleteType(Var->getLocation(), Type, | ||||||
12233 | diag::err_typecheck_decl_incomplete_type)) | ||||||
12234 | Var->setInvalidDecl(); | ||||||
12235 | |||||||
12236 | // Make sure that the type is not abstract. | ||||||
12237 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||||
12238 | RequireNonAbstractType(Var->getLocation(), Type, | ||||||
12239 | diag::err_abstract_type_in_decl, | ||||||
12240 | AbstractVariableType)) | ||||||
12241 | Var->setInvalidDecl(); | ||||||
12242 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||||
12243 | Var->getStorageClass() == SC_PrivateExtern) { | ||||||
12244 | Diag(Var->getLocation(), diag::warn_private_extern); | ||||||
12245 | Diag(Var->getLocation(), diag::note_private_extern); | ||||||
12246 | } | ||||||
12247 | |||||||
12248 | if (Context.getTargetInfo().allowDebugInfoForExternalVar() && | ||||||
12249 | !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) | ||||||
12250 | ExternalDeclarations.push_back(Var); | ||||||
12251 | |||||||
12252 | return; | ||||||
12253 | |||||||
12254 | case VarDecl::TentativeDefinition: | ||||||
12255 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | ||||||
12256 | // object that has file scope without an initializer, and without a | ||||||
12257 | // storage-class specifier or with the storage-class specifier "static", | ||||||
12258 | // constitutes a tentative definition. Note: A tentative definition with | ||||||
12259 | // external linkage is valid (C99 6.2.2p5). | ||||||
12260 | if (!Var->isInvalidDecl()) { | ||||||
12261 | if (const IncompleteArrayType *ArrayT | ||||||
12262 | = Context.getAsIncompleteArrayType(Type)) { | ||||||
12263 | if (RequireCompleteType(Var->getLocation(), | ||||||
12264 | ArrayT->getElementType(), | ||||||
12265 | diag::err_illegal_decl_array_incomplete_type)) | ||||||
12266 | Var->setInvalidDecl(); | ||||||
12267 | } else if (Var->getStorageClass() == SC_Static) { | ||||||
12268 | // C99 6.9.2p3: If the declaration of an identifier for an object is | ||||||
12269 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | ||||||
12270 | // declared type shall not be an incomplete type. | ||||||
12271 | // NOTE: code such as the following | ||||||
12272 | // static struct s; | ||||||
12273 | // struct s { int a; }; | ||||||
12274 | // is accepted by gcc. Hence here we issue a warning instead of | ||||||
12275 | // an error and we do not invalidate the static declaration. | ||||||
12276 | // NOTE: to avoid multiple warnings, only check the first declaration. | ||||||
12277 | if (Var->isFirstDecl()) | ||||||
12278 | RequireCompleteType(Var->getLocation(), Type, | ||||||
12279 | diag::ext_typecheck_decl_incomplete_type); | ||||||
12280 | } | ||||||
12281 | } | ||||||
12282 | |||||||
12283 | // Record the tentative definition; we're done. | ||||||
12284 | if (!Var->isInvalidDecl()) | ||||||
12285 | TentativeDefinitions.push_back(Var); | ||||||
12286 | return; | ||||||
12287 | } | ||||||
12288 | |||||||
12289 | // Provide a specific diagnostic for uninitialized variable | ||||||
12290 | // definitions with incomplete array type. | ||||||
12291 | if (Type->isIncompleteArrayType()) { | ||||||
12292 | Diag(Var->getLocation(), | ||||||
12293 | diag::err_typecheck_incomplete_array_needs_initializer); | ||||||
12294 | Var->setInvalidDecl(); | ||||||
12295 | return; | ||||||
12296 | } | ||||||
12297 | |||||||
12298 | // Provide a specific diagnostic for uninitialized variable | ||||||
12299 | // definitions with reference type. | ||||||
12300 | if (Type->isReferenceType()) { | ||||||
12301 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | ||||||
12302 | << Var->getDeclName() | ||||||
12303 | << SourceRange(Var->getLocation(), Var->getLocation()); | ||||||
12304 | Var->setInvalidDecl(); | ||||||
12305 | return; | ||||||
12306 | } | ||||||
12307 | |||||||
12308 | // Do not attempt to type-check the default initializer for a | ||||||
12309 | // variable with dependent type. | ||||||
12310 | if (Type->isDependentType()) | ||||||
12311 | return; | ||||||
12312 | |||||||
12313 | if (Var->isInvalidDecl()) | ||||||
12314 | return; | ||||||
12315 | |||||||
12316 | if (!Var->hasAttr<AliasAttr>()) { | ||||||
12317 | if (RequireCompleteType(Var->getLocation(), | ||||||
12318 | Context.getBaseElementType(Type), | ||||||
12319 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12320 | Var->setInvalidDecl(); | ||||||
12321 | return; | ||||||
12322 | } | ||||||
12323 | } else { | ||||||
12324 | return; | ||||||
12325 | } | ||||||
12326 | |||||||
12327 | // The variable can not have an abstract class type. | ||||||
12328 | if (RequireNonAbstractType(Var->getLocation(), Type, | ||||||
12329 | diag::err_abstract_type_in_decl, | ||||||
12330 | AbstractVariableType)) { | ||||||
12331 | Var->setInvalidDecl(); | ||||||
12332 | return; | ||||||
12333 | } | ||||||
12334 | |||||||
12335 | // Check for jumps past the implicit initializer. C++0x | ||||||
12336 | // clarifies that this applies to a "variable with automatic | ||||||
12337 | // storage duration", not a "local variable". | ||||||
12338 | // C++11 [stmt.dcl]p3 | ||||||
12339 | // A program that jumps from a point where a variable with automatic | ||||||
12340 | // storage duration is not in scope to a point where it is in scope is | ||||||
12341 | // ill-formed unless the variable has scalar type, class type with a | ||||||
12342 | // trivial default constructor and a trivial destructor, a cv-qualified | ||||||
12343 | // version of one of these types, or an array of one of the preceding | ||||||
12344 | // types and is declared without an initializer. | ||||||
12345 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | ||||||
12346 | if (const RecordType *Record | ||||||
12347 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | ||||||
12348 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | ||||||
12349 | // Mark the function (if we're in one) for further checking even if the | ||||||
12350 | // looser rules of C++11 do not require such checks, so that we can | ||||||
12351 | // diagnose incompatibilities with C++98. | ||||||
12352 | if (!CXXRecord->isPOD()) | ||||||
12353 | setFunctionHasBranchProtectedScope(); | ||||||
12354 | } | ||||||
12355 | } | ||||||
12356 | // In OpenCL, we can't initialize objects in the __local address space, | ||||||
12357 | // even implicitly, so don't synthesize an implicit initializer. | ||||||
12358 | if (getLangOpts().OpenCL && | ||||||
12359 | Var->getType().getAddressSpace() == LangAS::opencl_local) | ||||||
12360 | return; | ||||||
12361 | // C++03 [dcl.init]p9: | ||||||
12362 | // If no initializer is specified for an object, and the | ||||||
12363 | // object is of (possibly cv-qualified) non-POD class type (or | ||||||
12364 | // array thereof), the object shall be default-initialized; if | ||||||
12365 | // the object is of const-qualified type, the underlying class | ||||||
12366 | // type shall have a user-declared default | ||||||
12367 | // constructor. Otherwise, if no initializer is specified for | ||||||
12368 | // a non- static object, the object and its subobjects, if | ||||||
12369 | // any, have an indeterminate initial value); if the object | ||||||
12370 | // or any of its subobjects are of const-qualified type, the | ||||||
12371 | // program is ill-formed. | ||||||
12372 | // C++0x [dcl.init]p11: | ||||||
12373 | // If no initializer is specified for an object, the object is | ||||||
12374 | // default-initialized; [...]. | ||||||
12375 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | ||||||
12376 | InitializationKind Kind | ||||||
12377 | = InitializationKind::CreateDefault(Var->getLocation()); | ||||||
12378 | |||||||
12379 | InitializationSequence InitSeq(*this, Entity, Kind, None); | ||||||
12380 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | ||||||
12381 | if (Init.isInvalid()) | ||||||
12382 | Var->setInvalidDecl(); | ||||||
12383 | else if (Init.get()) { | ||||||
12384 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | ||||||
12385 | // This is important for template substitution. | ||||||
12386 | Var->setInitStyle(VarDecl::CallInit); | ||||||
12387 | } | ||||||
12388 | |||||||
12389 | CheckCompleteVariableDeclaration(Var); | ||||||
12390 | } | ||||||
12391 | } | ||||||
12392 | |||||||
12393 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | ||||||
12394 | // If there is no declaration, there was an error parsing it. Ignore it. | ||||||
12395 | if (!D) | ||||||
12396 | return; | ||||||
12397 | |||||||
12398 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
12399 | if (!VD) { | ||||||
12400 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | ||||||
12401 | D->setInvalidDecl(); | ||||||
12402 | return; | ||||||
12403 | } | ||||||
12404 | |||||||
12405 | VD->setCXXForRangeDecl(true); | ||||||
12406 | |||||||
12407 | // for-range-declaration cannot be given a storage class specifier. | ||||||
12408 | int Error = -1; | ||||||
12409 | switch (VD->getStorageClass()) { | ||||||
12410 | case SC_None: | ||||||
12411 | break; | ||||||
12412 | case SC_Extern: | ||||||
12413 | Error = 0; | ||||||
12414 | break; | ||||||
12415 | case SC_Static: | ||||||
12416 | Error = 1; | ||||||
12417 | break; | ||||||
12418 | case SC_PrivateExtern: | ||||||
12419 | Error = 2; | ||||||
12420 | break; | ||||||
12421 | case SC_Auto: | ||||||
12422 | Error = 3; | ||||||
12423 | break; | ||||||
12424 | case SC_Register: | ||||||
12425 | Error = 4; | ||||||
12426 | break; | ||||||
12427 | } | ||||||
12428 | if (Error != -1) { | ||||||
12429 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | ||||||
12430 | << VD->getDeclName() << Error; | ||||||
12431 | D->setInvalidDecl(); | ||||||
12432 | } | ||||||
12433 | } | ||||||
12434 | |||||||
12435 | StmtResult | ||||||
12436 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | ||||||
12437 | IdentifierInfo *Ident, | ||||||
12438 | ParsedAttributes &Attrs, | ||||||
12439 | SourceLocation AttrEnd) { | ||||||
12440 | // C++1y [stmt.iter]p1: | ||||||
12441 | // A range-based for statement of the form | ||||||
12442 | // for ( for-range-identifier : for-range-initializer ) statement | ||||||
12443 | // is equivalent to | ||||||
12444 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | ||||||
12445 | DeclSpec DS(Attrs.getPool().getFactory()); | ||||||
12446 | |||||||
12447 | const char *PrevSpec; | ||||||
12448 | unsigned DiagID; | ||||||
12449 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | ||||||
12450 | getPrintingPolicy()); | ||||||
12451 | |||||||
12452 | Declarator D(DS, DeclaratorContext::ForContext); | ||||||
12453 | D.SetIdentifier(Ident, IdentLoc); | ||||||
12454 | D.takeAttributes(Attrs, AttrEnd); | ||||||
12455 | |||||||
12456 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | ||||||
12457 | IdentLoc); | ||||||
12458 | Decl *Var = ActOnDeclarator(S, D); | ||||||
12459 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | ||||||
12460 | FinalizeDeclaration(Var); | ||||||
12461 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | ||||||
12462 | AttrEnd.isValid() ? AttrEnd : IdentLoc); | ||||||
12463 | } | ||||||
12464 | |||||||
12465 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | ||||||
12466 | if (var->isInvalidDecl()) return; | ||||||
| |||||||
12467 | |||||||
12468 | if (getLangOpts().OpenCL) { | ||||||
12469 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | ||||||
12470 | // initialiser | ||||||
12471 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | ||||||
12472 | !var->hasInit()) { | ||||||
12473 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||||
12474 | << 1 /*Init*/; | ||||||
12475 | var->setInvalidDecl(); | ||||||
12476 | return; | ||||||
12477 | } | ||||||
12478 | } | ||||||
12479 | |||||||
12480 | // In Objective-C, don't allow jumps past the implicit initialization of a | ||||||
12481 | // local retaining variable. | ||||||
12482 | if (getLangOpts().ObjC && | ||||||
12483 | var->hasLocalStorage()) { | ||||||
12484 | switch (var->getType().getObjCLifetime()) { | ||||||
12485 | case Qualifiers::OCL_None: | ||||||
12486 | case Qualifiers::OCL_ExplicitNone: | ||||||
12487 | case Qualifiers::OCL_Autoreleasing: | ||||||
12488 | break; | ||||||
12489 | |||||||
12490 | case Qualifiers::OCL_Weak: | ||||||
12491 | case Qualifiers::OCL_Strong: | ||||||
12492 | setFunctionHasBranchProtectedScope(); | ||||||
12493 | break; | ||||||
12494 | } | ||||||
12495 | } | ||||||
12496 | |||||||
12497 | if (var->hasLocalStorage() && | ||||||
12498 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||
12499 | setFunctionHasBranchProtectedScope(); | ||||||
12500 | |||||||
12501 | // Warn about externally-visible variables being defined without a | ||||||
12502 | // prior declaration. We only want to do this for global | ||||||
12503 | // declarations, but we also specifically need to avoid doing it for | ||||||
12504 | // class members because the linkage of an anonymous class can | ||||||
12505 | // change if it's later given a typedef name. | ||||||
12506 | if (var->isThisDeclarationADefinition() && | ||||||
12507 | var->getDeclContext()->getRedeclContext()->isFileContext() && | ||||||
12508 | var->isExternallyVisible() && var->hasLinkage() && | ||||||
12509 | !var->isInline() && !var->getDescribedVarTemplate() && | ||||||
12510 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | ||||||
12511 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | ||||||
12512 | var->getLocation())) { | ||||||
12513 | // Find a previous declaration that's not a definition. | ||||||
12514 | VarDecl *prev = var->getPreviousDecl(); | ||||||
12515 | while (prev && prev->isThisDeclarationADefinition()) | ||||||
12516 | prev = prev->getPreviousDecl(); | ||||||
12517 | |||||||
12518 | if (!prev) { | ||||||
12519 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | ||||||
12520 | Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||||
12521 | << /* variable */ 0; | ||||||
12522 | } | ||||||
12523 | } | ||||||
12524 | |||||||
12525 | // Cache the result of checking for constant initialization. | ||||||
12526 | Optional<bool> CacheHasConstInit; | ||||||
12527 | const Expr *CacheCulprit = nullptr; | ||||||
12528 | auto checkConstInit = [&]() mutable { | ||||||
12529 | if (!CacheHasConstInit) | ||||||
12530 | CacheHasConstInit = var->getInit()->isConstantInitializer( | ||||||
12531 | Context, var->getType()->isReferenceType(), &CacheCulprit); | ||||||
12532 | return *CacheHasConstInit; | ||||||
12533 | }; | ||||||
12534 | |||||||
12535 | if (var->getTLSKind() == VarDecl::TLS_Static) { | ||||||
12536 | if (var->getType().isDestructedType()) { | ||||||
12537 | // GNU C++98 edits for __thread, [basic.start.term]p3: | ||||||
12538 | // The type of an object with thread storage duration shall not | ||||||
12539 | // have a non-trivial destructor. | ||||||
12540 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | ||||||
12541 | if (getLangOpts().CPlusPlus11) | ||||||
12542 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||||
12543 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | ||||||
12544 | if (!checkConstInit()) { | ||||||
12545 | // GNU C++98 edits for __thread, [basic.start.init]p4: | ||||||
12546 | // An object of thread storage duration shall not require dynamic | ||||||
12547 | // initialization. | ||||||
12548 | // FIXME: Need strict checking here. | ||||||
12549 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | ||||||
12550 | << CacheCulprit->getSourceRange(); | ||||||
12551 | if (getLangOpts().CPlusPlus11) | ||||||
12552 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||||
12553 | } | ||||||
12554 | } | ||||||
12555 | } | ||||||
12556 | |||||||
12557 | // Apply section attributes and pragmas to global variables. | ||||||
12558 | bool GlobalStorage = var->hasGlobalStorage(); | ||||||
12559 | if (GlobalStorage
| ||||||
12560 | !inTemplateInstantiation()) { | ||||||
12561 | PragmaStack<StringLiteral *> *Stack = nullptr; | ||||||
12562 | int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; | ||||||
12563 | if (var->getType().isConstQualified()) | ||||||
12564 | Stack = &ConstSegStack; | ||||||
12565 | else if (!var->getInit()) { | ||||||
12566 | Stack = &BSSSegStack; | ||||||
12567 | SectionFlags |= ASTContext::PSF_Write; | ||||||
12568 | } else { | ||||||
12569 | Stack = &DataSegStack; | ||||||
12570 | SectionFlags |= ASTContext::PSF_Write; | ||||||
12571 | } | ||||||
12572 | if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) | ||||||
12573 | var->addAttr(SectionAttr::CreateImplicit( | ||||||
12574 | Context, Stack->CurrentValue->getString(), | ||||||
12575 | Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
12576 | SectionAttr::Declspec_allocate)); | ||||||
12577 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) | ||||||
12578 | if (UnifySection(SA->getName(), SectionFlags, var)) | ||||||
12579 | var->dropAttr<SectionAttr>(); | ||||||
12580 | |||||||
12581 | // Apply the init_seg attribute if this has an initializer. If the | ||||||
12582 | // initializer turns out to not be dynamic, we'll end up ignoring this | ||||||
12583 | // attribute. | ||||||
12584 | if (CurInitSeg && var->getInit()) | ||||||
12585 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | ||||||
12586 | CurInitSegLoc, | ||||||
12587 | AttributeCommonInfo::AS_Pragma)); | ||||||
12588 | } | ||||||
12589 | |||||||
12590 | // All the following checks are C++ only. | ||||||
12591 | if (!getLangOpts().CPlusPlus) { | ||||||
12592 | // If this variable must be emitted, add it as an initializer for the | ||||||
12593 | // current module. | ||||||
12594 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||||
12595 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||||
12596 | return; | ||||||
12597 | } | ||||||
12598 | |||||||
12599 | if (auto *DD
| ||||||
12600 | CheckCompleteDecompositionDeclaration(DD); | ||||||
12601 | |||||||
12602 | QualType type = var->getType(); | ||||||
12603 | if (type->isDependentType()) return; | ||||||
12604 | |||||||
12605 | if (var->hasAttr<BlocksAttr>()) | ||||||
12606 | getCurFunction()->addByrefBlockVar(var); | ||||||
12607 | |||||||
12608 | Expr *Init = var->getInit(); | ||||||
12609 | bool IsGlobal = GlobalStorage
| ||||||
12610 | QualType baseType = Context.getBaseElementType(type); | ||||||
12611 | |||||||
12612 | if (Init && !Init->isValueDependent()) { | ||||||
12613 | if (var->isConstexpr()) { | ||||||
12614 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
12615 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { | ||||||
12616 | SourceLocation DiagLoc = var->getLocation(); | ||||||
12617 | // If the note doesn't add any useful information other than a source | ||||||
12618 | // location, fold it into the primary diagnostic. | ||||||
12619 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||||
12620 | diag::note_invalid_subexpr_in_const_expr) { | ||||||
12621 | DiagLoc = Notes[0].first; | ||||||
12622 | Notes.clear(); | ||||||
12623 | } | ||||||
12624 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | ||||||
12625 | << var << Init->getSourceRange(); | ||||||
12626 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | ||||||
12627 | Diag(Notes[I].first, Notes[I].second); | ||||||
12628 | } | ||||||
12629 | } else if (var->mightBeUsableInConstantExpressions(Context)) { | ||||||
12630 | // Check whether the initializer of a const variable of integral or | ||||||
12631 | // enumeration type is an ICE now, since we can't tell whether it was | ||||||
12632 | // initialized by a constant expression if we check later. | ||||||
12633 | var->checkInitIsICE(); | ||||||
12634 | } | ||||||
12635 | |||||||
12636 | // Don't emit further diagnostics about constexpr globals since they | ||||||
12637 | // were just diagnosed. | ||||||
12638 | if (!var->isConstexpr() && GlobalStorage
| ||||||
12639 | // FIXME: Need strict checking in C++03 here. | ||||||
12640 | bool DiagErr = getLangOpts().CPlusPlus11 | ||||||
12641 | ? !var->checkInitIsICE() : !checkConstInit(); | ||||||
12642 | if (DiagErr
| ||||||
12643 | auto *Attr = var->getAttr<ConstInitAttr>(); | ||||||
12644 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | ||||||
12645 | << Init->getSourceRange(); | ||||||
12646 | Diag(Attr->getLocation(), | ||||||
12647 | diag::note_declared_required_constant_init_here) | ||||||
12648 | << Attr->getRange() << Attr->isConstinit(); | ||||||
12649 | if (getLangOpts().CPlusPlus11) { | ||||||
12650 | APValue Value; | ||||||
12651 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
12652 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); | ||||||
12653 | for (auto &it : Notes) | ||||||
12654 | Diag(it.first, it.second); | ||||||
12655 | } else { | ||||||
12656 | Diag(CacheCulprit->getExprLoc(), | ||||||
| |||||||
12657 | diag::note_invalid_subexpr_in_const_expr) | ||||||
12658 | << CacheCulprit->getSourceRange(); | ||||||
12659 | } | ||||||
12660 | } | ||||||
12661 | } | ||||||
12662 | else if (!var->isConstexpr() && IsGlobal && | ||||||
12663 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | ||||||
12664 | var->getLocation())) { | ||||||
12665 | // Warn about globals which don't have a constant initializer. Don't | ||||||
12666 | // warn about globals with a non-trivial destructor because we already | ||||||
12667 | // warned about them. | ||||||
12668 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | ||||||
12669 | if (!(RD && !RD->hasTrivialDestructor())) { | ||||||
12670 | if (!checkConstInit()) | ||||||
12671 | Diag(var->getLocation(), diag::warn_global_constructor) | ||||||
12672 | << Init->getSourceRange(); | ||||||
12673 | } | ||||||
12674 | } | ||||||
12675 | } | ||||||
12676 | |||||||
12677 | // Require the destructor. | ||||||
12678 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | ||||||
12679 | FinalizeVarWithDestructor(var, recordType); | ||||||
12680 | |||||||
12681 | // If this variable must be emitted, add it as an initializer for the current | ||||||
12682 | // module. | ||||||
12683 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||||
12684 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||||
12685 | } | ||||||
12686 | |||||||
12687 | /// Determines if a variable's alignment is dependent. | ||||||
12688 | static bool hasDependentAlignment(VarDecl *VD) { | ||||||
12689 | if (VD->getType()->isDependentType()) | ||||||
12690 | return true; | ||||||
12691 | for (auto *I : VD->specific_attrs<AlignedAttr>()) | ||||||
12692 | if (I->isAlignmentDependent()) | ||||||
12693 | return true; | ||||||
12694 | return false; | ||||||
12695 | } | ||||||
12696 | |||||||
12697 | /// Check if VD needs to be dllexport/dllimport due to being in a | ||||||
12698 | /// dllexport/import function. | ||||||
12699 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { | ||||||
12700 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 12700, __PRETTY_FUNCTION__)); | ||||||
12701 | |||||||
12702 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||||
12703 | |||||||
12704 | // Find outermost function when VD is in lambda function. | ||||||
12705 | while (FD && !getDLLAttr(FD) && | ||||||
12706 | !FD->hasAttr<DLLExportStaticLocalAttr>() && | ||||||
12707 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { | ||||||
12708 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); | ||||||
12709 | } | ||||||
12710 | |||||||
12711 | if (!FD) | ||||||
12712 | return; | ||||||
12713 | |||||||
12714 | // Static locals inherit dll attributes from their function. | ||||||
12715 | if (Attr *A = getDLLAttr(FD)) { | ||||||
12716 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | ||||||
12717 | NewAttr->setInherited(true); | ||||||
12718 | VD->addAttr(NewAttr); | ||||||
12719 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { | ||||||
12720 | auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); | ||||||
12721 | NewAttr->setInherited(true); | ||||||
12722 | VD->addAttr(NewAttr); | ||||||
12723 | |||||||
12724 | // Export this function to enforce exporting this static variable even | ||||||
12725 | // if it is not used in this compilation unit. | ||||||
12726 | if (!FD->hasAttr<DLLExportAttr>()) | ||||||
12727 | FD->addAttr(NewAttr); | ||||||
12728 | |||||||
12729 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { | ||||||
12730 | auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); | ||||||
12731 | NewAttr->setInherited(true); | ||||||
12732 | VD->addAttr(NewAttr); | ||||||
12733 | } | ||||||
12734 | } | ||||||
12735 | |||||||
12736 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | ||||||
12737 | /// any semantic actions necessary after any initializer has been attached. | ||||||
12738 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | ||||||
12739 | // Note that we are no longer parsing the initializer for this declaration. | ||||||
12740 | ParsingInitForAutoVars.erase(ThisDecl); | ||||||
12741 | |||||||
12742 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | ||||||
12743 | if (!VD) | ||||||
12744 | return; | ||||||
12745 | |||||||
12746 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | ||||||
12747 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | ||||||
12748 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | ||||||
12749 | if (PragmaClangBSSSection.Valid) | ||||||
12750 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( | ||||||
12751 | Context, PragmaClangBSSSection.SectionName, | ||||||
12752 | PragmaClangBSSSection.PragmaLocation, | ||||||
12753 | AttributeCommonInfo::AS_Pragma)); | ||||||
12754 | if (PragmaClangDataSection.Valid) | ||||||
12755 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( | ||||||
12756 | Context, PragmaClangDataSection.SectionName, | ||||||
12757 | PragmaClangDataSection.PragmaLocation, | ||||||
12758 | AttributeCommonInfo::AS_Pragma)); | ||||||
12759 | if (PragmaClangRodataSection.Valid) | ||||||
12760 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( | ||||||
12761 | Context, PragmaClangRodataSection.SectionName, | ||||||
12762 | PragmaClangRodataSection.PragmaLocation, | ||||||
12763 | AttributeCommonInfo::AS_Pragma)); | ||||||
12764 | if (PragmaClangRelroSection.Valid) | ||||||
12765 | VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( | ||||||
12766 | Context, PragmaClangRelroSection.SectionName, | ||||||
12767 | PragmaClangRelroSection.PragmaLocation, | ||||||
12768 | AttributeCommonInfo::AS_Pragma)); | ||||||
12769 | } | ||||||
12770 | |||||||
12771 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | ||||||
12772 | for (auto *BD : DD->bindings()) { | ||||||
12773 | FinalizeDeclaration(BD); | ||||||
12774 | } | ||||||
12775 | } | ||||||
12776 | |||||||
12777 | checkAttributesAfterMerging(*this, *VD); | ||||||
12778 | |||||||
12779 | // Perform TLS alignment check here after attributes attached to the variable | ||||||
12780 | // which may affect the alignment have been processed. Only perform the check | ||||||
12781 | // if the target has a maximum TLS alignment (zero means no constraints). | ||||||
12782 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | ||||||
12783 | // Protect the check so that it's not performed on dependent types and | ||||||
12784 | // dependent alignments (we can't determine the alignment in that case). | ||||||
12785 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && | ||||||
12786 | !VD->isInvalidDecl()) { | ||||||
12787 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | ||||||
12788 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | ||||||
12789 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | ||||||
12790 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | ||||||
12791 | << (unsigned)MaxAlignChars.getQuantity(); | ||||||
12792 | } | ||||||
12793 | } | ||||||
12794 | } | ||||||
12795 | |||||||
12796 | if (VD->isStaticLocal()) { | ||||||
12797 | CheckStaticLocalForDllExport(VD); | ||||||
12798 | |||||||
12799 | if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { | ||||||
12800 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ | ||||||
12801 | // function, only __shared__ variables or variables without any device | ||||||
12802 | // memory qualifiers may be declared with static storage class. | ||||||
12803 | // Note: It is unclear how a function-scope non-const static variable | ||||||
12804 | // without device memory qualifier is implemented, therefore only static | ||||||
12805 | // const variable without device memory qualifier is allowed. | ||||||
12806 | [&]() { | ||||||
12807 | if (!getLangOpts().CUDA) | ||||||
12808 | return; | ||||||
12809 | if (VD->hasAttr<CUDASharedAttr>()) | ||||||
12810 | return; | ||||||
12811 | if (VD->getType().isConstQualified() && | ||||||
12812 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) | ||||||
12813 | return; | ||||||
12814 | if (CUDADiagIfDeviceCode(VD->getLocation(), | ||||||
12815 | diag::err_device_static_local_var) | ||||||
12816 | << CurrentCUDATarget()) | ||||||
12817 | VD->setInvalidDecl(); | ||||||
12818 | }(); | ||||||
12819 | } | ||||||
12820 | } | ||||||
12821 | |||||||
12822 | // Perform check for initializers of device-side global variables. | ||||||
12823 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | ||||||
12824 | // 7.5). We must also apply the same checks to all __shared__ | ||||||
12825 | // variables whether they are local or not. CUDA also allows | ||||||
12826 | // constant initializers for __constant__ and __device__ variables. | ||||||
12827 | if (getLangOpts().CUDA) | ||||||
12828 | checkAllowedCUDAInitializer(VD); | ||||||
12829 | |||||||
12830 | // Grab the dllimport or dllexport attribute off of the VarDecl. | ||||||
12831 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | ||||||
12832 | |||||||
12833 | // Imported static data members cannot be defined out-of-line. | ||||||
12834 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | ||||||
12835 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | ||||||
12836 | VD->isThisDeclarationADefinition()) { | ||||||
12837 | // We allow definitions of dllimport class template static data members | ||||||
12838 | // with a warning. | ||||||
12839 | CXXRecordDecl *Context = | ||||||
12840 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | ||||||
12841 | bool IsClassTemplateMember = | ||||||
12842 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | ||||||
12843 | Context->getDescribedClassTemplate(); | ||||||
12844 | |||||||
12845 | Diag(VD->getLocation(), | ||||||
12846 | IsClassTemplateMember | ||||||
12847 | ? diag::warn_attribute_dllimport_static_field_definition | ||||||
12848 | : diag::err_attribute_dllimport_static_field_definition); | ||||||
12849 | Diag(IA->getLocation(), diag::note_attribute); | ||||||
12850 | if (!IsClassTemplateMember) | ||||||
12851 | VD->setInvalidDecl(); | ||||||
12852 | } | ||||||
12853 | } | ||||||
12854 | |||||||
12855 | // dllimport/dllexport variables cannot be thread local, their TLS index | ||||||
12856 | // isn't exported with the variable. | ||||||
12857 | if (DLLAttr && VD->getTLSKind()) { | ||||||
12858 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||||
12859 | if (F && getDLLAttr(F)) { | ||||||
12860 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 12860, __PRETTY_FUNCTION__)); | ||||||
12861 | // But if this is a static local in a dlimport/dllexport function, the | ||||||
12862 | // function will never be inlined, which means the var would never be | ||||||
12863 | // imported, so having it marked import/export is safe. | ||||||
12864 | } else { | ||||||
12865 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | ||||||
12866 | << DLLAttr; | ||||||
12867 | VD->setInvalidDecl(); | ||||||
12868 | } | ||||||
12869 | } | ||||||
12870 | |||||||
12871 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | ||||||
12872 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | ||||||
12873 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; | ||||||
12874 | VD->dropAttr<UsedAttr>(); | ||||||
12875 | } | ||||||
12876 | } | ||||||
12877 | |||||||
12878 | const DeclContext *DC = VD->getDeclContext(); | ||||||
12879 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||||
12880 | // member, set the visibility of this variable. | ||||||
12881 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | ||||||
12882 | AddPushedVisibilityAttribute(VD); | ||||||
12883 | |||||||
12884 | // FIXME: Warn on unused var template partial specializations. | ||||||
12885 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | ||||||
12886 | MarkUnusedFileScopedDecl(VD); | ||||||
12887 | |||||||
12888 | // Now we have parsed the initializer and can update the table of magic | ||||||
12889 | // tag values. | ||||||
12890 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | ||||||
12891 | !VD->getType()->isIntegralOrEnumerationType()) | ||||||
12892 | return; | ||||||
12893 | |||||||
12894 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | ||||||
12895 | const Expr *MagicValueExpr = VD->getInit(); | ||||||
12896 | if (!MagicValueExpr) { | ||||||
12897 | continue; | ||||||
12898 | } | ||||||
12899 | llvm::APSInt MagicValueInt; | ||||||
12900 | if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { | ||||||
12901 | Diag(I->getRange().getBegin(), | ||||||
12902 | diag::err_type_tag_for_datatype_not_ice) | ||||||
12903 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||||
12904 | continue; | ||||||
12905 | } | ||||||
12906 | if (MagicValueInt.getActiveBits() > 64) { | ||||||
12907 | Diag(I->getRange().getBegin(), | ||||||
12908 | diag::err_type_tag_for_datatype_too_large) | ||||||
12909 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||||
12910 | continue; | ||||||
12911 | } | ||||||
12912 | uint64_t MagicValue = MagicValueInt.getZExtValue(); | ||||||
12913 | RegisterTypeTagForDatatype(I->getArgumentKind(), | ||||||
12914 | MagicValue, | ||||||
12915 | I->getMatchingCType(), | ||||||
12916 | I->getLayoutCompatible(), | ||||||
12917 | I->getMustBeNull()); | ||||||
12918 | } | ||||||
12919 | } | ||||||
12920 | |||||||
12921 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | ||||||
12922 | auto *VD = dyn_cast<VarDecl>(DD); | ||||||
12923 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | ||||||
12924 | } | ||||||
12925 | |||||||
12926 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | ||||||
12927 | ArrayRef<Decl *> Group) { | ||||||
12928 | SmallVector<Decl*, 8> Decls; | ||||||
12929 | |||||||
12930 | if (DS.isTypeSpecOwned()) | ||||||
12931 | Decls.push_back(DS.getRepAsDecl()); | ||||||
12932 | |||||||
12933 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | ||||||
12934 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | ||||||
12935 | bool DiagnosedMultipleDecomps = false; | ||||||
12936 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | ||||||
12937 | bool DiagnosedNonDeducedAuto = false; | ||||||
12938 | |||||||
12939 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||||
12940 | if (Decl *D = Group[i]) { | ||||||
12941 | // For declarators, there are some additional syntactic-ish checks we need | ||||||
12942 | // to perform. | ||||||
12943 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | ||||||
12944 | if (!FirstDeclaratorInGroup) | ||||||
12945 | FirstDeclaratorInGroup = DD; | ||||||
12946 | if (!FirstDecompDeclaratorInGroup) | ||||||
12947 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | ||||||
12948 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | ||||||
12949 | !hasDeducedAuto(DD)) | ||||||
12950 | FirstNonDeducedAutoInGroup = DD; | ||||||
12951 | |||||||
12952 | if (FirstDeclaratorInGroup != DD) { | ||||||
12953 | // A decomposition declaration cannot be combined with any other | ||||||
12954 | // declaration in the same group. | ||||||
12955 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | ||||||
12956 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | ||||||
12957 | diag::err_decomp_decl_not_alone) | ||||||
12958 | << FirstDeclaratorInGroup->getSourceRange() | ||||||
12959 | << DD->getSourceRange(); | ||||||
12960 | DiagnosedMultipleDecomps = true; | ||||||
12961 | } | ||||||
12962 | |||||||
12963 | // A declarator that uses 'auto' in any way other than to declare a | ||||||
12964 | // variable with a deduced type cannot be combined with any other | ||||||
12965 | // declarator in the same group. | ||||||
12966 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | ||||||
12967 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | ||||||
12968 | diag::err_auto_non_deduced_not_alone) | ||||||
12969 | << FirstNonDeducedAutoInGroup->getType() | ||||||
12970 | ->hasAutoForTrailingReturnType() | ||||||
12971 | << FirstDeclaratorInGroup->getSourceRange() | ||||||
12972 | << DD->getSourceRange(); | ||||||
12973 | DiagnosedNonDeducedAuto = true; | ||||||
12974 | } | ||||||
12975 | } | ||||||
12976 | } | ||||||
12977 | |||||||
12978 | Decls.push_back(D); | ||||||
12979 | } | ||||||
12980 | } | ||||||
12981 | |||||||
12982 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | ||||||
12983 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | ||||||
12984 | handleTagNumbering(Tag, S); | ||||||
12985 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | ||||||
12986 | getLangOpts().CPlusPlus) | ||||||
12987 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | ||||||
12988 | } | ||||||
12989 | } | ||||||
12990 | |||||||
12991 | return BuildDeclaratorGroup(Decls); | ||||||
12992 | } | ||||||
12993 | |||||||
12994 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | ||||||
12995 | /// group, performing any necessary semantic checking. | ||||||
12996 | Sema::DeclGroupPtrTy | ||||||
12997 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | ||||||
12998 | // C++14 [dcl.spec.auto]p7: (DR1347) | ||||||
12999 | // If the type that replaces the placeholder type is not the same in each | ||||||
13000 | // deduction, the program is ill-formed. | ||||||
13001 | if (Group.size() > 1) { | ||||||
13002 | QualType Deduced; | ||||||
13003 | VarDecl *DeducedDecl = nullptr; | ||||||
13004 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||||
13005 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | ||||||
13006 | if (!D || D->isInvalidDecl()) | ||||||
13007 | break; | ||||||
13008 | DeducedType *DT = D->getType()->getContainedDeducedType(); | ||||||
13009 | if (!DT || DT->getDeducedType().isNull()) | ||||||
13010 | continue; | ||||||
13011 | if (Deduced.isNull()) { | ||||||
13012 | Deduced = DT->getDeducedType(); | ||||||
13013 | DeducedDecl = D; | ||||||
13014 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | ||||||
13015 | auto *AT = dyn_cast<AutoType>(DT); | ||||||
13016 | Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | ||||||
13017 | diag::err_auto_different_deductions) | ||||||
13018 | << (AT ? (unsigned)AT->getKeyword() : 3) | ||||||
13019 | << Deduced << DeducedDecl->getDeclName() | ||||||
13020 | << DT->getDeducedType() << D->getDeclName() | ||||||
13021 | << DeducedDecl->getInit()->getSourceRange() | ||||||
13022 | << D->getInit()->getSourceRange(); | ||||||
13023 | D->setInvalidDecl(); | ||||||
13024 | break; | ||||||
13025 | } | ||||||
13026 | } | ||||||
13027 | } | ||||||
13028 | |||||||
13029 | ActOnDocumentableDecls(Group); | ||||||
13030 | |||||||
13031 | return DeclGroupPtrTy::make( | ||||||
13032 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | ||||||
13033 | } | ||||||
13034 | |||||||
13035 | void Sema::ActOnDocumentableDecl(Decl *D) { | ||||||
13036 | ActOnDocumentableDecls(D); | ||||||
13037 | } | ||||||
13038 | |||||||
13039 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | ||||||
13040 | // Don't parse the comment if Doxygen diagnostics are ignored. | ||||||
13041 | if (Group.empty() || !Group[0]) | ||||||
13042 | return; | ||||||
13043 | |||||||
13044 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | ||||||
13045 | Group[0]->getLocation()) && | ||||||
13046 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | ||||||
13047 | Group[0]->getLocation())) | ||||||
13048 | return; | ||||||
13049 | |||||||
13050 | if (Group.size() >= 2) { | ||||||
13051 | // This is a decl group. Normally it will contain only declarations | ||||||
13052 | // produced from declarator list. But in case we have any definitions or | ||||||
13053 | // additional declaration references: | ||||||
13054 | // 'typedef struct S {} S;' | ||||||
13055 | // 'typedef struct S *S;' | ||||||
13056 | // 'struct S *pS;' | ||||||
13057 | // FinalizeDeclaratorGroup adds these as separate declarations. | ||||||
13058 | Decl *MaybeTagDecl = Group[0]; | ||||||
13059 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | ||||||
13060 | Group = Group.slice(1); | ||||||
13061 | } | ||||||
13062 | } | ||||||
13063 | |||||||
13064 | // FIMXE: We assume every Decl in the group is in the same file. | ||||||
13065 | // This is false when preprocessor constructs the group from decls in | ||||||
13066 | // different files (e. g. macros or #include). | ||||||
13067 | Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); | ||||||
13068 | } | ||||||
13069 | |||||||
13070 | /// Common checks for a parameter-declaration that should apply to both function | ||||||
13071 | /// parameters and non-type template parameters. | ||||||
13072 | void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { | ||||||
13073 | // Check that there are no default arguments inside the type of this | ||||||
13074 | // parameter. | ||||||
13075 | if (getLangOpts().CPlusPlus) | ||||||
13076 | CheckExtraCXXDefaultArguments(D); | ||||||
13077 | |||||||
13078 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||||
13079 | if (D.getCXXScopeSpec().isSet()) { | ||||||
13080 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | ||||||
13081 | << D.getCXXScopeSpec().getRange(); | ||||||
13082 | } | ||||||
13083 | |||||||
13084 | // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a | ||||||
13085 | // simple identifier except [...irrelevant cases...]. | ||||||
13086 | switch (D.getName().getKind()) { | ||||||
13087 | case UnqualifiedIdKind::IK_Identifier: | ||||||
13088 | break; | ||||||
13089 | |||||||
13090 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||||
13091 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||||
13092 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||||
13093 | case UnqualifiedIdKind::IK_ConstructorName: | ||||||
13094 | case UnqualifiedIdKind::IK_DestructorName: | ||||||
13095 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||||
13096 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||||
13097 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | ||||||
13098 | << GetNameForDeclarator(D).getName(); | ||||||
13099 | break; | ||||||
13100 | |||||||
13101 | case UnqualifiedIdKind::IK_TemplateId: | ||||||
13102 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||||
13103 | // GetNameForDeclarator would not produce a useful name in this case. | ||||||
13104 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); | ||||||
13105 | break; | ||||||
13106 | } | ||||||
13107 | } | ||||||
13108 | |||||||
13109 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | ||||||
13110 | /// to introduce parameters into function prototype scope. | ||||||
13111 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | ||||||
13112 | const DeclSpec &DS = D.getDeclSpec(); | ||||||
13113 | |||||||
13114 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | ||||||
13115 | |||||||
13116 | // C++03 [dcl.stc]p2 also permits 'auto'. | ||||||
13117 | StorageClass SC = SC_None; | ||||||
13118 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | ||||||
13119 | SC = SC_Register; | ||||||
13120 | // In C++11, the 'register' storage class specifier is deprecated. | ||||||
13121 | // In C++17, it is not allowed, but we tolerate it as an extension. | ||||||
13122 | if (getLangOpts().CPlusPlus11) { | ||||||
13123 | Diag(DS.getStorageClassSpecLoc(), | ||||||
13124 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||||
13125 | : diag::warn_deprecated_register) | ||||||
13126 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
13127 | } | ||||||
13128 | } else if (getLangOpts().CPlusPlus && | ||||||
13129 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | ||||||
13130 | SC = SC_Auto; | ||||||
13131 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | ||||||
13132 | Diag(DS.getStorageClassSpecLoc(), | ||||||
13133 | diag::err_invalid_storage_class_in_func_decl); | ||||||
13134 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||||
13135 | } | ||||||
13136 | |||||||
13137 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||||
13138 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | ||||||
13139 | << DeclSpec::getSpecifierName(TSCS); | ||||||
13140 | if (DS.isInlineSpecified()) | ||||||
13141 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
13142 | << getLangOpts().CPlusPlus17; | ||||||
13143 | if (DS.hasConstexprSpecifier()) | ||||||
13144 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||||
13145 | << 0 << D.getDeclSpec().getConstexprSpecifier(); | ||||||
13146 | |||||||
13147 | DiagnoseFunctionSpecifiers(DS); | ||||||
13148 | |||||||
13149 | CheckFunctionOrTemplateParamDeclarator(S, D); | ||||||
13150 | |||||||
13151 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
13152 | QualType parmDeclType = TInfo->getType(); | ||||||
13153 | |||||||
13154 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | ||||||
13155 | IdentifierInfo *II = D.getIdentifier(); | ||||||
13156 | if (II) { | ||||||
13157 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | ||||||
13158 | ForVisibleRedeclaration); | ||||||
13159 | LookupName(R, S); | ||||||
13160 | if (R.isSingleResult()) { | ||||||
13161 | NamedDecl *PrevDecl = R.getFoundDecl(); | ||||||
13162 | if (PrevDecl->isTemplateParameter()) { | ||||||
13163 | // Maybe we will complain about the shadowed template parameter. | ||||||
13164 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||||
13165 | // Just pretend that we didn't see the previous declaration. | ||||||
13166 | PrevDecl = nullptr; | ||||||
13167 | } else if (S->isDeclScope(PrevDecl)) { | ||||||
13168 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | ||||||
13169 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
13170 | |||||||
13171 | // Recover by removing the name | ||||||
13172 | II = nullptr; | ||||||
13173 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | ||||||
13174 | D.setInvalidType(true); | ||||||
13175 | } | ||||||
13176 | } | ||||||
13177 | } | ||||||
13178 | |||||||
13179 | // Temporarily put parameter variables in the translation unit, not | ||||||
13180 | // the enclosing context. This prevents them from accidentally | ||||||
13181 | // looking like class members in C++. | ||||||
13182 | ParmVarDecl *New = | ||||||
13183 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), | ||||||
13184 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); | ||||||
13185 | |||||||
13186 | if (D.isInvalidType()) | ||||||
13187 | New->setInvalidDecl(); | ||||||
13188 | |||||||
13189 | assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void> (0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13189, __PRETTY_FUNCTION__)); | ||||||
13190 | assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast< void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13190, __PRETTY_FUNCTION__)); | ||||||
13191 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | ||||||
13192 | S->getNextFunctionPrototypeIndex()); | ||||||
13193 | |||||||
13194 | // Add the parameter declaration into this scope. | ||||||
13195 | S->AddDecl(New); | ||||||
13196 | if (II) | ||||||
13197 | IdResolver.AddDecl(New); | ||||||
13198 | |||||||
13199 | ProcessDeclAttributes(S, New, D); | ||||||
13200 | |||||||
13201 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
13202 | Diag(New->getLocation(), diag::err_module_private_local) | ||||||
13203 | << 1 << New->getDeclName() | ||||||
13204 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
13205 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
13206 | |||||||
13207 | if (New->hasAttr<BlocksAttr>()) { | ||||||
13208 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | ||||||
13209 | } | ||||||
13210 | |||||||
13211 | if (getLangOpts().OpenCL) | ||||||
13212 | deduceOpenCLAddressSpace(New); | ||||||
13213 | |||||||
13214 | return New; | ||||||
13215 | } | ||||||
13216 | |||||||
13217 | /// Synthesizes a variable for a parameter arising from a | ||||||
13218 | /// typedef. | ||||||
13219 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | ||||||
13220 | SourceLocation Loc, | ||||||
13221 | QualType T) { | ||||||
13222 | /* FIXME: setting StartLoc == Loc. | ||||||
13223 | Would it be worth to modify callers so as to provide proper source | ||||||
13224 | location for the unnamed parameters, embedding the parameter's type? */ | ||||||
13225 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | ||||||
13226 | T, Context.getTrivialTypeSourceInfo(T, Loc), | ||||||
13227 | SC_None, nullptr); | ||||||
13228 | Param->setImplicit(); | ||||||
13229 | return Param; | ||||||
13230 | } | ||||||
13231 | |||||||
13232 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | ||||||
13233 | // Don't diagnose unused-parameter errors in template instantiations; we | ||||||
13234 | // will already have done so in the template itself. | ||||||
13235 | if (inTemplateInstantiation()) | ||||||
13236 | return; | ||||||
13237 | |||||||
13238 | for (const ParmVarDecl *Parameter : Parameters) { | ||||||
13239 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | ||||||
13240 | !Parameter->hasAttr<UnusedAttr>()) { | ||||||
13241 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | ||||||
13242 | << Parameter->getDeclName(); | ||||||
13243 | } | ||||||
13244 | } | ||||||
13245 | } | ||||||
13246 | |||||||
13247 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | ||||||
13248 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | ||||||
13249 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | ||||||
13250 | return; | ||||||
13251 | |||||||
13252 | // Warn if the return value is pass-by-value and larger than the specified | ||||||
13253 | // threshold. | ||||||
13254 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | ||||||
13255 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | ||||||
13256 | if (Size > LangOpts.NumLargeByValueCopy) | ||||||
13257 | Diag(D->getLocation(), diag::warn_return_value_size) | ||||||
13258 | << D->getDeclName() << Size; | ||||||
13259 | } | ||||||
13260 | |||||||
13261 | // Warn if any parameter is pass-by-value and larger than the specified | ||||||
13262 | // threshold. | ||||||
13263 | for (const ParmVarDecl *Parameter : Parameters) { | ||||||
13264 | QualType T = Parameter->getType(); | ||||||
13265 | if (T->isDependentType() || !T.isPODType(Context)) | ||||||
13266 | continue; | ||||||
13267 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | ||||||
13268 | if (Size > LangOpts.NumLargeByValueCopy) | ||||||
13269 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | ||||||
13270 | << Parameter->getDeclName() << Size; | ||||||
13271 | } | ||||||
13272 | } | ||||||
13273 | |||||||
13274 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | ||||||
13275 | SourceLocation NameLoc, IdentifierInfo *Name, | ||||||
13276 | QualType T, TypeSourceInfo *TSInfo, | ||||||
13277 | StorageClass SC) { | ||||||
13278 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | ||||||
13279 | if (getLangOpts().ObjCAutoRefCount && | ||||||
13280 | T.getObjCLifetime() == Qualifiers::OCL_None && | ||||||
13281 | T->isObjCLifetimeType()) { | ||||||
13282 | |||||||
13283 | Qualifiers::ObjCLifetime lifetime; | ||||||
13284 | |||||||
13285 | // Special cases for arrays: | ||||||
13286 | // - if it's const, use __unsafe_unretained | ||||||
13287 | // - otherwise, it's an error | ||||||
13288 | if (T->isArrayType()) { | ||||||
13289 | if (!T.isConstQualified()) { | ||||||
13290 | if (DelayedDiagnostics.shouldDelayDiagnostics()) | ||||||
13291 | DelayedDiagnostics.add( | ||||||
13292 | sema::DelayedDiagnostic::makeForbiddenType( | ||||||
13293 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | ||||||
13294 | else | ||||||
13295 | Diag(NameLoc, diag::err_arc_array_param_no_ownership) | ||||||
13296 | << TSInfo->getTypeLoc().getSourceRange(); | ||||||
13297 | } | ||||||
13298 | lifetime = Qualifiers::OCL_ExplicitNone; | ||||||
13299 | } else { | ||||||
13300 | lifetime = T->getObjCARCImplicitLifetime(); | ||||||
13301 | } | ||||||
13302 | T = Context.getLifetimeQualifiedType(T, lifetime); | ||||||
13303 | } | ||||||
13304 | |||||||
13305 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | ||||||
13306 | Context.getAdjustedParameterType(T), | ||||||
13307 | TSInfo, SC, nullptr); | ||||||
13308 | |||||||
13309 | // Make a note if we created a new pack in the scope of a lambda, so that | ||||||
13310 | // we know that references to that pack must also be expanded within the | ||||||
13311 | // lambda scope. | ||||||
13312 | if (New->isParameterPack()) | ||||||
13313 | if (auto *LSI = getEnclosingLambda()) | ||||||
13314 | LSI->LocalPacks.push_back(New); | ||||||
13315 | |||||||
13316 | if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||
13317 | New->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
13318 | checkNonTrivialCUnion(New->getType(), New->getLocation(), | ||||||
13319 | NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); | ||||||
13320 | |||||||
13321 | // Parameters can not be abstract class types. | ||||||
13322 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||||
13323 | // the class has been completely parsed. | ||||||
13324 | if (!CurContext->isRecord() && | ||||||
13325 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | ||||||
13326 | AbstractParamType)) | ||||||
13327 | New->setInvalidDecl(); | ||||||
13328 | |||||||
13329 | // Parameter declarators cannot be interface types. All ObjC objects are | ||||||
13330 | // passed by reference. | ||||||
13331 | if (T->isObjCObjectType()) { | ||||||
13332 | SourceLocation TypeEndLoc = | ||||||
13333 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); | ||||||
13334 | Diag(NameLoc, | ||||||
13335 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | ||||||
13336 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | ||||||
13337 | T = Context.getObjCObjectPointerType(T); | ||||||
13338 | New->setType(T); | ||||||
13339 | } | ||||||
13340 | |||||||
13341 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | ||||||
13342 | // duration shall not be qualified by an address-space qualifier." | ||||||
13343 | // Since all parameters have automatic store duration, they can not have | ||||||
13344 | // an address space. | ||||||
13345 | if (T.getAddressSpace() != LangAS::Default && | ||||||
13346 | // OpenCL allows function arguments declared to be an array of a type | ||||||
13347 | // to be qualified with an address space. | ||||||
13348 | !(getLangOpts().OpenCL && | ||||||
13349 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | ||||||
13350 | Diag(NameLoc, diag::err_arg_with_address_space); | ||||||
13351 | New->setInvalidDecl(); | ||||||
13352 | } | ||||||
13353 | |||||||
13354 | return New; | ||||||
13355 | } | ||||||
13356 | |||||||
13357 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | ||||||
13358 | SourceLocation LocAfterDecls) { | ||||||
13359 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||||
13360 | |||||||
13361 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | ||||||
13362 | // for a K&R function. | ||||||
13363 | if (!FTI.hasPrototype) { | ||||||
13364 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | ||||||
13365 | --i; | ||||||
13366 | if (FTI.Params[i].Param == nullptr) { | ||||||
13367 | SmallString<256> Code; | ||||||
13368 | llvm::raw_svector_ostream(Code) | ||||||
13369 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | ||||||
13370 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | ||||||
13371 | << FTI.Params[i].Ident | ||||||
13372 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | ||||||
13373 | |||||||
13374 | // Implicitly declare the argument as type 'int' for lack of a better | ||||||
13375 | // type. | ||||||
13376 | AttributeFactory attrs; | ||||||
13377 | DeclSpec DS(attrs); | ||||||
13378 | const char* PrevSpec; // unused | ||||||
13379 | unsigned DiagID; // unused | ||||||
13380 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | ||||||
13381 | DiagID, Context.getPrintingPolicy()); | ||||||
13382 | // Use the identifier location for the type source range. | ||||||
13383 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | ||||||
13384 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | ||||||
13385 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); | ||||||
13386 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | ||||||
13387 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | ||||||
13388 | } | ||||||
13389 | } | ||||||
13390 | } | ||||||
13391 | } | ||||||
13392 | |||||||
13393 | Decl * | ||||||
13394 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | ||||||
13395 | MultiTemplateParamsArg TemplateParameterLists, | ||||||
13396 | SkipBodyInfo *SkipBody) { | ||||||
13397 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused" ) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13397, __PRETTY_FUNCTION__)); | ||||||
13398 | assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!" ) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13398, __PRETTY_FUNCTION__)); | ||||||
13399 | Scope *ParentScope = FnBodyScope->getParent(); | ||||||
13400 | |||||||
13401 | D.setFunctionDefinitionKind(FDK_Definition); | ||||||
13402 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | ||||||
13403 | return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); | ||||||
13404 | } | ||||||
13405 | |||||||
13406 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | ||||||
13407 | Consumer.HandleInlineFunctionDefinition(D); | ||||||
13408 | } | ||||||
13409 | |||||||
13410 | static bool | ||||||
13411 | ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | ||||||
13412 | const FunctionDecl *&PossiblePrototype) { | ||||||
13413 | // Don't warn about invalid declarations. | ||||||
13414 | if (FD->isInvalidDecl()) | ||||||
13415 | return false; | ||||||
13416 | |||||||
13417 | // Or declarations that aren't global. | ||||||
13418 | if (!FD->isGlobal()) | ||||||
13419 | return false; | ||||||
13420 | |||||||
13421 | // Don't warn about C++ member functions. | ||||||
13422 | if (isa<CXXMethodDecl>(FD)) | ||||||
13423 | return false; | ||||||
13424 | |||||||
13425 | // Don't warn about 'main'. | ||||||
13426 | if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) | ||||||
13427 | if (IdentifierInfo *II = FD->getIdentifier()) | ||||||
13428 | if (II->isStr("main")) | ||||||
13429 | return false; | ||||||
13430 | |||||||
13431 | // Don't warn about inline functions. | ||||||
13432 | if (FD->isInlined()) | ||||||
13433 | return false; | ||||||
13434 | |||||||
13435 | // Don't warn about function templates. | ||||||
13436 | if (FD->getDescribedFunctionTemplate()) | ||||||
13437 | return false; | ||||||
13438 | |||||||
13439 | // Don't warn about function template specializations. | ||||||
13440 | if (FD->isFunctionTemplateSpecialization()) | ||||||
13441 | return false; | ||||||
13442 | |||||||
13443 | // Don't warn for OpenCL kernels. | ||||||
13444 | if (FD->hasAttr<OpenCLKernelAttr>()) | ||||||
13445 | return false; | ||||||
13446 | |||||||
13447 | // Don't warn on explicitly deleted functions. | ||||||
13448 | if (FD->isDeleted()) | ||||||
13449 | return false; | ||||||
13450 | |||||||
13451 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | ||||||
13452 | Prev; Prev = Prev->getPreviousDecl()) { | ||||||
13453 | // Ignore any declarations that occur in function or method | ||||||
13454 | // scope, because they aren't visible from the header. | ||||||
13455 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
13456 | continue; | ||||||
13457 | |||||||
13458 | PossiblePrototype = Prev; | ||||||
13459 | return Prev->getType()->isFunctionNoProtoType(); | ||||||
13460 | } | ||||||
13461 | |||||||
13462 | return true; | ||||||
13463 | } | ||||||
13464 | |||||||
13465 | void | ||||||
13466 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | ||||||
13467 | const FunctionDecl *EffectiveDefinition, | ||||||
13468 | SkipBodyInfo *SkipBody) { | ||||||
13469 | const FunctionDecl *Definition = EffectiveDefinition; | ||||||
13470 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { | ||||||
13471 | // If this is a friend function defined in a class template, it does not | ||||||
13472 | // have a body until it is used, nevertheless it is a definition, see | ||||||
13473 | // [temp.inst]p2: | ||||||
13474 | // | ||||||
13475 | // ... for the purpose of determining whether an instantiated redeclaration | ||||||
13476 | // is valid according to [basic.def.odr] and [class.mem], a declaration that | ||||||
13477 | // corresponds to a definition in the template is considered to be a | ||||||
13478 | // definition. | ||||||
13479 | // | ||||||
13480 | // The following code must produce redefinition error: | ||||||
13481 | // | ||||||
13482 | // template<typename T> struct C20 { friend void func_20() {} }; | ||||||
13483 | // C20<int> c20i; | ||||||
13484 | // void func_20() {} | ||||||
13485 | // | ||||||
13486 | for (auto I : FD->redecls()) { | ||||||
13487 | if (I != FD && !I->isInvalidDecl() && | ||||||
13488 | I->getFriendObjectKind() != Decl::FOK_None) { | ||||||
13489 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { | ||||||
13490 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | ||||||
13491 | // A merged copy of the same function, instantiated as a member of | ||||||
13492 | // the same class, is OK. | ||||||
13493 | if (declaresSameEntity(OrigFD, Original) && | ||||||
13494 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), | ||||||
13495 | cast<Decl>(FD->getLexicalDeclContext()))) | ||||||
13496 | continue; | ||||||
13497 | } | ||||||
13498 | |||||||
13499 | if (Original->isThisDeclarationADefinition()) { | ||||||
13500 | Definition = I; | ||||||
13501 | break; | ||||||
13502 | } | ||||||
13503 | } | ||||||
13504 | } | ||||||
13505 | } | ||||||
13506 | } | ||||||
13507 | |||||||
13508 | if (!Definition) | ||||||
13509 | // Similar to friend functions a friend function template may be a | ||||||
13510 | // definition and do not have a body if it is instantiated in a class | ||||||
13511 | // template. | ||||||
13512 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { | ||||||
13513 | for (auto I : FTD->redecls()) { | ||||||
13514 | auto D = cast<FunctionTemplateDecl>(I); | ||||||
13515 | if (D != FTD) { | ||||||
13516 | assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13517, __PRETTY_FUNCTION__)) | ||||||
13517 | "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13517, __PRETTY_FUNCTION__)); | ||||||
13518 | if (D->getFriendObjectKind() != Decl::FOK_None) | ||||||
13519 | if (FunctionTemplateDecl *FT = | ||||||
13520 | D->getInstantiatedFromMemberTemplate()) { | ||||||
13521 | if (FT->isThisDeclarationADefinition()) { | ||||||
13522 | Definition = D->getTemplatedDecl(); | ||||||
13523 | break; | ||||||
13524 | } | ||||||
13525 | } | ||||||
13526 | } | ||||||
13527 | } | ||||||
13528 | } | ||||||
13529 | |||||||
13530 | if (!Definition) | ||||||
13531 | return; | ||||||
13532 | |||||||
13533 | if (canRedefineFunction(Definition, getLangOpts())) | ||||||
13534 | return; | ||||||
13535 | |||||||
13536 | // Don't emit an error when this is redefinition of a typo-corrected | ||||||
13537 | // definition. | ||||||
13538 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | ||||||
13539 | return; | ||||||
13540 | |||||||
13541 | // If we don't have a visible definition of the function, and it's inline or | ||||||
13542 | // a template, skip the new definition. | ||||||
13543 | if (SkipBody && !hasVisibleDefinition(Definition) && | ||||||
13544 | (Definition->getFormalLinkage() == InternalLinkage || | ||||||
13545 | Definition->isInlined() || | ||||||
13546 | Definition->getDescribedFunctionTemplate() || | ||||||
13547 | Definition->getNumTemplateParameterLists())) { | ||||||
13548 | SkipBody->ShouldSkip = true; | ||||||
13549 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); | ||||||
13550 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | ||||||
13551 | makeMergedDefinitionVisible(TD); | ||||||
13552 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | ||||||
13553 | return; | ||||||
13554 | } | ||||||
13555 | |||||||
13556 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | ||||||
13557 | Definition->getStorageClass() == SC_Extern) | ||||||
13558 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | ||||||
13559 | << FD->getDeclName() << getLangOpts().CPlusPlus; | ||||||
13560 | else | ||||||
13561 | Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); | ||||||
13562 | |||||||
13563 | Diag(Definition->getLocation(), diag::note_previous_definition); | ||||||
13564 | FD->setInvalidDecl(); | ||||||
13565 | } | ||||||
13566 | |||||||
13567 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | ||||||
13568 | Sema &S) { | ||||||
13569 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | ||||||
13570 | |||||||
13571 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | ||||||
13572 | LSI->CallOperator = CallOperator; | ||||||
13573 | LSI->Lambda = LambdaClass; | ||||||
13574 | LSI->ReturnType = CallOperator->getReturnType(); | ||||||
13575 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | ||||||
13576 | |||||||
13577 | if (LCD == LCD_None) | ||||||
13578 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | ||||||
13579 | else if (LCD == LCD_ByCopy) | ||||||
13580 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | ||||||
13581 | else if (LCD == LCD_ByRef) | ||||||
13582 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | ||||||
13583 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | ||||||
13584 | |||||||
13585 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | ||||||
13586 | LSI->Mutable = !CallOperator->isConst(); | ||||||
13587 | |||||||
13588 | // Add the captures to the LSI so they can be noted as already | ||||||
13589 | // captured within tryCaptureVar. | ||||||
13590 | auto I = LambdaClass->field_begin(); | ||||||
13591 | for (const auto &C : LambdaClass->captures()) { | ||||||
13592 | if (C.capturesVariable()) { | ||||||
13593 | VarDecl *VD = C.getCapturedVar(); | ||||||
13594 | if (VD->isInitCapture()) | ||||||
13595 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | ||||||
13596 | QualType CaptureType = VD->getType(); | ||||||
13597 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | ||||||
13598 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | ||||||
13599 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | ||||||
13600 | /*EllipsisLoc*/C.isPackExpansion() | ||||||
13601 | ? C.getEllipsisLoc() : SourceLocation(), | ||||||
13602 | CaptureType, /*Invalid*/false); | ||||||
13603 | |||||||
13604 | } else if (C.capturesThis()) { | ||||||
13605 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), | ||||||
13606 | C.getCaptureKind() == LCK_StarThis); | ||||||
13607 | } else { | ||||||
13608 | LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), | ||||||
13609 | I->getType()); | ||||||
13610 | } | ||||||
13611 | ++I; | ||||||
13612 | } | ||||||
13613 | } | ||||||
13614 | |||||||
13615 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | ||||||
13616 | SkipBodyInfo *SkipBody) { | ||||||
13617 | if (!D) { | ||||||
13618 | // Parsing the function declaration failed in some way. Push on a fake scope | ||||||
13619 | // anyway so we can try to parse the function body. | ||||||
13620 | PushFunctionScope(); | ||||||
13621 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||||
13622 | return D; | ||||||
13623 | } | ||||||
13624 | |||||||
13625 | FunctionDecl *FD = nullptr; | ||||||
13626 | |||||||
13627 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | ||||||
13628 | FD = FunTmpl->getTemplatedDecl(); | ||||||
13629 | else | ||||||
13630 | FD = cast<FunctionDecl>(D); | ||||||
13631 | |||||||
13632 | // Do not push if it is a lambda because one is already pushed when building | ||||||
13633 | // the lambda in ActOnStartOfLambdaDefinition(). | ||||||
13634 | if (!isLambdaCallOperator(FD)) | ||||||
13635 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||||
13636 | |||||||
13637 | // Check for defining attributes before the check for redefinition. | ||||||
13638 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | ||||||
13639 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | ||||||
13640 | FD->dropAttr<AliasAttr>(); | ||||||
13641 | FD->setInvalidDecl(); | ||||||
13642 | } | ||||||
13643 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | ||||||
13644 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | ||||||
13645 | FD->dropAttr<IFuncAttr>(); | ||||||
13646 | FD->setInvalidDecl(); | ||||||
13647 | } | ||||||
13648 | |||||||
13649 | // See if this is a redefinition. If 'will have body' is already set, then | ||||||
13650 | // these checks were already performed when it was set. | ||||||
13651 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { | ||||||
13652 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | ||||||
13653 | |||||||
13654 | // If we're skipping the body, we're done. Don't enter the scope. | ||||||
13655 | if (SkipBody && SkipBody->ShouldSkip) | ||||||
13656 | return D; | ||||||
13657 | } | ||||||
13658 | |||||||
13659 | // Mark this function as "will have a body eventually". This lets users to | ||||||
13660 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | ||||||
13661 | // this function. | ||||||
13662 | FD->setWillHaveBody(); | ||||||
13663 | |||||||
13664 | // If we are instantiating a generic lambda call operator, push | ||||||
13665 | // a LambdaScopeInfo onto the function stack. But use the information | ||||||
13666 | // that's already been calculated (ActOnLambdaExpr) to prime the current | ||||||
13667 | // LambdaScopeInfo. | ||||||
13668 | // When the template operator is being specialized, the LambdaScopeInfo, | ||||||
13669 | // has to be properly restored so that tryCaptureVariable doesn't try | ||||||
13670 | // and capture any new variables. In addition when calculating potential | ||||||
13671 | // captures during transformation of nested lambdas, it is necessary to | ||||||
13672 | // have the LSI properly restored. | ||||||
13673 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | ||||||
13674 | assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13676, __PRETTY_FUNCTION__)) | ||||||
13675 | "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13676, __PRETTY_FUNCTION__)) | ||||||
13676 | "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13676, __PRETTY_FUNCTION__)); | ||||||
13677 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | ||||||
13678 | } else { | ||||||
13679 | // Enter a new function scope | ||||||
13680 | PushFunctionScope(); | ||||||
13681 | } | ||||||
13682 | |||||||
13683 | // Builtin functions cannot be defined. | ||||||
13684 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||||
13685 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | ||||||
13686 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | ||||||
13687 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | ||||||
13688 | FD->setInvalidDecl(); | ||||||
13689 | } | ||||||
13690 | } | ||||||
13691 | |||||||
13692 | // The return type of a function definition must be complete | ||||||
13693 | // (C99 6.9.1p3, C++ [dcl.fct]p6). | ||||||
13694 | QualType ResultType = FD->getReturnType(); | ||||||
13695 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | ||||||
13696 | !FD->isInvalidDecl() && | ||||||
13697 | RequireCompleteType(FD->getLocation(), ResultType, | ||||||
13698 | diag::err_func_def_incomplete_result)) | ||||||
13699 | FD->setInvalidDecl(); | ||||||
13700 | |||||||
13701 | if (FnBodyScope) | ||||||
13702 | PushDeclContext(FnBodyScope, FD); | ||||||
13703 | |||||||
13704 | // Check the validity of our function parameters | ||||||
13705 | CheckParmsForFunctionDef(FD->parameters(), | ||||||
13706 | /*CheckParameterNames=*/true); | ||||||
13707 | |||||||
13708 | // Add non-parameter declarations already in the function to the current | ||||||
13709 | // scope. | ||||||
13710 | if (FnBodyScope) { | ||||||
13711 | for (Decl *NPD : FD->decls()) { | ||||||
13712 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | ||||||
13713 | if (!NonParmDecl) | ||||||
13714 | continue; | ||||||
13715 | assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13716, __PRETTY_FUNCTION__)) | ||||||
13716 | "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13716, __PRETTY_FUNCTION__)); | ||||||
13717 | |||||||
13718 | // If the decl has a name, make it accessible in the current scope. | ||||||
13719 | if (NonParmDecl->getDeclName()) | ||||||
13720 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | ||||||
13721 | |||||||
13722 | // Similarly, dive into enums and fish their constants out, making them | ||||||
13723 | // accessible in this scope. | ||||||
13724 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | ||||||
13725 | for (auto *EI : ED->enumerators()) | ||||||
13726 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | ||||||
13727 | } | ||||||
13728 | } | ||||||
13729 | } | ||||||
13730 | |||||||
13731 | // Introduce our parameters into the function scope | ||||||
13732 | for (auto Param : FD->parameters()) { | ||||||
13733 | Param->setOwningFunction(FD); | ||||||
13734 | |||||||
13735 | // If this has an identifier, add it to the scope stack. | ||||||
13736 | if (Param->getIdentifier() && FnBodyScope) { | ||||||
13737 | CheckShadow(FnBodyScope, Param); | ||||||
13738 | |||||||
13739 | PushOnScopeChains(Param, FnBodyScope); | ||||||
13740 | } | ||||||
13741 | } | ||||||
13742 | |||||||
13743 | // Ensure that the function's exception specification is instantiated. | ||||||
13744 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | ||||||
13745 | ResolveExceptionSpec(D->getLocation(), FPT); | ||||||
13746 | |||||||
13747 | // dllimport cannot be applied to non-inline function definitions. | ||||||
13748 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | ||||||
13749 | !FD->isTemplateInstantiation()) { | ||||||
13750 | assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void > (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 13750, __PRETTY_FUNCTION__)); | ||||||
13751 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | ||||||
13752 | FD->setInvalidDecl(); | ||||||
13753 | return D; | ||||||
13754 | } | ||||||
13755 | // We want to attach documentation to original Decl (which might be | ||||||
13756 | // a function template). | ||||||
13757 | ActOnDocumentableDecl(D); | ||||||
13758 | if (getCurLexicalContext()->isObjCContainer() && | ||||||
13759 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | ||||||
13760 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | ||||||
13761 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | ||||||
13762 | |||||||
13763 | return D; | ||||||
13764 | } | ||||||
13765 | |||||||
13766 | /// Given the set of return statements within a function body, | ||||||
13767 | /// compute the variables that are subject to the named return value | ||||||
13768 | /// optimization. | ||||||
13769 | /// | ||||||
13770 | /// Each of the variables that is subject to the named return value | ||||||
13771 | /// optimization will be marked as NRVO variables in the AST, and any | ||||||
13772 | /// return statement that has a marked NRVO variable as its NRVO candidate can | ||||||
13773 | /// use the named return value optimization. | ||||||
13774 | /// | ||||||
13775 | /// This function applies a very simplistic algorithm for NRVO: if every return | ||||||
13776 | /// statement in the scope of a variable has the same NRVO candidate, that | ||||||
13777 | /// candidate is an NRVO variable. | ||||||
13778 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | ||||||
13779 | ReturnStmt **Returns = Scope->Returns.data(); | ||||||
13780 | |||||||
13781 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | ||||||
13782 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | ||||||
13783 | if (!NRVOCandidate->isNRVOVariable()) | ||||||
13784 | Returns[I]->setNRVOCandidate(nullptr); | ||||||
13785 | } | ||||||
13786 | } | ||||||
13787 | } | ||||||
13788 | |||||||
13789 | bool Sema::canDelayFunctionBody(const Declarator &D) { | ||||||
13790 | // We can't delay parsing the body of a constexpr function template (yet). | ||||||
13791 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||||
13792 | return false; | ||||||
13793 | |||||||
13794 | // We can't delay parsing the body of a function template with a deduced | ||||||
13795 | // return type (yet). | ||||||
13796 | if (D.getDeclSpec().hasAutoTypeSpec()) { | ||||||
13797 | // If the placeholder introduces a non-deduced trailing return type, | ||||||
13798 | // we can still delay parsing it. | ||||||
13799 | if (D.getNumTypeObjects()) { | ||||||
13800 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | ||||||
13801 | if (Outer.Kind == DeclaratorChunk::Function && | ||||||
13802 | Outer.Fun.hasTrailingReturnType()) { | ||||||
13803 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | ||||||
13804 | return Ty.isNull() || !Ty->isUndeducedType(); | ||||||
13805 | } | ||||||
13806 | } | ||||||
13807 | return false; | ||||||
13808 | } | ||||||
13809 | |||||||
13810 | return true; | ||||||
13811 | } | ||||||
13812 | |||||||
13813 | bool Sema::canSkipFunctionBody(Decl *D) { | ||||||
13814 | // We cannot skip the body of a function (or function template) which is | ||||||
13815 | // constexpr, since we may need to evaluate its body in order to parse the | ||||||
13816 | // rest of the file. | ||||||
13817 | // We cannot skip the body of a function with an undeduced return type, | ||||||
13818 | // because any callers of that function need to know the type. | ||||||
13819 | if (const FunctionDecl *FD = D->getAsFunction()) { | ||||||
13820 | if (FD->isConstexpr()) | ||||||
13821 | return false; | ||||||
13822 | // We can't simply call Type::isUndeducedType here, because inside template | ||||||
13823 | // auto can be deduced to a dependent type, which is not considered | ||||||
13824 | // "undeduced". | ||||||
13825 | if (FD->getReturnType()->getContainedDeducedType()) | ||||||
13826 | return false; | ||||||
13827 | } | ||||||
13828 | return Consumer.shouldSkipFunctionBody(D); | ||||||
13829 | } | ||||||
13830 | |||||||
13831 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | ||||||
13832 | if (!Decl) | ||||||
13833 | return nullptr; | ||||||
13834 | if (FunctionDecl *FD = Decl->getAsFunction()) | ||||||
13835 | FD->setHasSkippedBody(); | ||||||
13836 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | ||||||
13837 | MD->setHasSkippedBody(); | ||||||
13838 | return Decl; | ||||||
13839 | } | ||||||
13840 | |||||||
13841 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | ||||||
13842 | return ActOnFinishFunctionBody(D, BodyArg, false); | ||||||
13843 | } | ||||||
13844 | |||||||
13845 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function | ||||||
13846 | /// body. | ||||||
13847 | class ExitFunctionBodyRAII { | ||||||
13848 | public: | ||||||
13849 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} | ||||||
13850 | ~ExitFunctionBodyRAII() { | ||||||
13851 | if (!IsLambda) | ||||||
13852 | S.PopExpressionEvaluationContext(); | ||||||
13853 | } | ||||||
13854 | |||||||
13855 | private: | ||||||
13856 | Sema &S; | ||||||
13857 | bool IsLambda = false; | ||||||
13858 | }; | ||||||
13859 | |||||||
13860 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { | ||||||
13861 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; | ||||||
13862 | |||||||
13863 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { | ||||||
13864 | if (EscapeInfo.count(BD)) | ||||||
13865 | return EscapeInfo[BD]; | ||||||
13866 | |||||||
13867 | bool R = false; | ||||||
13868 | const BlockDecl *CurBD = BD; | ||||||
13869 | |||||||
13870 | do { | ||||||
13871 | R = !CurBD->doesNotEscape(); | ||||||
13872 | if (R) | ||||||
13873 | break; | ||||||
13874 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); | ||||||
13875 | } while (CurBD); | ||||||
13876 | |||||||
13877 | return EscapeInfo[BD] = R; | ||||||
13878 | }; | ||||||
13879 | |||||||
13880 | // If the location where 'self' is implicitly retained is inside a escaping | ||||||
13881 | // block, emit a diagnostic. | ||||||
13882 | for (const std::pair<SourceLocation, const BlockDecl *> &P : | ||||||
13883 | S.ImplicitlyRetainedSelfLocs) | ||||||
13884 | if (IsOrNestedInEscapingBlock(P.second)) | ||||||
13885 | S.Diag(P.first, diag::warn_implicitly_retains_self) | ||||||
13886 | << FixItHint::CreateInsertion(P.first, "self->"); | ||||||
13887 | } | ||||||
13888 | |||||||
13889 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | ||||||
13890 | bool IsInstantiation) { | ||||||
13891 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | ||||||
13892 | |||||||
13893 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||||
13894 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | ||||||
13895 | |||||||
13896 | if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) | ||||||
13897 | CheckCompletedCoroutineBody(FD, Body); | ||||||
13898 | |||||||
13899 | // Do not call PopExpressionEvaluationContext() if it is a lambda because one | ||||||
13900 | // is already popped when finishing the lambda in BuildLambdaExpr(). This is | ||||||
13901 | // meant to pop the context added in ActOnStartOfFunctionDef(). | ||||||
13902 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); | ||||||
13903 | |||||||
13904 | if (FD) { | ||||||
13905 | FD->setBody(Body); | ||||||
13906 | FD->setWillHaveBody(false); | ||||||
13907 | |||||||
13908 | if (getLangOpts().CPlusPlus14) { | ||||||
13909 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | ||||||
13910 | FD->getReturnType()->isUndeducedType()) { | ||||||
13911 | // If the function has a deduced result type but contains no 'return' | ||||||
13912 | // statements, the result type as written must be exactly 'auto', and | ||||||
13913 | // the deduced result type is 'void'. | ||||||
13914 | if (!FD->getReturnType()->getAs<AutoType>()) { | ||||||
13915 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | ||||||
13916 | << FD->getReturnType(); | ||||||
13917 | FD->setInvalidDecl(); | ||||||
13918 | } else { | ||||||
13919 | // Substitute 'void' for the 'auto' in the type. | ||||||
13920 | TypeLoc ResultType = getReturnTypeLoc(FD); | ||||||
13921 | Context.adjustDeducedFunctionResultType( | ||||||
13922 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); | ||||||
13923 | } | ||||||
13924 | } | ||||||
13925 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | ||||||
13926 | // In C++11, we don't use 'auto' deduction rules for lambda call | ||||||
13927 | // operators because we don't support return type deduction. | ||||||
13928 | auto *LSI = getCurLambda(); | ||||||
13929 | if (LSI->HasImplicitReturnType) { | ||||||
13930 | deduceClosureReturnType(*LSI); | ||||||
13931 | |||||||
13932 | // C++11 [expr.prim.lambda]p4: | ||||||
13933 | // [...] if there are no return statements in the compound-statement | ||||||
13934 | // [the deduced type is] the type void | ||||||
13935 | QualType RetType = | ||||||
13936 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | ||||||
13937 | |||||||
13938 | // Update the return type to the deduced type. | ||||||
13939 | const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); | ||||||
13940 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | ||||||
13941 | Proto->getExtProtoInfo())); | ||||||
13942 | } | ||||||
13943 | } | ||||||
13944 | |||||||
13945 | // If the function implicitly returns zero (like 'main') or is naked, | ||||||
13946 | // don't complain about missing return statements. | ||||||
13947 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | ||||||
13948 | WP.disableCheckFallThrough(); | ||||||
13949 | |||||||
13950 | // MSVC permits the use of pure specifier (=0) on function definition, | ||||||
13951 | // defined at class scope, warn about this non-standard construct. | ||||||
13952 | if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) | ||||||
13953 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | ||||||
13954 | |||||||
13955 | if (!FD->isInvalidDecl()) { | ||||||
13956 | // Don't diagnose unused parameters of defaulted or deleted functions. | ||||||
13957 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) | ||||||
13958 | DiagnoseUnusedParameters(FD->parameters()); | ||||||
13959 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | ||||||
13960 | FD->getReturnType(), FD); | ||||||
13961 | |||||||
13962 | // If this is a structor, we need a vtable. | ||||||
13963 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | ||||||
13964 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | ||||||
13965 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) | ||||||
13966 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | ||||||
13967 | |||||||
13968 | // Try to apply the named return value optimization. We have to check | ||||||
13969 | // if we can do this here because lambdas keep return statements around | ||||||
13970 | // to deduce an implicit return type. | ||||||
13971 | if (FD->getReturnType()->isRecordType() && | ||||||
13972 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | ||||||
13973 | computeNRVO(Body, getCurFunction()); | ||||||
13974 | } | ||||||
13975 | |||||||
13976 | // GNU warning -Wmissing-prototypes: | ||||||
13977 | // Warn if a global function is defined without a previous | ||||||
13978 | // prototype declaration. This warning is issued even if the | ||||||
13979 | // definition itself provides a prototype. The aim is to detect | ||||||
13980 | // global functions that fail to be declared in header files. | ||||||
13981 | const FunctionDecl *PossiblePrototype = nullptr; | ||||||
13982 | if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { | ||||||
13983 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | ||||||
13984 | |||||||
13985 | if (PossiblePrototype) { | ||||||
13986 | // We found a declaration that is not a prototype, | ||||||
13987 | // but that could be a zero-parameter prototype | ||||||
13988 | if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { | ||||||
13989 | TypeLoc TL = TI->getTypeLoc(); | ||||||
13990 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | ||||||
13991 | Diag(PossiblePrototype->getLocation(), | ||||||
13992 | diag::note_declaration_not_a_prototype) | ||||||
13993 | << (FD->getNumParams() != 0) | ||||||
13994 | << (FD->getNumParams() == 0 | ||||||
13995 | ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") | ||||||
13996 | : FixItHint{}); | ||||||
13997 | } | ||||||
13998 | } else { | ||||||
13999 | Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||||
14000 | << /* function */ 1 | ||||||
14001 | << (FD->getStorageClass() == SC_None | ||||||
14002 | ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), | ||||||
14003 | "static ") | ||||||
14004 | : FixItHint{}); | ||||||
14005 | } | ||||||
14006 | |||||||
14007 | // GNU warning -Wstrict-prototypes | ||||||
14008 | // Warn if K&R function is defined without a previous declaration. | ||||||
14009 | // This warning is issued only if the definition itself does not provide | ||||||
14010 | // a prototype. Only K&R definitions do not provide a prototype. | ||||||
14011 | // An empty list in a function declarator that is part of a definition | ||||||
14012 | // of that function specifies that the function has no parameters | ||||||
14013 | // (C99 6.7.5.3p14) | ||||||
14014 | if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && | ||||||
14015 | !LangOpts.CPlusPlus) { | ||||||
14016 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); | ||||||
14017 | TypeLoc TL = TI->getTypeLoc(); | ||||||
14018 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); | ||||||
14019 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; | ||||||
14020 | } | ||||||
14021 | } | ||||||
14022 | |||||||
14023 | // Warn on CPUDispatch with an actual body. | ||||||
14024 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | ||||||
14025 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | ||||||
14026 | if (!CmpndBody->body_empty()) | ||||||
14027 | Diag(CmpndBody->body_front()->getBeginLoc(), | ||||||
14028 | diag::warn_dispatch_body_ignored); | ||||||
14029 | |||||||
14030 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
14031 | const CXXMethodDecl *KeyFunction; | ||||||
14032 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | ||||||
14033 | MD->isVirtual() && | ||||||
14034 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | ||||||
14035 | MD == KeyFunction->getCanonicalDecl()) { | ||||||
14036 | // Update the key-function state if necessary for this ABI. | ||||||
14037 | if (FD->isInlined() && | ||||||
14038 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | ||||||
14039 | Context.setNonKeyFunction(MD); | ||||||
14040 | |||||||
14041 | // If the newly-chosen key function is already defined, then we | ||||||
14042 | // need to mark the vtable as used retroactively. | ||||||
14043 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | ||||||
14044 | const FunctionDecl *Definition; | ||||||
14045 | if (KeyFunction && KeyFunction->isDefined(Definition)) | ||||||
14046 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | ||||||
14047 | } else { | ||||||
14048 | // We just defined they key function; mark the vtable as used. | ||||||
14049 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | ||||||
14050 | } | ||||||
14051 | } | ||||||
14052 | } | ||||||
14053 | |||||||
14054 | assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14055, __PRETTY_FUNCTION__)) | ||||||
14055 | "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14055, __PRETTY_FUNCTION__)); | ||||||
14056 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | ||||||
14057 | assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused" ) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14057, __PRETTY_FUNCTION__)); | ||||||
14058 | MD->setBody(Body); | ||||||
14059 | if (!MD->isInvalidDecl()) { | ||||||
14060 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | ||||||
14061 | MD->getReturnType(), MD); | ||||||
14062 | |||||||
14063 | if (Body) | ||||||
14064 | computeNRVO(Body, getCurFunction()); | ||||||
14065 | } | ||||||
14066 | if (getCurFunction()->ObjCShouldCallSuper) { | ||||||
14067 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) | ||||||
14068 | << MD->getSelector().getAsString(); | ||||||
14069 | getCurFunction()->ObjCShouldCallSuper = false; | ||||||
14070 | } | ||||||
14071 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { | ||||||
14072 | const ObjCMethodDecl *InitMethod = nullptr; | ||||||
14073 | bool isDesignated = | ||||||
14074 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | ||||||
14075 | assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void> (0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14075, __PRETTY_FUNCTION__)); | ||||||
14076 | (void)isDesignated; | ||||||
14077 | |||||||
14078 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | ||||||
14079 | auto IFace = MD->getClassInterface(); | ||||||
14080 | if (!IFace) | ||||||
14081 | return false; | ||||||
14082 | auto SuperD = IFace->getSuperClass(); | ||||||
14083 | if (!SuperD) | ||||||
14084 | return false; | ||||||
14085 | return SuperD->getIdentifier() == | ||||||
14086 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | ||||||
14087 | }; | ||||||
14088 | // Don't issue this warning for unavailable inits or direct subclasses | ||||||
14089 | // of NSObject. | ||||||
14090 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | ||||||
14091 | Diag(MD->getLocation(), | ||||||
14092 | diag::warn_objc_designated_init_missing_super_call); | ||||||
14093 | Diag(InitMethod->getLocation(), | ||||||
14094 | diag::note_objc_designated_init_marked_here); | ||||||
14095 | } | ||||||
14096 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; | ||||||
14097 | } | ||||||
14098 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { | ||||||
14099 | // Don't issue this warning for unavaialable inits. | ||||||
14100 | if (!MD->isUnavailable()) | ||||||
14101 | Diag(MD->getLocation(), | ||||||
14102 | diag::warn_objc_secondary_init_missing_init_call); | ||||||
14103 | getCurFunction()->ObjCWarnForNoInitDelegation = false; | ||||||
14104 | } | ||||||
14105 | |||||||
14106 | diagnoseImplicitlyRetainedSelf(*this); | ||||||
14107 | } else { | ||||||
14108 | // Parsing the function declaration failed in some way. Pop the fake scope | ||||||
14109 | // we pushed on. | ||||||
14110 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||||
14111 | return nullptr; | ||||||
14112 | } | ||||||
14113 | |||||||
14114 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||||
14115 | DiagnoseUnguardedAvailabilityViolations(dcl); | ||||||
14116 | |||||||
14117 | assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14119, __PRETTY_FUNCTION__)) | ||||||
14118 | "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14119, __PRETTY_FUNCTION__)) | ||||||
14119 | "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14119, __PRETTY_FUNCTION__)); | ||||||
14120 | |||||||
14121 | // Verify and clean out per-function state. | ||||||
14122 | if (Body && (!FD || !FD->isDefaulted())) { | ||||||
14123 | // C++ constructors that have function-try-blocks can't have return | ||||||
14124 | // statements in the handlers of that block. (C++ [except.handle]p14) | ||||||
14125 | // Verify this. | ||||||
14126 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | ||||||
14127 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | ||||||
14128 | |||||||
14129 | // Verify that gotos and switch cases don't jump into scopes illegally. | ||||||
14130 | if (getCurFunction()->NeedsScopeChecking() && | ||||||
14131 | !PP.isCodeCompletionEnabled()) | ||||||
14132 | DiagnoseInvalidJumps(Body); | ||||||
14133 | |||||||
14134 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | ||||||
14135 | if (!Destructor->getParent()->isDependentType()) | ||||||
14136 | CheckDestructor(Destructor); | ||||||
14137 | |||||||
14138 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | ||||||
14139 | Destructor->getParent()); | ||||||
14140 | } | ||||||
14141 | |||||||
14142 | // If any errors have occurred, clear out any temporaries that may have | ||||||
14143 | // been leftover. This ensures that these temporaries won't be picked up for | ||||||
14144 | // deletion in some later function. | ||||||
14145 | if (getDiagnostics().hasErrorOccurred() || | ||||||
14146 | getDiagnostics().getSuppressAllDiagnostics()) { | ||||||
14147 | DiscardCleanupsInEvaluationContext(); | ||||||
14148 | } | ||||||
14149 | if (!getDiagnostics().hasUncompilableErrorOccurred() && | ||||||
14150 | !isa<FunctionTemplateDecl>(dcl)) { | ||||||
14151 | // Since the body is valid, issue any analysis-based warnings that are | ||||||
14152 | // enabled. | ||||||
14153 | ActivePolicy = &WP; | ||||||
14154 | } | ||||||
14155 | |||||||
14156 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | ||||||
14157 | !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) | ||||||
14158 | FD->setInvalidDecl(); | ||||||
14159 | |||||||
14160 | if (FD && FD->hasAttr<NakedAttr>()) { | ||||||
14161 | for (const Stmt *S : Body->children()) { | ||||||
14162 | // Allow local register variables without initializer as they don't | ||||||
14163 | // require prologue. | ||||||
14164 | bool RegisterVariables = false; | ||||||
14165 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | ||||||
14166 | for (const auto *Decl : DS->decls()) { | ||||||
14167 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | ||||||
14168 | RegisterVariables = | ||||||
14169 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | ||||||
14170 | if (!RegisterVariables) | ||||||
14171 | break; | ||||||
14172 | } | ||||||
14173 | } | ||||||
14174 | } | ||||||
14175 | if (RegisterVariables) | ||||||
14176 | continue; | ||||||
14177 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | ||||||
14178 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); | ||||||
14179 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | ||||||
14180 | FD->setInvalidDecl(); | ||||||
14181 | break; | ||||||
14182 | } | ||||||
14183 | } | ||||||
14184 | } | ||||||
14185 | |||||||
14186 | assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14188, __PRETTY_FUNCTION__)) | ||||||
14187 | ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14188, __PRETTY_FUNCTION__)) | ||||||
14188 | "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14188, __PRETTY_FUNCTION__)); | ||||||
14189 | assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14189, __PRETTY_FUNCTION__)); | ||||||
14190 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14191, __PRETTY_FUNCTION__)) | ||||||
14191 | "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14191, __PRETTY_FUNCTION__)); | ||||||
14192 | } | ||||||
14193 | |||||||
14194 | if (!IsInstantiation) | ||||||
14195 | PopDeclContext(); | ||||||
14196 | |||||||
14197 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||||
14198 | // If any errors have occurred, clear out any temporaries that may have | ||||||
14199 | // been leftover. This ensures that these temporaries won't be picked up for | ||||||
14200 | // deletion in some later function. | ||||||
14201 | if (getDiagnostics().hasErrorOccurred()) { | ||||||
14202 | DiscardCleanupsInEvaluationContext(); | ||||||
14203 | } | ||||||
14204 | |||||||
14205 | return dcl; | ||||||
14206 | } | ||||||
14207 | |||||||
14208 | /// When we finish delayed parsing of an attribute, we must attach it to the | ||||||
14209 | /// relevant Decl. | ||||||
14210 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | ||||||
14211 | ParsedAttributes &Attrs) { | ||||||
14212 | // Always attach attributes to the underlying decl. | ||||||
14213 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | ||||||
14214 | D = TD->getTemplatedDecl(); | ||||||
14215 | ProcessDeclAttributeList(S, D, Attrs); | ||||||
14216 | |||||||
14217 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | ||||||
14218 | if (Method->isStatic()) | ||||||
14219 | checkThisInStaticMemberFunctionAttributes(Method); | ||||||
14220 | } | ||||||
14221 | |||||||
14222 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | ||||||
14223 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | ||||||
14224 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | ||||||
14225 | IdentifierInfo &II, Scope *S) { | ||||||
14226 | // Find the scope in which the identifier is injected and the corresponding | ||||||
14227 | // DeclContext. | ||||||
14228 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | ||||||
14229 | // In that case, we inject the declaration into the translation unit scope | ||||||
14230 | // instead. | ||||||
14231 | Scope *BlockScope = S; | ||||||
14232 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | ||||||
14233 | BlockScope = BlockScope->getParent(); | ||||||
14234 | |||||||
14235 | Scope *ContextScope = BlockScope; | ||||||
14236 | while (!ContextScope->getEntity()) | ||||||
14237 | ContextScope = ContextScope->getParent(); | ||||||
14238 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | ||||||
14239 | |||||||
14240 | // Before we produce a declaration for an implicitly defined | ||||||
14241 | // function, see whether there was a locally-scoped declaration of | ||||||
14242 | // this name as a function or variable. If so, use that | ||||||
14243 | // (non-visible) declaration, and complain about it. | ||||||
14244 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | ||||||
14245 | if (ExternCPrev) { | ||||||
14246 | // We still need to inject the function into the enclosing block scope so | ||||||
14247 | // that later (non-call) uses can see it. | ||||||
14248 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | ||||||
14249 | |||||||
14250 | // C89 footnote 38: | ||||||
14251 | // If in fact it is not defined as having type "function returning int", | ||||||
14252 | // the behavior is undefined. | ||||||
14253 | if (!isa<FunctionDecl>(ExternCPrev) || | ||||||
14254 | !Context.typesAreCompatible( | ||||||
14255 | cast<FunctionDecl>(ExternCPrev)->getType(), | ||||||
14256 | Context.getFunctionNoProtoType(Context.IntTy))) { | ||||||
14257 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | ||||||
14258 | << ExternCPrev << !getLangOpts().C99; | ||||||
14259 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | ||||||
14260 | return ExternCPrev; | ||||||
14261 | } | ||||||
14262 | } | ||||||
14263 | |||||||
14264 | // Extension in C99. Legal in C90, but warn about it. | ||||||
14265 | unsigned diag_id; | ||||||
14266 | if (II.getName().startswith("__builtin_")) | ||||||
14267 | diag_id = diag::warn_builtin_unknown; | ||||||
14268 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | ||||||
14269 | else if (getLangOpts().OpenCL) | ||||||
14270 | diag_id = diag::err_opencl_implicit_function_decl; | ||||||
14271 | else if (getLangOpts().C99) | ||||||
14272 | diag_id = diag::ext_implicit_function_decl; | ||||||
14273 | else | ||||||
14274 | diag_id = diag::warn_implicit_function_decl; | ||||||
14275 | Diag(Loc, diag_id) << &II; | ||||||
14276 | |||||||
14277 | // If we found a prior declaration of this function, don't bother building | ||||||
14278 | // another one. We've already pushed that one into scope, so there's nothing | ||||||
14279 | // more to do. | ||||||
14280 | if (ExternCPrev) | ||||||
14281 | return ExternCPrev; | ||||||
14282 | |||||||
14283 | // Because typo correction is expensive, only do it if the implicit | ||||||
14284 | // function declaration is going to be treated as an error. | ||||||
14285 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { | ||||||
14286 | TypoCorrection Corrected; | ||||||
14287 | DeclFilterCCC<FunctionDecl> CCC{}; | ||||||
14288 | if (S && (Corrected = | ||||||
14289 | CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, | ||||||
14290 | S, nullptr, CCC, CTK_NonError))) | ||||||
14291 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | ||||||
14292 | /*ErrorRecovery*/false); | ||||||
14293 | } | ||||||
14294 | |||||||
14295 | // Set a Declarator for the implicit definition: int foo(); | ||||||
14296 | const char *Dummy; | ||||||
14297 | AttributeFactory attrFactory; | ||||||
14298 | DeclSpec DS(attrFactory); | ||||||
14299 | unsigned DiagID; | ||||||
14300 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | ||||||
14301 | Context.getPrintingPolicy()); | ||||||
14302 | (void)Error; // Silence warning. | ||||||
14303 | assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast <void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14303, __PRETTY_FUNCTION__)); | ||||||
14304 | SourceLocation NoLoc; | ||||||
14305 | Declarator D(DS, DeclaratorContext::BlockContext); | ||||||
14306 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | ||||||
14307 | /*IsAmbiguous=*/false, | ||||||
14308 | /*LParenLoc=*/NoLoc, | ||||||
14309 | /*Params=*/nullptr, | ||||||
14310 | /*NumParams=*/0, | ||||||
14311 | /*EllipsisLoc=*/NoLoc, | ||||||
14312 | /*RParenLoc=*/NoLoc, | ||||||
14313 | /*RefQualifierIsLvalueRef=*/true, | ||||||
14314 | /*RefQualifierLoc=*/NoLoc, | ||||||
14315 | /*MutableLoc=*/NoLoc, EST_None, | ||||||
14316 | /*ESpecRange=*/SourceRange(), | ||||||
14317 | /*Exceptions=*/nullptr, | ||||||
14318 | /*ExceptionRanges=*/nullptr, | ||||||
14319 | /*NumExceptions=*/0, | ||||||
14320 | /*NoexceptExpr=*/nullptr, | ||||||
14321 | /*ExceptionSpecTokens=*/nullptr, | ||||||
14322 | /*DeclsInPrototype=*/None, Loc, | ||||||
14323 | Loc, D), | ||||||
14324 | std::move(DS.getAttributes()), SourceLocation()); | ||||||
14325 | D.SetIdentifier(&II, Loc); | ||||||
14326 | |||||||
14327 | // Insert this function into the enclosing block scope. | ||||||
14328 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | ||||||
14329 | FD->setImplicit(); | ||||||
14330 | |||||||
14331 | AddKnownFunctionAttributes(FD); | ||||||
14332 | |||||||
14333 | return FD; | ||||||
14334 | } | ||||||
14335 | |||||||
14336 | /// Adds any function attributes that we know a priori based on | ||||||
14337 | /// the declaration of this function. | ||||||
14338 | /// | ||||||
14339 | /// These attributes can apply both to implicitly-declared builtins | ||||||
14340 | /// (like __builtin___printf_chk) or to library-declared functions | ||||||
14341 | /// like NSLog or printf. | ||||||
14342 | /// | ||||||
14343 | /// We need to check for duplicate attributes both here and where user-written | ||||||
14344 | /// attributes are applied to declarations. | ||||||
14345 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | ||||||
14346 | if (FD->isInvalidDecl()) | ||||||
14347 | return; | ||||||
14348 | |||||||
14349 | // If this is a built-in function, map its builtin attributes to | ||||||
14350 | // actual attributes. | ||||||
14351 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||||
14352 | // Handle printf-formatting attributes. | ||||||
14353 | unsigned FormatIdx; | ||||||
14354 | bool HasVAListArg; | ||||||
14355 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | ||||||
14356 | if (!FD->hasAttr<FormatAttr>()) { | ||||||
14357 | const char *fmt = "printf"; | ||||||
14358 | unsigned int NumParams = FD->getNumParams(); | ||||||
14359 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | ||||||
14360 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | ||||||
14361 | fmt = "NSString"; | ||||||
14362 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14363 | &Context.Idents.get(fmt), | ||||||
14364 | FormatIdx+1, | ||||||
14365 | HasVAListArg ? 0 : FormatIdx+2, | ||||||
14366 | FD->getLocation())); | ||||||
14367 | } | ||||||
14368 | } | ||||||
14369 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | ||||||
14370 | HasVAListArg)) { | ||||||
14371 | if (!FD->hasAttr<FormatAttr>()) | ||||||
14372 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14373 | &Context.Idents.get("scanf"), | ||||||
14374 | FormatIdx+1, | ||||||
14375 | HasVAListArg ? 0 : FormatIdx+2, | ||||||
14376 | FD->getLocation())); | ||||||
14377 | } | ||||||
14378 | |||||||
14379 | // Handle automatically recognized callbacks. | ||||||
14380 | SmallVector<int, 4> Encoding; | ||||||
14381 | if (!FD->hasAttr<CallbackAttr>() && | ||||||
14382 | Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) | ||||||
14383 | FD->addAttr(CallbackAttr::CreateImplicit( | ||||||
14384 | Context, Encoding.data(), Encoding.size(), FD->getLocation())); | ||||||
14385 | |||||||
14386 | // Mark const if we don't care about errno and that is the only thing | ||||||
14387 | // preventing the function from being const. This allows IRgen to use LLVM | ||||||
14388 | // intrinsics for such functions. | ||||||
14389 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | ||||||
14390 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | ||||||
14391 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14392 | |||||||
14393 | // We make "fma" on some platforms const because we know it does not set | ||||||
14394 | // errno in those environments even though it could set errno based on the | ||||||
14395 | // C standard. | ||||||
14396 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | ||||||
14397 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && | ||||||
14398 | !FD->hasAttr<ConstAttr>()) { | ||||||
14399 | switch (BuiltinID) { | ||||||
14400 | case Builtin::BI__builtin_fma: | ||||||
14401 | case Builtin::BI__builtin_fmaf: | ||||||
14402 | case Builtin::BI__builtin_fmal: | ||||||
14403 | case Builtin::BIfma: | ||||||
14404 | case Builtin::BIfmaf: | ||||||
14405 | case Builtin::BIfmal: | ||||||
14406 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14407 | break; | ||||||
14408 | default: | ||||||
14409 | break; | ||||||
14410 | } | ||||||
14411 | } | ||||||
14412 | |||||||
14413 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | ||||||
14414 | !FD->hasAttr<ReturnsTwiceAttr>()) | ||||||
14415 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | ||||||
14416 | FD->getLocation())); | ||||||
14417 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | ||||||
14418 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14419 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | ||||||
14420 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14421 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | ||||||
14422 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14423 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | ||||||
14424 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | ||||||
14425 | // Add the appropriate attribute, depending on the CUDA compilation mode | ||||||
14426 | // and which target the builtin belongs to. For example, during host | ||||||
14427 | // compilation, aux builtins are __device__, while the rest are __host__. | ||||||
14428 | if (getLangOpts().CUDAIsDevice != | ||||||
14429 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | ||||||
14430 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14431 | else | ||||||
14432 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14433 | } | ||||||
14434 | } | ||||||
14435 | |||||||
14436 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | ||||||
14437 | // throw, add an implicit nothrow attribute to any extern "C" function we come | ||||||
14438 | // across. | ||||||
14439 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | ||||||
14440 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | ||||||
14441 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | ||||||
14442 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | ||||||
14443 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14444 | } | ||||||
14445 | |||||||
14446 | IdentifierInfo *Name = FD->getIdentifier(); | ||||||
14447 | if (!Name) | ||||||
14448 | return; | ||||||
14449 | if ((!getLangOpts().CPlusPlus && | ||||||
14450 | FD->getDeclContext()->isTranslationUnit()) || | ||||||
14451 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | ||||||
14452 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | ||||||
14453 | LinkageSpecDecl::lang_c)) { | ||||||
14454 | // Okay: this could be a libc/libm/Objective-C function we know | ||||||
14455 | // about. | ||||||
14456 | } else | ||||||
14457 | return; | ||||||
14458 | |||||||
14459 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | ||||||
14460 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | ||||||
14461 | // target-specific builtins, perhaps? | ||||||
14462 | if (!FD->hasAttr<FormatAttr>()) | ||||||
14463 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14464 | &Context.Idents.get("printf"), 2, | ||||||
14465 | Name->isStr("vasprintf") ? 0 : 3, | ||||||
14466 | FD->getLocation())); | ||||||
14467 | } | ||||||
14468 | |||||||
14469 | if (Name->isStr("__CFStringMakeConstantString")) { | ||||||
14470 | // We already have a __builtin___CFStringMakeConstantString, | ||||||
14471 | // but builds that use -fno-constant-cfstrings don't go through that. | ||||||
14472 | if (!FD->hasAttr<FormatArgAttr>()) | ||||||
14473 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | ||||||
14474 | FD->getLocation())); | ||||||
14475 | } | ||||||
14476 | } | ||||||
14477 | |||||||
14478 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | ||||||
14479 | TypeSourceInfo *TInfo) { | ||||||
14480 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14480, __PRETTY_FUNCTION__)); | ||||||
14481 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14481, __PRETTY_FUNCTION__)); | ||||||
14482 | |||||||
14483 | if (!TInfo) { | ||||||
14484 | assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type" ) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14484, __PRETTY_FUNCTION__)); | ||||||
14485 | TInfo = Context.getTrivialTypeSourceInfo(T); | ||||||
14486 | } | ||||||
14487 | |||||||
14488 | // Scope manipulation handled by caller. | ||||||
14489 | TypedefDecl *NewTD = | ||||||
14490 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), | ||||||
14491 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); | ||||||
14492 | |||||||
14493 | // Bail out immediately if we have an invalid declaration. | ||||||
14494 | if (D.isInvalidType()) { | ||||||
14495 | NewTD->setInvalidDecl(); | ||||||
14496 | return NewTD; | ||||||
14497 | } | ||||||
14498 | |||||||
14499 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
14500 | if (CurContext->isFunctionOrMethod()) | ||||||
14501 | Diag(NewTD->getLocation(), diag::err_module_private_local) | ||||||
14502 | << 2 << NewTD->getDeclName() | ||||||
14503 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
14504 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
14505 | else | ||||||
14506 | NewTD->setModulePrivate(); | ||||||
14507 | } | ||||||
14508 | |||||||
14509 | // C++ [dcl.typedef]p8: | ||||||
14510 | // If the typedef declaration defines an unnamed class (or | ||||||
14511 | // enum), the first typedef-name declared by the declaration | ||||||
14512 | // to be that class type (or enum type) is used to denote the | ||||||
14513 | // class type (or enum type) for linkage purposes only. | ||||||
14514 | // We need to check whether the type was declared in the declaration. | ||||||
14515 | switch (D.getDeclSpec().getTypeSpecType()) { | ||||||
14516 | case TST_enum: | ||||||
14517 | case TST_struct: | ||||||
14518 | case TST_interface: | ||||||
14519 | case TST_union: | ||||||
14520 | case TST_class: { | ||||||
14521 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | ||||||
14522 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | ||||||
14523 | break; | ||||||
14524 | } | ||||||
14525 | |||||||
14526 | default: | ||||||
14527 | break; | ||||||
14528 | } | ||||||
14529 | |||||||
14530 | return NewTD; | ||||||
14531 | } | ||||||
14532 | |||||||
14533 | /// Check that this is a valid underlying type for an enum declaration. | ||||||
14534 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | ||||||
14535 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | ||||||
14536 | QualType T = TI->getType(); | ||||||
14537 | |||||||
14538 | if (T->isDependentType()) | ||||||
14539 | return false; | ||||||
14540 | |||||||
14541 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | ||||||
14542 | if (BT->isInteger()) | ||||||
14543 | return false; | ||||||
14544 | |||||||
14545 | Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | ||||||
14546 | return true; | ||||||
14547 | } | ||||||
14548 | |||||||
14549 | /// Check whether this is a valid redeclaration of a previous enumeration. | ||||||
14550 | /// \return true if the redeclaration was invalid. | ||||||
14551 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | ||||||
14552 | QualType EnumUnderlyingTy, bool IsFixed, | ||||||
14553 | const EnumDecl *Prev) { | ||||||
14554 | if (IsScoped != Prev->isScoped()) { | ||||||
14555 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | ||||||
14556 | << Prev->isScoped(); | ||||||
14557 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||||
14558 | return true; | ||||||
14559 | } | ||||||
14560 | |||||||
14561 | if (IsFixed && Prev->isFixed()) { | ||||||
14562 | if (!EnumUnderlyingTy->isDependentType() && | ||||||
14563 | !Prev->getIntegerType()->isDependentType() && | ||||||
14564 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | ||||||
14565 | Prev->getIntegerType())) { | ||||||
14566 | // TODO: Highlight the underlying type of the redeclaration. | ||||||
14567 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | ||||||
14568 | << EnumUnderlyingTy << Prev->getIntegerType(); | ||||||
14569 | Diag(Prev->getLocation(), diag::note_previous_declaration) | ||||||
14570 | << Prev->getIntegerTypeRange(); | ||||||
14571 | return true; | ||||||
14572 | } | ||||||
14573 | } else if (IsFixed != Prev->isFixed()) { | ||||||
14574 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | ||||||
14575 | << Prev->isFixed(); | ||||||
14576 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||||
14577 | return true; | ||||||
14578 | } | ||||||
14579 | |||||||
14580 | return false; | ||||||
14581 | } | ||||||
14582 | |||||||
14583 | /// Get diagnostic %select index for tag kind for | ||||||
14584 | /// redeclaration diagnostic message. | ||||||
14585 | /// WARNING: Indexes apply to particular diagnostics only! | ||||||
14586 | /// | ||||||
14587 | /// \returns diagnostic %select index. | ||||||
14588 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | ||||||
14589 | switch (Tag) { | ||||||
14590 | case TTK_Struct: return 0; | ||||||
14591 | case TTK_Interface: return 1; | ||||||
14592 | case TTK_Class: return 2; | ||||||
14593 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14593); | ||||||
14594 | } | ||||||
14595 | } | ||||||
14596 | |||||||
14597 | /// Determine if tag kind is a class-key compatible with | ||||||
14598 | /// class for redeclaration (class, struct, or __interface). | ||||||
14599 | /// | ||||||
14600 | /// \returns true iff the tag kind is compatible. | ||||||
14601 | static bool isClassCompatTagKind(TagTypeKind Tag) | ||||||
14602 | { | ||||||
14603 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | ||||||
14604 | } | ||||||
14605 | |||||||
14606 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | ||||||
14607 | TagTypeKind TTK) { | ||||||
14608 | if (isa<TypedefDecl>(PrevDecl)) | ||||||
14609 | return NTK_Typedef; | ||||||
14610 | else if (isa<TypeAliasDecl>(PrevDecl)) | ||||||
14611 | return NTK_TypeAlias; | ||||||
14612 | else if (isa<ClassTemplateDecl>(PrevDecl)) | ||||||
14613 | return NTK_Template; | ||||||
14614 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | ||||||
14615 | return NTK_TypeAliasTemplate; | ||||||
14616 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | ||||||
14617 | return NTK_TemplateTemplateArgument; | ||||||
14618 | switch (TTK) { | ||||||
14619 | case TTK_Struct: | ||||||
14620 | case TTK_Interface: | ||||||
14621 | case TTK_Class: | ||||||
14622 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | ||||||
14623 | case TTK_Union: | ||||||
14624 | return NTK_NonUnion; | ||||||
14625 | case TTK_Enum: | ||||||
14626 | return NTK_NonEnum; | ||||||
14627 | } | ||||||
14628 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14628); | ||||||
14629 | } | ||||||
14630 | |||||||
14631 | /// Determine whether a tag with a given kind is acceptable | ||||||
14632 | /// as a redeclaration of the given tag declaration. | ||||||
14633 | /// | ||||||
14634 | /// \returns true if the new tag kind is acceptable, false otherwise. | ||||||
14635 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | ||||||
14636 | TagTypeKind NewTag, bool isDefinition, | ||||||
14637 | SourceLocation NewTagLoc, | ||||||
14638 | const IdentifierInfo *Name) { | ||||||
14639 | // C++ [dcl.type.elab]p3: | ||||||
14640 | // The class-key or enum keyword present in the | ||||||
14641 | // elaborated-type-specifier shall agree in kind with the | ||||||
14642 | // declaration to which the name in the elaborated-type-specifier | ||||||
14643 | // refers. This rule also applies to the form of | ||||||
14644 | // elaborated-type-specifier that declares a class-name or | ||||||
14645 | // friend class since it can be construed as referring to the | ||||||
14646 | // definition of the class. Thus, in any | ||||||
14647 | // elaborated-type-specifier, the enum keyword shall be used to | ||||||
14648 | // refer to an enumeration (7.2), the union class-key shall be | ||||||
14649 | // used to refer to a union (clause 9), and either the class or | ||||||
14650 | // struct class-key shall be used to refer to a class (clause 9) | ||||||
14651 | // declared using the class or struct class-key. | ||||||
14652 | TagTypeKind OldTag = Previous->getTagKind(); | ||||||
14653 | if (OldTag != NewTag && | ||||||
14654 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) | ||||||
14655 | return false; | ||||||
14656 | |||||||
14657 | // Tags are compatible, but we might still want to warn on mismatched tags. | ||||||
14658 | // Non-class tags can't be mismatched at this point. | ||||||
14659 | if (!isClassCompatTagKind(NewTag)) | ||||||
14660 | return true; | ||||||
14661 | |||||||
14662 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored | ||||||
14663 | // by our warning analysis. We don't want to warn about mismatches with (eg) | ||||||
14664 | // declarations in system headers that are designed to be specialized, but if | ||||||
14665 | // a user asks us to warn, we should warn if their code contains mismatched | ||||||
14666 | // declarations. | ||||||
14667 | auto IsIgnoredLoc = [&](SourceLocation Loc) { | ||||||
14668 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, | ||||||
14669 | Loc); | ||||||
14670 | }; | ||||||
14671 | if (IsIgnoredLoc(NewTagLoc)) | ||||||
14672 | return true; | ||||||
14673 | |||||||
14674 | auto IsIgnored = [&](const TagDecl *Tag) { | ||||||
14675 | return IsIgnoredLoc(Tag->getLocation()); | ||||||
14676 | }; | ||||||
14677 | while (IsIgnored(Previous)) { | ||||||
14678 | Previous = Previous->getPreviousDecl(); | ||||||
14679 | if (!Previous) | ||||||
14680 | return true; | ||||||
14681 | OldTag = Previous->getTagKind(); | ||||||
14682 | } | ||||||
14683 | |||||||
14684 | bool isTemplate = false; | ||||||
14685 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | ||||||
14686 | isTemplate = Record->getDescribedClassTemplate(); | ||||||
14687 | |||||||
14688 | if (inTemplateInstantiation()) { | ||||||
14689 | if (OldTag != NewTag) { | ||||||
14690 | // In a template instantiation, do not offer fix-its for tag mismatches | ||||||
14691 | // since they usually mess up the template instead of fixing the problem. | ||||||
14692 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||||
14693 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
14694 | << getRedeclDiagFromTagKind(OldTag); | ||||||
14695 | // FIXME: Note previous location? | ||||||
14696 | } | ||||||
14697 | return true; | ||||||
14698 | } | ||||||
14699 | |||||||
14700 | if (isDefinition) { | ||||||
14701 | // On definitions, check all previous tags and issue a fix-it for each | ||||||
14702 | // one that doesn't match the current tag. | ||||||
14703 | if (Previous->getDefinition()) { | ||||||
14704 | // Don't suggest fix-its for redefinitions. | ||||||
14705 | return true; | ||||||
14706 | } | ||||||
14707 | |||||||
14708 | bool previousMismatch = false; | ||||||
14709 | for (const TagDecl *I : Previous->redecls()) { | ||||||
14710 | if (I->getTagKind() != NewTag) { | ||||||
14711 | // Ignore previous declarations for which the warning was disabled. | ||||||
14712 | if (IsIgnored(I)) | ||||||
14713 | continue; | ||||||
14714 | |||||||
14715 | if (!previousMismatch) { | ||||||
14716 | previousMismatch = true; | ||||||
14717 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | ||||||
14718 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
14719 | << getRedeclDiagFromTagKind(I->getTagKind()); | ||||||
14720 | } | ||||||
14721 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | ||||||
14722 | << getRedeclDiagFromTagKind(NewTag) | ||||||
14723 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | ||||||
14724 | TypeWithKeyword::getTagTypeKindName(NewTag)); | ||||||
14725 | } | ||||||
14726 | } | ||||||
14727 | return true; | ||||||
14728 | } | ||||||
14729 | |||||||
14730 | // Identify the prevailing tag kind: this is the kind of the definition (if | ||||||
14731 | // there is a non-ignored definition), or otherwise the kind of the prior | ||||||
14732 | // (non-ignored) declaration. | ||||||
14733 | const TagDecl *PrevDef = Previous->getDefinition(); | ||||||
14734 | if (PrevDef && IsIgnored(PrevDef)) | ||||||
14735 | PrevDef = nullptr; | ||||||
14736 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; | ||||||
14737 | if (Redecl->getTagKind() != NewTag) { | ||||||
14738 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||||
14739 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
14740 | << getRedeclDiagFromTagKind(OldTag); | ||||||
14741 | Diag(Redecl->getLocation(), diag::note_previous_use); | ||||||
14742 | |||||||
14743 | // If there is a previous definition, suggest a fix-it. | ||||||
14744 | if (PrevDef) { | ||||||
14745 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | ||||||
14746 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | ||||||
14747 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | ||||||
14748 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | ||||||
14749 | } | ||||||
14750 | } | ||||||
14751 | |||||||
14752 | return true; | ||||||
14753 | } | ||||||
14754 | |||||||
14755 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | ||||||
14756 | /// from an outer enclosing namespace or file scope inside a friend declaration. | ||||||
14757 | /// This should provide the commented out code in the following snippet: | ||||||
14758 | /// namespace N { | ||||||
14759 | /// struct X; | ||||||
14760 | /// namespace M { | ||||||
14761 | /// struct Y { friend struct /*N::*/ X; }; | ||||||
14762 | /// } | ||||||
14763 | /// } | ||||||
14764 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | ||||||
14765 | SourceLocation NameLoc) { | ||||||
14766 | // While the decl is in a namespace, do repeated lookup of that name and see | ||||||
14767 | // if we get the same namespace back. If we do not, continue until | ||||||
14768 | // translation unit scope, at which point we have a fully qualified NNS. | ||||||
14769 | SmallVector<IdentifierInfo *, 4> Namespaces; | ||||||
14770 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||||
14771 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | ||||||
14772 | // This tag should be declared in a namespace, which can only be enclosed by | ||||||
14773 | // other namespaces. Bail if there's an anonymous namespace in the chain. | ||||||
14774 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | ||||||
14775 | if (!Namespace || Namespace->isAnonymousNamespace()) | ||||||
14776 | return FixItHint(); | ||||||
14777 | IdentifierInfo *II = Namespace->getIdentifier(); | ||||||
14778 | Namespaces.push_back(II); | ||||||
14779 | NamedDecl *Lookup = SemaRef.LookupSingleName( | ||||||
14780 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | ||||||
14781 | if (Lookup == Namespace) | ||||||
14782 | break; | ||||||
14783 | } | ||||||
14784 | |||||||
14785 | // Once we have all the namespaces, reverse them to go outermost first, and | ||||||
14786 | // build an NNS. | ||||||
14787 | SmallString<64> Insertion; | ||||||
14788 | llvm::raw_svector_ostream OS(Insertion); | ||||||
14789 | if (DC->isTranslationUnit()) | ||||||
14790 | OS << "::"; | ||||||
14791 | std::reverse(Namespaces.begin(), Namespaces.end()); | ||||||
14792 | for (auto *II : Namespaces) | ||||||
14793 | OS << II->getName() << "::"; | ||||||
14794 | return FixItHint::CreateInsertion(NameLoc, Insertion); | ||||||
14795 | } | ||||||
14796 | |||||||
14797 | /// Determine whether a tag originally declared in context \p OldDC can | ||||||
14798 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | ||||||
14799 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | ||||||
14800 | /// using-declaration). | ||||||
14801 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | ||||||
14802 | DeclContext *NewDC) { | ||||||
14803 | OldDC = OldDC->getRedeclContext(); | ||||||
14804 | NewDC = NewDC->getRedeclContext(); | ||||||
14805 | |||||||
14806 | if (OldDC->Equals(NewDC)) | ||||||
14807 | return true; | ||||||
14808 | |||||||
14809 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | ||||||
14810 | // encloses the other). | ||||||
14811 | if (S.getLangOpts().MSVCCompat && | ||||||
14812 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | ||||||
14813 | return true; | ||||||
14814 | |||||||
14815 | return false; | ||||||
14816 | } | ||||||
14817 | |||||||
14818 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | ||||||
14819 | /// former case, Name will be non-null. In the later case, Name will be null. | ||||||
14820 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | ||||||
14821 | /// reference/declaration/definition of a tag. | ||||||
14822 | /// | ||||||
14823 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | ||||||
14824 | /// trailing-type-specifier) other than one in an alias-declaration. | ||||||
14825 | /// | ||||||
14826 | /// \param SkipBody If non-null, will be set to indicate if the caller should | ||||||
14827 | /// skip the definition of this tag and treat it as if it were a declaration. | ||||||
14828 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | ||||||
14829 | SourceLocation KWLoc, CXXScopeSpec &SS, | ||||||
14830 | IdentifierInfo *Name, SourceLocation NameLoc, | ||||||
14831 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | ||||||
14832 | SourceLocation ModulePrivateLoc, | ||||||
14833 | MultiTemplateParamsArg TemplateParameterLists, | ||||||
14834 | bool &OwnedDecl, bool &IsDependent, | ||||||
14835 | SourceLocation ScopedEnumKWLoc, | ||||||
14836 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | ||||||
14837 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | ||||||
14838 | SkipBodyInfo *SkipBody) { | ||||||
14839 | // If this is not a definition, it must have a name. | ||||||
14840 | IdentifierInfo *OrigName = Name; | ||||||
14841 | assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14842, __PRETTY_FUNCTION__)) | ||||||
14842 | "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14842, __PRETTY_FUNCTION__)); | ||||||
14843 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14843, __PRETTY_FUNCTION__)); | ||||||
14844 | |||||||
14845 | OwnedDecl = false; | ||||||
14846 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | ||||||
14847 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | ||||||
14848 | |||||||
14849 | // FIXME: Check member specializations more carefully. | ||||||
14850 | bool isMemberSpecialization = false; | ||||||
14851 | bool Invalid = false; | ||||||
14852 | |||||||
14853 | // We only need to do this matching if we have template parameters | ||||||
14854 | // or a scope specifier, which also conveniently avoids this work | ||||||
14855 | // for non-C++ cases. | ||||||
14856 | if (TemplateParameterLists.size() > 0 || | ||||||
14857 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | ||||||
14858 | if (TemplateParameterList *TemplateParams = | ||||||
14859 | MatchTemplateParametersToScopeSpecifier( | ||||||
14860 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | ||||||
14861 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | ||||||
14862 | if (Kind == TTK_Enum) { | ||||||
14863 | Diag(KWLoc, diag::err_enum_template); | ||||||
14864 | return nullptr; | ||||||
14865 | } | ||||||
14866 | |||||||
14867 | if (TemplateParams->size() > 0) { | ||||||
14868 | // This is a declaration or definition of a class template (which may | ||||||
14869 | // be a member of another template). | ||||||
14870 | |||||||
14871 | if (Invalid) | ||||||
14872 | return nullptr; | ||||||
14873 | |||||||
14874 | OwnedDecl = false; | ||||||
14875 | DeclResult Result = CheckClassTemplate( | ||||||
14876 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | ||||||
14877 | AS, ModulePrivateLoc, | ||||||
14878 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | ||||||
14879 | TemplateParameterLists.data(), SkipBody); | ||||||
14880 | return Result.get(); | ||||||
14881 | } else { | ||||||
14882 | // The "template<>" header is extraneous. | ||||||
14883 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | ||||||
14884 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | ||||||
14885 | isMemberSpecialization = true; | ||||||
14886 | } | ||||||
14887 | } | ||||||
14888 | } | ||||||
14889 | |||||||
14890 | // Figure out the underlying type if this a enum declaration. We need to do | ||||||
14891 | // this early, because it's needed to detect if this is an incompatible | ||||||
14892 | // redeclaration. | ||||||
14893 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | ||||||
14894 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | ||||||
14895 | |||||||
14896 | if (Kind == TTK_Enum) { | ||||||
14897 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | ||||||
14898 | // No underlying type explicitly specified, or we failed to parse the | ||||||
14899 | // type, default to int. | ||||||
14900 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14901 | } else if (UnderlyingType.get()) { | ||||||
14902 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | ||||||
14903 | // integral type; any cv-qualification is ignored. | ||||||
14904 | TypeSourceInfo *TI = nullptr; | ||||||
14905 | GetTypeFromParser(UnderlyingType.get(), &TI); | ||||||
14906 | EnumUnderlying = TI; | ||||||
14907 | |||||||
14908 | if (CheckEnumUnderlyingType(TI)) | ||||||
14909 | // Recover by falling back to int. | ||||||
14910 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14911 | |||||||
14912 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | ||||||
14913 | UPPC_FixedUnderlyingType)) | ||||||
14914 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14915 | |||||||
14916 | } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { | ||||||
14917 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | ||||||
14918 | // of 'int'. However, if this is an unfixed forward declaration, don't set | ||||||
14919 | // the underlying type unless the user enables -fms-compatibility. This | ||||||
14920 | // makes unfixed forward declared enums incomplete and is more conforming. | ||||||
14921 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | ||||||
14922 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14923 | } | ||||||
14924 | } | ||||||
14925 | |||||||
14926 | DeclContext *SearchDC = CurContext; | ||||||
14927 | DeclContext *DC = CurContext; | ||||||
14928 | bool isStdBadAlloc = false; | ||||||
14929 | bool isStdAlignValT = false; | ||||||
14930 | |||||||
14931 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | ||||||
14932 | if (TUK == TUK_Friend || TUK == TUK_Reference) | ||||||
14933 | Redecl = NotForRedeclaration; | ||||||
14934 | |||||||
14935 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | ||||||
14936 | /// implemented asks for structural equivalence checking, the returned decl | ||||||
14937 | /// here is passed back to the parser, allowing the tag body to be parsed. | ||||||
14938 | auto createTagFromNewDecl = [&]() -> TagDecl * { | ||||||
14939 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage" ) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 14939, __PRETTY_FUNCTION__)); | ||||||
14940 | // If there is an identifier, use the location of the identifier as the | ||||||
14941 | // location of the decl, otherwise use the location of the struct/union | ||||||
14942 | // keyword. | ||||||
14943 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||||
14944 | TagDecl *New = nullptr; | ||||||
14945 | |||||||
14946 | if (Kind == TTK_Enum) { | ||||||
14947 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | ||||||
14948 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | ||||||
14949 | // If this is an undefined enum, bail. | ||||||
14950 | if (TUK != TUK_Definition && !Invalid) | ||||||
14951 | return nullptr; | ||||||
14952 | if (EnumUnderlying) { | ||||||
14953 | EnumDecl *ED = cast<EnumDecl>(New); | ||||||
14954 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | ||||||
14955 | ED->setIntegerTypeSourceInfo(TI); | ||||||
14956 | else | ||||||
14957 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | ||||||
14958 | ED->setPromotionType(ED->getIntegerType()); | ||||||
14959 | } | ||||||
14960 | } else { // struct/union | ||||||
14961 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
14962 | nullptr); | ||||||
14963 | } | ||||||
14964 | |||||||
14965 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||||
14966 | // Add alignment attributes if necessary; these attributes are checked | ||||||
14967 | // when the ASTContext lays out the structure. | ||||||
14968 | // | ||||||
14969 | // It is important for implementing the correct semantics that this | ||||||
14970 | // happen here (in ActOnTag). The #pragma pack stack is | ||||||
14971 | // maintained as a result of parser callbacks which can occur at | ||||||
14972 | // many points during the parsing of a struct declaration (because | ||||||
14973 | // the #pragma tokens are effectively skipped over during the | ||||||
14974 | // parsing of the struct). | ||||||
14975 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||||
14976 | AddAlignmentAttributesForRecord(RD); | ||||||
14977 | AddMsStructLayoutForRecord(RD); | ||||||
14978 | } | ||||||
14979 | } | ||||||
14980 | New->setLexicalDeclContext(CurContext); | ||||||
14981 | return New; | ||||||
14982 | }; | ||||||
14983 | |||||||
14984 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | ||||||
14985 | if (Name && SS.isNotEmpty()) { | ||||||
14986 | // We have a nested-name tag ('struct foo::bar'). | ||||||
14987 | |||||||
14988 | // Check for invalid 'foo::'. | ||||||
14989 | if (SS.isInvalid()) { | ||||||
14990 | Name = nullptr; | ||||||
14991 | goto CreateNewDecl; | ||||||
14992 | } | ||||||
14993 | |||||||
14994 | // If this is a friend or a reference to a class in a dependent | ||||||
14995 | // context, don't try to make a decl for it. | ||||||
14996 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||||
14997 | DC = computeDeclContext(SS, false); | ||||||
14998 | if (!DC) { | ||||||
14999 | IsDependent = true; | ||||||
15000 | return nullptr; | ||||||
15001 | } | ||||||
15002 | } else { | ||||||
15003 | DC = computeDeclContext(SS, true); | ||||||
15004 | if (!DC) { | ||||||
15005 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | ||||||
15006 | << SS.getRange(); | ||||||
15007 | return nullptr; | ||||||
15008 | } | ||||||
15009 | } | ||||||
15010 | |||||||
15011 | if (RequireCompleteDeclContext(SS, DC)) | ||||||
15012 | return nullptr; | ||||||
15013 | |||||||
15014 | SearchDC = DC; | ||||||
15015 | // Look-up name inside 'foo::'. | ||||||
15016 | LookupQualifiedName(Previous, DC); | ||||||
15017 | |||||||
15018 | if (Previous.isAmbiguous()) | ||||||
15019 | return nullptr; | ||||||
15020 | |||||||
15021 | if (Previous.empty()) { | ||||||
15022 | // Name lookup did not find anything. However, if the | ||||||
15023 | // nested-name-specifier refers to the current instantiation, | ||||||
15024 | // and that current instantiation has any dependent base | ||||||
15025 | // classes, we might find something at instantiation time: treat | ||||||
15026 | // this as a dependent elaborated-type-specifier. | ||||||
15027 | // But this only makes any sense for reference-like lookups. | ||||||
15028 | if (Previous.wasNotFoundInCurrentInstantiation() && | ||||||
15029 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | ||||||
15030 | IsDependent = true; | ||||||
15031 | return nullptr; | ||||||
15032 | } | ||||||
15033 | |||||||
15034 | // A tag 'foo::bar' must already exist. | ||||||
15035 | Diag(NameLoc, diag::err_not_tag_in_scope) | ||||||
15036 | << Kind << Name << DC << SS.getRange(); | ||||||
15037 | Name = nullptr; | ||||||
15038 | Invalid = true; | ||||||
15039 | goto CreateNewDecl; | ||||||
15040 | } | ||||||
15041 | } else if (Name) { | ||||||
15042 | // C++14 [class.mem]p14: | ||||||
15043 | // If T is the name of a class, then each of the following shall have a | ||||||
15044 | // name different from T: | ||||||
15045 | // -- every member of class T that is itself a type | ||||||
15046 | if (TUK != TUK_Reference && TUK != TUK_Friend && | ||||||
15047 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | ||||||
15048 | return nullptr; | ||||||
15049 | |||||||
15050 | // If this is a named struct, check to see if there was a previous forward | ||||||
15051 | // declaration or definition. | ||||||
15052 | // FIXME: We're looking into outer scopes here, even when we | ||||||
15053 | // shouldn't be. Doing so can result in ambiguities that we | ||||||
15054 | // shouldn't be diagnosing. | ||||||
15055 | LookupName(Previous, S); | ||||||
15056 | |||||||
15057 | // When declaring or defining a tag, ignore ambiguities introduced | ||||||
15058 | // by types using'ed into this scope. | ||||||
15059 | if (Previous.isAmbiguous() && | ||||||
15060 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | ||||||
15061 | LookupResult::Filter F = Previous.makeFilter(); | ||||||
15062 | while (F.hasNext()) { | ||||||
15063 | NamedDecl *ND = F.next(); | ||||||
15064 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | ||||||
15065 | SearchDC->getRedeclContext())) | ||||||
15066 | F.erase(); | ||||||
15067 | } | ||||||
15068 | F.done(); | ||||||
15069 | } | ||||||
15070 | |||||||
15071 | // C++11 [namespace.memdef]p3: | ||||||
15072 | // If the name in a friend declaration is neither qualified nor | ||||||
15073 | // a template-id and the declaration is a function or an | ||||||
15074 | // elaborated-type-specifier, the lookup to determine whether | ||||||
15075 | // the entity has been previously declared shall not consider | ||||||
15076 | // any scopes outside the innermost enclosing namespace. | ||||||
15077 | // | ||||||
15078 | // MSVC doesn't implement the above rule for types, so a friend tag | ||||||
15079 | // declaration may be a redeclaration of a type declared in an enclosing | ||||||
15080 | // scope. They do implement this rule for friend functions. | ||||||
15081 | // | ||||||
15082 | // Does it matter that this should be by scope instead of by | ||||||
15083 | // semantic context? | ||||||
15084 | if (!Previous.empty() && TUK == TUK_Friend) { | ||||||
15085 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | ||||||
15086 | LookupResult::Filter F = Previous.makeFilter(); | ||||||
15087 | bool FriendSawTagOutsideEnclosingNamespace = false; | ||||||
15088 | while (F.hasNext()) { | ||||||
15089 | NamedDecl *ND = F.next(); | ||||||
15090 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||||
15091 | if (DC->isFileContext() && | ||||||
15092 | !EnclosingNS->Encloses(ND->getDeclContext())) { | ||||||
15093 | if (getLangOpts().MSVCCompat) | ||||||
15094 | FriendSawTagOutsideEnclosingNamespace = true; | ||||||
15095 | else | ||||||
15096 | F.erase(); | ||||||
15097 | } | ||||||
15098 | } | ||||||
15099 | F.done(); | ||||||
15100 | |||||||
15101 | // Diagnose this MSVC extension in the easy case where lookup would have | ||||||
15102 | // unambiguously found something outside the enclosing namespace. | ||||||
15103 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | ||||||
15104 | NamedDecl *ND = Previous.getFoundDecl(); | ||||||
15105 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | ||||||
15106 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | ||||||
15107 | } | ||||||
15108 | } | ||||||
15109 | |||||||
15110 | // Note: there used to be some attempt at recovery here. | ||||||
15111 | if (Previous.isAmbiguous()) | ||||||
15112 | return nullptr; | ||||||
15113 | |||||||
15114 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | ||||||
15115 | // FIXME: This makes sure that we ignore the contexts associated | ||||||
15116 | // with C structs, unions, and enums when looking for a matching | ||||||
15117 | // tag declaration or definition. See the similar lookup tweak | ||||||
15118 | // in Sema::LookupName; is there a better way to deal with this? | ||||||
15119 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) | ||||||
15120 | SearchDC = SearchDC->getParent(); | ||||||
15121 | } | ||||||
15122 | } | ||||||
15123 | |||||||
15124 | if (Previous.isSingleResult() && | ||||||
15125 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||||
15126 | // Maybe we will complain about the shadowed template parameter. | ||||||
15127 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | ||||||
15128 | // Just pretend that we didn't see the previous declaration. | ||||||
15129 | Previous.clear(); | ||||||
15130 | } | ||||||
15131 | |||||||
15132 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | ||||||
15133 | DC->Equals(getStdNamespace())) { | ||||||
15134 | if (Name->isStr("bad_alloc")) { | ||||||
15135 | // This is a declaration of or a reference to "std::bad_alloc". | ||||||
15136 | isStdBadAlloc = true; | ||||||
15137 | |||||||
15138 | // If std::bad_alloc has been implicitly declared (but made invisible to | ||||||
15139 | // name lookup), fill in this implicit declaration as the previous | ||||||
15140 | // declaration, so that the declarations get chained appropriately. | ||||||
15141 | if (Previous.empty() && StdBadAlloc) | ||||||
15142 | Previous.addDecl(getStdBadAlloc()); | ||||||
15143 | } else if (Name->isStr("align_val_t")) { | ||||||
15144 | isStdAlignValT = true; | ||||||
15145 | if (Previous.empty() && StdAlignValT) | ||||||
15146 | Previous.addDecl(getStdAlignValT()); | ||||||
15147 | } | ||||||
15148 | } | ||||||
15149 | |||||||
15150 | // If we didn't find a previous declaration, and this is a reference | ||||||
15151 | // (or friend reference), move to the correct scope. In C++, we | ||||||
15152 | // also need to do a redeclaration lookup there, just in case | ||||||
15153 | // there's a shadow friend decl. | ||||||
15154 | if (Name && Previous.empty() && | ||||||
15155 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | ||||||
15156 | if (Invalid) goto CreateNewDecl; | ||||||
15157 | assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15157, __PRETTY_FUNCTION__)); | ||||||
15158 | |||||||
15159 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | ||||||
15160 | // C++ [basic.scope.pdecl]p5: | ||||||
15161 | // -- for an elaborated-type-specifier of the form | ||||||
15162 | // | ||||||
15163 | // class-key identifier | ||||||
15164 | // | ||||||
15165 | // if the elaborated-type-specifier is used in the | ||||||
15166 | // decl-specifier-seq or parameter-declaration-clause of a | ||||||
15167 | // function defined in namespace scope, the identifier is | ||||||
15168 | // declared as a class-name in the namespace that contains | ||||||
15169 | // the declaration; otherwise, except as a friend | ||||||
15170 | // declaration, the identifier is declared in the smallest | ||||||
15171 | // non-class, non-function-prototype scope that contains the | ||||||
15172 | // declaration. | ||||||
15173 | // | ||||||
15174 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | ||||||
15175 | // C structs and unions. | ||||||
15176 | // | ||||||
15177 | // It is an error in C++ to declare (rather than define) an enum | ||||||
15178 | // type, including via an elaborated type specifier. We'll | ||||||
15179 | // diagnose that later; for now, declare the enum in the same | ||||||
15180 | // scope as we would have picked for any other tag type. | ||||||
15181 | // | ||||||
15182 | // GNU C also supports this behavior as part of its incomplete | ||||||
15183 | // enum types extension, while GNU C++ does not. | ||||||
15184 | // | ||||||
15185 | // Find the context where we'll be declaring the tag. | ||||||
15186 | // FIXME: We would like to maintain the current DeclContext as the | ||||||
15187 | // lexical context, | ||||||
15188 | SearchDC = getTagInjectionContext(SearchDC); | ||||||
15189 | |||||||
15190 | // Find the scope where we'll be declaring the tag. | ||||||
15191 | S = getTagInjectionScope(S, getLangOpts()); | ||||||
15192 | } else { | ||||||
15193 | assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15193, __PRETTY_FUNCTION__)); | ||||||
15194 | // C++ [namespace.memdef]p3: | ||||||
15195 | // If a friend declaration in a non-local class first declares a | ||||||
15196 | // class or function, the friend class or function is a member of | ||||||
15197 | // the innermost enclosing namespace. | ||||||
15198 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | ||||||
15199 | } | ||||||
15200 | |||||||
15201 | // In C++, we need to do a redeclaration lookup to properly | ||||||
15202 | // diagnose some problems. | ||||||
15203 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | ||||||
15204 | // hidden declaration so that we don't get ambiguity errors when using a | ||||||
15205 | // type declared by an elaborated-type-specifier. In C that is not correct | ||||||
15206 | // and we should instead merge compatible types found by lookup. | ||||||
15207 | if (getLangOpts().CPlusPlus) { | ||||||
15208 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||||
15209 | LookupQualifiedName(Previous, SearchDC); | ||||||
15210 | } else { | ||||||
15211 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||||
15212 | LookupName(Previous, S); | ||||||
15213 | } | ||||||
15214 | } | ||||||
15215 | |||||||
15216 | // If we have a known previous declaration to use, then use it. | ||||||
15217 | if (Previous.empty() && SkipBody && SkipBody->Previous) | ||||||
15218 | Previous.addDecl(SkipBody->Previous); | ||||||
15219 | |||||||
15220 | if (!Previous.empty()) { | ||||||
15221 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | ||||||
15222 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | ||||||
15223 | |||||||
15224 | // It's okay to have a tag decl in the same scope as a typedef | ||||||
15225 | // which hides a tag decl in the same scope. Finding this | ||||||
15226 | // insanity with a redeclaration lookup can only actually happen | ||||||
15227 | // in C++. | ||||||
15228 | // | ||||||
15229 | // This is also okay for elaborated-type-specifiers, which is | ||||||
15230 | // technically forbidden by the current standard but which is | ||||||
15231 | // okay according to the likely resolution of an open issue; | ||||||
15232 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | ||||||
15233 | if (getLangOpts().CPlusPlus) { | ||||||
15234 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||||
15235 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | ||||||
15236 | TagDecl *Tag = TT->getDecl(); | ||||||
15237 | if (Tag->getDeclName() == Name && | ||||||
15238 | Tag->getDeclContext()->getRedeclContext() | ||||||
15239 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | ||||||
15240 | PrevDecl = Tag; | ||||||
15241 | Previous.clear(); | ||||||
15242 | Previous.addDecl(Tag); | ||||||
15243 | Previous.resolveKind(); | ||||||
15244 | } | ||||||
15245 | } | ||||||
15246 | } | ||||||
15247 | } | ||||||
15248 | |||||||
15249 | // If this is a redeclaration of a using shadow declaration, it must | ||||||
15250 | // declare a tag in the same context. In MSVC mode, we allow a | ||||||
15251 | // redefinition if either context is within the other. | ||||||
15252 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | ||||||
15253 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | ||||||
15254 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | ||||||
15255 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | ||||||
15256 | !(OldTag && isAcceptableTagRedeclContext( | ||||||
15257 | *this, OldTag->getDeclContext(), SearchDC))) { | ||||||
15258 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | ||||||
15259 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||||
15260 | diag::note_using_decl_target); | ||||||
15261 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) | ||||||
15262 | << 0; | ||||||
15263 | // Recover by ignoring the old declaration. | ||||||
15264 | Previous.clear(); | ||||||
15265 | goto CreateNewDecl; | ||||||
15266 | } | ||||||
15267 | } | ||||||
15268 | |||||||
15269 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | ||||||
15270 | // If this is a use of a previous tag, or if the tag is already declared | ||||||
15271 | // in the same scope (so that the definition/declaration completes or | ||||||
15272 | // rementions the tag), reuse the decl. | ||||||
15273 | if (TUK == TUK_Reference || TUK == TUK_Friend || | ||||||
15274 | isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||||
15275 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||||
15276 | // Make sure that this wasn't declared as an enum and now used as a | ||||||
15277 | // struct or something similar. | ||||||
15278 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | ||||||
15279 | TUK == TUK_Definition, KWLoc, | ||||||
15280 | Name)) { | ||||||
15281 | bool SafeToContinue | ||||||
15282 | = (PrevTagDecl->getTagKind() != TTK_Enum && | ||||||
15283 | Kind != TTK_Enum); | ||||||
15284 | if (SafeToContinue) | ||||||
15285 | Diag(KWLoc, diag::err_use_with_wrong_tag) | ||||||
15286 | << Name | ||||||
15287 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | ||||||
15288 | PrevTagDecl->getKindName()); | ||||||
15289 | else | ||||||
15290 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | ||||||
15291 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | ||||||
15292 | |||||||
15293 | if (SafeToContinue) | ||||||
15294 | Kind = PrevTagDecl->getTagKind(); | ||||||
15295 | else { | ||||||
15296 | // Recover by making this an anonymous redefinition. | ||||||
15297 | Name = nullptr; | ||||||
15298 | Previous.clear(); | ||||||
15299 | Invalid = true; | ||||||
15300 | } | ||||||
15301 | } | ||||||
15302 | |||||||
15303 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | ||||||
15304 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | ||||||
15305 | |||||||
15306 | // If this is an elaborated-type-specifier for a scoped enumeration, | ||||||
15307 | // the 'class' keyword is not necessary and not permitted. | ||||||
15308 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15309 | if (ScopedEnum) | ||||||
15310 | Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) | ||||||
15311 | << PrevEnum->isScoped() | ||||||
15312 | << FixItHint::CreateRemoval(ScopedEnumKWLoc); | ||||||
15313 | return PrevTagDecl; | ||||||
15314 | } | ||||||
15315 | |||||||
15316 | QualType EnumUnderlyingTy; | ||||||
15317 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||||
15318 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | ||||||
15319 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | ||||||
15320 | EnumUnderlyingTy = QualType(T, 0); | ||||||
15321 | |||||||
15322 | // All conflicts with previous declarations are recovered by | ||||||
15323 | // returning the previous declaration, unless this is a definition, | ||||||
15324 | // in which case we want the caller to bail out. | ||||||
15325 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | ||||||
15326 | ScopedEnum, EnumUnderlyingTy, | ||||||
15327 | IsFixed, PrevEnum)) | ||||||
15328 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | ||||||
15329 | } | ||||||
15330 | |||||||
15331 | // C++11 [class.mem]p1: | ||||||
15332 | // A member shall not be declared twice in the member-specification, | ||||||
15333 | // except that a nested class or member class template can be declared | ||||||
15334 | // and then later defined. | ||||||
15335 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | ||||||
15336 | S->isDeclScope(PrevDecl)) { | ||||||
15337 | Diag(NameLoc, diag::ext_member_redeclared); | ||||||
15338 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | ||||||
15339 | } | ||||||
15340 | |||||||
15341 | if (!Invalid) { | ||||||
15342 | // If this is a use, just return the declaration we found, unless | ||||||
15343 | // we have attributes. | ||||||
15344 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15345 | if (!Attrs.empty()) { | ||||||
15346 | // FIXME: Diagnose these attributes. For now, we create a new | ||||||
15347 | // declaration to hold them. | ||||||
15348 | } else if (TUK == TUK_Reference && | ||||||
15349 | (PrevTagDecl->getFriendObjectKind() == | ||||||
15350 | Decl::FOK_Undeclared || | ||||||
15351 | PrevDecl->getOwningModule() != getCurrentModule()) && | ||||||
15352 | SS.isEmpty()) { | ||||||
15353 | // This declaration is a reference to an existing entity, but | ||||||
15354 | // has different visibility from that entity: it either makes | ||||||
15355 | // a friend visible or it makes a type visible in a new module. | ||||||
15356 | // In either case, create a new declaration. We only do this if | ||||||
15357 | // the declaration would have meant the same thing if no prior | ||||||
15358 | // declaration were found, that is, if it was found in the same | ||||||
15359 | // scope where we would have injected a declaration. | ||||||
15360 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | ||||||
15361 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | ||||||
15362 | return PrevTagDecl; | ||||||
15363 | // This is in the injected scope, create a new declaration in | ||||||
15364 | // that scope. | ||||||
15365 | S = getTagInjectionScope(S, getLangOpts()); | ||||||
15366 | } else { | ||||||
15367 | return PrevTagDecl; | ||||||
15368 | } | ||||||
15369 | } | ||||||
15370 | |||||||
15371 | // Diagnose attempts to redefine a tag. | ||||||
15372 | if (TUK == TUK_Definition) { | ||||||
15373 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | ||||||
15374 | // If we're defining a specialization and the previous definition | ||||||
15375 | // is from an implicit instantiation, don't emit an error | ||||||
15376 | // here; we'll catch this in the general case below. | ||||||
15377 | bool IsExplicitSpecializationAfterInstantiation = false; | ||||||
15378 | if (isMemberSpecialization) { | ||||||
15379 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | ||||||
15380 | IsExplicitSpecializationAfterInstantiation = | ||||||
15381 | RD->getTemplateSpecializationKind() != | ||||||
15382 | TSK_ExplicitSpecialization; | ||||||
15383 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | ||||||
15384 | IsExplicitSpecializationAfterInstantiation = | ||||||
15385 | ED->getTemplateSpecializationKind() != | ||||||
15386 | TSK_ExplicitSpecialization; | ||||||
15387 | } | ||||||
15388 | |||||||
15389 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | ||||||
15390 | // not keep more that one definition around (merge them). However, | ||||||
15391 | // ensure the decl passes the structural compatibility check in | ||||||
15392 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | ||||||
15393 | NamedDecl *Hidden = nullptr; | ||||||
15394 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | ||||||
15395 | // There is a definition of this tag, but it is not visible. We | ||||||
15396 | // explicitly make use of C++'s one definition rule here, and | ||||||
15397 | // assume that this definition is identical to the hidden one | ||||||
15398 | // we already have. Make the existing definition visible and | ||||||
15399 | // use it in place of this one. | ||||||
15400 | if (!getLangOpts().CPlusPlus) { | ||||||
15401 | // Postpone making the old definition visible until after we | ||||||
15402 | // complete parsing the new one and do the structural | ||||||
15403 | // comparison. | ||||||
15404 | SkipBody->CheckSameAsPrevious = true; | ||||||
15405 | SkipBody->New = createTagFromNewDecl(); | ||||||
15406 | SkipBody->Previous = Def; | ||||||
15407 | return Def; | ||||||
15408 | } else { | ||||||
15409 | SkipBody->ShouldSkip = true; | ||||||
15410 | SkipBody->Previous = Def; | ||||||
15411 | makeMergedDefinitionVisible(Hidden); | ||||||
15412 | // Carry on and handle it like a normal definition. We'll | ||||||
15413 | // skip starting the definitiion later. | ||||||
15414 | } | ||||||
15415 | } else if (!IsExplicitSpecializationAfterInstantiation) { | ||||||
15416 | // A redeclaration in function prototype scope in C isn't | ||||||
15417 | // visible elsewhere, so merely issue a warning. | ||||||
15418 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | ||||||
15419 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | ||||||
15420 | else | ||||||
15421 | Diag(NameLoc, diag::err_redefinition) << Name; | ||||||
15422 | notePreviousDefinition(Def, | ||||||
15423 | NameLoc.isValid() ? NameLoc : KWLoc); | ||||||
15424 | // If this is a redefinition, recover by making this | ||||||
15425 | // struct be anonymous, which will make any later | ||||||
15426 | // references get the previous definition. | ||||||
15427 | Name = nullptr; | ||||||
15428 | Previous.clear(); | ||||||
15429 | Invalid = true; | ||||||
15430 | } | ||||||
15431 | } else { | ||||||
15432 | // If the type is currently being defined, complain | ||||||
15433 | // about a nested redefinition. | ||||||
15434 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | ||||||
15435 | if (TD->isBeingDefined()) { | ||||||
15436 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | ||||||
15437 | Diag(PrevTagDecl->getLocation(), | ||||||
15438 | diag::note_previous_definition); | ||||||
15439 | Name = nullptr; | ||||||
15440 | Previous.clear(); | ||||||
15441 | Invalid = true; | ||||||
15442 | } | ||||||
15443 | } | ||||||
15444 | |||||||
15445 | // Okay, this is definition of a previously declared or referenced | ||||||
15446 | // tag. We're going to create a new Decl for it. | ||||||
15447 | } | ||||||
15448 | |||||||
15449 | // Okay, we're going to make a redeclaration. If this is some kind | ||||||
15450 | // of reference, make sure we build the redeclaration in the same DC | ||||||
15451 | // as the original, and ignore the current access specifier. | ||||||
15452 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||||
15453 | SearchDC = PrevTagDecl->getDeclContext(); | ||||||
15454 | AS = AS_none; | ||||||
15455 | } | ||||||
15456 | } | ||||||
15457 | // If we get here we have (another) forward declaration or we | ||||||
15458 | // have a definition. Just create a new decl. | ||||||
15459 | |||||||
15460 | } else { | ||||||
15461 | // If we get here, this is a definition of a new tag type in a nested | ||||||
15462 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | ||||||
15463 | // new decl/type. We set PrevDecl to NULL so that the entities | ||||||
15464 | // have distinct types. | ||||||
15465 | Previous.clear(); | ||||||
15466 | } | ||||||
15467 | // If we get here, we're going to create a new Decl. If PrevDecl | ||||||
15468 | // is non-NULL, it's a definition of the tag declared by | ||||||
15469 | // PrevDecl. If it's NULL, we have a new definition. | ||||||
15470 | |||||||
15471 | // Otherwise, PrevDecl is not a tag, but was found with tag | ||||||
15472 | // lookup. This is only actually possible in C++, where a few | ||||||
15473 | // things like templates still live in the tag namespace. | ||||||
15474 | } else { | ||||||
15475 | // Use a better diagnostic if an elaborated-type-specifier | ||||||
15476 | // found the wrong kind of type on the first | ||||||
15477 | // (non-redeclaration) lookup. | ||||||
15478 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | ||||||
15479 | !Previous.isForRedeclaration()) { | ||||||
15480 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||||
15481 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | ||||||
15482 | << Kind; | ||||||
15483 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | ||||||
15484 | Invalid = true; | ||||||
15485 | |||||||
15486 | // Otherwise, only diagnose if the declaration is in scope. | ||||||
15487 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||||
15488 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||||
15489 | // do nothing | ||||||
15490 | |||||||
15491 | // Diagnose implicit declarations introduced by elaborated types. | ||||||
15492 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15493 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||||
15494 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | ||||||
15495 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||||
15496 | Invalid = true; | ||||||
15497 | |||||||
15498 | // Otherwise it's a declaration. Call out a particularly common | ||||||
15499 | // case here. | ||||||
15500 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||||
15501 | unsigned Kind = 0; | ||||||
15502 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | ||||||
15503 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | ||||||
15504 | << Name << Kind << TND->getUnderlyingType(); | ||||||
15505 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||||
15506 | Invalid = true; | ||||||
15507 | |||||||
15508 | // Otherwise, diagnose. | ||||||
15509 | } else { | ||||||
15510 | // The tag name clashes with something else in the target scope, | ||||||
15511 | // issue an error and recover by making this tag be anonymous. | ||||||
15512 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | ||||||
15513 | notePreviousDefinition(PrevDecl, NameLoc); | ||||||
15514 | Name = nullptr; | ||||||
15515 | Invalid = true; | ||||||
15516 | } | ||||||
15517 | |||||||
15518 | // The existing declaration isn't relevant to us; we're in a | ||||||
15519 | // new scope, so clear out the previous declaration. | ||||||
15520 | Previous.clear(); | ||||||
15521 | } | ||||||
15522 | } | ||||||
15523 | |||||||
15524 | CreateNewDecl: | ||||||
15525 | |||||||
15526 | TagDecl *PrevDecl = nullptr; | ||||||
15527 | if (Previous.isSingleResult()) | ||||||
15528 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | ||||||
15529 | |||||||
15530 | // If there is an identifier, use the location of the identifier as the | ||||||
15531 | // location of the decl, otherwise use the location of the struct/union | ||||||
15532 | // keyword. | ||||||
15533 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||||
15534 | |||||||
15535 | // Otherwise, create a new declaration. If there is a previous | ||||||
15536 | // declaration of the same entity, the two will be linked via | ||||||
15537 | // PrevDecl. | ||||||
15538 | TagDecl *New; | ||||||
15539 | |||||||
15540 | if (Kind == TTK_Enum) { | ||||||
15541 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||||
15542 | // enum X { A, B, C } D; D should chain to X. | ||||||
15543 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | ||||||
15544 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | ||||||
15545 | ScopedEnumUsesClassTag, IsFixed); | ||||||
15546 | |||||||
15547 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | ||||||
15548 | StdAlignValT = cast<EnumDecl>(New); | ||||||
15549 | |||||||
15550 | // If this is an undefined enum, warn. | ||||||
15551 | if (TUK != TUK_Definition && !Invalid) { | ||||||
15552 | TagDecl *Def; | ||||||
15553 | if (IsFixed && cast<EnumDecl>(New)->isFixed()) { | ||||||
15554 | // C++0x: 7.2p2: opaque-enum-declaration. | ||||||
15555 | // Conflicts are diagnosed above. Do nothing. | ||||||
15556 | } | ||||||
15557 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | ||||||
15558 | Diag(Loc, diag::ext_forward_ref_enum_def) | ||||||
15559 | << New; | ||||||
15560 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
15561 | } else { | ||||||
15562 | unsigned DiagID = diag::ext_forward_ref_enum; | ||||||
15563 | if (getLangOpts().MSVCCompat) | ||||||
15564 | DiagID = diag::ext_ms_forward_ref_enum; | ||||||
15565 | else if (getLangOpts().CPlusPlus) | ||||||
15566 | DiagID = diag::err_forward_ref_enum; | ||||||
15567 | Diag(Loc, DiagID); | ||||||
15568 | } | ||||||
15569 | } | ||||||
15570 | |||||||
15571 | if (EnumUnderlying) { | ||||||
15572 | EnumDecl *ED = cast<EnumDecl>(New); | ||||||
15573 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||||
15574 | ED->setIntegerTypeSourceInfo(TI); | ||||||
15575 | else | ||||||
15576 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | ||||||
15577 | ED->setPromotionType(ED->getIntegerType()); | ||||||
15578 | assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete" ) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15578, __PRETTY_FUNCTION__)); | ||||||
15579 | } | ||||||
15580 | } else { | ||||||
15581 | // struct/union/class | ||||||
15582 | |||||||
15583 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||||
15584 | // struct X { int A; } D; D should chain to X. | ||||||
15585 | if (getLangOpts().CPlusPlus) { | ||||||
15586 | // FIXME: Look for a way to use RecordDecl for simple structs. | ||||||
15587 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
15588 | cast_or_null<CXXRecordDecl>(PrevDecl)); | ||||||
15589 | |||||||
15590 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | ||||||
15591 | StdBadAlloc = cast<CXXRecordDecl>(New); | ||||||
15592 | } else | ||||||
15593 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
15594 | cast_or_null<RecordDecl>(PrevDecl)); | ||||||
15595 | } | ||||||
15596 | |||||||
15597 | // C++11 [dcl.type]p3: | ||||||
15598 | // A type-specifier-seq shall not define a class or enumeration [...]. | ||||||
15599 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | ||||||
15600 | TUK == TUK_Definition) { | ||||||
15601 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | ||||||
15602 | << Context.getTagDeclType(New); | ||||||
15603 | Invalid = true; | ||||||
15604 | } | ||||||
15605 | |||||||
15606 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | ||||||
15607 | DC->getDeclKind() == Decl::Enum) { | ||||||
15608 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | ||||||
15609 | << Context.getTagDeclType(New); | ||||||
15610 | Invalid = true; | ||||||
15611 | } | ||||||
15612 | |||||||
15613 | // Maybe add qualifier info. | ||||||
15614 | if (SS.isNotEmpty()) { | ||||||
15615 | if (SS.isSet()) { | ||||||
15616 | // If this is either a declaration or a definition, check the | ||||||
15617 | // nested-name-specifier against the current context. | ||||||
15618 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | ||||||
15619 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | ||||||
15620 | isMemberSpecialization)) | ||||||
15621 | Invalid = true; | ||||||
15622 | |||||||
15623 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | ||||||
15624 | if (TemplateParameterLists.size() > 0) { | ||||||
15625 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | ||||||
15626 | } | ||||||
15627 | } | ||||||
15628 | else | ||||||
15629 | Invalid = true; | ||||||
15630 | } | ||||||
15631 | |||||||
15632 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||||
15633 | // Add alignment attributes if necessary; these attributes are checked when | ||||||
15634 | // the ASTContext lays out the structure. | ||||||
15635 | // | ||||||
15636 | // It is important for implementing the correct semantics that this | ||||||
15637 | // happen here (in ActOnTag). The #pragma pack stack is | ||||||
15638 | // maintained as a result of parser callbacks which can occur at | ||||||
15639 | // many points during the parsing of a struct declaration (because | ||||||
15640 | // the #pragma tokens are effectively skipped over during the | ||||||
15641 | // parsing of the struct). | ||||||
15642 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||||
15643 | AddAlignmentAttributesForRecord(RD); | ||||||
15644 | AddMsStructLayoutForRecord(RD); | ||||||
15645 | } | ||||||
15646 | } | ||||||
15647 | |||||||
15648 | if (ModulePrivateLoc.isValid()) { | ||||||
15649 | if (isMemberSpecialization) | ||||||
15650 | Diag(New->getLocation(), diag::err_module_private_specialization) | ||||||
15651 | << 2 | ||||||
15652 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||||
15653 | // __module_private__ does not apply to local classes. However, we only | ||||||
15654 | // diagnose this as an error when the declaration specifiers are | ||||||
15655 | // freestanding. Here, we just ignore the __module_private__. | ||||||
15656 | else if (!SearchDC->isFunctionOrMethod()) | ||||||
15657 | New->setModulePrivate(); | ||||||
15658 | } | ||||||
15659 | |||||||
15660 | // If this is a specialization of a member class (of a class template), | ||||||
15661 | // check the specialization. | ||||||
15662 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | ||||||
15663 | Invalid = true; | ||||||
15664 | |||||||
15665 | // If we're declaring or defining a tag in function prototype scope in C, | ||||||
15666 | // note that this type can only be used within the function and add it to | ||||||
15667 | // the list of decls to inject into the function definition scope. | ||||||
15668 | if ((Name || Kind == TTK_Enum) && | ||||||
15669 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | ||||||
15670 | if (getLangOpts().CPlusPlus) { | ||||||
15671 | // C++ [dcl.fct]p6: | ||||||
15672 | // Types shall not be defined in return or parameter types. | ||||||
15673 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | ||||||
15674 | Diag(Loc, diag::err_type_defined_in_param_type) | ||||||
15675 | << Name; | ||||||
15676 | Invalid = true; | ||||||
15677 | } | ||||||
15678 | } else if (!PrevDecl) { | ||||||
15679 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | ||||||
15680 | } | ||||||
15681 | } | ||||||
15682 | |||||||
15683 | if (Invalid) | ||||||
15684 | New->setInvalidDecl(); | ||||||
15685 | |||||||
15686 | // Set the lexical context. If the tag has a C++ scope specifier, the | ||||||
15687 | // lexical context will be different from the semantic context. | ||||||
15688 | New->setLexicalDeclContext(CurContext); | ||||||
15689 | |||||||
15690 | // Mark this as a friend decl if applicable. | ||||||
15691 | // In Microsoft mode, a friend declaration also acts as a forward | ||||||
15692 | // declaration so we always pass true to setObjectOfFriendDecl to make | ||||||
15693 | // the tag name visible. | ||||||
15694 | if (TUK == TUK_Friend) | ||||||
15695 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | ||||||
15696 | |||||||
15697 | // Set the access specifier. | ||||||
15698 | if (!Invalid && SearchDC->isRecord()) | ||||||
15699 | SetMemberAccessSpecifier(New, PrevDecl, AS); | ||||||
15700 | |||||||
15701 | if (PrevDecl) | ||||||
15702 | CheckRedeclarationModuleOwnership(New, PrevDecl); | ||||||
15703 | |||||||
15704 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) | ||||||
15705 | New->startDefinition(); | ||||||
15706 | |||||||
15707 | ProcessDeclAttributeList(S, New, Attrs); | ||||||
15708 | AddPragmaAttributes(S, New); | ||||||
15709 | |||||||
15710 | // If this has an identifier, add it to the scope stack. | ||||||
15711 | if (TUK == TUK_Friend) { | ||||||
15712 | // We might be replacing an existing declaration in the lookup tables; | ||||||
15713 | // if so, borrow its access specifier. | ||||||
15714 | if (PrevDecl) | ||||||
15715 | New->setAccess(PrevDecl->getAccess()); | ||||||
15716 | |||||||
15717 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | ||||||
15718 | DC->makeDeclVisibleInContext(New); | ||||||
15719 | if (Name) // can be null along some error paths | ||||||
15720 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | ||||||
15721 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | ||||||
15722 | } else if (Name) { | ||||||
15723 | S = getNonFieldDeclScope(S); | ||||||
15724 | PushOnScopeChains(New, S, true); | ||||||
15725 | } else { | ||||||
15726 | CurContext->addDecl(New); | ||||||
15727 | } | ||||||
15728 | |||||||
15729 | // If this is the C FILE type, notify the AST context. | ||||||
15730 | if (IdentifierInfo *II = New->getIdentifier()) | ||||||
15731 | if (!New->isInvalidDecl() && | ||||||
15732 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||||
15733 | II->isStr("FILE")) | ||||||
15734 | Context.setFILEDecl(New); | ||||||
15735 | |||||||
15736 | if (PrevDecl) | ||||||
15737 | mergeDeclAttributes(New, PrevDecl); | ||||||
15738 | |||||||
15739 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) | ||||||
15740 | inferGslOwnerPointerAttribute(CXXRD); | ||||||
15741 | |||||||
15742 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||||
15743 | // record. | ||||||
15744 | AddPushedVisibilityAttribute(New); | ||||||
15745 | |||||||
15746 | if (isMemberSpecialization && !New->isInvalidDecl()) | ||||||
15747 | CompleteMemberSpecialization(New, Previous); | ||||||
15748 | |||||||
15749 | OwnedDecl = true; | ||||||
15750 | // In C++, don't return an invalid declaration. We can't recover well from | ||||||
15751 | // the cases where we make the type anonymous. | ||||||
15752 | if (Invalid && getLangOpts().CPlusPlus) { | ||||||
15753 | if (New->isBeingDefined()) | ||||||
15754 | if (auto RD = dyn_cast<RecordDecl>(New)) | ||||||
15755 | RD->completeDefinition(); | ||||||
15756 | return nullptr; | ||||||
15757 | } else if (SkipBody && SkipBody->ShouldSkip) { | ||||||
15758 | return SkipBody->Previous; | ||||||
15759 | } else { | ||||||
15760 | return New; | ||||||
15761 | } | ||||||
15762 | } | ||||||
15763 | |||||||
15764 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | ||||||
15765 | AdjustDeclIfTemplate(TagD); | ||||||
15766 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
15767 | |||||||
15768 | // Enter the tag context. | ||||||
15769 | PushDeclContext(S, Tag); | ||||||
15770 | |||||||
15771 | ActOnDocumentableDecl(TagD); | ||||||
15772 | |||||||
15773 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||||
15774 | // record. | ||||||
15775 | AddPushedVisibilityAttribute(Tag); | ||||||
15776 | } | ||||||
15777 | |||||||
15778 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | ||||||
15779 | SkipBodyInfo &SkipBody) { | ||||||
15780 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | ||||||
15781 | return false; | ||||||
15782 | |||||||
15783 | // Make the previous decl visible. | ||||||
15784 | makeMergedDefinitionVisible(SkipBody.Previous); | ||||||
15785 | return true; | ||||||
15786 | } | ||||||
15787 | |||||||
15788 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | ||||||
15789 | assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15790, __PRETTY_FUNCTION__)) | ||||||
15790 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15790, __PRETTY_FUNCTION__)); | ||||||
15791 | DeclContext *OCD = cast<DeclContext>(IDecl); | ||||||
15792 | assert(getContainingDC(OCD) == CurContext &&((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15793, __PRETTY_FUNCTION__)) | ||||||
15793 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15793, __PRETTY_FUNCTION__)); | ||||||
15794 | CurContext = OCD; | ||||||
15795 | return IDecl; | ||||||
15796 | } | ||||||
15797 | |||||||
15798 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | ||||||
15799 | SourceLocation FinalLoc, | ||||||
15800 | bool IsFinalSpelledSealed, | ||||||
15801 | SourceLocation LBraceLoc) { | ||||||
15802 | AdjustDeclIfTemplate(TagD); | ||||||
15803 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | ||||||
15804 | |||||||
15805 | FieldCollector->StartClass(); | ||||||
15806 | |||||||
15807 | if (!Record->getIdentifier()) | ||||||
15808 | return; | ||||||
15809 | |||||||
15810 | if (FinalLoc.isValid()) | ||||||
15811 | Record->addAttr(FinalAttr::Create( | ||||||
15812 | Context, FinalLoc, AttributeCommonInfo::AS_Keyword, | ||||||
15813 | static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); | ||||||
15814 | |||||||
15815 | // C++ [class]p2: | ||||||
15816 | // [...] The class-name is also inserted into the scope of the | ||||||
15817 | // class itself; this is known as the injected-class-name. For | ||||||
15818 | // purposes of access checking, the injected-class-name is treated | ||||||
15819 | // as if it were a public member name. | ||||||
15820 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( | ||||||
15821 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), | ||||||
15822 | Record->getLocation(), Record->getIdentifier(), | ||||||
15823 | /*PrevDecl=*/nullptr, | ||||||
15824 | /*DelayTypeCreation=*/true); | ||||||
15825 | Context.getTypeDeclType(InjectedClassName, Record); | ||||||
15826 | InjectedClassName->setImplicit(); | ||||||
15827 | InjectedClassName->setAccess(AS_public); | ||||||
15828 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | ||||||
15829 | InjectedClassName->setDescribedClassTemplate(Template); | ||||||
15830 | PushOnScopeChains(InjectedClassName, S); | ||||||
15831 | assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15832, __PRETTY_FUNCTION__)) | ||||||
15832 | "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15832, __PRETTY_FUNCTION__)); | ||||||
15833 | } | ||||||
15834 | |||||||
15835 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | ||||||
15836 | SourceRange BraceRange) { | ||||||
15837 | AdjustDeclIfTemplate(TagD); | ||||||
15838 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
15839 | Tag->setBraceRange(BraceRange); | ||||||
15840 | |||||||
15841 | // Make sure we "complete" the definition even it is invalid. | ||||||
15842 | if (Tag->isBeingDefined()) { | ||||||
15843 | assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it" ) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15843, __PRETTY_FUNCTION__)); | ||||||
15844 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||||
15845 | RD->completeDefinition(); | ||||||
15846 | } | ||||||
15847 | |||||||
15848 | if (isa<CXXRecordDecl>(Tag)) { | ||||||
15849 | FieldCollector->FinishClass(); | ||||||
15850 | } | ||||||
15851 | |||||||
15852 | // Exit this scope of this tag's definition. | ||||||
15853 | PopDeclContext(); | ||||||
15854 | |||||||
15855 | if (getCurLexicalContext()->isObjCContainer() && | ||||||
15856 | Tag->getDeclContext()->isFileContext()) | ||||||
15857 | Tag->setTopLevelDeclInObjCContainer(); | ||||||
15858 | |||||||
15859 | // Notify the consumer that we've defined a tag. | ||||||
15860 | if (!Tag->isInvalidDecl()) | ||||||
15861 | Consumer.HandleTagDeclDefinition(Tag); | ||||||
15862 | } | ||||||
15863 | |||||||
15864 | void Sema::ActOnObjCContainerFinishDefinition() { | ||||||
15865 | // Exit this scope of this interface definition. | ||||||
15866 | PopDeclContext(); | ||||||
15867 | } | ||||||
15868 | |||||||
15869 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | ||||||
15870 | assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts" ) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 15870, __PRETTY_FUNCTION__)); | ||||||
15871 | OriginalLexicalContext = DC; | ||||||
15872 | ActOnObjCContainerFinishDefinition(); | ||||||
15873 | } | ||||||
15874 | |||||||
15875 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | ||||||
15876 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | ||||||
15877 | OriginalLexicalContext = nullptr; | ||||||
15878 | } | ||||||
15879 | |||||||
15880 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | ||||||
15881 | AdjustDeclIfTemplate(TagD); | ||||||
15882 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
15883 | Tag->setInvalidDecl(); | ||||||
15884 | |||||||
15885 | // Make sure we "complete" the definition even it is invalid. | ||||||
15886 | if (Tag->isBeingDefined()) { | ||||||
15887 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||||
15888 | RD->completeDefinition(); | ||||||
15889 | } | ||||||
15890 | |||||||
15891 | // We're undoing ActOnTagStartDefinition here, not | ||||||
15892 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | ||||||
15893 | // the FieldCollector. | ||||||
15894 | |||||||
15895 | PopDeclContext(); | ||||||
15896 | } | ||||||
15897 | |||||||
15898 | // Note that FieldName may be null for anonymous bitfields. | ||||||
15899 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | ||||||
15900 | IdentifierInfo *FieldName, | ||||||
15901 | QualType FieldTy, bool IsMsStruct, | ||||||
15902 | Expr *BitWidth, bool *ZeroWidth) { | ||||||
15903 | // Default to true; that shouldn't confuse checks for emptiness | ||||||
15904 | if (ZeroWidth) | ||||||
15905 | *ZeroWidth = true; | ||||||
15906 | |||||||
15907 | // C99 6.7.2.1p4 - verify the field type. | ||||||
15908 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | ||||||
15909 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | ||||||
15910 | // Handle incomplete types with specific error. | ||||||
15911 | if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) | ||||||
15912 | return ExprError(); | ||||||
15913 | if (FieldName) | ||||||
15914 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | ||||||
15915 | << FieldName << FieldTy << BitWidth->getSourceRange(); | ||||||
15916 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | ||||||
15917 | << FieldTy << BitWidth->getSourceRange(); | ||||||
15918 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | ||||||
15919 | UPPC_BitFieldWidth)) | ||||||
15920 | return ExprError(); | ||||||
15921 | |||||||
15922 | // If the bit-width is type- or value-dependent, don't try to check | ||||||
15923 | // it now. | ||||||
15924 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | ||||||
15925 | return BitWidth; | ||||||
15926 | |||||||
15927 | llvm::APSInt Value; | ||||||
15928 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); | ||||||
15929 | if (ICE.isInvalid()) | ||||||
15930 | return ICE; | ||||||
15931 | BitWidth = ICE.get(); | ||||||
15932 | |||||||
15933 | if (Value != 0 && ZeroWidth) | ||||||
15934 | *ZeroWidth = false; | ||||||
15935 | |||||||
15936 | // Zero-width bitfield is ok for anonymous field. | ||||||
15937 | if (Value == 0 && FieldName) | ||||||
15938 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | ||||||
15939 | |||||||
15940 | if (Value.isSigned() && Value.isNegative()) { | ||||||
15941 | if (FieldName) | ||||||
15942 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | ||||||
15943 | << FieldName << Value.toString(10); | ||||||
15944 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | ||||||
15945 | << Value.toString(10); | ||||||
15946 | } | ||||||
15947 | |||||||
15948 | if (!FieldTy->isDependentType()) { | ||||||
15949 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | ||||||
15950 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | ||||||
15951 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | ||||||
15952 | |||||||
15953 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | ||||||
15954 | // ABI. | ||||||
15955 | bool CStdConstraintViolation = | ||||||
15956 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | ||||||
15957 | bool MSBitfieldViolation = | ||||||
15958 | Value.ugt(TypeStorageSize) && | ||||||
15959 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | ||||||
15960 | if (CStdConstraintViolation || MSBitfieldViolation) { | ||||||
15961 | unsigned DiagWidth = | ||||||
15962 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | ||||||
15963 | if (FieldName) | ||||||
15964 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | ||||||
15965 | << FieldName << (unsigned)Value.getZExtValue() | ||||||
15966 | << !CStdConstraintViolation << DiagWidth; | ||||||
15967 | |||||||
15968 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) | ||||||
15969 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation | ||||||
15970 | << DiagWidth; | ||||||
15971 | } | ||||||
15972 | |||||||
15973 | // Warn on types where the user might conceivably expect to get all | ||||||
15974 | // specified bits as value bits: that's all integral types other than | ||||||
15975 | // 'bool'. | ||||||
15976 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { | ||||||
15977 | if (FieldName) | ||||||
15978 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | ||||||
15979 | << FieldName << (unsigned)Value.getZExtValue() | ||||||
15980 | << (unsigned)TypeWidth; | ||||||
15981 | else | ||||||
15982 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) | ||||||
15983 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; | ||||||
15984 | } | ||||||
15985 | } | ||||||
15986 | |||||||
15987 | return BitWidth; | ||||||
15988 | } | ||||||
15989 | |||||||
15990 | /// ActOnField - Each field of a C struct/union is passed into this in order | ||||||
15991 | /// to create a FieldDecl object for it. | ||||||
15992 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | ||||||
15993 | Declarator &D, Expr *BitfieldWidth) { | ||||||
15994 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | ||||||
15995 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | ||||||
15996 | /*InitStyle=*/ICIS_NoInit, AS_public); | ||||||
15997 | return Res; | ||||||
15998 | } | ||||||
15999 | |||||||
16000 | /// HandleField - Analyze a field of a C struct or a C++ data member. | ||||||
16001 | /// | ||||||
16002 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | ||||||
16003 | SourceLocation DeclStart, | ||||||
16004 | Declarator &D, Expr *BitWidth, | ||||||
16005 | InClassInitStyle InitStyle, | ||||||
16006 | AccessSpecifier AS) { | ||||||
16007 | if (D.isDecompositionDeclarator()) { | ||||||
16008 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | ||||||
16009 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | ||||||
16010 | << Decomp.getSourceRange(); | ||||||
16011 | return nullptr; | ||||||
16012 | } | ||||||
16013 | |||||||
16014 | IdentifierInfo *II = D.getIdentifier(); | ||||||
16015 | SourceLocation Loc = DeclStart; | ||||||
16016 | if (II) Loc = D.getIdentifierLoc(); | ||||||
16017 | |||||||
16018 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
16019 | QualType T = TInfo->getType(); | ||||||
16020 | if (getLangOpts().CPlusPlus) { | ||||||
16021 | CheckExtraCXXDefaultArguments(D); | ||||||
16022 | |||||||
16023 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||||
16024 | UPPC_DataMemberType)) { | ||||||
16025 | D.setInvalidType(); | ||||||
16026 | T = Context.IntTy; | ||||||
16027 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||||
16028 | } | ||||||
16029 | } | ||||||
16030 | |||||||
16031 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
16032 | |||||||
16033 | if (D.getDeclSpec().isInlineSpecified()) | ||||||
16034 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
16035 | << getLangOpts().CPlusPlus17; | ||||||
16036 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||||
16037 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
16038 | diag::err_invalid_thread) | ||||||
16039 | << DeclSpec::getSpecifierName(TSCS); | ||||||
16040 | |||||||
16041 | // Check to see if this name was declared as a member previously | ||||||
16042 | NamedDecl *PrevDecl = nullptr; | ||||||
16043 | LookupResult Previous(*this, II, Loc, LookupMemberName, | ||||||
16044 | ForVisibleRedeclaration); | ||||||
16045 | LookupName(Previous, S); | ||||||
16046 | switch (Previous.getResultKind()) { | ||||||
16047 | case LookupResult::Found: | ||||||
16048 | case LookupResult::FoundUnresolvedValue: | ||||||
16049 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | ||||||
16050 | break; | ||||||
16051 | |||||||
16052 | case LookupResult::FoundOverloaded: | ||||||
16053 | PrevDecl = Previous.getRepresentativeDecl(); | ||||||
16054 | break; | ||||||
16055 | |||||||
16056 | case LookupResult::NotFound: | ||||||
16057 | case LookupResult::NotFoundInCurrentInstantiation: | ||||||
16058 | case LookupResult::Ambiguous: | ||||||
16059 | break; | ||||||
16060 | } | ||||||
16061 | Previous.suppressDiagnostics(); | ||||||
16062 | |||||||
16063 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||||
16064 | // Maybe we will complain about the shadowed template parameter. | ||||||
16065 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||||
16066 | // Just pretend that we didn't see the previous declaration. | ||||||
16067 | PrevDecl = nullptr; | ||||||
16068 | } | ||||||
16069 | |||||||
16070 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | ||||||
16071 | PrevDecl = nullptr; | ||||||
16072 | |||||||
16073 | bool Mutable | ||||||
16074 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | ||||||
16075 | SourceLocation TSSL = D.getBeginLoc(); | ||||||
16076 | FieldDecl *NewFD | ||||||
16077 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | ||||||
16078 | TSSL, AS, PrevDecl, &D); | ||||||
16079 | |||||||
16080 | if (NewFD->isInvalidDecl()) | ||||||
16081 | Record->setInvalidDecl(); | ||||||
16082 | |||||||
16083 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
16084 | NewFD->setModulePrivate(); | ||||||
16085 | |||||||
16086 | if (NewFD->isInvalidDecl() && PrevDecl) { | ||||||
16087 | // Don't introduce NewFD into scope; there's already something | ||||||
16088 | // with the same name in the same scope. | ||||||
16089 | } else if (II) { | ||||||
16090 | PushOnScopeChains(NewFD, S); | ||||||
16091 | } else | ||||||
16092 | Record->addDecl(NewFD); | ||||||
16093 | |||||||
16094 | return NewFD; | ||||||
16095 | } | ||||||
16096 | |||||||
16097 | /// Build a new FieldDecl and check its well-formedness. | ||||||
16098 | /// | ||||||
16099 | /// This routine builds a new FieldDecl given the fields name, type, | ||||||
16100 | /// record, etc. \p PrevDecl should refer to any previous declaration | ||||||
16101 | /// with the same name and in the same scope as the field to be | ||||||
16102 | /// created. | ||||||
16103 | /// | ||||||
16104 | /// \returns a new FieldDecl. | ||||||
16105 | /// | ||||||
16106 | /// \todo The Declarator argument is a hack. It will be removed once | ||||||
16107 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | ||||||
16108 | TypeSourceInfo *TInfo, | ||||||
16109 | RecordDecl *Record, SourceLocation Loc, | ||||||
16110 | bool Mutable, Expr *BitWidth, | ||||||
16111 | InClassInitStyle InitStyle, | ||||||
16112 | SourceLocation TSSL, | ||||||
16113 | AccessSpecifier AS, NamedDecl *PrevDecl, | ||||||
16114 | Declarator *D) { | ||||||
16115 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||
16116 | bool InvalidDecl = false; | ||||||
16117 | if (D) InvalidDecl = D->isInvalidType(); | ||||||
16118 | |||||||
16119 | // If we receive a broken type, recover by assuming 'int' and | ||||||
16120 | // marking this declaration as invalid. | ||||||
16121 | if (T.isNull()) { | ||||||
16122 | InvalidDecl = true; | ||||||
16123 | T = Context.IntTy; | ||||||
16124 | } | ||||||
16125 | |||||||
16126 | QualType EltTy = Context.getBaseElementType(T); | ||||||
16127 | if (!EltTy->isDependentType()) { | ||||||
16128 | if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { | ||||||
16129 | // Fields of incomplete type force their record to be invalid. | ||||||
16130 | Record->setInvalidDecl(); | ||||||
16131 | InvalidDecl = true; | ||||||
16132 | } else { | ||||||
16133 | NamedDecl *Def; | ||||||
16134 | EltTy->isIncompleteType(&Def); | ||||||
16135 | if (Def && Def->isInvalidDecl()) { | ||||||
16136 | Record->setInvalidDecl(); | ||||||
16137 | InvalidDecl = true; | ||||||
16138 | } | ||||||
16139 | } | ||||||
16140 | } | ||||||
16141 | |||||||
16142 | // TR 18037 does not allow fields to be declared with address space | ||||||
16143 | if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || | ||||||
16144 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | ||||||
16145 | Diag(Loc, diag::err_field_with_address_space); | ||||||
16146 | Record->setInvalidDecl(); | ||||||
16147 | InvalidDecl = true; | ||||||
16148 | } | ||||||
16149 | |||||||
16150 | if (LangOpts.OpenCL) { | ||||||
16151 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | ||||||
16152 | // used as structure or union field: image, sampler, event or block types. | ||||||
16153 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || | ||||||
16154 | T->isBlockPointerType()) { | ||||||
16155 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | ||||||
16156 | Record->setInvalidDecl(); | ||||||
16157 | InvalidDecl = true; | ||||||
16158 | } | ||||||
16159 | // OpenCL v1.2 s6.9.c: bitfields are not supported. | ||||||
16160 | if (BitWidth) { | ||||||
16161 | Diag(Loc, diag::err_opencl_bitfields); | ||||||
16162 | InvalidDecl = true; | ||||||
16163 | } | ||||||
16164 | } | ||||||
16165 | |||||||
16166 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | ||||||
16167 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | ||||||
16168 | T.hasQualifiers()) { | ||||||
16169 | InvalidDecl = true; | ||||||
16170 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | ||||||
16171 | } | ||||||
16172 | |||||||
16173 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||||
16174 | // than a variably modified type. | ||||||
16175 | if (!InvalidDecl && T->isVariablyModifiedType()) { | ||||||
16176 | bool SizeIsNegative; | ||||||
16177 | llvm::APSInt Oversized; | ||||||
16178 | |||||||
16179 | TypeSourceInfo *FixedTInfo = | ||||||
16180 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||||
16181 | SizeIsNegative, | ||||||
16182 | Oversized); | ||||||
16183 | if (FixedTInfo) { | ||||||
16184 | Diag(Loc, diag::warn_illegal_constant_array_size); | ||||||
16185 | TInfo = FixedTInfo; | ||||||
16186 | T = FixedTInfo->getType(); | ||||||
16187 | } else { | ||||||
16188 | if (SizeIsNegative) | ||||||
16189 | Diag(Loc, diag::err_typecheck_negative_array_size); | ||||||
16190 | else if (Oversized.getBoolValue()) | ||||||
16191 | Diag(Loc, diag::err_array_too_large) | ||||||
16192 | << Oversized.toString(10); | ||||||
16193 | else | ||||||
16194 | Diag(Loc, diag::err_typecheck_field_variable_size); | ||||||
16195 | InvalidDecl = true; | ||||||
16196 | } | ||||||
16197 | } | ||||||
16198 | |||||||
16199 | // Fields can not have abstract class types | ||||||
16200 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | ||||||
16201 | diag::err_abstract_type_in_decl, | ||||||
16202 | AbstractFieldType)) | ||||||
16203 | InvalidDecl = true; | ||||||
16204 | |||||||
16205 | bool ZeroWidth = false; | ||||||
16206 | if (InvalidDecl) | ||||||
16207 | BitWidth = nullptr; | ||||||
16208 | // If this is declared as a bit-field, check the bit-field. | ||||||
16209 | if (BitWidth) { | ||||||
16210 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | ||||||
16211 | &ZeroWidth).get(); | ||||||
16212 | if (!BitWidth) { | ||||||
16213 | InvalidDecl = true; | ||||||
16214 | BitWidth = nullptr; | ||||||
16215 | ZeroWidth = false; | ||||||
16216 | } | ||||||
16217 | } | ||||||
16218 | |||||||
16219 | // Check that 'mutable' is consistent with the type of the declaration. | ||||||
16220 | if (!InvalidDecl && Mutable) { | ||||||
16221 | unsigned DiagID = 0; | ||||||
16222 | if (T->isReferenceType()) | ||||||
16223 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | ||||||
16224 | : diag::err_mutable_reference; | ||||||
16225 | else if (T.isConstQualified()) | ||||||
16226 | DiagID = diag::err_mutable_const; | ||||||
16227 | |||||||
16228 | if (DiagID) { | ||||||
16229 | SourceLocation ErrLoc = Loc; | ||||||
16230 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | ||||||
16231 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | ||||||
16232 | Diag(ErrLoc, DiagID); | ||||||
16233 | if (DiagID != diag::ext_mutable_reference) { | ||||||
16234 | Mutable = false; | ||||||
16235 | InvalidDecl = true; | ||||||
16236 | } | ||||||
16237 | } | ||||||
16238 | } | ||||||
16239 | |||||||
16240 | // C++11 [class.union]p8 (DR1460): | ||||||
16241 | // At most one variant member of a union may have a | ||||||
16242 | // brace-or-equal-initializer. | ||||||
16243 | if (InitStyle != ICIS_NoInit) | ||||||
16244 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | ||||||
16245 | |||||||
16246 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | ||||||
16247 | BitWidth, Mutable, InitStyle); | ||||||
16248 | if (InvalidDecl) | ||||||
16249 | NewFD->setInvalidDecl(); | ||||||
16250 | |||||||
16251 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | ||||||
16252 | Diag(Loc, diag::err_duplicate_member) << II; | ||||||
16253 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
16254 | NewFD->setInvalidDecl(); | ||||||
16255 | } | ||||||
16256 | |||||||
16257 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | ||||||
16258 | if (Record->isUnion()) { | ||||||
16259 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||||
16260 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||||
16261 | if (RDecl->getDefinition()) { | ||||||
16262 | // C++ [class.union]p1: An object of a class with a non-trivial | ||||||
16263 | // constructor, a non-trivial copy constructor, a non-trivial | ||||||
16264 | // destructor, or a non-trivial copy assignment operator | ||||||
16265 | // cannot be a member of a union, nor can an array of such | ||||||
16266 | // objects. | ||||||
16267 | if (CheckNontrivialField(NewFD)) | ||||||
16268 | NewFD->setInvalidDecl(); | ||||||
16269 | } | ||||||
16270 | } | ||||||
16271 | |||||||
16272 | // C++ [class.union]p1: If a union contains a member of reference type, | ||||||
16273 | // the program is ill-formed, except when compiling with MSVC extensions | ||||||
16274 | // enabled. | ||||||
16275 | if (EltTy->isReferenceType()) { | ||||||
16276 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | ||||||
16277 | diag::ext_union_member_of_reference_type : | ||||||
16278 | diag::err_union_member_of_reference_type) | ||||||
16279 | << NewFD->getDeclName() << EltTy; | ||||||
16280 | if (!getLangOpts().MicrosoftExt) | ||||||
16281 | NewFD->setInvalidDecl(); | ||||||
16282 | } | ||||||
16283 | } | ||||||
16284 | } | ||||||
16285 | |||||||
16286 | // FIXME: We need to pass in the attributes given an AST | ||||||
16287 | // representation, not a parser representation. | ||||||
16288 | if (D) { | ||||||
16289 | // FIXME: The current scope is almost... but not entirely... correct here. | ||||||
16290 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | ||||||
16291 | |||||||
16292 | if (NewFD->hasAttrs()) | ||||||
16293 | CheckAlignasUnderalignment(NewFD); | ||||||
16294 | } | ||||||
16295 | |||||||
16296 | // In auto-retain/release, infer strong retension for fields of | ||||||
16297 | // retainable type. | ||||||
16298 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | ||||||
16299 | NewFD->setInvalidDecl(); | ||||||
16300 | |||||||
16301 | if (T.isObjCGCWeak()) | ||||||
16302 | Diag(Loc, diag::warn_attribute_weak_on_field); | ||||||
16303 | |||||||
16304 | NewFD->setAccess(AS); | ||||||
16305 | return NewFD; | ||||||
16306 | } | ||||||
16307 | |||||||
16308 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | ||||||
16309 | assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16309, __PRETTY_FUNCTION__)); | ||||||
16310 | assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16310, __PRETTY_FUNCTION__)); | ||||||
16311 | |||||||
16312 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | ||||||
16313 | return false; | ||||||
16314 | |||||||
16315 | QualType EltTy = Context.getBaseElementType(FD->getType()); | ||||||
16316 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||||
16317 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||||
16318 | if (RDecl->getDefinition()) { | ||||||
16319 | // We check for copy constructors before constructors | ||||||
16320 | // because otherwise we'll never get complaints about | ||||||
16321 | // copy constructors. | ||||||
16322 | |||||||
16323 | CXXSpecialMember member = CXXInvalid; | ||||||
16324 | // We're required to check for any non-trivial constructors. Since the | ||||||
16325 | // implicit default constructor is suppressed if there are any | ||||||
16326 | // user-declared constructors, we just need to check that there is a | ||||||
16327 | // trivial default constructor and a trivial copy constructor. (We don't | ||||||
16328 | // worry about move constructors here, since this is a C++98 check.) | ||||||
16329 | if (RDecl->hasNonTrivialCopyConstructor()) | ||||||
16330 | member = CXXCopyConstructor; | ||||||
16331 | else if (!RDecl->hasTrivialDefaultConstructor()) | ||||||
16332 | member = CXXDefaultConstructor; | ||||||
16333 | else if (RDecl->hasNonTrivialCopyAssignment()) | ||||||
16334 | member = CXXCopyAssignment; | ||||||
16335 | else if (RDecl->hasNonTrivialDestructor()) | ||||||
16336 | member = CXXDestructor; | ||||||
16337 | |||||||
16338 | if (member != CXXInvalid) { | ||||||
16339 | if (!getLangOpts().CPlusPlus11 && | ||||||
16340 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | ||||||
16341 | // Objective-C++ ARC: it is an error to have a non-trivial field of | ||||||
16342 | // a union. However, system headers in Objective-C programs | ||||||
16343 | // occasionally have Objective-C lifetime objects within unions, | ||||||
16344 | // and rather than cause the program to fail, we make those | ||||||
16345 | // members unavailable. | ||||||
16346 | SourceLocation Loc = FD->getLocation(); | ||||||
16347 | if (getSourceManager().isInSystemHeader(Loc)) { | ||||||
16348 | if (!FD->hasAttr<UnavailableAttr>()) | ||||||
16349 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | ||||||
16350 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | ||||||
16351 | return false; | ||||||
16352 | } | ||||||
16353 | } | ||||||
16354 | |||||||
16355 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | ||||||
16356 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | ||||||
16357 | diag::err_illegal_union_or_anon_struct_member) | ||||||
16358 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | ||||||
16359 | DiagnoseNontrivial(RDecl, member); | ||||||
16360 | return !getLangOpts().CPlusPlus11; | ||||||
16361 | } | ||||||
16362 | } | ||||||
16363 | } | ||||||
16364 | |||||||
16365 | return false; | ||||||
16366 | } | ||||||
16367 | |||||||
16368 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | ||||||
16369 | /// AST enum value. | ||||||
16370 | static ObjCIvarDecl::AccessControl | ||||||
16371 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | ||||||
16372 | switch (ivarVisibility) { | ||||||
16373 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16373); | ||||||
16374 | case tok::objc_private: return ObjCIvarDecl::Private; | ||||||
16375 | case tok::objc_public: return ObjCIvarDecl::Public; | ||||||
16376 | case tok::objc_protected: return ObjCIvarDecl::Protected; | ||||||
16377 | case tok::objc_package: return ObjCIvarDecl::Package; | ||||||
16378 | } | ||||||
16379 | } | ||||||
16380 | |||||||
16381 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | ||||||
16382 | /// in order to create an IvarDecl object for it. | ||||||
16383 | Decl *Sema::ActOnIvar(Scope *S, | ||||||
16384 | SourceLocation DeclStart, | ||||||
16385 | Declarator &D, Expr *BitfieldWidth, | ||||||
16386 | tok::ObjCKeywordKind Visibility) { | ||||||
16387 | |||||||
16388 | IdentifierInfo *II = D.getIdentifier(); | ||||||
16389 | Expr *BitWidth = (Expr*)BitfieldWidth; | ||||||
16390 | SourceLocation Loc = DeclStart; | ||||||
16391 | if (II) Loc = D.getIdentifierLoc(); | ||||||
16392 | |||||||
16393 | // FIXME: Unnamed fields can be handled in various different ways, for | ||||||
16394 | // example, unnamed unions inject all members into the struct namespace! | ||||||
16395 | |||||||
16396 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
16397 | QualType T = TInfo->getType(); | ||||||
16398 | |||||||
16399 | if (BitWidth) { | ||||||
16400 | // 6.7.2.1p3, 6.7.2.1p4 | ||||||
16401 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | ||||||
16402 | if (!BitWidth) | ||||||
16403 | D.setInvalidType(); | ||||||
16404 | } else { | ||||||
16405 | // Not a bitfield. | ||||||
16406 | |||||||
16407 | // validate II. | ||||||
16408 | |||||||
16409 | } | ||||||
16410 | if (T->isReferenceType()) { | ||||||
16411 | Diag(Loc, diag::err_ivar_reference_type); | ||||||
16412 | D.setInvalidType(); | ||||||
16413 | } | ||||||
16414 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||||
16415 | // than a variably modified type. | ||||||
16416 | else if (T->isVariablyModifiedType()) { | ||||||
16417 | Diag(Loc, diag::err_typecheck_ivar_variable_size); | ||||||
16418 | D.setInvalidType(); | ||||||
16419 | } | ||||||
16420 | |||||||
16421 | // Get the visibility (access control) for this ivar. | ||||||
16422 | ObjCIvarDecl::AccessControl ac = | ||||||
16423 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | ||||||
16424 | : ObjCIvarDecl::None; | ||||||
16425 | // Must set ivar's DeclContext to its enclosing interface. | ||||||
16426 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | ||||||
16427 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | ||||||
16428 | return nullptr; | ||||||
16429 | ObjCContainerDecl *EnclosingContext; | ||||||
16430 | if (ObjCImplementationDecl *IMPDecl = | ||||||
16431 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||||
16432 | if (LangOpts.ObjCRuntime.isFragile()) { | ||||||
16433 | // Case of ivar declared in an implementation. Context is that of its class. | ||||||
16434 | EnclosingContext = IMPDecl->getClassInterface(); | ||||||
16435 | assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!" ) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16435, __PRETTY_FUNCTION__)); | ||||||
16436 | } | ||||||
16437 | else | ||||||
16438 | EnclosingContext = EnclosingDecl; | ||||||
16439 | } else { | ||||||
16440 | if (ObjCCategoryDecl *CDecl = | ||||||
16441 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||||
16442 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | ||||||
16443 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | ||||||
16444 | return nullptr; | ||||||
16445 | } | ||||||
16446 | } | ||||||
16447 | EnclosingContext = EnclosingDecl; | ||||||
16448 | } | ||||||
16449 | |||||||
16450 | // Construct the decl. | ||||||
16451 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | ||||||
16452 | DeclStart, Loc, II, T, | ||||||
16453 | TInfo, ac, (Expr *)BitfieldWidth); | ||||||
16454 | |||||||
16455 | if (II) { | ||||||
16456 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | ||||||
16457 | ForVisibleRedeclaration); | ||||||
16458 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | ||||||
16459 | && !isa<TagDecl>(PrevDecl)) { | ||||||
16460 | Diag(Loc, diag::err_duplicate_member) << II; | ||||||
16461 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
16462 | NewID->setInvalidDecl(); | ||||||
16463 | } | ||||||
16464 | } | ||||||
16465 | |||||||
16466 | // Process attributes attached to the ivar. | ||||||
16467 | ProcessDeclAttributes(S, NewID, D); | ||||||
16468 | |||||||
16469 | if (D.isInvalidType()) | ||||||
16470 | NewID->setInvalidDecl(); | ||||||
16471 | |||||||
16472 | // In ARC, infer 'retaining' for ivars of retainable type. | ||||||
16473 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | ||||||
16474 | NewID->setInvalidDecl(); | ||||||
16475 | |||||||
16476 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
16477 | NewID->setModulePrivate(); | ||||||
16478 | |||||||
16479 | if (II) { | ||||||
16480 | // FIXME: When interfaces are DeclContexts, we'll need to add | ||||||
16481 | // these to the interface. | ||||||
16482 | S->AddDecl(NewID); | ||||||
16483 | IdResolver.AddDecl(NewID); | ||||||
16484 | } | ||||||
16485 | |||||||
16486 | if (LangOpts.ObjCRuntime.isNonFragile() && | ||||||
16487 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | ||||||
16488 | Diag(Loc, diag::warn_ivars_in_interface); | ||||||
16489 | |||||||
16490 | return NewID; | ||||||
16491 | } | ||||||
16492 | |||||||
16493 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | ||||||
16494 | /// class and class extensions. For every class \@interface and class | ||||||
16495 | /// extension \@interface, if the last ivar is a bitfield of any type, | ||||||
16496 | /// then add an implicit `char :0` ivar to the end of that interface. | ||||||
16497 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | ||||||
16498 | SmallVectorImpl<Decl *> &AllIvarDecls) { | ||||||
16499 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | ||||||
16500 | return; | ||||||
16501 | |||||||
16502 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | ||||||
16503 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | ||||||
16504 | |||||||
16505 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | ||||||
16506 | return; | ||||||
16507 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | ||||||
16508 | if (!ID) { | ||||||
16509 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | ||||||
16510 | if (!CD->IsClassExtension()) | ||||||
16511 | return; | ||||||
16512 | } | ||||||
16513 | // No need to add this to end of @implementation. | ||||||
16514 | else | ||||||
16515 | return; | ||||||
16516 | } | ||||||
16517 | // All conditions are met. Add a new bitfield to the tail end of ivars. | ||||||
16518 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | ||||||
16519 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | ||||||
16520 | |||||||
16521 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | ||||||
16522 | DeclLoc, DeclLoc, nullptr, | ||||||
16523 | Context.CharTy, | ||||||
16524 | Context.getTrivialTypeSourceInfo(Context.CharTy, | ||||||
16525 | DeclLoc), | ||||||
16526 | ObjCIvarDecl::Private, BW, | ||||||
16527 | true); | ||||||
16528 | AllIvarDecls.push_back(Ivar); | ||||||
16529 | } | ||||||
16530 | |||||||
16531 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | ||||||
16532 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | ||||||
16533 | SourceLocation RBrac, | ||||||
16534 | const ParsedAttributesView &Attrs) { | ||||||
16535 | assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl" ) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16535, __PRETTY_FUNCTION__)); | ||||||
16536 | |||||||
16537 | // If this is an Objective-C @implementation or category and we have | ||||||
16538 | // new fields here we should reset the layout of the interface since | ||||||
16539 | // it will now change. | ||||||
16540 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | ||||||
16541 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | ||||||
16542 | switch (DC->getKind()) { | ||||||
16543 | default: break; | ||||||
16544 | case Decl::ObjCCategory: | ||||||
16545 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | ||||||
16546 | break; | ||||||
16547 | case Decl::ObjCImplementation: | ||||||
16548 | Context. | ||||||
16549 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | ||||||
16550 | break; | ||||||
16551 | } | ||||||
16552 | } | ||||||
16553 | |||||||
16554 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | ||||||
16555 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); | ||||||
16556 | |||||||
16557 | // Start counting up the number of named members; make sure to include | ||||||
16558 | // members of anonymous structs and unions in the total. | ||||||
16559 | unsigned NumNamedMembers = 0; | ||||||
16560 | if (Record) { | ||||||
16561 | for (const auto *I : Record->decls()) { | ||||||
16562 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||||
16563 | if (IFD->getDeclName()) | ||||||
16564 | ++NumNamedMembers; | ||||||
16565 | } | ||||||
16566 | } | ||||||
16567 | |||||||
16568 | // Verify that all the fields are okay. | ||||||
16569 | SmallVector<FieldDecl*, 32> RecFields; | ||||||
16570 | |||||||
16571 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | ||||||
16572 | i != end; ++i) { | ||||||
16573 | FieldDecl *FD = cast<FieldDecl>(*i); | ||||||
16574 | |||||||
16575 | // Get the type for the field. | ||||||
16576 | const Type *FDTy = FD->getType().getTypePtr(); | ||||||
16577 | |||||||
16578 | if (!FD->isAnonymousStructOrUnion()) { | ||||||
16579 | // Remember all fields written by the user. | ||||||
16580 | RecFields.push_back(FD); | ||||||
16581 | } | ||||||
16582 | |||||||
16583 | // If the field is already invalid for some reason, don't emit more | ||||||
16584 | // diagnostics about it. | ||||||
16585 | if (FD->isInvalidDecl()) { | ||||||
16586 | EnclosingDecl->setInvalidDecl(); | ||||||
16587 | continue; | ||||||
16588 | } | ||||||
16589 | |||||||
16590 | // C99 6.7.2.1p2: | ||||||
16591 | // A structure or union shall not contain a member with | ||||||
16592 | // incomplete or function type (hence, a structure shall not | ||||||
16593 | // contain an instance of itself, but may contain a pointer to | ||||||
16594 | // an instance of itself), except that the last member of a | ||||||
16595 | // structure with more than one named member may have incomplete | ||||||
16596 | // array type; such a structure (and any union containing, | ||||||
16597 | // possibly recursively, a member that is such a structure) | ||||||
16598 | // shall not be a member of a structure or an element of an | ||||||
16599 | // array. | ||||||
16600 | bool IsLastField = (i + 1 == Fields.end()); | ||||||
16601 | if (FDTy->isFunctionType()) { | ||||||
16602 | // Field declared as a function. | ||||||
16603 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | ||||||
16604 | << FD->getDeclName(); | ||||||
16605 | FD->setInvalidDecl(); | ||||||
16606 | EnclosingDecl->setInvalidDecl(); | ||||||
16607 | continue; | ||||||
16608 | } else if (FDTy->isIncompleteArrayType() && | ||||||
16609 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | ||||||
16610 | if (Record) { | ||||||
16611 | // Flexible array member. | ||||||
16612 | // Microsoft and g++ is more permissive regarding flexible array. | ||||||
16613 | // It will accept flexible array in union and also | ||||||
16614 | // as the sole element of a struct/class. | ||||||
16615 | unsigned DiagID = 0; | ||||||
16616 | if (!Record->isUnion() && !IsLastField) { | ||||||
16617 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | ||||||
16618 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | ||||||
16619 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | ||||||
16620 | FD->setInvalidDecl(); | ||||||
16621 | EnclosingDecl->setInvalidDecl(); | ||||||
16622 | continue; | ||||||
16623 | } else if (Record->isUnion()) | ||||||
16624 | DiagID = getLangOpts().MicrosoftExt | ||||||
16625 | ? diag::ext_flexible_array_union_ms | ||||||
16626 | : getLangOpts().CPlusPlus | ||||||
16627 | ? diag::ext_flexible_array_union_gnu | ||||||
16628 | : diag::err_flexible_array_union; | ||||||
16629 | else if (NumNamedMembers < 1) | ||||||
16630 | DiagID = getLangOpts().MicrosoftExt | ||||||
16631 | ? diag::ext_flexible_array_empty_aggregate_ms | ||||||
16632 | : getLangOpts().CPlusPlus | ||||||
16633 | ? diag::ext_flexible_array_empty_aggregate_gnu | ||||||
16634 | : diag::err_flexible_array_empty_aggregate; | ||||||
16635 | |||||||
16636 | if (DiagID) | ||||||
16637 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | ||||||
16638 | << Record->getTagKind(); | ||||||
16639 | // While the layout of types that contain virtual bases is not specified | ||||||
16640 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | ||||||
16641 | // virtual bases after the derived members. This would make a flexible | ||||||
16642 | // array member declared at the end of an object not adjacent to the end | ||||||
16643 | // of the type. | ||||||
16644 | if (CXXRecord && CXXRecord->getNumVBases() != 0) | ||||||
16645 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | ||||||
16646 | << FD->getDeclName() << Record->getTagKind(); | ||||||
16647 | if (!getLangOpts().C99) | ||||||
16648 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | ||||||
16649 | << FD->getDeclName() << Record->getTagKind(); | ||||||
16650 | |||||||
16651 | // If the element type has a non-trivial destructor, we would not | ||||||
16652 | // implicitly destroy the elements, so disallow it for now. | ||||||
16653 | // | ||||||
16654 | // FIXME: GCC allows this. We should probably either implicitly delete | ||||||
16655 | // the destructor of the containing class, or just allow this. | ||||||
16656 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | ||||||
16657 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | ||||||
16658 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | ||||||
16659 | << FD->getDeclName() << FD->getType(); | ||||||
16660 | FD->setInvalidDecl(); | ||||||
16661 | EnclosingDecl->setInvalidDecl(); | ||||||
16662 | continue; | ||||||
16663 | } | ||||||
16664 | // Okay, we have a legal flexible array member at the end of the struct. | ||||||
16665 | Record->setHasFlexibleArrayMember(true); | ||||||
16666 | } else { | ||||||
16667 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | ||||||
16668 | // unless they are followed by another ivar. That check is done | ||||||
16669 | // elsewhere, after synthesized ivars are known. | ||||||
16670 | } | ||||||
16671 | } else if (!FDTy->isDependentType() && | ||||||
16672 | RequireCompleteType(FD->getLocation(), FD->getType(), | ||||||
16673 | diag::err_field_incomplete)) { | ||||||
16674 | // Incomplete type | ||||||
16675 | FD->setInvalidDecl(); | ||||||
16676 | EnclosingDecl->setInvalidDecl(); | ||||||
16677 | continue; | ||||||
16678 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | ||||||
16679 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | ||||||
16680 | // A type which contains a flexible array member is considered to be a | ||||||
16681 | // flexible array member. | ||||||
16682 | Record->setHasFlexibleArrayMember(true); | ||||||
16683 | if (!Record->isUnion()) { | ||||||
16684 | // If this is a struct/class and this is not the last element, reject | ||||||
16685 | // it. Note that GCC supports variable sized arrays in the middle of | ||||||
16686 | // structures. | ||||||
16687 | if (!IsLastField) | ||||||
16688 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | ||||||
16689 | << FD->getDeclName() << FD->getType(); | ||||||
16690 | else { | ||||||
16691 | // We support flexible arrays at the end of structs in | ||||||
16692 | // other structs as an extension. | ||||||
16693 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | ||||||
16694 | << FD->getDeclName(); | ||||||
16695 | } | ||||||
16696 | } | ||||||
16697 | } | ||||||
16698 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | ||||||
16699 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | ||||||
16700 | diag::err_abstract_type_in_decl, | ||||||
16701 | AbstractIvarType)) { | ||||||
16702 | // Ivars can not have abstract class types | ||||||
16703 | FD->setInvalidDecl(); | ||||||
16704 | } | ||||||
16705 | if (Record && FDTTy->getDecl()->hasObjectMember()) | ||||||
16706 | Record->setHasObjectMember(true); | ||||||
16707 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | ||||||
16708 | Record->setHasVolatileMember(true); | ||||||
16709 | } else if (FDTy->isObjCObjectType()) { | ||||||
16710 | /// A field cannot be an Objective-c object | ||||||
16711 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | ||||||
16712 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | ||||||
16713 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | ||||||
16714 | FD->setType(T); | ||||||
16715 | } else if (Record && Record->isUnion() && | ||||||
16716 | FD->getType().hasNonTrivialObjCLifetime() && | ||||||
16717 | getSourceManager().isInSystemHeader(FD->getLocation()) && | ||||||
16718 | !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && | ||||||
16719 | (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || | ||||||
16720 | !Context.hasDirectOwnershipQualifier(FD->getType()))) { | ||||||
16721 | // For backward compatibility, fields of C unions declared in system | ||||||
16722 | // headers that have non-trivial ObjC ownership qualifications are marked | ||||||
16723 | // as unavailable unless the qualifier is explicit and __strong. This can | ||||||
16724 | // break ABI compatibility between programs compiled with ARC and MRR, but | ||||||
16725 | // is a better option than rejecting programs using those unions under | ||||||
16726 | // ARC. | ||||||
16727 | FD->addAttr(UnavailableAttr::CreateImplicit( | ||||||
16728 | Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, | ||||||
16729 | FD->getLocation())); | ||||||
16730 | } else if (getLangOpts().ObjC && | ||||||
16731 | getLangOpts().getGC() != LangOptions::NonGC && | ||||||
16732 | Record && !Record->hasObjectMember()) { | ||||||
16733 | if (FD->getType()->isObjCObjectPointerType() || | ||||||
16734 | FD->getType().isObjCGCStrong()) | ||||||
16735 | Record->setHasObjectMember(true); | ||||||
16736 | else if (Context.getAsArrayType(FD->getType())) { | ||||||
16737 | QualType BaseType = Context.getBaseElementType(FD->getType()); | ||||||
16738 | if (BaseType->isRecordType() && | ||||||
16739 | BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) | ||||||
16740 | Record->setHasObjectMember(true); | ||||||
16741 | else if (BaseType->isObjCObjectPointerType() || | ||||||
16742 | BaseType.isObjCGCStrong()) | ||||||
16743 | Record->setHasObjectMember(true); | ||||||
16744 | } | ||||||
16745 | } | ||||||
16746 | |||||||
16747 | if (Record && !getLangOpts().CPlusPlus && | ||||||
16748 | !shouldIgnoreForRecordTriviality(FD)) { | ||||||
16749 | QualType FT = FD->getType(); | ||||||
16750 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { | ||||||
16751 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | ||||||
16752 | if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||
16753 | Record->isUnion()) | ||||||
16754 | Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); | ||||||
16755 | } | ||||||
16756 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | ||||||
16757 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { | ||||||
16758 | Record->setNonTrivialToPrimitiveCopy(true); | ||||||
16759 | if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) | ||||||
16760 | Record->setHasNonTrivialToPrimitiveCopyCUnion(true); | ||||||
16761 | } | ||||||
16762 | if (FT.isDestructedType()) { | ||||||
16763 | Record->setNonTrivialToPrimitiveDestroy(true); | ||||||
16764 | Record->setParamDestroyedInCallee(true); | ||||||
16765 | if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) | ||||||
16766 | Record->setHasNonTrivialToPrimitiveDestructCUnion(true); | ||||||
16767 | } | ||||||
16768 | |||||||
16769 | if (const auto *RT = FT->getAs<RecordType>()) { | ||||||
16770 | if (RT->getDecl()->getArgPassingRestrictions() == | ||||||
16771 | RecordDecl::APK_CanNeverPassInRegs) | ||||||
16772 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||||
16773 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||
16774 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||||
16775 | } | ||||||
16776 | |||||||
16777 | if (Record && FD->getType().isVolatileQualified()) | ||||||
16778 | Record->setHasVolatileMember(true); | ||||||
16779 | // Keep track of the number of named members. | ||||||
16780 | if (FD->getIdentifier()) | ||||||
16781 | ++NumNamedMembers; | ||||||
16782 | } | ||||||
16783 | |||||||
16784 | // Okay, we successfully defined 'Record'. | ||||||
16785 | if (Record) { | ||||||
16786 | bool Completed = false; | ||||||
16787 | if (CXXRecord) { | ||||||
16788 | if (!CXXRecord->isInvalidDecl()) { | ||||||
16789 | // Set access bits correctly on the directly-declared conversions. | ||||||
16790 | for (CXXRecordDecl::conversion_iterator | ||||||
16791 | I = CXXRecord->conversion_begin(), | ||||||
16792 | E = CXXRecord->conversion_end(); I != E; ++I) | ||||||
16793 | I.setAccess((*I)->getAccess()); | ||||||
16794 | } | ||||||
16795 | |||||||
16796 | if (!CXXRecord->isDependentType()) { | ||||||
16797 | // Add any implicitly-declared members to this class. | ||||||
16798 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | ||||||
16799 | |||||||
16800 | if (!CXXRecord->isInvalidDecl()) { | ||||||
16801 | // If we have virtual base classes, we may end up finding multiple | ||||||
16802 | // final overriders for a given virtual function. Check for this | ||||||
16803 | // problem now. | ||||||
16804 | if (CXXRecord->getNumVBases()) { | ||||||
16805 | CXXFinalOverriderMap FinalOverriders; | ||||||
16806 | CXXRecord->getFinalOverriders(FinalOverriders); | ||||||
16807 | |||||||
16808 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | ||||||
16809 | MEnd = FinalOverriders.end(); | ||||||
16810 | M != MEnd; ++M) { | ||||||
16811 | for (OverridingMethods::iterator SO = M->second.begin(), | ||||||
16812 | SOEnd = M->second.end(); | ||||||
16813 | SO != SOEnd; ++SO) { | ||||||
16814 | assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16815, __PRETTY_FUNCTION__)) | ||||||
16815 | "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16815, __PRETTY_FUNCTION__)); | ||||||
16816 | if (SO->second.size() == 1) | ||||||
16817 | continue; | ||||||
16818 | |||||||
16819 | // C++ [class.virtual]p2: | ||||||
16820 | // In a derived class, if a virtual member function of a base | ||||||
16821 | // class subobject has more than one final overrider the | ||||||
16822 | // program is ill-formed. | ||||||
16823 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | ||||||
16824 | << (const NamedDecl *)M->first << Record; | ||||||
16825 | Diag(M->first->getLocation(), | ||||||
16826 | diag::note_overridden_virtual_function); | ||||||
16827 | for (OverridingMethods::overriding_iterator | ||||||
16828 | OM = SO->second.begin(), | ||||||
16829 | OMEnd = SO->second.end(); | ||||||
16830 | OM != OMEnd; ++OM) | ||||||
16831 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | ||||||
16832 | << (const NamedDecl *)M->first << OM->Method->getParent(); | ||||||
16833 | |||||||
16834 | Record->setInvalidDecl(); | ||||||
16835 | } | ||||||
16836 | } | ||||||
16837 | CXXRecord->completeDefinition(&FinalOverriders); | ||||||
16838 | Completed = true; | ||||||
16839 | } | ||||||
16840 | } | ||||||
16841 | } | ||||||
16842 | } | ||||||
16843 | |||||||
16844 | if (!Completed) | ||||||
16845 | Record->completeDefinition(); | ||||||
16846 | |||||||
16847 | // Handle attributes before checking the layout. | ||||||
16848 | ProcessDeclAttributeList(S, Record, Attrs); | ||||||
16849 | |||||||
16850 | // We may have deferred checking for a deleted destructor. Check now. | ||||||
16851 | if (CXXRecord) { | ||||||
16852 | auto *Dtor = CXXRecord->getDestructor(); | ||||||
16853 | if (Dtor && Dtor->isImplicit() && | ||||||
16854 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | ||||||
16855 | CXXRecord->setImplicitDestructorIsDeleted(); | ||||||
16856 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | ||||||
16857 | } | ||||||
16858 | } | ||||||
16859 | |||||||
16860 | if (Record->hasAttrs()) { | ||||||
16861 | CheckAlignasUnderalignment(Record); | ||||||
16862 | |||||||
16863 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | ||||||
16864 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | ||||||
16865 | IA->getRange(), IA->getBestCase(), | ||||||
16866 | IA->getInheritanceModel()); | ||||||
16867 | } | ||||||
16868 | |||||||
16869 | // Check if the structure/union declaration is a type that can have zero | ||||||
16870 | // size in C. For C this is a language extension, for C++ it may cause | ||||||
16871 | // compatibility problems. | ||||||
16872 | bool CheckForZeroSize; | ||||||
16873 | if (!getLangOpts().CPlusPlus) { | ||||||
16874 | CheckForZeroSize = true; | ||||||
16875 | } else { | ||||||
16876 | // For C++ filter out types that cannot be referenced in C code. | ||||||
16877 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | ||||||
16878 | CheckForZeroSize = | ||||||
16879 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | ||||||
16880 | !CXXRecord->isDependentType() && | ||||||
16881 | CXXRecord->isCLike(); | ||||||
16882 | } | ||||||
16883 | if (CheckForZeroSize) { | ||||||
16884 | bool ZeroSize = true; | ||||||
16885 | bool IsEmpty = true; | ||||||
16886 | unsigned NonBitFields = 0; | ||||||
16887 | for (RecordDecl::field_iterator I = Record->field_begin(), | ||||||
16888 | E = Record->field_end(); | ||||||
16889 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | ||||||
16890 | IsEmpty = false; | ||||||
16891 | if (I->isUnnamedBitfield()) { | ||||||
16892 | if (!I->isZeroLengthBitField(Context)) | ||||||
16893 | ZeroSize = false; | ||||||
16894 | } else { | ||||||
16895 | ++NonBitFields; | ||||||
16896 | QualType FieldType = I->getType(); | ||||||
16897 | if (FieldType->isIncompleteType() || | ||||||
16898 | !Context.getTypeSizeInChars(FieldType).isZero()) | ||||||
16899 | ZeroSize = false; | ||||||
16900 | } | ||||||
16901 | } | ||||||
16902 | |||||||
16903 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | ||||||
16904 | // allowed in C++, but warn if its declaration is inside | ||||||
16905 | // extern "C" block. | ||||||
16906 | if (ZeroSize) { | ||||||
16907 | Diag(RecLoc, getLangOpts().CPlusPlus ? | ||||||
16908 | diag::warn_zero_size_struct_union_in_extern_c : | ||||||
16909 | diag::warn_zero_size_struct_union_compat) | ||||||
16910 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | ||||||
16911 | } | ||||||
16912 | |||||||
16913 | // Structs without named members are extension in C (C99 6.7.2.1p7), | ||||||
16914 | // but are accepted by GCC. | ||||||
16915 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | ||||||
16916 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | ||||||
16917 | diag::ext_no_named_members_in_struct_union) | ||||||
16918 | << Record->isUnion(); | ||||||
16919 | } | ||||||
16920 | } | ||||||
16921 | } else { | ||||||
16922 | ObjCIvarDecl **ClsFields = | ||||||
16923 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | ||||||
16924 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | ||||||
16925 | ID->setEndOfDefinitionLoc(RBrac); | ||||||
16926 | // Add ivar's to class's DeclContext. | ||||||
16927 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||||
16928 | ClsFields[i]->setLexicalDeclContext(ID); | ||||||
16929 | ID->addDecl(ClsFields[i]); | ||||||
16930 | } | ||||||
16931 | // Must enforce the rule that ivars in the base classes may not be | ||||||
16932 | // duplicates. | ||||||
16933 | if (ID->getSuperClass()) | ||||||
16934 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | ||||||
16935 | } else if (ObjCImplementationDecl *IMPDecl = | ||||||
16936 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||||
16937 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16937, __PRETTY_FUNCTION__)); | ||||||
16938 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | ||||||
16939 | // Ivar declared in @implementation never belongs to the implementation. | ||||||
16940 | // Only it is in implementation's lexical context. | ||||||
16941 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | ||||||
16942 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | ||||||
16943 | IMPDecl->setIvarLBraceLoc(LBrac); | ||||||
16944 | IMPDecl->setIvarRBraceLoc(RBrac); | ||||||
16945 | } else if (ObjCCategoryDecl *CDecl = | ||||||
16946 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||||
16947 | // case of ivars in class extension; all other cases have been | ||||||
16948 | // reported as errors elsewhere. | ||||||
16949 | // FIXME. Class extension does not have a LocEnd field. | ||||||
16950 | // CDecl->setLocEnd(RBrac); | ||||||
16951 | // Add ivar's to class extension's DeclContext. | ||||||
16952 | // Diagnose redeclaration of private ivars. | ||||||
16953 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | ||||||
16954 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||||
16955 | if (IDecl) { | ||||||
16956 | if (const ObjCIvarDecl *ClsIvar = | ||||||
16957 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||||
16958 | Diag(ClsFields[i]->getLocation(), | ||||||
16959 | diag::err_duplicate_ivar_declaration); | ||||||
16960 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | ||||||
16961 | continue; | ||||||
16962 | } | ||||||
16963 | for (const auto *Ext : IDecl->known_extensions()) { | ||||||
16964 | if (const ObjCIvarDecl *ClsExtIvar | ||||||
16965 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||||
16966 | Diag(ClsFields[i]->getLocation(), | ||||||
16967 | diag::err_duplicate_ivar_declaration); | ||||||
16968 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | ||||||
16969 | continue; | ||||||
16970 | } | ||||||
16971 | } | ||||||
16972 | } | ||||||
16973 | ClsFields[i]->setLexicalDeclContext(CDecl); | ||||||
16974 | CDecl->addDecl(ClsFields[i]); | ||||||
16975 | } | ||||||
16976 | CDecl->setIvarLBraceLoc(LBrac); | ||||||
16977 | CDecl->setIvarRBraceLoc(RBrac); | ||||||
16978 | } | ||||||
16979 | } | ||||||
16980 | } | ||||||
16981 | |||||||
16982 | /// Determine whether the given integral value is representable within | ||||||
16983 | /// the given type T. | ||||||
16984 | static bool isRepresentableIntegerValue(ASTContext &Context, | ||||||
16985 | llvm::APSInt &Value, | ||||||
16986 | QualType T) { | ||||||
16987 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16988, __PRETTY_FUNCTION__)) | ||||||
16988 | "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 16988, __PRETTY_FUNCTION__)); | ||||||
16989 | unsigned BitWidth = Context.getIntWidth(T); | ||||||
16990 | |||||||
16991 | if (Value.isUnsigned() || Value.isNonNegative()) { | ||||||
16992 | if (T->isSignedIntegerOrEnumerationType()) | ||||||
16993 | --BitWidth; | ||||||
16994 | return Value.getActiveBits() <= BitWidth; | ||||||
16995 | } | ||||||
16996 | return Value.getMinSignedBits() <= BitWidth; | ||||||
16997 | } | ||||||
16998 | |||||||
16999 | // Given an integral type, return the next larger integral type | ||||||
17000 | // (or a NULL type of no such type exists). | ||||||
17001 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | ||||||
17002 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | ||||||
17003 | // enum checking below. | ||||||
17004 | assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17005, __PRETTY_FUNCTION__)) | ||||||
17005 | T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17005, __PRETTY_FUNCTION__)); | ||||||
17006 | const unsigned NumTypes = 4; | ||||||
17007 | QualType SignedIntegralTypes[NumTypes] = { | ||||||
17008 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | ||||||
17009 | }; | ||||||
17010 | QualType UnsignedIntegralTypes[NumTypes] = { | ||||||
17011 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | ||||||
17012 | Context.UnsignedLongLongTy | ||||||
17013 | }; | ||||||
17014 | |||||||
17015 | unsigned BitWidth = Context.getTypeSize(T); | ||||||
17016 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | ||||||
17017 | : UnsignedIntegralTypes; | ||||||
17018 | for (unsigned I = 0; I != NumTypes; ++I) | ||||||
17019 | if (Context.getTypeSize(Types[I]) > BitWidth) | ||||||
17020 | return Types[I]; | ||||||
17021 | |||||||
17022 | return QualType(); | ||||||
17023 | } | ||||||
17024 | |||||||
17025 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | ||||||
17026 | EnumConstantDecl *LastEnumConst, | ||||||
17027 | SourceLocation IdLoc, | ||||||
17028 | IdentifierInfo *Id, | ||||||
17029 | Expr *Val) { | ||||||
17030 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||||
17031 | llvm::APSInt EnumVal(IntWidth); | ||||||
17032 | QualType EltTy; | ||||||
17033 | |||||||
17034 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | ||||||
17035 | Val = nullptr; | ||||||
17036 | |||||||
17037 | if (Val) | ||||||
17038 | Val = DefaultLvalueConversion(Val).get(); | ||||||
17039 | |||||||
17040 | if (Val) { | ||||||
17041 | if (Enum->isDependentType() || Val->isTypeDependent()) | ||||||
17042 | EltTy = Context.DependentTy; | ||||||
17043 | else { | ||||||
17044 | if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { | ||||||
17045 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | ||||||
17046 | // constant-expression in the enumerator-definition shall be a converted | ||||||
17047 | // constant expression of the underlying type. | ||||||
17048 | EltTy = Enum->getIntegerType(); | ||||||
17049 | ExprResult Converted = | ||||||
17050 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | ||||||
17051 | CCEK_Enumerator); | ||||||
17052 | if (Converted.isInvalid()) | ||||||
17053 | Val = nullptr; | ||||||
17054 | else | ||||||
17055 | Val = Converted.get(); | ||||||
17056 | } else if (!Val->isValueDependent() && | ||||||
17057 | !(Val = VerifyIntegerConstantExpression(Val, | ||||||
17058 | &EnumVal).get())) { | ||||||
17059 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | ||||||
17060 | } else { | ||||||
17061 | if (Enum->isComplete()) { | ||||||
17062 | EltTy = Enum->getIntegerType(); | ||||||
17063 | |||||||
17064 | // In Obj-C and Microsoft mode, require the enumeration value to be | ||||||
17065 | // representable in the underlying type of the enumeration. In C++11, | ||||||
17066 | // we perform a non-narrowing conversion as part of converted constant | ||||||
17067 | // expression checking. | ||||||
17068 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||||
17069 | if (Context.getTargetInfo() | ||||||
17070 | .getTriple() | ||||||
17071 | .isWindowsMSVCEnvironment()) { | ||||||
17072 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | ||||||
17073 | } else { | ||||||
17074 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | ||||||
17075 | } | ||||||
17076 | } | ||||||
17077 | |||||||
17078 | // Cast to the underlying type. | ||||||
17079 | Val = ImpCastExprToType(Val, EltTy, | ||||||
17080 | EltTy->isBooleanType() ? CK_IntegralToBoolean | ||||||
17081 | : CK_IntegralCast) | ||||||
17082 | .get(); | ||||||
17083 | } else if (getLangOpts().CPlusPlus) { | ||||||
17084 | // C++11 [dcl.enum]p5: | ||||||
17085 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17086 | // is the type of its initializing value: | ||||||
17087 | // - If an initializer is specified for an enumerator, the | ||||||
17088 | // initializing value has the same type as the expression. | ||||||
17089 | EltTy = Val->getType(); | ||||||
17090 | } else { | ||||||
17091 | // C99 6.7.2.2p2: | ||||||
17092 | // The expression that defines the value of an enumeration constant | ||||||
17093 | // shall be an integer constant expression that has a value | ||||||
17094 | // representable as an int. | ||||||
17095 | |||||||
17096 | // Complain if the value is not representable in an int. | ||||||
17097 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | ||||||
17098 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||||
17099 | << EnumVal.toString(10) << Val->getSourceRange() | ||||||
17100 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | ||||||
17101 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | ||||||
17102 | // Force the type of the expression to 'int'. | ||||||
17103 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | ||||||
17104 | } | ||||||
17105 | EltTy = Val->getType(); | ||||||
17106 | } | ||||||
17107 | } | ||||||
17108 | } | ||||||
17109 | } | ||||||
17110 | |||||||
17111 | if (!Val) { | ||||||
17112 | if (Enum->isDependentType()) | ||||||
17113 | EltTy = Context.DependentTy; | ||||||
17114 | else if (!LastEnumConst) { | ||||||
17115 | // C++0x [dcl.enum]p5: | ||||||
17116 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17117 | // is the type of its initializing value: | ||||||
17118 | // - If no initializer is specified for the first enumerator, the | ||||||
17119 | // initializing value has an unspecified integral type. | ||||||
17120 | // | ||||||
17121 | // GCC uses 'int' for its unspecified integral type, as does | ||||||
17122 | // C99 6.7.2.2p3. | ||||||
17123 | if (Enum->isFixed()) { | ||||||
17124 | EltTy = Enum->getIntegerType(); | ||||||
17125 | } | ||||||
17126 | else { | ||||||
17127 | EltTy = Context.IntTy; | ||||||
17128 | } | ||||||
17129 | } else { | ||||||
17130 | // Assign the last value + 1. | ||||||
17131 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17132 | ++EnumVal; | ||||||
17133 | EltTy = LastEnumConst->getType(); | ||||||
17134 | |||||||
17135 | // Check for overflow on increment. | ||||||
17136 | if (EnumVal < LastEnumConst->getInitVal()) { | ||||||
17137 | // C++0x [dcl.enum]p5: | ||||||
17138 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17139 | // is the type of its initializing value: | ||||||
17140 | // | ||||||
17141 | // - Otherwise the type of the initializing value is the same as | ||||||
17142 | // the type of the initializing value of the preceding enumerator | ||||||
17143 | // unless the incremented value is not representable in that type, | ||||||
17144 | // in which case the type is an unspecified integral type | ||||||
17145 | // sufficient to contain the incremented value. If no such type | ||||||
17146 | // exists, the program is ill-formed. | ||||||
17147 | QualType T = getNextLargerIntegralType(Context, EltTy); | ||||||
17148 | if (T.isNull() || Enum->isFixed()) { | ||||||
17149 | // There is no integral type larger enough to represent this | ||||||
17150 | // value. Complain, then allow the value to wrap around. | ||||||
17151 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17152 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | ||||||
17153 | ++EnumVal; | ||||||
17154 | if (Enum->isFixed()) | ||||||
17155 | // When the underlying type is fixed, this is ill-formed. | ||||||
17156 | Diag(IdLoc, diag::err_enumerator_wrapped) | ||||||
17157 | << EnumVal.toString(10) | ||||||
17158 | << EltTy; | ||||||
17159 | else | ||||||
17160 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | ||||||
17161 | << EnumVal.toString(10); | ||||||
17162 | } else { | ||||||
17163 | EltTy = T; | ||||||
17164 | } | ||||||
17165 | |||||||
17166 | // Retrieve the last enumerator's value, extent that type to the | ||||||
17167 | // type that is supposed to be large enough to represent the incremented | ||||||
17168 | // value, then increment. | ||||||
17169 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17170 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||||
17171 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | ||||||
17172 | ++EnumVal; | ||||||
17173 | |||||||
17174 | // If we're not in C++, diagnose the overflow of enumerator values, | ||||||
17175 | // which in C99 means that the enumerator value is not representable in | ||||||
17176 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | ||||||
17177 | // permits enumerator values that are representable in some larger | ||||||
17178 | // integral type. | ||||||
17179 | if (!getLangOpts().CPlusPlus && !T.isNull()) | ||||||
17180 | Diag(IdLoc, diag::warn_enum_value_overflow); | ||||||
17181 | } else if (!getLangOpts().CPlusPlus && | ||||||
17182 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||||
17183 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | ||||||
17184 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||||
17185 | << EnumVal.toString(10) << 1; | ||||||
17186 | } | ||||||
17187 | } | ||||||
17188 | } | ||||||
17189 | |||||||
17190 | if (!EltTy->isDependentType()) { | ||||||
17191 | // Make the enumerator value match the signedness and size of the | ||||||
17192 | // enumerator's type. | ||||||
17193 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | ||||||
17194 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||||
17195 | } | ||||||
17196 | |||||||
17197 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | ||||||
17198 | Val, EnumVal); | ||||||
17199 | } | ||||||
17200 | |||||||
17201 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | ||||||
17202 | SourceLocation IILoc) { | ||||||
17203 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | ||||||
17204 | !getLangOpts().CPlusPlus) | ||||||
17205 | return SkipBodyInfo(); | ||||||
17206 | |||||||
17207 | // We have an anonymous enum definition. Look up the first enumerator to | ||||||
17208 | // determine if we should merge the definition with an existing one and | ||||||
17209 | // skip the body. | ||||||
17210 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | ||||||
17211 | forRedeclarationInCurContext()); | ||||||
17212 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | ||||||
17213 | if (!PrevECD) | ||||||
17214 | return SkipBodyInfo(); | ||||||
17215 | |||||||
17216 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | ||||||
17217 | NamedDecl *Hidden; | ||||||
17218 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | ||||||
17219 | SkipBodyInfo Skip; | ||||||
17220 | Skip.Previous = Hidden; | ||||||
17221 | return Skip; | ||||||
17222 | } | ||||||
17223 | |||||||
17224 | return SkipBodyInfo(); | ||||||
17225 | } | ||||||
17226 | |||||||
17227 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | ||||||
17228 | SourceLocation IdLoc, IdentifierInfo *Id, | ||||||
17229 | const ParsedAttributesView &Attrs, | ||||||
17230 | SourceLocation EqualLoc, Expr *Val) { | ||||||
17231 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | ||||||
17232 | EnumConstantDecl *LastEnumConst = | ||||||
17233 | cast_or_null<EnumConstantDecl>(lastEnumConst); | ||||||
17234 | |||||||
17235 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||||
17236 | // we find one that is. | ||||||
17237 | S = getNonFieldDeclScope(S); | ||||||
17238 | |||||||
17239 | // Verify that there isn't already something declared with this name in this | ||||||
17240 | // scope. | ||||||
17241 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); | ||||||
17242 | LookupName(R, S); | ||||||
17243 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); | ||||||
17244 | |||||||
17245 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||||
17246 | // Maybe we will complain about the shadowed template parameter. | ||||||
17247 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | ||||||
17248 | // Just pretend that we didn't see the previous declaration. | ||||||
17249 | PrevDecl = nullptr; | ||||||
17250 | } | ||||||
17251 | |||||||
17252 | // C++ [class.mem]p15: | ||||||
17253 | // If T is the name of a class, then each of the following shall have a name | ||||||
17254 | // different from T: | ||||||
17255 | // - every enumerator of every member of class T that is an unscoped | ||||||
17256 | // enumerated type | ||||||
17257 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | ||||||
17258 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | ||||||
17259 | DeclarationNameInfo(Id, IdLoc)); | ||||||
17260 | |||||||
17261 | EnumConstantDecl *New = | ||||||
17262 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | ||||||
17263 | if (!New) | ||||||
17264 | return nullptr; | ||||||
17265 | |||||||
17266 | if (PrevDecl) { | ||||||
17267 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { | ||||||
17268 | // Check for other kinds of shadowing not already handled. | ||||||
17269 | CheckShadow(New, PrevDecl, R); | ||||||
17270 | } | ||||||
17271 | |||||||
17272 | // When in C++, we may get a TagDecl with the same name; in this case the | ||||||
17273 | // enum constant will 'hide' the tag. | ||||||
17274 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17275, __PRETTY_FUNCTION__)) | ||||||
17275 | "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17275, __PRETTY_FUNCTION__)); | ||||||
17276 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | ||||||
17277 | if (isa<EnumConstantDecl>(PrevDecl)) | ||||||
17278 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | ||||||
17279 | else | ||||||
17280 | Diag(IdLoc, diag::err_redefinition) << Id; | ||||||
17281 | notePreviousDefinition(PrevDecl, IdLoc); | ||||||
17282 | return nullptr; | ||||||
17283 | } | ||||||
17284 | } | ||||||
17285 | |||||||
17286 | // Process attributes. | ||||||
17287 | ProcessDeclAttributeList(S, New, Attrs); | ||||||
17288 | AddPragmaAttributes(S, New); | ||||||
17289 | |||||||
17290 | // Register this decl in the current scope stack. | ||||||
17291 | New->setAccess(TheEnumDecl->getAccess()); | ||||||
17292 | PushOnScopeChains(New, S); | ||||||
17293 | |||||||
17294 | ActOnDocumentableDecl(New); | ||||||
17295 | |||||||
17296 | return New; | ||||||
17297 | } | ||||||
17298 | |||||||
17299 | // Returns true when the enum initial expression does not trigger the | ||||||
17300 | // duplicate enum warning. A few common cases are exempted as follows: | ||||||
17301 | // Element2 = Element1 | ||||||
17302 | // Element2 = Element1 + 1 | ||||||
17303 | // Element2 = Element1 - 1 | ||||||
17304 | // Where Element2 and Element1 are from the same enum. | ||||||
17305 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | ||||||
17306 | Expr *InitExpr = ECD->getInitExpr(); | ||||||
17307 | if (!InitExpr) | ||||||
17308 | return true; | ||||||
17309 | InitExpr = InitExpr->IgnoreImpCasts(); | ||||||
17310 | |||||||
17311 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | ||||||
17312 | if (!BO->isAdditiveOp()) | ||||||
17313 | return true; | ||||||
17314 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | ||||||
17315 | if (!IL) | ||||||
17316 | return true; | ||||||
17317 | if (IL->getValue() != 1) | ||||||
17318 | return true; | ||||||
17319 | |||||||
17320 | InitExpr = BO->getLHS(); | ||||||
17321 | } | ||||||
17322 | |||||||
17323 | // This checks if the elements are from the same enum. | ||||||
17324 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | ||||||
17325 | if (!DRE) | ||||||
17326 | return true; | ||||||
17327 | |||||||
17328 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | ||||||
17329 | if (!EnumConstant) | ||||||
17330 | return true; | ||||||
17331 | |||||||
17332 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | ||||||
17333 | Enum) | ||||||
17334 | return true; | ||||||
17335 | |||||||
17336 | return false; | ||||||
17337 | } | ||||||
17338 | |||||||
17339 | // Emits a warning when an element is implicitly set a value that | ||||||
17340 | // a previous element has already been set to. | ||||||
17341 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | ||||||
17342 | EnumDecl *Enum, QualType EnumType) { | ||||||
17343 | // Avoid anonymous enums | ||||||
17344 | if (!Enum->getIdentifier()) | ||||||
17345 | return; | ||||||
17346 | |||||||
17347 | // Only check for small enums. | ||||||
17348 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | ||||||
17349 | return; | ||||||
17350 | |||||||
17351 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | ||||||
17352 | return; | ||||||
17353 | |||||||
17354 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | ||||||
17355 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | ||||||
17356 | |||||||
17357 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | ||||||
17358 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; | ||||||
17359 | |||||||
17360 | // Use int64_t as a key to avoid needing special handling for DenseMap keys. | ||||||
17361 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | ||||||
17362 | llvm::APSInt Val = D->getInitVal(); | ||||||
17363 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | ||||||
17364 | }; | ||||||
17365 | |||||||
17366 | DuplicatesVector DupVector; | ||||||
17367 | ValueToVectorMap EnumMap; | ||||||
17368 | |||||||
17369 | // Populate the EnumMap with all values represented by enum constants without | ||||||
17370 | // an initializer. | ||||||
17371 | for (auto *Element : Elements) { | ||||||
17372 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | ||||||
17373 | |||||||
17374 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | ||||||
17375 | // this constant. Skip this enum since it may be ill-formed. | ||||||
17376 | if (!ECD) { | ||||||
17377 | return; | ||||||
17378 | } | ||||||
17379 | |||||||
17380 | // Constants with initalizers are handled in the next loop. | ||||||
17381 | if (ECD->getInitExpr()) | ||||||
17382 | continue; | ||||||
17383 | |||||||
17384 | // Duplicate values are handled in the next loop. | ||||||
17385 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | ||||||
17386 | } | ||||||
17387 | |||||||
17388 | if (EnumMap.size() == 0) | ||||||
17389 | return; | ||||||
17390 | |||||||
17391 | // Create vectors for any values that has duplicates. | ||||||
17392 | for (auto *Element : Elements) { | ||||||
17393 | // The last loop returned if any constant was null. | ||||||
17394 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | ||||||
17395 | if (!ValidDuplicateEnum(ECD, Enum)) | ||||||
17396 | continue; | ||||||
17397 | |||||||
17398 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | ||||||
17399 | if (Iter == EnumMap.end()) | ||||||
17400 | continue; | ||||||
17401 | |||||||
17402 | DeclOrVector& Entry = Iter->second; | ||||||
17403 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | ||||||
17404 | // Ensure constants are different. | ||||||
17405 | if (D == ECD) | ||||||
17406 | continue; | ||||||
17407 | |||||||
17408 | // Create new vector and push values onto it. | ||||||
17409 | auto Vec = std::make_unique<ECDVector>(); | ||||||
17410 | Vec->push_back(D); | ||||||
17411 | Vec->push_back(ECD); | ||||||
17412 | |||||||
17413 | // Update entry to point to the duplicates vector. | ||||||
17414 | Entry = Vec.get(); | ||||||
17415 | |||||||
17416 | // Store the vector somewhere we can consult later for quick emission of | ||||||
17417 | // diagnostics. | ||||||
17418 | DupVector.emplace_back(std::move(Vec)); | ||||||
17419 | continue; | ||||||
17420 | } | ||||||
17421 | |||||||
17422 | ECDVector *Vec = Entry.get<ECDVector*>(); | ||||||
17423 | // Make sure constants are not added more than once. | ||||||
17424 | if (*Vec->begin() == ECD) | ||||||
17425 | continue; | ||||||
17426 | |||||||
17427 | Vec->push_back(ECD); | ||||||
17428 | } | ||||||
17429 | |||||||
17430 | // Emit diagnostics. | ||||||
17431 | for (const auto &Vec : DupVector) { | ||||||
17432 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17432, __PRETTY_FUNCTION__)); | ||||||
17433 | |||||||
17434 | // Emit warning for one enum constant. | ||||||
17435 | auto *FirstECD = Vec->front(); | ||||||
17436 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | ||||||
17437 | << FirstECD << FirstECD->getInitVal().toString(10) | ||||||
17438 | << FirstECD->getSourceRange(); | ||||||
17439 | |||||||
17440 | // Emit one note for each of the remaining enum constants with | ||||||
17441 | // the same value. | ||||||
17442 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) | ||||||
17443 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | ||||||
17444 | << ECD << ECD->getInitVal().toString(10) | ||||||
17445 | << ECD->getSourceRange(); | ||||||
17446 | } | ||||||
17447 | } | ||||||
17448 | |||||||
17449 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | ||||||
17450 | bool AllowMask) const { | ||||||
17451 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17451, __PRETTY_FUNCTION__)); | ||||||
17452 | assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition" ) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17452, __PRETTY_FUNCTION__)); | ||||||
17453 | |||||||
17454 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | ||||||
17455 | llvm::APInt &FlagBits = R.first->second; | ||||||
17456 | |||||||
17457 | if (R.second) { | ||||||
17458 | for (auto *E : ED->enumerators()) { | ||||||
17459 | const auto &EVal = E->getInitVal(); | ||||||
17460 | // Only single-bit enumerators introduce new flag values. | ||||||
17461 | if (EVal.isPowerOf2()) | ||||||
17462 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | ||||||
17463 | } | ||||||
17464 | } | ||||||
17465 | |||||||
17466 | // A value is in a flag enum if either its bits are a subset of the enum's | ||||||
17467 | // flag bits (the first condition) or we are allowing masks and the same is | ||||||
17468 | // true of its complement (the second condition). When masks are allowed, we | ||||||
17469 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | ||||||
17470 | // | ||||||
17471 | // While it's true that any value could be used as a mask, the assumption is | ||||||
17472 | // that a mask will have all of the insignificant bits set. Anything else is | ||||||
17473 | // likely a logic error. | ||||||
17474 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | ||||||
17475 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | ||||||
17476 | } | ||||||
17477 | |||||||
17478 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | ||||||
17479 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | ||||||
17480 | const ParsedAttributesView &Attrs) { | ||||||
17481 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | ||||||
17482 | QualType EnumType = Context.getTypeDeclType(Enum); | ||||||
17483 | |||||||
17484 | ProcessDeclAttributeList(S, Enum, Attrs); | ||||||
17485 | |||||||
17486 | if (Enum->isDependentType()) { | ||||||
17487 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||||
17488 | EnumConstantDecl *ECD = | ||||||
17489 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||||
17490 | if (!ECD) continue; | ||||||
17491 | |||||||
17492 | ECD->setType(EnumType); | ||||||
17493 | } | ||||||
17494 | |||||||
17495 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | ||||||
17496 | return; | ||||||
17497 | } | ||||||
17498 | |||||||
17499 | // TODO: If the result value doesn't fit in an int, it must be a long or long | ||||||
17500 | // long value. ISO C does not support this, but GCC does as an extension, | ||||||
17501 | // emit a warning. | ||||||
17502 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||||
17503 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | ||||||
17504 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | ||||||
17505 | |||||||
17506 | // Verify that all the values are okay, compute the size of the values, and | ||||||
17507 | // reverse the list. | ||||||
17508 | unsigned NumNegativeBits = 0; | ||||||
17509 | unsigned NumPositiveBits = 0; | ||||||
17510 | |||||||
17511 | // Keep track of whether all elements have type int. | ||||||
17512 | bool AllElementsInt = true; | ||||||
17513 | |||||||
17514 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||||
17515 | EnumConstantDecl *ECD = | ||||||
17516 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||||
17517 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
17518 | |||||||
17519 | const llvm::APSInt &InitVal = ECD->getInitVal(); | ||||||
17520 | |||||||
17521 | // Keep track of the size of positive and negative values. | ||||||
17522 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | ||||||
17523 | NumPositiveBits = std::max(NumPositiveBits, | ||||||
17524 | (unsigned)InitVal.getActiveBits()); | ||||||
17525 | else | ||||||
17526 | NumNegativeBits = std::max(NumNegativeBits, | ||||||
17527 | (unsigned)InitVal.getMinSignedBits()); | ||||||
17528 | |||||||
17529 | // Keep track of whether every enum element has type int (very common). | ||||||
17530 | if (AllElementsInt) | ||||||
17531 | AllElementsInt = ECD->getType() == Context.IntTy; | ||||||
17532 | } | ||||||
17533 | |||||||
17534 | // Figure out the type that should be used for this enum. | ||||||
17535 | QualType BestType; | ||||||
17536 | unsigned BestWidth; | ||||||
17537 | |||||||
17538 | // C++0x N3000 [conv.prom]p3: | ||||||
17539 | // An rvalue of an unscoped enumeration type whose underlying | ||||||
17540 | // type is not fixed can be converted to an rvalue of the first | ||||||
17541 | // of the following types that can represent all the values of | ||||||
17542 | // the enumeration: int, unsigned int, long int, unsigned long | ||||||
17543 | // int, long long int, or unsigned long long int. | ||||||
17544 | // C99 6.4.4.3p2: | ||||||
17545 | // An identifier declared as an enumeration constant has type int. | ||||||
17546 | // The C99 rule is modified by a gcc extension | ||||||
17547 | QualType BestPromotionType; | ||||||
17548 | |||||||
17549 | bool Packed = Enum->hasAttr<PackedAttr>(); | ||||||
17550 | // -fshort-enums is the equivalent to specifying the packed attribute on all | ||||||
17551 | // enum definitions. | ||||||
17552 | if (LangOpts.ShortEnums) | ||||||
17553 | Packed = true; | ||||||
17554 | |||||||
17555 | // If the enum already has a type because it is fixed or dictated by the | ||||||
17556 | // target, promote that type instead of analyzing the enumerators. | ||||||
17557 | if (Enum->isComplete()) { | ||||||
17558 | BestType = Enum->getIntegerType(); | ||||||
17559 | if (BestType->isPromotableIntegerType()) | ||||||
17560 | BestPromotionType = Context.getPromotedIntegerType(BestType); | ||||||
17561 | else | ||||||
17562 | BestPromotionType = BestType; | ||||||
17563 | |||||||
17564 | BestWidth = Context.getIntWidth(BestType); | ||||||
17565 | } | ||||||
17566 | else if (NumNegativeBits) { | ||||||
17567 | // If there is a negative value, figure out the smallest integer type (of | ||||||
17568 | // int/long/longlong) that fits. | ||||||
17569 | // If it's packed, check also if it fits a char or a short. | ||||||
17570 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | ||||||
17571 | BestType = Context.SignedCharTy; | ||||||
17572 | BestWidth = CharWidth; | ||||||
17573 | } else if (Packed && NumNegativeBits <= ShortWidth && | ||||||
17574 | NumPositiveBits < ShortWidth) { | ||||||
17575 | BestType = Context.ShortTy; | ||||||
17576 | BestWidth = ShortWidth; | ||||||
17577 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | ||||||
17578 | BestType = Context.IntTy; | ||||||
17579 | BestWidth = IntWidth; | ||||||
17580 | } else { | ||||||
17581 | BestWidth = Context.getTargetInfo().getLongWidth(); | ||||||
17582 | |||||||
17583 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | ||||||
17584 | BestType = Context.LongTy; | ||||||
17585 | } else { | ||||||
17586 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||||
17587 | |||||||
17588 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | ||||||
17589 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | ||||||
17590 | BestType = Context.LongLongTy; | ||||||
17591 | } | ||||||
17592 | } | ||||||
17593 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | ||||||
17594 | } else { | ||||||
17595 | // If there is no negative value, figure out the smallest type that fits | ||||||
17596 | // all of the enumerator values. | ||||||
17597 | // If it's packed, check also if it fits a char or a short. | ||||||
17598 | if (Packed && NumPositiveBits <= CharWidth) { | ||||||
17599 | BestType = Context.UnsignedCharTy; | ||||||
17600 | BestPromotionType = Context.IntTy; | ||||||
17601 | BestWidth = CharWidth; | ||||||
17602 | } else if (Packed && NumPositiveBits <= ShortWidth) { | ||||||
17603 | BestType = Context.UnsignedShortTy; | ||||||
17604 | BestPromotionType = Context.IntTy; | ||||||
17605 | BestWidth = ShortWidth; | ||||||
17606 | } else if (NumPositiveBits <= IntWidth) { | ||||||
17607 | BestType = Context.UnsignedIntTy; | ||||||
17608 | BestWidth = IntWidth; | ||||||
17609 | BestPromotionType | ||||||
17610 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
17611 | ? Context.UnsignedIntTy : Context.IntTy; | ||||||
17612 | } else if (NumPositiveBits <= | ||||||
17613 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | ||||||
17614 | BestType = Context.UnsignedLongTy; | ||||||
17615 | BestPromotionType | ||||||
17616 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
17617 | ? Context.UnsignedLongTy : Context.LongTy; | ||||||
17618 | } else { | ||||||
17619 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||||
17620 | assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17621, __PRETTY_FUNCTION__)) | ||||||
17621 | "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDecl.cpp" , 17621, __PRETTY_FUNCTION__)); | ||||||
17622 | BestType = Context.UnsignedLongLongTy; | ||||||
17623 | BestPromotionType | ||||||
17624 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
17625 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | ||||||
17626 | } | ||||||
17627 | } | ||||||
17628 | |||||||
17629 | // Loop over all of the enumerator constants, changing their types to match | ||||||
17630 | // the type of the enum if needed. | ||||||
17631 | for (auto *D : Elements) { | ||||||
17632 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | ||||||
17633 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
17634 | |||||||
17635 | // Standard C says the enumerators have int type, but we allow, as an | ||||||
17636 | // extension, the enumerators to be larger than int size. If each | ||||||
17637 | // enumerator value fits in an int, type it as an int, otherwise type it the | ||||||
17638 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | ||||||
17639 | // that X has type 'int', not 'unsigned'. | ||||||
17640 | |||||||
17641 | // Determine whether the value fits into an int. | ||||||
17642 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||||
17643 | |||||||
17644 | // If it fits into an integer type, force it. Otherwise force it to match | ||||||
17645 | // the enum decl type. | ||||||
17646 | QualType NewTy; | ||||||
17647 | unsigned NewWidth; | ||||||
17648 | bool NewSign; | ||||||
17649 | if (!getLangOpts().CPlusPlus && | ||||||
17650 | !Enum->isFixed() && | ||||||
17651 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | ||||||
17652 | NewTy = Context.IntTy; | ||||||
17653 | NewWidth = IntWidth; | ||||||
17654 | NewSign = true; | ||||||
17655 | } else if (ECD->getType() == BestType) { | ||||||
17656 | // Already the right type! | ||||||
17657 | if (getLangOpts().CPlusPlus) | ||||||
17658 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||||
17659 | // enum-specifier, each enumerator has the type of its | ||||||
17660 | // enumeration. | ||||||
17661 | ECD->setType(EnumType); | ||||||
17662 | continue; | ||||||
17663 | } else { | ||||||
17664 | NewTy = BestType; | ||||||
17665 | NewWidth = BestWidth; | ||||||
17666 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | ||||||
17667 | } | ||||||
17668 | |||||||
17669 | // Adjust the APSInt value. | ||||||
17670 | InitVal = InitVal.extOrTrunc(NewWidth); | ||||||
17671 | InitVal.setIsSigned(NewSign); | ||||||
17672 | ECD->setInitVal(InitVal); | ||||||
17673 | |||||||
17674 | // Adjust the Expr initializer and type. | ||||||
17675 | if (ECD->getInitExpr() && | ||||||
17676 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | ||||||
17677 | ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, | ||||||
17678 | CK_IntegralCast, | ||||||
17679 | ECD->getInitExpr(), | ||||||
17680 | /*base paths*/ nullptr, | ||||||
17681 | VK_RValue)); | ||||||
17682 | if (getLangOpts().CPlusPlus) | ||||||
17683 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||||
17684 | // enum-specifier, each enumerator has the type of its | ||||||
17685 | // enumeration. | ||||||
17686 | ECD->setType(EnumType); | ||||||
17687 | else | ||||||
17688 | ECD->setType(NewTy); | ||||||
17689 | } | ||||||
17690 | |||||||
17691 | Enum->completeDefinition(BestType, BestPromotionType, | ||||||
17692 | NumPositiveBits, NumNegativeBits); | ||||||
17693 | |||||||
17694 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | ||||||
17695 | |||||||
17696 | if (Enum->isClosedFlag()) { | ||||||
17697 | for (Decl *D : Elements) { | ||||||
17698 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | ||||||
17699 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
17700 | |||||||
17701 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||||
17702 | if (InitVal != 0 && !InitVal.isPowerOf2() && | ||||||
17703 | !IsValueInFlagEnum(Enum, InitVal, true)) | ||||||
17704 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | ||||||
17705 | << ECD << Enum; | ||||||
17706 | } | ||||||
17707 | } | ||||||
17708 | |||||||
17709 | // Now that the enum type is defined, ensure it's not been underaligned. | ||||||
17710 | if (Enum->hasAttrs()) | ||||||
17711 | CheckAlignasUnderalignment(Enum); | ||||||
17712 | } | ||||||
17713 | |||||||
17714 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | ||||||
17715 | SourceLocation StartLoc, | ||||||
17716 | SourceLocation EndLoc) { | ||||||
17717 | StringLiteral *AsmString = cast<StringLiteral>(expr); | ||||||
17718 | |||||||
17719 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | ||||||
17720 | AsmString, StartLoc, | ||||||
17721 | EndLoc); | ||||||
17722 | CurContext->addDecl(New); | ||||||
17723 | return New; | ||||||
17724 | } | ||||||
17725 | |||||||
17726 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | ||||||
17727 | IdentifierInfo* AliasName, | ||||||
17728 | SourceLocation PragmaLoc, | ||||||
17729 | SourceLocation NameLoc, | ||||||
17730 | SourceLocation AliasNameLoc) { | ||||||
17731 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | ||||||
17732 | LookupOrdinaryName); | ||||||
17733 | AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), | ||||||
17734 | AttributeCommonInfo::AS_Pragma); | ||||||
17735 | AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( | ||||||
17736 | Context, AliasName->getName(), /*LiteralLabel=*/true, Info); | ||||||
17737 | |||||||
17738 | // If a declaration that: | ||||||
17739 | // 1) declares a function or a variable | ||||||
17740 | // 2) has external linkage | ||||||
17741 | // already exists, add a label attribute to it. | ||||||
17742 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||||
17743 | if (isDeclExternC(PrevDecl)) | ||||||
17744 | PrevDecl->addAttr(Attr); | ||||||
17745 | else | ||||||
17746 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
17747 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | ||||||
17748 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | ||||||
17749 | } else | ||||||
17750 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | ||||||
17751 | } | ||||||
17752 | |||||||
17753 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | ||||||
17754 | SourceLocation PragmaLoc, | ||||||
17755 | SourceLocation NameLoc) { | ||||||
17756 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | ||||||
17757 | |||||||
17758 | if (PrevDecl) { | ||||||
17759 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); | ||||||
17760 | } else { | ||||||
17761 | (void)WeakUndeclaredIdentifiers.insert( | ||||||
17762 | std::pair<IdentifierInfo*,WeakInfo> | ||||||
17763 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); | ||||||
17764 | } | ||||||
17765 | } | ||||||
17766 | |||||||
17767 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | ||||||
17768 | IdentifierInfo* AliasName, | ||||||
17769 | SourceLocation PragmaLoc, | ||||||
17770 | SourceLocation NameLoc, | ||||||
17771 | SourceLocation AliasNameLoc) { | ||||||
17772 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | ||||||
17773 | LookupOrdinaryName); | ||||||
17774 | WeakInfo W = WeakInfo(Name, NameLoc); | ||||||
17775 | |||||||
17776 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||||
17777 | if (!PrevDecl->hasAttr<AliasAttr>()) | ||||||
17778 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | ||||||
17779 | DeclApplyPragmaWeak(TUScope, ND, W); | ||||||
17780 | } else { | ||||||
17781 | (void)WeakUndeclaredIdentifiers.insert( | ||||||
17782 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); | ||||||
17783 | } | ||||||
17784 | } | ||||||
17785 | |||||||
17786 | Decl *Sema::getObjCDeclContext() const { | ||||||
17787 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | ||||||
17788 | } | ||||||
17789 | |||||||
17790 | Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { | ||||||
17791 | // Templates are emitted when they're instantiated. | ||||||
17792 | if (FD->isDependentContext()) | ||||||
17793 | return FunctionEmissionStatus::TemplateDiscarded; | ||||||
17794 | |||||||
17795 | FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; | ||||||
17796 | if (LangOpts.OpenMPIsDevice) { | ||||||
17797 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | ||||||
17798 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | ||||||
17799 | if (DevTy.hasValue()) { | ||||||
17800 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) | ||||||
17801 | OMPES = FunctionEmissionStatus::OMPDiscarded; | ||||||
17802 | else if (DeviceKnownEmittedFns.count(FD) > 0) | ||||||
17803 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
17804 | } | ||||||
17805 | } else if (LangOpts.OpenMP) { | ||||||
17806 | // In OpenMP 4.5 all the functions are host functions. | ||||||
17807 | if (LangOpts.OpenMP <= 45) { | ||||||
17808 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
17809 | } else { | ||||||
17810 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | ||||||
17811 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | ||||||
17812 | // In OpenMP 5.0 or above, DevTy may be changed later by | ||||||
17813 | // #pragma omp declare target to(*) device_type(*). Therefore DevTy | ||||||
17814 | // having no value does not imply host. The emission status will be | ||||||
17815 | // checked again at the end of compilation unit. | ||||||
17816 | if (DevTy.hasValue()) { | ||||||
17817 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { | ||||||
17818 | OMPES = FunctionEmissionStatus::OMPDiscarded; | ||||||
17819 | } else if (DeviceKnownEmittedFns.count(FD) > 0) { | ||||||
17820 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
17821 | } | ||||||
17822 | } | ||||||
17823 | } | ||||||
17824 | } | ||||||
17825 | if (OMPES == FunctionEmissionStatus::OMPDiscarded || | ||||||
17826 | (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) | ||||||
17827 | return OMPES; | ||||||
17828 | |||||||
17829 | if (LangOpts.CUDA) { | ||||||
17830 | // When compiling for device, host functions are never emitted. Similarly, | ||||||
17831 | // when compiling for host, device and global functions are never emitted. | ||||||
17832 | // (Technically, we do emit a host-side stub for global functions, but this | ||||||
17833 | // doesn't count for our purposes here.) | ||||||
17834 | Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); | ||||||
17835 | if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) | ||||||
17836 | return FunctionEmissionStatus::CUDADiscarded; | ||||||
17837 | if (!LangOpts.CUDAIsDevice && | ||||||
17838 | (T == Sema::CFT_Device || T == Sema::CFT_Global)) | ||||||
17839 | return FunctionEmissionStatus::CUDADiscarded; | ||||||
17840 | |||||||
17841 | // Check whether this function is externally visible -- if so, it's | ||||||
17842 | // known-emitted. | ||||||
17843 | // | ||||||
17844 | // We have to check the GVA linkage of the function's *definition* -- if we | ||||||
17845 | // only have a declaration, we don't know whether or not the function will | ||||||
17846 | // be emitted, because (say) the definition could include "inline". | ||||||
17847 | FunctionDecl *Def = FD->getDefinition(); | ||||||
17848 | |||||||
17849 | if (Def && | ||||||
17850 | !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) | ||||||
17851 | && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) | ||||||
17852 | return FunctionEmissionStatus::Emitted; | ||||||
17853 | } | ||||||
17854 | |||||||
17855 | // Otherwise, the function is known-emitted if it's in our set of | ||||||
17856 | // known-emitted functions. | ||||||
17857 | return (DeviceKnownEmittedFns.count(FD) > 0) | ||||||
17858 | ? FunctionEmissionStatus::Emitted | ||||||
17859 | : FunctionEmissionStatus::Unknown; | ||||||
17860 | } | ||||||
17861 | |||||||
17862 | bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { | ||||||
17863 | // Host-side references to a __global__ function refer to the stub, so the | ||||||
17864 | // function itself is never emitted and therefore should not be marked. | ||||||
17865 | // If we have host fn calls kernel fn calls host+device, the HD function | ||||||
17866 | // does not get instantiated on the host. We model this by omitting at the | ||||||
17867 | // call to the kernel from the callgraph. This ensures that, when compiling | ||||||
17868 | // for host, only HD functions actually called from the host get marked as | ||||||
17869 | // known-emitted. | ||||||
17870 | return LangOpts.CUDA && !LangOpts.CUDAIsDevice && | ||||||
17871 | IdentifyCUDATarget(Callee) == CFT_Global; | ||||||
17872 | } |
1 | //===- Decl.h - Classes for representing declarations -----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the Decl subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_DECL_H |
14 | #define LLVM_CLANG_AST_DECL_H |
15 | |
16 | #include "clang/AST/APValue.h" |
17 | #include "clang/AST/ASTContextAllocate.h" |
18 | #include "clang/AST/DeclAccessPair.h" |
19 | #include "clang/AST/DeclBase.h" |
20 | #include "clang/AST/DeclarationName.h" |
21 | #include "clang/AST/ExternalASTSource.h" |
22 | #include "clang/AST/NestedNameSpecifier.h" |
23 | #include "clang/AST/Redeclarable.h" |
24 | #include "clang/AST/Type.h" |
25 | #include "clang/Basic/AddressSpaces.h" |
26 | #include "clang/Basic/Diagnostic.h" |
27 | #include "clang/Basic/IdentifierTable.h" |
28 | #include "clang/Basic/LLVM.h" |
29 | #include "clang/Basic/Linkage.h" |
30 | #include "clang/Basic/OperatorKinds.h" |
31 | #include "clang/Basic/PartialDiagnostic.h" |
32 | #include "clang/Basic/PragmaKinds.h" |
33 | #include "clang/Basic/SourceLocation.h" |
34 | #include "clang/Basic/Specifiers.h" |
35 | #include "clang/Basic/Visibility.h" |
36 | #include "llvm/ADT/APSInt.h" |
37 | #include "llvm/ADT/ArrayRef.h" |
38 | #include "llvm/ADT/Optional.h" |
39 | #include "llvm/ADT/PointerIntPair.h" |
40 | #include "llvm/ADT/PointerUnion.h" |
41 | #include "llvm/ADT/StringRef.h" |
42 | #include "llvm/ADT/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/TrailingObjects.h" |
46 | #include <cassert> |
47 | #include <cstddef> |
48 | #include <cstdint> |
49 | #include <string> |
50 | #include <utility> |
51 | |
52 | namespace clang { |
53 | |
54 | class ASTContext; |
55 | struct ASTTemplateArgumentListInfo; |
56 | class Attr; |
57 | class CompoundStmt; |
58 | class DependentFunctionTemplateSpecializationInfo; |
59 | class EnumDecl; |
60 | class Expr; |
61 | class FunctionTemplateDecl; |
62 | class FunctionTemplateSpecializationInfo; |
63 | class FunctionTypeLoc; |
64 | class LabelStmt; |
65 | class MemberSpecializationInfo; |
66 | class Module; |
67 | class NamespaceDecl; |
68 | class ParmVarDecl; |
69 | class RecordDecl; |
70 | class Stmt; |
71 | class StringLiteral; |
72 | class TagDecl; |
73 | class TemplateArgumentList; |
74 | class TemplateArgumentListInfo; |
75 | class TemplateParameterList; |
76 | class TypeAliasTemplateDecl; |
77 | class TypeLoc; |
78 | class UnresolvedSetImpl; |
79 | class VarTemplateDecl; |
80 | |
81 | /// The top declaration context. |
82 | class TranslationUnitDecl : public Decl, public DeclContext { |
83 | ASTContext &Ctx; |
84 | |
85 | /// The (most recently entered) anonymous namespace for this |
86 | /// translation unit, if one has been created. |
87 | NamespaceDecl *AnonymousNamespace = nullptr; |
88 | |
89 | explicit TranslationUnitDecl(ASTContext &ctx); |
90 | |
91 | virtual void anchor(); |
92 | |
93 | public: |
94 | ASTContext &getASTContext() const { return Ctx; } |
95 | |
96 | NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } |
97 | void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } |
98 | |
99 | static TranslationUnitDecl *Create(ASTContext &C); |
100 | |
101 | // Implement isa/cast/dyncast/etc. |
102 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
103 | static bool classofKind(Kind K) { return K == TranslationUnit; } |
104 | static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { |
105 | return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); |
106 | } |
107 | static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { |
108 | return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); |
109 | } |
110 | }; |
111 | |
112 | /// Represents a `#pragma comment` line. Always a child of |
113 | /// TranslationUnitDecl. |
114 | class PragmaCommentDecl final |
115 | : public Decl, |
116 | private llvm::TrailingObjects<PragmaCommentDecl, char> { |
117 | friend class ASTDeclReader; |
118 | friend class ASTDeclWriter; |
119 | friend TrailingObjects; |
120 | |
121 | PragmaMSCommentKind CommentKind; |
122 | |
123 | PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc, |
124 | PragmaMSCommentKind CommentKind) |
125 | : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {} |
126 | |
127 | virtual void anchor(); |
128 | |
129 | public: |
130 | static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC, |
131 | SourceLocation CommentLoc, |
132 | PragmaMSCommentKind CommentKind, |
133 | StringRef Arg); |
134 | static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
135 | unsigned ArgSize); |
136 | |
137 | PragmaMSCommentKind getCommentKind() const { return CommentKind; } |
138 | |
139 | StringRef getArg() const { return getTrailingObjects<char>(); } |
140 | |
141 | // Implement isa/cast/dyncast/etc. |
142 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
143 | static bool classofKind(Kind K) { return K == PragmaComment; } |
144 | }; |
145 | |
146 | /// Represents a `#pragma detect_mismatch` line. Always a child of |
147 | /// TranslationUnitDecl. |
148 | class PragmaDetectMismatchDecl final |
149 | : public Decl, |
150 | private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> { |
151 | friend class ASTDeclReader; |
152 | friend class ASTDeclWriter; |
153 | friend TrailingObjects; |
154 | |
155 | size_t ValueStart; |
156 | |
157 | PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc, |
158 | size_t ValueStart) |
159 | : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {} |
160 | |
161 | virtual void anchor(); |
162 | |
163 | public: |
164 | static PragmaDetectMismatchDecl *Create(const ASTContext &C, |
165 | TranslationUnitDecl *DC, |
166 | SourceLocation Loc, StringRef Name, |
167 | StringRef Value); |
168 | static PragmaDetectMismatchDecl * |
169 | CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); |
170 | |
171 | StringRef getName() const { return getTrailingObjects<char>(); } |
172 | StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; } |
173 | |
174 | // Implement isa/cast/dyncast/etc. |
175 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
176 | static bool classofKind(Kind K) { return K == PragmaDetectMismatch; } |
177 | }; |
178 | |
179 | /// Declaration context for names declared as extern "C" in C++. This |
180 | /// is neither the semantic nor lexical context for such declarations, but is |
181 | /// used to check for conflicts with other extern "C" declarations. Example: |
182 | /// |
183 | /// \code |
184 | /// namespace N { extern "C" void f(); } // #1 |
185 | /// void N::f() {} // #2 |
186 | /// namespace M { extern "C" void f(); } // #3 |
187 | /// \endcode |
188 | /// |
189 | /// The semantic context of #1 is namespace N and its lexical context is the |
190 | /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical |
191 | /// context is the TU. However, both declarations are also visible in the |
192 | /// extern "C" context. |
193 | /// |
194 | /// The declaration at #3 finds it is a redeclaration of \c N::f through |
195 | /// lookup in the extern "C" context. |
196 | class ExternCContextDecl : public Decl, public DeclContext { |
197 | explicit ExternCContextDecl(TranslationUnitDecl *TU) |
198 | : Decl(ExternCContext, TU, SourceLocation()), |
199 | DeclContext(ExternCContext) {} |
200 | |
201 | virtual void anchor(); |
202 | |
203 | public: |
204 | static ExternCContextDecl *Create(const ASTContext &C, |
205 | TranslationUnitDecl *TU); |
206 | |
207 | // Implement isa/cast/dyncast/etc. |
208 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
209 | static bool classofKind(Kind K) { return K == ExternCContext; } |
210 | static DeclContext *castToDeclContext(const ExternCContextDecl *D) { |
211 | return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D)); |
212 | } |
213 | static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) { |
214 | return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC)); |
215 | } |
216 | }; |
217 | |
218 | /// This represents a decl that may have a name. Many decls have names such |
219 | /// as ObjCMethodDecl, but not \@class, etc. |
220 | /// |
221 | /// Note that not every NamedDecl is actually named (e.g., a struct might |
222 | /// be anonymous), and not every name is an identifier. |
223 | class NamedDecl : public Decl { |
224 | /// The name of this declaration, which is typically a normal |
225 | /// identifier but may also be a special kind of name (C++ |
226 | /// constructor, Objective-C selector, etc.) |
227 | DeclarationName Name; |
228 | |
229 | virtual void anchor(); |
230 | |
231 | private: |
232 | NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__)); |
233 | |
234 | protected: |
235 | NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) |
236 | : Decl(DK, DC, L), Name(N) {} |
237 | |
238 | public: |
239 | /// Get the identifier that names this declaration, if there is one. |
240 | /// |
241 | /// This will return NULL if this declaration has no name (e.g., for |
242 | /// an unnamed class) or if the name is a special name (C++ constructor, |
243 | /// Objective-C selector, etc.). |
244 | IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } |
245 | |
246 | /// Get the name of identifier for this declaration as a StringRef. |
247 | /// |
248 | /// This requires that the declaration have a name and that it be a simple |
249 | /// identifier. |
250 | StringRef getName() const { |
251 | assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier" ) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 251, __PRETTY_FUNCTION__)); |
252 | return getIdentifier() ? getIdentifier()->getName() : ""; |
253 | } |
254 | |
255 | /// Get a human-readable name for the declaration, even if it is one of the |
256 | /// special kinds of names (C++ constructor, Objective-C selector, etc). |
257 | /// |
258 | /// Creating this name requires expensive string manipulation, so it should |
259 | /// be called only when performance doesn't matter. For simple declarations, |
260 | /// getNameAsCString() should suffice. |
261 | // |
262 | // FIXME: This function should be renamed to indicate that it is not just an |
263 | // alternate form of getName(), and clients should move as appropriate. |
264 | // |
265 | // FIXME: Deprecated, move clients to getName(). |
266 | std::string getNameAsString() const { return Name.getAsString(); } |
267 | |
268 | virtual void printName(raw_ostream &os) const; |
269 | |
270 | /// Get the actual, stored name of the declaration, which may be a special |
271 | /// name. |
272 | DeclarationName getDeclName() const { return Name; } |
273 | |
274 | /// Set the name of this declaration. |
275 | void setDeclName(DeclarationName N) { Name = N; } |
276 | |
277 | /// Returns a human-readable qualified name for this declaration, like |
278 | /// A::B::i, for i being member of namespace A::B. |
279 | /// |
280 | /// If the declaration is not a member of context which can be named (record, |
281 | /// namespace), it will return the same result as printName(). |
282 | /// |
283 | /// Creating this name is expensive, so it should be called only when |
284 | /// performance doesn't matter. |
285 | void printQualifiedName(raw_ostream &OS) const; |
286 | void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
287 | |
288 | /// Print only the nested name specifier part of a fully-qualified name, |
289 | /// including the '::' at the end. E.g. |
290 | /// when `printQualifiedName(D)` prints "A::B::i", |
291 | /// this function prints "A::B::". |
292 | void printNestedNameSpecifier(raw_ostream &OS) const; |
293 | void printNestedNameSpecifier(raw_ostream &OS, |
294 | const PrintingPolicy &Policy) const; |
295 | |
296 | // FIXME: Remove string version. |
297 | std::string getQualifiedNameAsString() const; |
298 | |
299 | /// Appends a human-readable name for this declaration into the given stream. |
300 | /// |
301 | /// This is the method invoked by Sema when displaying a NamedDecl |
302 | /// in a diagnostic. It does not necessarily produce the same |
303 | /// result as printName(); for example, class template |
304 | /// specializations are printed with their template arguments. |
305 | virtual void getNameForDiagnostic(raw_ostream &OS, |
306 | const PrintingPolicy &Policy, |
307 | bool Qualified) const; |
308 | |
309 | /// Determine whether this declaration, if known to be well-formed within |
310 | /// its context, will replace the declaration OldD if introduced into scope. |
311 | /// |
312 | /// A declaration will replace another declaration if, for example, it is |
313 | /// a redeclaration of the same variable or function, but not if it is a |
314 | /// declaration of a different kind (function vs. class) or an overloaded |
315 | /// function. |
316 | /// |
317 | /// \param IsKnownNewer \c true if this declaration is known to be newer |
318 | /// than \p OldD (for instance, if this declaration is newly-created). |
319 | bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const; |
320 | |
321 | /// Determine whether this declaration has linkage. |
322 | bool hasLinkage() const; |
323 | |
324 | using Decl::isModulePrivate; |
325 | using Decl::setModulePrivate; |
326 | |
327 | /// Determine whether this declaration is a C++ class member. |
328 | bool isCXXClassMember() const { |
329 | const DeclContext *DC = getDeclContext(); |
330 | |
331 | // C++0x [class.mem]p1: |
332 | // The enumerators of an unscoped enumeration defined in |
333 | // the class are members of the class. |
334 | if (isa<EnumDecl>(DC)) |
335 | DC = DC->getRedeclContext(); |
336 | |
337 | return DC->isRecord(); |
338 | } |
339 | |
340 | /// Determine whether the given declaration is an instance member of |
341 | /// a C++ class. |
342 | bool isCXXInstanceMember() const; |
343 | |
344 | /// Determine what kind of linkage this entity has. |
345 | /// |
346 | /// This is not the linkage as defined by the standard or the codegen notion |
347 | /// of linkage. It is just an implementation detail that is used to compute |
348 | /// those. |
349 | Linkage getLinkageInternal() const; |
350 | |
351 | /// Get the linkage from a semantic point of view. Entities in |
352 | /// anonymous namespaces are external (in c++98). |
353 | Linkage getFormalLinkage() const { |
354 | return clang::getFormalLinkage(getLinkageInternal()); |
355 | } |
356 | |
357 | /// True if this decl has external linkage. |
358 | bool hasExternalFormalLinkage() const { |
359 | return isExternalFormalLinkage(getLinkageInternal()); |
360 | } |
361 | |
362 | bool isExternallyVisible() const { |
363 | return clang::isExternallyVisible(getLinkageInternal()); |
364 | } |
365 | |
366 | /// Determine whether this declaration can be redeclared in a |
367 | /// different translation unit. |
368 | bool isExternallyDeclarable() const { |
369 | return isExternallyVisible() && !getOwningModuleForLinkage(); |
370 | } |
371 | |
372 | /// Determines the visibility of this entity. |
373 | Visibility getVisibility() const { |
374 | return getLinkageAndVisibility().getVisibility(); |
375 | } |
376 | |
377 | /// Determines the linkage and visibility of this entity. |
378 | LinkageInfo getLinkageAndVisibility() const; |
379 | |
380 | /// Kinds of explicit visibility. |
381 | enum ExplicitVisibilityKind { |
382 | /// Do an LV computation for, ultimately, a type. |
383 | /// Visibility may be restricted by type visibility settings and |
384 | /// the visibility of template arguments. |
385 | VisibilityForType, |
386 | |
387 | /// Do an LV computation for, ultimately, a non-type declaration. |
388 | /// Visibility may be restricted by value visibility settings and |
389 | /// the visibility of template arguments. |
390 | VisibilityForValue |
391 | }; |
392 | |
393 | /// If visibility was explicitly specified for this |
394 | /// declaration, return that visibility. |
395 | Optional<Visibility> |
396 | getExplicitVisibility(ExplicitVisibilityKind kind) const; |
397 | |
398 | /// True if the computed linkage is valid. Used for consistency |
399 | /// checking. Should always return true. |
400 | bool isLinkageValid() const; |
401 | |
402 | /// True if something has required us to compute the linkage |
403 | /// of this declaration. |
404 | /// |
405 | /// Language features which can retroactively change linkage (like a |
406 | /// typedef name for linkage purposes) may need to consider this, |
407 | /// but hopefully only in transitory ways during parsing. |
408 | bool hasLinkageBeenComputed() const { |
409 | return hasCachedLinkage(); |
410 | } |
411 | |
412 | /// Looks through UsingDecls and ObjCCompatibleAliasDecls for |
413 | /// the underlying named decl. |
414 | NamedDecl *getUnderlyingDecl() { |
415 | // Fast-path the common case. |
416 | if (this->getKind() != UsingShadow && |
417 | this->getKind() != ConstructorUsingShadow && |
418 | this->getKind() != ObjCCompatibleAlias && |
419 | this->getKind() != NamespaceAlias) |
420 | return this; |
421 | |
422 | return getUnderlyingDeclImpl(); |
423 | } |
424 | const NamedDecl *getUnderlyingDecl() const { |
425 | return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); |
426 | } |
427 | |
428 | NamedDecl *getMostRecentDecl() { |
429 | return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl()); |
430 | } |
431 | const NamedDecl *getMostRecentDecl() const { |
432 | return const_cast<NamedDecl*>(this)->getMostRecentDecl(); |
433 | } |
434 | |
435 | ObjCStringFormatFamily getObjCFStringFormattingFamily() const; |
436 | |
437 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
438 | static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } |
439 | }; |
440 | |
441 | inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { |
442 | ND.printName(OS); |
443 | return OS; |
444 | } |
445 | |
446 | /// Represents the declaration of a label. Labels also have a |
447 | /// corresponding LabelStmt, which indicates the position that the label was |
448 | /// defined at. For normal labels, the location of the decl is the same as the |
449 | /// location of the statement. For GNU local labels (__label__), the decl |
450 | /// location is where the __label__ is. |
451 | class LabelDecl : public NamedDecl { |
452 | LabelStmt *TheStmt; |
453 | StringRef MSAsmName; |
454 | bool MSAsmNameResolved = false; |
455 | |
456 | /// For normal labels, this is the same as the main declaration |
457 | /// label, i.e., the location of the identifier; for GNU local labels, |
458 | /// this is the location of the __label__ keyword. |
459 | SourceLocation LocStart; |
460 | |
461 | LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, |
462 | LabelStmt *S, SourceLocation StartL) |
463 | : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} |
464 | |
465 | void anchor() override; |
466 | |
467 | public: |
468 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
469 | SourceLocation IdentL, IdentifierInfo *II); |
470 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
471 | SourceLocation IdentL, IdentifierInfo *II, |
472 | SourceLocation GnuLabelL); |
473 | static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
474 | |
475 | LabelStmt *getStmt() const { return TheStmt; } |
476 | void setStmt(LabelStmt *T) { TheStmt = T; } |
477 | |
478 | bool isGnuLocal() const { return LocStart != getLocation(); } |
479 | void setLocStart(SourceLocation L) { LocStart = L; } |
480 | |
481 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
482 | return SourceRange(LocStart, getLocation()); |
483 | } |
484 | |
485 | bool isMSAsmLabel() const { return !MSAsmName.empty(); } |
486 | bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; } |
487 | void setMSAsmLabel(StringRef Name); |
488 | StringRef getMSAsmLabel() const { return MSAsmName; } |
489 | void setMSAsmLabelResolved() { MSAsmNameResolved = true; } |
490 | |
491 | // Implement isa/cast/dyncast/etc. |
492 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
493 | static bool classofKind(Kind K) { return K == Label; } |
494 | }; |
495 | |
496 | /// Represent a C++ namespace. |
497 | class NamespaceDecl : public NamedDecl, public DeclContext, |
498 | public Redeclarable<NamespaceDecl> |
499 | { |
500 | /// The starting location of the source range, pointing |
501 | /// to either the namespace or the inline keyword. |
502 | SourceLocation LocStart; |
503 | |
504 | /// The ending location of the source range. |
505 | SourceLocation RBraceLoc; |
506 | |
507 | /// A pointer to either the anonymous namespace that lives just inside |
508 | /// this namespace or to the first namespace in the chain (the latter case |
509 | /// only when this is not the first in the chain), along with a |
510 | /// boolean value indicating whether this is an inline namespace. |
511 | llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; |
512 | |
513 | NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, |
514 | SourceLocation StartLoc, SourceLocation IdLoc, |
515 | IdentifierInfo *Id, NamespaceDecl *PrevDecl); |
516 | |
517 | using redeclarable_base = Redeclarable<NamespaceDecl>; |
518 | |
519 | NamespaceDecl *getNextRedeclarationImpl() override; |
520 | NamespaceDecl *getPreviousDeclImpl() override; |
521 | NamespaceDecl *getMostRecentDeclImpl() override; |
522 | |
523 | public: |
524 | friend class ASTDeclReader; |
525 | friend class ASTDeclWriter; |
526 | |
527 | static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, |
528 | bool Inline, SourceLocation StartLoc, |
529 | SourceLocation IdLoc, IdentifierInfo *Id, |
530 | NamespaceDecl *PrevDecl); |
531 | |
532 | static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
533 | |
534 | using redecl_range = redeclarable_base::redecl_range; |
535 | using redecl_iterator = redeclarable_base::redecl_iterator; |
536 | |
537 | using redeclarable_base::redecls_begin; |
538 | using redeclarable_base::redecls_end; |
539 | using redeclarable_base::redecls; |
540 | using redeclarable_base::getPreviousDecl; |
541 | using redeclarable_base::getMostRecentDecl; |
542 | using redeclarable_base::isFirstDecl; |
543 | |
544 | /// Returns true if this is an anonymous namespace declaration. |
545 | /// |
546 | /// For example: |
547 | /// \code |
548 | /// namespace { |
549 | /// ... |
550 | /// }; |
551 | /// \endcode |
552 | /// q.v. C++ [namespace.unnamed] |
553 | bool isAnonymousNamespace() const { |
554 | return !getIdentifier(); |
555 | } |
556 | |
557 | /// Returns true if this is an inline namespace declaration. |
558 | bool isInline() const { |
559 | return AnonOrFirstNamespaceAndInline.getInt(); |
560 | } |
561 | |
562 | /// Set whether this is an inline namespace declaration. |
563 | void setInline(bool Inline) { |
564 | AnonOrFirstNamespaceAndInline.setInt(Inline); |
565 | } |
566 | |
567 | /// Get the original (first) namespace declaration. |
568 | NamespaceDecl *getOriginalNamespace(); |
569 | |
570 | /// Get the original (first) namespace declaration. |
571 | const NamespaceDecl *getOriginalNamespace() const; |
572 | |
573 | /// Return true if this declaration is an original (first) declaration |
574 | /// of the namespace. This is false for non-original (subsequent) namespace |
575 | /// declarations and anonymous namespaces. |
576 | bool isOriginalNamespace() const; |
577 | |
578 | /// Retrieve the anonymous namespace nested inside this namespace, |
579 | /// if any. |
580 | NamespaceDecl *getAnonymousNamespace() const { |
581 | return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); |
582 | } |
583 | |
584 | void setAnonymousNamespace(NamespaceDecl *D) { |
585 | getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); |
586 | } |
587 | |
588 | /// Retrieves the canonical declaration of this namespace. |
589 | NamespaceDecl *getCanonicalDecl() override { |
590 | return getOriginalNamespace(); |
591 | } |
592 | const NamespaceDecl *getCanonicalDecl() const { |
593 | return getOriginalNamespace(); |
594 | } |
595 | |
596 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
597 | return SourceRange(LocStart, RBraceLoc); |
598 | } |
599 | |
600 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
601 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
602 | void setLocStart(SourceLocation L) { LocStart = L; } |
603 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
604 | |
605 | // Implement isa/cast/dyncast/etc. |
606 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
607 | static bool classofKind(Kind K) { return K == Namespace; } |
608 | static DeclContext *castToDeclContext(const NamespaceDecl *D) { |
609 | return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); |
610 | } |
611 | static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { |
612 | return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); |
613 | } |
614 | }; |
615 | |
616 | /// Represent the declaration of a variable (in which case it is |
617 | /// an lvalue) a function (in which case it is a function designator) or |
618 | /// an enum constant. |
619 | class ValueDecl : public NamedDecl { |
620 | QualType DeclType; |
621 | |
622 | void anchor() override; |
623 | |
624 | protected: |
625 | ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, |
626 | DeclarationName N, QualType T) |
627 | : NamedDecl(DK, DC, L, N), DeclType(T) {} |
628 | |
629 | public: |
630 | QualType getType() const { return DeclType; } |
631 | void setType(QualType newType) { DeclType = newType; } |
632 | |
633 | /// Determine whether this symbol is weakly-imported, |
634 | /// or declared with the weak or weak-ref attr. |
635 | bool isWeak() const; |
636 | |
637 | // Implement isa/cast/dyncast/etc. |
638 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
639 | static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } |
640 | }; |
641 | |
642 | /// A struct with extended info about a syntactic |
643 | /// name qualifier, to be used for the case of out-of-line declarations. |
644 | struct QualifierInfo { |
645 | NestedNameSpecifierLoc QualifierLoc; |
646 | |
647 | /// The number of "outer" template parameter lists. |
648 | /// The count includes all of the template parameter lists that were matched |
649 | /// against the template-ids occurring into the NNS and possibly (in the |
650 | /// case of an explicit specialization) a final "template <>". |
651 | unsigned NumTemplParamLists = 0; |
652 | |
653 | /// A new-allocated array of size NumTemplParamLists, |
654 | /// containing pointers to the "outer" template parameter lists. |
655 | /// It includes all of the template parameter lists that were matched |
656 | /// against the template-ids occurring into the NNS and possibly (in the |
657 | /// case of an explicit specialization) a final "template <>". |
658 | TemplateParameterList** TemplParamLists = nullptr; |
659 | |
660 | QualifierInfo() = default; |
661 | QualifierInfo(const QualifierInfo &) = delete; |
662 | QualifierInfo& operator=(const QualifierInfo &) = delete; |
663 | |
664 | /// Sets info about "outer" template parameter lists. |
665 | void setTemplateParameterListsInfo(ASTContext &Context, |
666 | ArrayRef<TemplateParameterList *> TPLists); |
667 | }; |
668 | |
669 | /// Represents a ValueDecl that came out of a declarator. |
670 | /// Contains type source information through TypeSourceInfo. |
671 | class DeclaratorDecl : public ValueDecl { |
672 | // A struct representing a TInfo, a trailing requires-clause and a syntactic |
673 | // qualifier, to be used for the (uncommon) case of out-of-line declarations |
674 | // and constrained function decls. |
675 | struct ExtInfo : public QualifierInfo { |
676 | TypeSourceInfo *TInfo; |
677 | Expr *TrailingRequiresClause = nullptr; |
678 | }; |
679 | |
680 | llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo; |
681 | |
682 | /// The start of the source range for this declaration, |
683 | /// ignoring outer template declarations. |
684 | SourceLocation InnerLocStart; |
685 | |
686 | bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } |
687 | ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } |
688 | const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } |
689 | |
690 | protected: |
691 | DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, |
692 | DeclarationName N, QualType T, TypeSourceInfo *TInfo, |
693 | SourceLocation StartL) |
694 | : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {} |
695 | |
696 | public: |
697 | friend class ASTDeclReader; |
698 | friend class ASTDeclWriter; |
699 | |
700 | TypeSourceInfo *getTypeSourceInfo() const { |
701 | return hasExtInfo() |
702 | ? getExtInfo()->TInfo |
703 | : DeclInfo.get<TypeSourceInfo*>(); |
704 | } |
705 | |
706 | void setTypeSourceInfo(TypeSourceInfo *TI) { |
707 | if (hasExtInfo()) |
708 | getExtInfo()->TInfo = TI; |
709 | else |
710 | DeclInfo = TI; |
711 | } |
712 | |
713 | /// Return start of source range ignoring outer template declarations. |
714 | SourceLocation getInnerLocStart() const { return InnerLocStart; } |
715 | void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } |
716 | |
717 | /// Return start of source range taking into account any outer template |
718 | /// declarations. |
719 | SourceLocation getOuterLocStart() const; |
720 | |
721 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
722 | |
723 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
724 | return getOuterLocStart(); |
725 | } |
726 | |
727 | /// Retrieve the nested-name-specifier that qualifies the name of this |
728 | /// declaration, if it was present in the source. |
729 | NestedNameSpecifier *getQualifier() const { |
730 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
731 | : nullptr; |
732 | } |
733 | |
734 | /// Retrieve the nested-name-specifier (with source-location |
735 | /// information) that qualifies the name of this declaration, if it was |
736 | /// present in the source. |
737 | NestedNameSpecifierLoc getQualifierLoc() const { |
738 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
739 | : NestedNameSpecifierLoc(); |
740 | } |
741 | |
742 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
743 | |
744 | /// \brief Get the constraint-expression introduced by the trailing |
745 | /// requires-clause in the function/member declaration, or null if no |
746 | /// requires-clause was provided. |
747 | Expr *getTrailingRequiresClause() { |
748 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
749 | : nullptr; |
750 | } |
751 | |
752 | const Expr *getTrailingRequiresClause() const { |
753 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
754 | : nullptr; |
755 | } |
756 | |
757 | void setTrailingRequiresClause(Expr *TrailingRequiresClause); |
758 | |
759 | unsigned getNumTemplateParameterLists() const { |
760 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
761 | } |
762 | |
763 | TemplateParameterList *getTemplateParameterList(unsigned index) const { |
764 | assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast< void> (0) : __assert_fail ("index < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 764, __PRETTY_FUNCTION__)); |
765 | return getExtInfo()->TemplParamLists[index]; |
766 | } |
767 | |
768 | void setTemplateParameterListsInfo(ASTContext &Context, |
769 | ArrayRef<TemplateParameterList *> TPLists); |
770 | |
771 | SourceLocation getTypeSpecStartLoc() const; |
772 | SourceLocation getTypeSpecEndLoc() const; |
773 | |
774 | // Implement isa/cast/dyncast/etc. |
775 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
776 | static bool classofKind(Kind K) { |
777 | return K >= firstDeclarator && K <= lastDeclarator; |
778 | } |
779 | }; |
780 | |
781 | /// Structure used to store a statement, the constant value to |
782 | /// which it was evaluated (if any), and whether or not the statement |
783 | /// is an integral constant expression (if known). |
784 | struct EvaluatedStmt { |
785 | /// Whether this statement was already evaluated. |
786 | bool WasEvaluated : 1; |
787 | |
788 | /// Whether this statement is being evaluated. |
789 | bool IsEvaluating : 1; |
790 | |
791 | /// Whether we already checked whether this statement was an |
792 | /// integral constant expression. |
793 | bool CheckedICE : 1; |
794 | |
795 | /// Whether we are checking whether this statement is an |
796 | /// integral constant expression. |
797 | bool CheckingICE : 1; |
798 | |
799 | /// Whether this statement is an integral constant expression, |
800 | /// or in C++11, whether the statement is a constant expression. Only |
801 | /// valid if CheckedICE is true. |
802 | bool IsICE : 1; |
803 | |
804 | /// Whether this variable is known to have constant destruction. That is, |
805 | /// whether running the destructor on the initial value is a side-effect |
806 | /// (and doesn't inspect any state that might have changed during program |
807 | /// execution). This is currently only computed if the destructor is |
808 | /// non-trivial. |
809 | bool HasConstantDestruction : 1; |
810 | |
811 | Stmt *Value; |
812 | APValue Evaluated; |
813 | |
814 | EvaluatedStmt() |
815 | : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), |
816 | CheckingICE(false), IsICE(false), HasConstantDestruction(false) {} |
817 | }; |
818 | |
819 | /// Represents a variable declaration or definition. |
820 | class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { |
821 | public: |
822 | /// Initialization styles. |
823 | enum InitializationStyle { |
824 | /// C-style initialization with assignment |
825 | CInit, |
826 | |
827 | /// Call-style initialization (C++98) |
828 | CallInit, |
829 | |
830 | /// Direct list-initialization (C++11) |
831 | ListInit |
832 | }; |
833 | |
834 | /// Kinds of thread-local storage. |
835 | enum TLSKind { |
836 | /// Not a TLS variable. |
837 | TLS_None, |
838 | |
839 | /// TLS with a known-constant initializer. |
840 | TLS_Static, |
841 | |
842 | /// TLS with a dynamic initializer. |
843 | TLS_Dynamic |
844 | }; |
845 | |
846 | /// Return the string used to specify the storage class \p SC. |
847 | /// |
848 | /// It is illegal to call this function with SC == None. |
849 | static const char *getStorageClassSpecifierString(StorageClass SC); |
850 | |
851 | protected: |
852 | // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we |
853 | // have allocated the auxiliary struct of information there. |
854 | // |
855 | // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for |
856 | // this as *many* VarDecls are ParmVarDecls that don't have default |
857 | // arguments. We could save some space by moving this pointer union to be |
858 | // allocated in trailing space when necessary. |
859 | using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>; |
860 | |
861 | /// The initializer for this variable or, for a ParmVarDecl, the |
862 | /// C++ default argument. |
863 | mutable InitType Init; |
864 | |
865 | private: |
866 | friend class ASTDeclReader; |
867 | friend class ASTNodeImporter; |
868 | friend class StmtIteratorBase; |
869 | |
870 | class VarDeclBitfields { |
871 | friend class ASTDeclReader; |
872 | friend class VarDecl; |
873 | |
874 | unsigned SClass : 3; |
875 | unsigned TSCSpec : 2; |
876 | unsigned InitStyle : 2; |
877 | |
878 | /// Whether this variable is an ARC pseudo-__strong variable; see |
879 | /// isARCPseudoStrong() for details. |
880 | unsigned ARCPseudoStrong : 1; |
881 | }; |
882 | enum { NumVarDeclBits = 8 }; |
883 | |
884 | protected: |
885 | enum { NumParameterIndexBits = 8 }; |
886 | |
887 | enum DefaultArgKind { |
888 | DAK_None, |
889 | DAK_Unparsed, |
890 | DAK_Uninstantiated, |
891 | DAK_Normal |
892 | }; |
893 | |
894 | enum { NumScopeDepthOrObjCQualsBits = 7 }; |
895 | |
896 | class ParmVarDeclBitfields { |
897 | friend class ASTDeclReader; |
898 | friend class ParmVarDecl; |
899 | |
900 | unsigned : NumVarDeclBits; |
901 | |
902 | /// Whether this parameter inherits a default argument from a |
903 | /// prior declaration. |
904 | unsigned HasInheritedDefaultArg : 1; |
905 | |
906 | /// Describes the kind of default argument for this parameter. By default |
907 | /// this is none. If this is normal, then the default argument is stored in |
908 | /// the \c VarDecl initializer expression unless we were unable to parse |
909 | /// (even an invalid) expression for the default argument. |
910 | unsigned DefaultArgKind : 2; |
911 | |
912 | /// Whether this parameter undergoes K&R argument promotion. |
913 | unsigned IsKNRPromoted : 1; |
914 | |
915 | /// Whether this parameter is an ObjC method parameter or not. |
916 | unsigned IsObjCMethodParam : 1; |
917 | |
918 | /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. |
919 | /// Otherwise, the number of function parameter scopes enclosing |
920 | /// the function parameter scope in which this parameter was |
921 | /// declared. |
922 | unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits; |
923 | |
924 | /// The number of parameters preceding this parameter in the |
925 | /// function parameter scope in which it was declared. |
926 | unsigned ParameterIndex : NumParameterIndexBits; |
927 | }; |
928 | |
929 | class NonParmVarDeclBitfields { |
930 | friend class ASTDeclReader; |
931 | friend class ImplicitParamDecl; |
932 | friend class VarDecl; |
933 | |
934 | unsigned : NumVarDeclBits; |
935 | |
936 | // FIXME: We need something similar to CXXRecordDecl::DefinitionData. |
937 | /// Whether this variable is a definition which was demoted due to |
938 | /// module merge. |
939 | unsigned IsThisDeclarationADemotedDefinition : 1; |
940 | |
941 | /// Whether this variable is the exception variable in a C++ catch |
942 | /// or an Objective-C @catch statement. |
943 | unsigned ExceptionVar : 1; |
944 | |
945 | /// Whether this local variable could be allocated in the return |
946 | /// slot of its function, enabling the named return value optimization |
947 | /// (NRVO). |
948 | unsigned NRVOVariable : 1; |
949 | |
950 | /// Whether this variable is the for-range-declaration in a C++0x |
951 | /// for-range statement. |
952 | unsigned CXXForRangeDecl : 1; |
953 | |
954 | /// Whether this variable is the for-in loop declaration in Objective-C. |
955 | unsigned ObjCForDecl : 1; |
956 | |
957 | /// Whether this variable is (C++1z) inline. |
958 | unsigned IsInline : 1; |
959 | |
960 | /// Whether this variable has (C++1z) inline explicitly specified. |
961 | unsigned IsInlineSpecified : 1; |
962 | |
963 | /// Whether this variable is (C++0x) constexpr. |
964 | unsigned IsConstexpr : 1; |
965 | |
966 | /// Whether this variable is the implicit variable for a lambda |
967 | /// init-capture. |
968 | unsigned IsInitCapture : 1; |
969 | |
970 | /// Whether this local extern variable's previous declaration was |
971 | /// declared in the same block scope. This controls whether we should merge |
972 | /// the type of this declaration with its previous declaration. |
973 | unsigned PreviousDeclInSameBlockScope : 1; |
974 | |
975 | /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or |
976 | /// something else. |
977 | unsigned ImplicitParamKind : 3; |
978 | |
979 | unsigned EscapingByref : 1; |
980 | }; |
981 | |
982 | union { |
983 | unsigned AllBits; |
984 | VarDeclBitfields VarDeclBits; |
985 | ParmVarDeclBitfields ParmVarDeclBits; |
986 | NonParmVarDeclBitfields NonParmVarDeclBits; |
987 | }; |
988 | |
989 | VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
990 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
991 | TypeSourceInfo *TInfo, StorageClass SC); |
992 | |
993 | using redeclarable_base = Redeclarable<VarDecl>; |
994 | |
995 | VarDecl *getNextRedeclarationImpl() override { |
996 | return getNextRedeclaration(); |
997 | } |
998 | |
999 | VarDecl *getPreviousDeclImpl() override { |
1000 | return getPreviousDecl(); |
1001 | } |
1002 | |
1003 | VarDecl *getMostRecentDeclImpl() override { |
1004 | return getMostRecentDecl(); |
1005 | } |
1006 | |
1007 | public: |
1008 | using redecl_range = redeclarable_base::redecl_range; |
1009 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1010 | |
1011 | using redeclarable_base::redecls_begin; |
1012 | using redeclarable_base::redecls_end; |
1013 | using redeclarable_base::redecls; |
1014 | using redeclarable_base::getPreviousDecl; |
1015 | using redeclarable_base::getMostRecentDecl; |
1016 | using redeclarable_base::isFirstDecl; |
1017 | |
1018 | static VarDecl *Create(ASTContext &C, DeclContext *DC, |
1019 | SourceLocation StartLoc, SourceLocation IdLoc, |
1020 | IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, |
1021 | StorageClass S); |
1022 | |
1023 | static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1024 | |
1025 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1026 | |
1027 | /// Returns the storage class as written in the source. For the |
1028 | /// computed linkage of symbol, see getLinkage. |
1029 | StorageClass getStorageClass() const { |
1030 | return (StorageClass) VarDeclBits.SClass; |
1031 | } |
1032 | void setStorageClass(StorageClass SC); |
1033 | |
1034 | void setTSCSpec(ThreadStorageClassSpecifier TSC) { |
1035 | VarDeclBits.TSCSpec = TSC; |
1036 | assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast <void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1036, __PRETTY_FUNCTION__)); |
1037 | } |
1038 | ThreadStorageClassSpecifier getTSCSpec() const { |
1039 | return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); |
1040 | } |
1041 | TLSKind getTLSKind() const; |
1042 | |
1043 | /// Returns true if a variable with function scope is a non-static local |
1044 | /// variable. |
1045 | bool hasLocalStorage() const { |
1046 | if (getStorageClass() == SC_None) { |
1047 | // OpenCL v1.2 s6.5.3: The __constant or constant address space name is |
1048 | // used to describe variables allocated in global memory and which are |
1049 | // accessed inside a kernel(s) as read-only variables. As such, variables |
1050 | // in constant address space cannot have local storage. |
1051 | if (getType().getAddressSpace() == LangAS::opencl_constant) |
1052 | return false; |
1053 | // Second check is for C++11 [dcl.stc]p4. |
1054 | return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; |
1055 | } |
1056 | |
1057 | // Global Named Register (GNU extension) |
1058 | if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) |
1059 | return false; |
1060 | |
1061 | // Return true for: Auto, Register. |
1062 | // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. |
1063 | |
1064 | return getStorageClass() >= SC_Auto; |
1065 | } |
1066 | |
1067 | /// Returns true if a variable with function scope is a static local |
1068 | /// variable. |
1069 | bool isStaticLocal() const { |
1070 | return (getStorageClass() == SC_Static || |
1071 | // C++11 [dcl.stc]p4 |
1072 | (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local)) |
1073 | && !isFileVarDecl(); |
1074 | } |
1075 | |
1076 | /// Returns true if a variable has extern or __private_extern__ |
1077 | /// storage. |
1078 | bool hasExternalStorage() const { |
1079 | return getStorageClass() == SC_Extern || |
1080 | getStorageClass() == SC_PrivateExtern; |
1081 | } |
1082 | |
1083 | /// Returns true for all variables that do not have local storage. |
1084 | /// |
1085 | /// This includes all global variables as well as static variables declared |
1086 | /// within a function. |
1087 | bool hasGlobalStorage() const { return !hasLocalStorage(); } |
1088 | |
1089 | /// Get the storage duration of this variable, per C++ [basic.stc]. |
1090 | StorageDuration getStorageDuration() const { |
1091 | return hasLocalStorage() ? SD_Automatic : |
1092 | getTSCSpec() ? SD_Thread : SD_Static; |
1093 | } |
1094 | |
1095 | /// Compute the language linkage. |
1096 | LanguageLinkage getLanguageLinkage() const; |
1097 | |
1098 | /// Determines whether this variable is a variable with external, C linkage. |
1099 | bool isExternC() const; |
1100 | |
1101 | /// Determines whether this variable's context is, or is nested within, |
1102 | /// a C++ extern "C" linkage spec. |
1103 | bool isInExternCContext() const; |
1104 | |
1105 | /// Determines whether this variable's context is, or is nested within, |
1106 | /// a C++ extern "C++" linkage spec. |
1107 | bool isInExternCXXContext() const; |
1108 | |
1109 | /// Returns true for local variable declarations other than parameters. |
1110 | /// Note that this includes static variables inside of functions. It also |
1111 | /// includes variables inside blocks. |
1112 | /// |
1113 | /// void foo() { int x; static int y; extern int z; } |
1114 | bool isLocalVarDecl() const { |
1115 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1116 | return false; |
1117 | if (const DeclContext *DC = getLexicalDeclContext()) |
1118 | return DC->getRedeclContext()->isFunctionOrMethod(); |
1119 | return false; |
1120 | } |
1121 | |
1122 | /// Similar to isLocalVarDecl but also includes parameters. |
1123 | bool isLocalVarDeclOrParm() const { |
1124 | return isLocalVarDecl() || getKind() == Decl::ParmVar; |
1125 | } |
1126 | |
1127 | /// Similar to isLocalVarDecl, but excludes variables declared in blocks. |
1128 | bool isFunctionOrMethodVarDecl() const { |
1129 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1130 | return false; |
1131 | const DeclContext *DC = getLexicalDeclContext()->getRedeclContext(); |
1132 | return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; |
1133 | } |
1134 | |
1135 | /// Determines whether this is a static data member. |
1136 | /// |
1137 | /// This will only be true in C++, and applies to, e.g., the |
1138 | /// variable 'x' in: |
1139 | /// \code |
1140 | /// struct S { |
1141 | /// static int x; |
1142 | /// }; |
1143 | /// \endcode |
1144 | bool isStaticDataMember() const { |
1145 | // If it wasn't static, it would be a FieldDecl. |
1146 | return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); |
1147 | } |
1148 | |
1149 | VarDecl *getCanonicalDecl() override; |
1150 | const VarDecl *getCanonicalDecl() const { |
1151 | return const_cast<VarDecl*>(this)->getCanonicalDecl(); |
1152 | } |
1153 | |
1154 | enum DefinitionKind { |
1155 | /// This declaration is only a declaration. |
1156 | DeclarationOnly, |
1157 | |
1158 | /// This declaration is a tentative definition. |
1159 | TentativeDefinition, |
1160 | |
1161 | /// This declaration is definitely a definition. |
1162 | Definition |
1163 | }; |
1164 | |
1165 | /// Check whether this declaration is a definition. If this could be |
1166 | /// a tentative definition (in C), don't check whether there's an overriding |
1167 | /// definition. |
1168 | DefinitionKind isThisDeclarationADefinition(ASTContext &) const; |
1169 | DefinitionKind isThisDeclarationADefinition() const { |
1170 | return isThisDeclarationADefinition(getASTContext()); |
1171 | } |
1172 | |
1173 | /// Check whether this variable is defined in this translation unit. |
1174 | DefinitionKind hasDefinition(ASTContext &) const; |
1175 | DefinitionKind hasDefinition() const { |
1176 | return hasDefinition(getASTContext()); |
1177 | } |
1178 | |
1179 | /// Get the tentative definition that acts as the real definition in a TU. |
1180 | /// Returns null if there is a proper definition available. |
1181 | VarDecl *getActingDefinition(); |
1182 | const VarDecl *getActingDefinition() const { |
1183 | return const_cast<VarDecl*>(this)->getActingDefinition(); |
1184 | } |
1185 | |
1186 | /// Get the real (not just tentative) definition for this declaration. |
1187 | VarDecl *getDefinition(ASTContext &); |
1188 | const VarDecl *getDefinition(ASTContext &C) const { |
1189 | return const_cast<VarDecl*>(this)->getDefinition(C); |
1190 | } |
1191 | VarDecl *getDefinition() { |
1192 | return getDefinition(getASTContext()); |
1193 | } |
1194 | const VarDecl *getDefinition() const { |
1195 | return const_cast<VarDecl*>(this)->getDefinition(); |
1196 | } |
1197 | |
1198 | /// Determine whether this is or was instantiated from an out-of-line |
1199 | /// definition of a static data member. |
1200 | bool isOutOfLine() const override; |
1201 | |
1202 | /// Returns true for file scoped variable declaration. |
1203 | bool isFileVarDecl() const { |
1204 | Kind K = getKind(); |
1205 | if (K == ParmVar || K == ImplicitParam) |
1206 | return false; |
1207 | |
1208 | if (getLexicalDeclContext()->getRedeclContext()->isFileContext()) |
1209 | return true; |
1210 | |
1211 | if (isStaticDataMember()) |
1212 | return true; |
1213 | |
1214 | return false; |
1215 | } |
1216 | |
1217 | /// Get the initializer for this variable, no matter which |
1218 | /// declaration it is attached to. |
1219 | const Expr *getAnyInitializer() const { |
1220 | const VarDecl *D; |
1221 | return getAnyInitializer(D); |
1222 | } |
1223 | |
1224 | /// Get the initializer for this variable, no matter which |
1225 | /// declaration it is attached to. Also get that declaration. |
1226 | const Expr *getAnyInitializer(const VarDecl *&D) const; |
1227 | |
1228 | bool hasInit() const; |
1229 | const Expr *getInit() const { |
1230 | return const_cast<VarDecl *>(this)->getInit(); |
1231 | } |
1232 | Expr *getInit(); |
1233 | |
1234 | /// Retrieve the address of the initializer expression. |
1235 | Stmt **getInitAddress(); |
1236 | |
1237 | void setInit(Expr *I); |
1238 | |
1239 | /// Get the initializing declaration of this variable, if any. This is |
1240 | /// usually the definition, except that for a static data member it can be |
1241 | /// the in-class declaration. |
1242 | VarDecl *getInitializingDeclaration(); |
1243 | const VarDecl *getInitializingDeclaration() const { |
1244 | return const_cast<VarDecl *>(this)->getInitializingDeclaration(); |
1245 | } |
1246 | |
1247 | /// Determine whether this variable's value might be usable in a |
1248 | /// constant expression, according to the relevant language standard. |
1249 | /// This only checks properties of the declaration, and does not check |
1250 | /// whether the initializer is in fact a constant expression. |
1251 | bool mightBeUsableInConstantExpressions(ASTContext &C) const; |
1252 | |
1253 | /// Determine whether this variable's value can be used in a |
1254 | /// constant expression, according to the relevant language standard, |
1255 | /// including checking whether it was initialized by a constant expression. |
1256 | bool isUsableInConstantExpressions(ASTContext &C) const; |
1257 | |
1258 | EvaluatedStmt *ensureEvaluatedStmt() const; |
1259 | |
1260 | /// Attempt to evaluate the value of the initializer attached to this |
1261 | /// declaration, and produce notes explaining why it cannot be evaluated or is |
1262 | /// not a constant expression. Returns a pointer to the value if evaluation |
1263 | /// succeeded, 0 otherwise. |
1264 | APValue *evaluateValue() const; |
1265 | APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1266 | |
1267 | /// Return the already-evaluated value of this variable's |
1268 | /// initializer, or NULL if the value is not yet known. Returns pointer |
1269 | /// to untyped APValue if the value could not be evaluated. |
1270 | APValue *getEvaluatedValue() const; |
1271 | |
1272 | /// Evaluate the destruction of this variable to determine if it constitutes |
1273 | /// constant destruction. |
1274 | /// |
1275 | /// \pre isInitICE() |
1276 | /// \return \c true if this variable has constant destruction, \c false if |
1277 | /// not. |
1278 | bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1279 | |
1280 | /// Determines whether it is already known whether the |
1281 | /// initializer is an integral constant expression or not. |
1282 | bool isInitKnownICE() const; |
1283 | |
1284 | /// Determines whether the initializer is an integral constant |
1285 | /// expression, or in C++11, whether the initializer is a constant |
1286 | /// expression. |
1287 | /// |
1288 | /// \pre isInitKnownICE() |
1289 | bool isInitICE() const; |
1290 | |
1291 | /// Determine whether the value of the initializer attached to this |
1292 | /// declaration is an integral constant expression. |
1293 | bool checkInitIsICE() const; |
1294 | |
1295 | void setInitStyle(InitializationStyle Style) { |
1296 | VarDeclBits.InitStyle = Style; |
1297 | } |
1298 | |
1299 | /// The style of initialization for this declaration. |
1300 | /// |
1301 | /// C-style initialization is "int x = 1;". Call-style initialization is |
1302 | /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be |
1303 | /// the expression inside the parens or a "ClassType(a,b,c)" class constructor |
1304 | /// expression for class types. List-style initialization is C++11 syntax, |
1305 | /// e.g. "int x{1};". Clients can distinguish between different forms of |
1306 | /// initialization by checking this value. In particular, "int x = {1};" is |
1307 | /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the |
1308 | /// Init expression in all three cases is an InitListExpr. |
1309 | InitializationStyle getInitStyle() const { |
1310 | return static_cast<InitializationStyle>(VarDeclBits.InitStyle); |
1311 | } |
1312 | |
1313 | /// Whether the initializer is a direct-initializer (list or call). |
1314 | bool isDirectInit() const { |
1315 | return getInitStyle() != CInit; |
1316 | } |
1317 | |
1318 | /// If this definition should pretend to be a declaration. |
1319 | bool isThisDeclarationADemotedDefinition() const { |
1320 | return isa<ParmVarDecl>(this) ? false : |
1321 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition; |
1322 | } |
1323 | |
1324 | /// This is a definition which should be demoted to a declaration. |
1325 | /// |
1326 | /// In some cases (mostly module merging) we can end up with two visible |
1327 | /// definitions one of which needs to be demoted to a declaration to keep |
1328 | /// the AST invariants. |
1329 | void demoteThisDefinitionToDeclaration() { |
1330 | assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!" ) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1330, __PRETTY_FUNCTION__)); |
1331 | assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1331, __PRETTY_FUNCTION__)); |
1332 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1; |
1333 | } |
1334 | |
1335 | /// Determine whether this variable is the exception variable in a |
1336 | /// C++ catch statememt or an Objective-C \@catch statement. |
1337 | bool isExceptionVariable() const { |
1338 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar; |
1339 | } |
1340 | void setExceptionVariable(bool EV) { |
1341 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1341, __PRETTY_FUNCTION__)); |
1342 | NonParmVarDeclBits.ExceptionVar = EV; |
1343 | } |
1344 | |
1345 | /// Determine whether this local variable can be used with the named |
1346 | /// return value optimization (NRVO). |
1347 | /// |
1348 | /// The named return value optimization (NRVO) works by marking certain |
1349 | /// non-volatile local variables of class type as NRVO objects. These |
1350 | /// locals can be allocated within the return slot of their containing |
1351 | /// function, in which case there is no need to copy the object to the |
1352 | /// return slot when returning from the function. Within the function body, |
1353 | /// each return that returns the NRVO object will have this variable as its |
1354 | /// NRVO candidate. |
1355 | bool isNRVOVariable() const { |
1356 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable; |
1357 | } |
1358 | void setNRVOVariable(bool NRVO) { |
1359 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1359, __PRETTY_FUNCTION__)); |
1360 | NonParmVarDeclBits.NRVOVariable = NRVO; |
1361 | } |
1362 | |
1363 | /// Determine whether this variable is the for-range-declaration in |
1364 | /// a C++0x for-range statement. |
1365 | bool isCXXForRangeDecl() const { |
1366 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl; |
1367 | } |
1368 | void setCXXForRangeDecl(bool FRD) { |
1369 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1369, __PRETTY_FUNCTION__)); |
1370 | NonParmVarDeclBits.CXXForRangeDecl = FRD; |
1371 | } |
1372 | |
1373 | /// Determine whether this variable is a for-loop declaration for a |
1374 | /// for-in statement in Objective-C. |
1375 | bool isObjCForDecl() const { |
1376 | return NonParmVarDeclBits.ObjCForDecl; |
1377 | } |
1378 | |
1379 | void setObjCForDecl(bool FRD) { |
1380 | NonParmVarDeclBits.ObjCForDecl = FRD; |
1381 | } |
1382 | |
1383 | /// Determine whether this variable is an ARC pseudo-__strong variable. A |
1384 | /// pseudo-__strong variable has a __strong-qualified type but does not |
1385 | /// actually retain the object written into it. Generally such variables are |
1386 | /// also 'const' for safety. There are 3 cases where this will be set, 1) if |
1387 | /// the variable is annotated with the objc_externally_retained attribute, 2) |
1388 | /// if its 'self' in a non-init method, or 3) if its the variable in an for-in |
1389 | /// loop. |
1390 | bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; } |
1391 | void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; } |
1392 | |
1393 | /// Whether this variable is (C++1z) inline. |
1394 | bool isInline() const { |
1395 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline; |
1396 | } |
1397 | bool isInlineSpecified() const { |
1398 | return isa<ParmVarDecl>(this) ? false |
1399 | : NonParmVarDeclBits.IsInlineSpecified; |
1400 | } |
1401 | void setInlineSpecified() { |
1402 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1402, __PRETTY_FUNCTION__)); |
1403 | NonParmVarDeclBits.IsInline = true; |
1404 | NonParmVarDeclBits.IsInlineSpecified = true; |
1405 | } |
1406 | void setImplicitlyInline() { |
1407 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1407, __PRETTY_FUNCTION__)); |
1408 | NonParmVarDeclBits.IsInline = true; |
1409 | } |
1410 | |
1411 | /// Whether this variable is (C++11) constexpr. |
1412 | bool isConstexpr() const { |
1413 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr; |
1414 | } |
1415 | void setConstexpr(bool IC) { |
1416 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1416, __PRETTY_FUNCTION__)); |
1417 | NonParmVarDeclBits.IsConstexpr = IC; |
1418 | } |
1419 | |
1420 | /// Whether this variable is the implicit variable for a lambda init-capture. |
1421 | bool isInitCapture() const { |
1422 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture; |
1423 | } |
1424 | void setInitCapture(bool IC) { |
1425 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1425, __PRETTY_FUNCTION__)); |
1426 | NonParmVarDeclBits.IsInitCapture = IC; |
1427 | } |
1428 | |
1429 | /// Determine whether this variable is actually a function parameter pack or |
1430 | /// init-capture pack. |
1431 | bool isParameterPack() const; |
1432 | |
1433 | /// Whether this local extern variable declaration's previous declaration |
1434 | /// was declared in the same block scope. Only correct in C++. |
1435 | bool isPreviousDeclInSameBlockScope() const { |
1436 | return isa<ParmVarDecl>(this) |
1437 | ? false |
1438 | : NonParmVarDeclBits.PreviousDeclInSameBlockScope; |
1439 | } |
1440 | void setPreviousDeclInSameBlockScope(bool Same) { |
1441 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1441, __PRETTY_FUNCTION__)); |
1442 | NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same; |
1443 | } |
1444 | |
1445 | /// Indicates the capture is a __block variable that is captured by a block |
1446 | /// that can potentially escape (a block for which BlockDecl::doesNotEscape |
1447 | /// returns false). |
1448 | bool isEscapingByref() const; |
1449 | |
1450 | /// Indicates the capture is a __block variable that is never captured by an |
1451 | /// escaping block. |
1452 | bool isNonEscapingByref() const; |
1453 | |
1454 | void setEscapingByref() { |
1455 | NonParmVarDeclBits.EscapingByref = true; |
1456 | } |
1457 | |
1458 | /// Retrieve the variable declaration from which this variable could |
1459 | /// be instantiated, if it is an instantiation (rather than a non-template). |
1460 | VarDecl *getTemplateInstantiationPattern() const; |
1461 | |
1462 | /// If this variable is an instantiated static data member of a |
1463 | /// class template specialization, returns the templated static data member |
1464 | /// from which it was instantiated. |
1465 | VarDecl *getInstantiatedFromStaticDataMember() const; |
1466 | |
1467 | /// If this variable is an instantiation of a variable template or a |
1468 | /// static data member of a class template, determine what kind of |
1469 | /// template specialization or instantiation this is. |
1470 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1471 | |
1472 | /// Get the template specialization kind of this variable for the purposes of |
1473 | /// template instantiation. This differs from getTemplateSpecializationKind() |
1474 | /// for an instantiation of a class-scope explicit specialization. |
1475 | TemplateSpecializationKind |
1476 | getTemplateSpecializationKindForInstantiation() const; |
1477 | |
1478 | /// If this variable is an instantiation of a variable template or a |
1479 | /// static data member of a class template, determine its point of |
1480 | /// instantiation. |
1481 | SourceLocation getPointOfInstantiation() const; |
1482 | |
1483 | /// If this variable is an instantiation of a static data member of a |
1484 | /// class template specialization, retrieves the member specialization |
1485 | /// information. |
1486 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1487 | |
1488 | /// For a static data member that was instantiated from a static |
1489 | /// data member of a class template, set the template specialiation kind. |
1490 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
1491 | SourceLocation PointOfInstantiation = SourceLocation()); |
1492 | |
1493 | /// Specify that this variable is an instantiation of the |
1494 | /// static data member VD. |
1495 | void setInstantiationOfStaticDataMember(VarDecl *VD, |
1496 | TemplateSpecializationKind TSK); |
1497 | |
1498 | /// Retrieves the variable template that is described by this |
1499 | /// variable declaration. |
1500 | /// |
1501 | /// Every variable template is represented as a VarTemplateDecl and a |
1502 | /// VarDecl. The former contains template properties (such as |
1503 | /// the template parameter lists) while the latter contains the |
1504 | /// actual description of the template's |
1505 | /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the |
1506 | /// VarDecl that from a VarTemplateDecl, while |
1507 | /// getDescribedVarTemplate() retrieves the VarTemplateDecl from |
1508 | /// a VarDecl. |
1509 | VarTemplateDecl *getDescribedVarTemplate() const; |
1510 | |
1511 | void setDescribedVarTemplate(VarTemplateDecl *Template); |
1512 | |
1513 | // Is this variable known to have a definition somewhere in the complete |
1514 | // program? This may be true even if the declaration has internal linkage and |
1515 | // has no definition within this source file. |
1516 | bool isKnownToBeDefined() const; |
1517 | |
1518 | /// Is destruction of this variable entirely suppressed? If so, the variable |
1519 | /// need not have a usable destructor at all. |
1520 | bool isNoDestroy(const ASTContext &) const; |
1521 | |
1522 | /// Would the destruction of this variable have any effect, and if so, what |
1523 | /// kind? |
1524 | QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const; |
1525 | |
1526 | // Implement isa/cast/dyncast/etc. |
1527 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1528 | static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } |
1529 | }; |
1530 | |
1531 | class ImplicitParamDecl : public VarDecl { |
1532 | void anchor() override; |
1533 | |
1534 | public: |
1535 | /// Defines the kind of the implicit parameter: is this an implicit parameter |
1536 | /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured |
1537 | /// context or something else. |
1538 | enum ImplicitParamKind : unsigned { |
1539 | /// Parameter for Objective-C 'self' argument |
1540 | ObjCSelf, |
1541 | |
1542 | /// Parameter for Objective-C '_cmd' argument |
1543 | ObjCCmd, |
1544 | |
1545 | /// Parameter for C++ 'this' argument |
1546 | CXXThis, |
1547 | |
1548 | /// Parameter for C++ virtual table pointers |
1549 | CXXVTT, |
1550 | |
1551 | /// Parameter for captured context |
1552 | CapturedContext, |
1553 | |
1554 | /// Other implicit parameter |
1555 | Other, |
1556 | }; |
1557 | |
1558 | /// Create implicit parameter. |
1559 | static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, |
1560 | SourceLocation IdLoc, IdentifierInfo *Id, |
1561 | QualType T, ImplicitParamKind ParamKind); |
1562 | static ImplicitParamDecl *Create(ASTContext &C, QualType T, |
1563 | ImplicitParamKind ParamKind); |
1564 | |
1565 | static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1566 | |
1567 | ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, |
1568 | IdentifierInfo *Id, QualType Type, |
1569 | ImplicitParamKind ParamKind) |
1570 | : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type, |
1571 | /*TInfo=*/nullptr, SC_None) { |
1572 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1573 | setImplicit(); |
1574 | } |
1575 | |
1576 | ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind) |
1577 | : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(), |
1578 | SourceLocation(), /*Id=*/nullptr, Type, |
1579 | /*TInfo=*/nullptr, SC_None) { |
1580 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1581 | setImplicit(); |
1582 | } |
1583 | |
1584 | /// Returns the implicit parameter kind. |
1585 | ImplicitParamKind getParameterKind() const { |
1586 | return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind); |
1587 | } |
1588 | |
1589 | // Implement isa/cast/dyncast/etc. |
1590 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1591 | static bool classofKind(Kind K) { return K == ImplicitParam; } |
1592 | }; |
1593 | |
1594 | /// Represents a parameter to a function. |
1595 | class ParmVarDecl : public VarDecl { |
1596 | public: |
1597 | enum { MaxFunctionScopeDepth = 255 }; |
1598 | enum { MaxFunctionScopeIndex = 255 }; |
1599 | |
1600 | protected: |
1601 | ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1602 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1603 | TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg) |
1604 | : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) { |
1605 | assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast <void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1605, __PRETTY_FUNCTION__)); |
1606 | assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast< void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1606, __PRETTY_FUNCTION__)); |
1607 | assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void > (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1607, __PRETTY_FUNCTION__)); |
1608 | assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast< void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1608, __PRETTY_FUNCTION__)); |
1609 | setDefaultArg(DefArg); |
1610 | } |
1611 | |
1612 | public: |
1613 | static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, |
1614 | SourceLocation StartLoc, |
1615 | SourceLocation IdLoc, IdentifierInfo *Id, |
1616 | QualType T, TypeSourceInfo *TInfo, |
1617 | StorageClass S, Expr *DefArg); |
1618 | |
1619 | static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1620 | |
1621 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1622 | |
1623 | void setObjCMethodScopeInfo(unsigned parameterIndex) { |
1624 | ParmVarDeclBits.IsObjCMethodParam = true; |
1625 | setParameterIndex(parameterIndex); |
1626 | } |
1627 | |
1628 | void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { |
1629 | assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void> (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1629, __PRETTY_FUNCTION__)); |
1630 | |
1631 | ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; |
1632 | assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1633, __PRETTY_FUNCTION__)) |
1633 | && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1633, __PRETTY_FUNCTION__)); |
1634 | |
1635 | setParameterIndex(parameterIndex); |
1636 | } |
1637 | |
1638 | bool isObjCMethodParameter() const { |
1639 | return ParmVarDeclBits.IsObjCMethodParam; |
1640 | } |
1641 | |
1642 | unsigned getFunctionScopeDepth() const { |
1643 | if (ParmVarDeclBits.IsObjCMethodParam) return 0; |
1644 | return ParmVarDeclBits.ScopeDepthOrObjCQuals; |
1645 | } |
1646 | |
1647 | static constexpr unsigned getMaxFunctionScopeDepth() { |
1648 | return (1u << NumScopeDepthOrObjCQualsBits) - 1; |
1649 | } |
1650 | |
1651 | /// Returns the index of this parameter in its prototype or method scope. |
1652 | unsigned getFunctionScopeIndex() const { |
1653 | return getParameterIndex(); |
1654 | } |
1655 | |
1656 | ObjCDeclQualifier getObjCDeclQualifier() const { |
1657 | if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; |
1658 | return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); |
1659 | } |
1660 | void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { |
1661 | assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1661, __PRETTY_FUNCTION__)); |
1662 | ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; |
1663 | } |
1664 | |
1665 | /// True if the value passed to this parameter must undergo |
1666 | /// K&R-style default argument promotion: |
1667 | /// |
1668 | /// C99 6.5.2.2. |
1669 | /// If the expression that denotes the called function has a type |
1670 | /// that does not include a prototype, the integer promotions are |
1671 | /// performed on each argument, and arguments that have type float |
1672 | /// are promoted to double. |
1673 | bool isKNRPromoted() const { |
1674 | return ParmVarDeclBits.IsKNRPromoted; |
1675 | } |
1676 | void setKNRPromoted(bool promoted) { |
1677 | ParmVarDeclBits.IsKNRPromoted = promoted; |
1678 | } |
1679 | |
1680 | Expr *getDefaultArg(); |
1681 | const Expr *getDefaultArg() const { |
1682 | return const_cast<ParmVarDecl *>(this)->getDefaultArg(); |
1683 | } |
1684 | |
1685 | void setDefaultArg(Expr *defarg); |
1686 | |
1687 | /// Retrieve the source range that covers the entire default |
1688 | /// argument. |
1689 | SourceRange getDefaultArgRange() const; |
1690 | void setUninstantiatedDefaultArg(Expr *arg); |
1691 | Expr *getUninstantiatedDefaultArg(); |
1692 | const Expr *getUninstantiatedDefaultArg() const { |
1693 | return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg(); |
1694 | } |
1695 | |
1696 | /// Determines whether this parameter has a default argument, |
1697 | /// either parsed or not. |
1698 | bool hasDefaultArg() const; |
1699 | |
1700 | /// Determines whether this parameter has a default argument that has not |
1701 | /// yet been parsed. This will occur during the processing of a C++ class |
1702 | /// whose member functions have default arguments, e.g., |
1703 | /// @code |
1704 | /// class X { |
1705 | /// public: |
1706 | /// void f(int x = 17); // x has an unparsed default argument now |
1707 | /// }; // x has a regular default argument now |
1708 | /// @endcode |
1709 | bool hasUnparsedDefaultArg() const { |
1710 | return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed; |
1711 | } |
1712 | |
1713 | bool hasUninstantiatedDefaultArg() const { |
1714 | return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated; |
1715 | } |
1716 | |
1717 | /// Specify that this parameter has an unparsed default argument. |
1718 | /// The argument will be replaced with a real default argument via |
1719 | /// setDefaultArg when the class definition enclosing the function |
1720 | /// declaration that owns this default argument is completed. |
1721 | void setUnparsedDefaultArg() { |
1722 | ParmVarDeclBits.DefaultArgKind = DAK_Unparsed; |
1723 | } |
1724 | |
1725 | bool hasInheritedDefaultArg() const { |
1726 | return ParmVarDeclBits.HasInheritedDefaultArg; |
1727 | } |
1728 | |
1729 | void setHasInheritedDefaultArg(bool I = true) { |
1730 | ParmVarDeclBits.HasInheritedDefaultArg = I; |
1731 | } |
1732 | |
1733 | QualType getOriginalType() const; |
1734 | |
1735 | /// Sets the function declaration that owns this |
1736 | /// ParmVarDecl. Since ParmVarDecls are often created before the |
1737 | /// FunctionDecls that own them, this routine is required to update |
1738 | /// the DeclContext appropriately. |
1739 | void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } |
1740 | |
1741 | // Implement isa/cast/dyncast/etc. |
1742 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1743 | static bool classofKind(Kind K) { return K == ParmVar; } |
1744 | |
1745 | private: |
1746 | enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; |
1747 | |
1748 | void setParameterIndex(unsigned parameterIndex) { |
1749 | if (parameterIndex >= ParameterIndexSentinel) { |
1750 | setParameterIndexLarge(parameterIndex); |
1751 | return; |
1752 | } |
1753 | |
1754 | ParmVarDeclBits.ParameterIndex = parameterIndex; |
1755 | assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!") ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 1755, __PRETTY_FUNCTION__)); |
1756 | } |
1757 | unsigned getParameterIndex() const { |
1758 | unsigned d = ParmVarDeclBits.ParameterIndex; |
1759 | return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; |
1760 | } |
1761 | |
1762 | void setParameterIndexLarge(unsigned parameterIndex); |
1763 | unsigned getParameterIndexLarge() const; |
1764 | }; |
1765 | |
1766 | enum class MultiVersionKind { |
1767 | None, |
1768 | Target, |
1769 | CPUSpecific, |
1770 | CPUDispatch |
1771 | }; |
1772 | |
1773 | /// Represents a function declaration or definition. |
1774 | /// |
1775 | /// Since a given function can be declared several times in a program, |
1776 | /// there may be several FunctionDecls that correspond to that |
1777 | /// function. Only one of those FunctionDecls will be found when |
1778 | /// traversing the list of declarations in the context of the |
1779 | /// FunctionDecl (e.g., the translation unit); this FunctionDecl |
1780 | /// contains all of the information known about the function. Other, |
1781 | /// previous declarations of the function are available via the |
1782 | /// getPreviousDecl() chain. |
1783 | class FunctionDecl : public DeclaratorDecl, |
1784 | public DeclContext, |
1785 | public Redeclarable<FunctionDecl> { |
1786 | // This class stores some data in DeclContext::FunctionDeclBits |
1787 | // to save some space. Use the provided accessors to access it. |
1788 | public: |
1789 | /// The kind of templated function a FunctionDecl can be. |
1790 | enum TemplatedKind { |
1791 | // Not templated. |
1792 | TK_NonTemplate, |
1793 | // The pattern in a function template declaration. |
1794 | TK_FunctionTemplate, |
1795 | // A non-template function that is an instantiation or explicit |
1796 | // specialization of a member of a templated class. |
1797 | TK_MemberSpecialization, |
1798 | // An instantiation or explicit specialization of a function template. |
1799 | // Note: this might have been instantiated from a templated class if it |
1800 | // is a class-scope explicit specialization. |
1801 | TK_FunctionTemplateSpecialization, |
1802 | // A function template specialization that hasn't yet been resolved to a |
1803 | // particular specialized function template. |
1804 | TK_DependentFunctionTemplateSpecialization |
1805 | }; |
1806 | |
1807 | /// Stashed information about a defaulted function definition whose body has |
1808 | /// not yet been lazily generated. |
1809 | class DefaultedFunctionInfo final |
1810 | : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> { |
1811 | friend TrailingObjects; |
1812 | unsigned NumLookups; |
1813 | |
1814 | public: |
1815 | static DefaultedFunctionInfo *Create(ASTContext &Context, |
1816 | ArrayRef<DeclAccessPair> Lookups); |
1817 | /// Get the unqualified lookup results that should be used in this |
1818 | /// defaulted function definition. |
1819 | ArrayRef<DeclAccessPair> getUnqualifiedLookups() const { |
1820 | return {getTrailingObjects<DeclAccessPair>(), NumLookups}; |
1821 | } |
1822 | }; |
1823 | |
1824 | private: |
1825 | /// A new[]'d array of pointers to VarDecls for the formal |
1826 | /// parameters of this function. This is null if a prototype or if there are |
1827 | /// no formals. |
1828 | ParmVarDecl **ParamInfo = nullptr; |
1829 | |
1830 | /// The active member of this union is determined by |
1831 | /// FunctionDeclBits.HasDefaultedFunctionInfo. |
1832 | union { |
1833 | /// The body of the function. |
1834 | LazyDeclStmtPtr Body; |
1835 | /// Information about a future defaulted function definition. |
1836 | DefaultedFunctionInfo *DefaultedInfo; |
1837 | }; |
1838 | |
1839 | unsigned ODRHash; |
1840 | |
1841 | /// End part of this FunctionDecl's source range. |
1842 | /// |
1843 | /// We could compute the full range in getSourceRange(). However, when we're |
1844 | /// dealing with a function definition deserialized from a PCH/AST file, |
1845 | /// we can only compute the full range once the function body has been |
1846 | /// de-serialized, so it's far better to have the (sometimes-redundant) |
1847 | /// EndRangeLoc. |
1848 | SourceLocation EndRangeLoc; |
1849 | |
1850 | /// The template or declaration that this declaration |
1851 | /// describes or was instantiated from, respectively. |
1852 | /// |
1853 | /// For non-templates, this value will be NULL. For function |
1854 | /// declarations that describe a function template, this will be a |
1855 | /// pointer to a FunctionTemplateDecl. For member functions |
1856 | /// of class template specializations, this will be a MemberSpecializationInfo |
1857 | /// pointer containing information about the specialization. |
1858 | /// For function template specializations, this will be a |
1859 | /// FunctionTemplateSpecializationInfo, which contains information about |
1860 | /// the template being specialized and the template arguments involved in |
1861 | /// that specialization. |
1862 | llvm::PointerUnion4<FunctionTemplateDecl *, |
1863 | MemberSpecializationInfo *, |
1864 | FunctionTemplateSpecializationInfo *, |
1865 | DependentFunctionTemplateSpecializationInfo *> |
1866 | TemplateOrSpecialization; |
1867 | |
1868 | /// Provides source/type location info for the declaration name embedded in |
1869 | /// the DeclaratorDecl base class. |
1870 | DeclarationNameLoc DNLoc; |
1871 | |
1872 | /// Specify that this function declaration is actually a function |
1873 | /// template specialization. |
1874 | /// |
1875 | /// \param C the ASTContext. |
1876 | /// |
1877 | /// \param Template the function template that this function template |
1878 | /// specialization specializes. |
1879 | /// |
1880 | /// \param TemplateArgs the template arguments that produced this |
1881 | /// function template specialization from the template. |
1882 | /// |
1883 | /// \param InsertPos If non-NULL, the position in the function template |
1884 | /// specialization set where the function template specialization data will |
1885 | /// be inserted. |
1886 | /// |
1887 | /// \param TSK the kind of template specialization this is. |
1888 | /// |
1889 | /// \param TemplateArgsAsWritten location info of template arguments. |
1890 | /// |
1891 | /// \param PointOfInstantiation point at which the function template |
1892 | /// specialization was first instantiated. |
1893 | void setFunctionTemplateSpecialization(ASTContext &C, |
1894 | FunctionTemplateDecl *Template, |
1895 | const TemplateArgumentList *TemplateArgs, |
1896 | void *InsertPos, |
1897 | TemplateSpecializationKind TSK, |
1898 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
1899 | SourceLocation PointOfInstantiation); |
1900 | |
1901 | /// Specify that this record is an instantiation of the |
1902 | /// member function FD. |
1903 | void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, |
1904 | TemplateSpecializationKind TSK); |
1905 | |
1906 | void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); |
1907 | |
1908 | // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl |
1909 | // need to access this bit but we want to avoid making ASTDeclWriter |
1910 | // a friend of FunctionDeclBitfields just for this. |
1911 | bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; } |
1912 | |
1913 | /// Whether an ODRHash has been stored. |
1914 | bool hasODRHash() const { return FunctionDeclBits.HasODRHash; } |
1915 | |
1916 | /// State that an ODRHash has been stored. |
1917 | void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; } |
1918 | |
1919 | protected: |
1920 | FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1921 | const DeclarationNameInfo &NameInfo, QualType T, |
1922 | TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified, |
1923 | ConstexprSpecKind ConstexprKind, |
1924 | Expr *TrailingRequiresClause = nullptr); |
1925 | |
1926 | using redeclarable_base = Redeclarable<FunctionDecl>; |
1927 | |
1928 | FunctionDecl *getNextRedeclarationImpl() override { |
1929 | return getNextRedeclaration(); |
1930 | } |
1931 | |
1932 | FunctionDecl *getPreviousDeclImpl() override { |
1933 | return getPreviousDecl(); |
1934 | } |
1935 | |
1936 | FunctionDecl *getMostRecentDeclImpl() override { |
1937 | return getMostRecentDecl(); |
1938 | } |
1939 | |
1940 | public: |
1941 | friend class ASTDeclReader; |
1942 | friend class ASTDeclWriter; |
1943 | |
1944 | using redecl_range = redeclarable_base::redecl_range; |
1945 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1946 | |
1947 | using redeclarable_base::redecls_begin; |
1948 | using redeclarable_base::redecls_end; |
1949 | using redeclarable_base::redecls; |
1950 | using redeclarable_base::getPreviousDecl; |
1951 | using redeclarable_base::getMostRecentDecl; |
1952 | using redeclarable_base::isFirstDecl; |
1953 | |
1954 | static FunctionDecl * |
1955 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1956 | SourceLocation NLoc, DeclarationName N, QualType T, |
1957 | TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false, |
1958 | bool hasWrittenPrototype = true, |
1959 | ConstexprSpecKind ConstexprKind = CSK_unspecified, |
1960 | Expr *TrailingRequiresClause = nullptr) { |
1961 | DeclarationNameInfo NameInfo(N, NLoc); |
1962 | return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC, |
1963 | isInlineSpecified, hasWrittenPrototype, |
1964 | ConstexprKind, TrailingRequiresClause); |
1965 | } |
1966 | |
1967 | static FunctionDecl *Create(ASTContext &C, DeclContext *DC, |
1968 | SourceLocation StartLoc, |
1969 | const DeclarationNameInfo &NameInfo, QualType T, |
1970 | TypeSourceInfo *TInfo, StorageClass SC, |
1971 | bool isInlineSpecified, bool hasWrittenPrototype, |
1972 | ConstexprSpecKind ConstexprKind, |
1973 | Expr *TrailingRequiresClause); |
1974 | |
1975 | static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1976 | |
1977 | DeclarationNameInfo getNameInfo() const { |
1978 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
1979 | } |
1980 | |
1981 | void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, |
1982 | bool Qualified) const override; |
1983 | |
1984 | void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } |
1985 | |
1986 | /// Returns the location of the ellipsis of a variadic function. |
1987 | SourceLocation getEllipsisLoc() const { |
1988 | const auto *FPT = getType()->getAs<FunctionProtoType>(); |
1989 | if (FPT && FPT->isVariadic()) |
1990 | return FPT->getEllipsisLoc(); |
1991 | return SourceLocation(); |
1992 | } |
1993 | |
1994 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1995 | |
1996 | // Function definitions. |
1997 | // |
1998 | // A function declaration may be: |
1999 | // - a non defining declaration, |
2000 | // - a definition. A function may be defined because: |
2001 | // - it has a body, or will have it in the case of late parsing. |
2002 | // - it has an uninstantiated body. The body does not exist because the |
2003 | // function is not used yet, but the declaration is considered a |
2004 | // definition and does not allow other definition of this function. |
2005 | // - it does not have a user specified body, but it does not allow |
2006 | // redefinition, because it is deleted/defaulted or is defined through |
2007 | // some other mechanism (alias, ifunc). |
2008 | |
2009 | /// Returns true if the function has a body. |
2010 | /// |
2011 | /// The function body might be in any of the (re-)declarations of this |
2012 | /// function. The variant that accepts a FunctionDecl pointer will set that |
2013 | /// function declaration to the actual declaration containing the body (if |
2014 | /// there is one). |
2015 | bool hasBody(const FunctionDecl *&Definition) const; |
2016 | |
2017 | bool hasBody() const override { |
2018 | const FunctionDecl* Definition; |
2019 | return hasBody(Definition); |
2020 | } |
2021 | |
2022 | /// Returns whether the function has a trivial body that does not require any |
2023 | /// specific codegen. |
2024 | bool hasTrivialBody() const; |
2025 | |
2026 | /// Returns true if the function has a definition that does not need to be |
2027 | /// instantiated. |
2028 | /// |
2029 | /// The variant that accepts a FunctionDecl pointer will set that function |
2030 | /// declaration to the declaration that is a definition (if there is one). |
2031 | bool isDefined(const FunctionDecl *&Definition) const; |
2032 | |
2033 | virtual bool isDefined() const { |
2034 | const FunctionDecl* Definition; |
2035 | return isDefined(Definition); |
2036 | } |
2037 | |
2038 | /// Get the definition for this declaration. |
2039 | FunctionDecl *getDefinition() { |
2040 | const FunctionDecl *Definition; |
2041 | if (isDefined(Definition)) |
2042 | return const_cast<FunctionDecl *>(Definition); |
2043 | return nullptr; |
2044 | } |
2045 | const FunctionDecl *getDefinition() const { |
2046 | return const_cast<FunctionDecl *>(this)->getDefinition(); |
2047 | } |
2048 | |
2049 | /// Retrieve the body (definition) of the function. The function body might be |
2050 | /// in any of the (re-)declarations of this function. The variant that accepts |
2051 | /// a FunctionDecl pointer will set that function declaration to the actual |
2052 | /// declaration containing the body (if there is one). |
2053 | /// NOTE: For checking if there is a body, use hasBody() instead, to avoid |
2054 | /// unnecessary AST de-serialization of the body. |
2055 | Stmt *getBody(const FunctionDecl *&Definition) const; |
2056 | |
2057 | Stmt *getBody() const override { |
2058 | const FunctionDecl* Definition; |
2059 | return getBody(Definition); |
2060 | } |
2061 | |
2062 | /// Returns whether this specific declaration of the function is also a |
2063 | /// definition that does not contain uninstantiated body. |
2064 | /// |
2065 | /// This does not determine whether the function has been defined (e.g., in a |
2066 | /// previous definition); for that information, use isDefined. |
2067 | /// |
2068 | /// Note: the function declaration does not become a definition until the |
2069 | /// parser reaches the definition, if called before, this function will return |
2070 | /// `false`. |
2071 | bool isThisDeclarationADefinition() const { |
2072 | return isDeletedAsWritten() || isDefaulted() || |
2073 | doesThisDeclarationHaveABody() || hasSkippedBody() || |
2074 | willHaveBody() || hasDefiningAttr(); |
2075 | } |
2076 | |
2077 | /// Returns whether this specific declaration of the function has a body. |
2078 | bool doesThisDeclarationHaveABody() const { |
2079 | return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) || |
2080 | isLateTemplateParsed(); |
2081 | } |
2082 | |
2083 | void setBody(Stmt *B); |
2084 | void setLazyBody(uint64_t Offset) { |
2085 | FunctionDeclBits.HasDefaultedFunctionInfo = false; |
2086 | Body = LazyDeclStmtPtr(Offset); |
2087 | } |
2088 | |
2089 | void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info); |
2090 | DefaultedFunctionInfo *getDefaultedFunctionInfo() const; |
2091 | |
2092 | /// Whether this function is variadic. |
2093 | bool isVariadic() const; |
2094 | |
2095 | /// Whether this function is marked as virtual explicitly. |
2096 | bool isVirtualAsWritten() const { |
2097 | return FunctionDeclBits.IsVirtualAsWritten; |
2098 | } |
2099 | |
2100 | /// State that this function is marked as virtual explicitly. |
2101 | void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; } |
2102 | |
2103 | /// Whether this virtual function is pure, i.e. makes the containing class |
2104 | /// abstract. |
2105 | bool isPure() const { return FunctionDeclBits.IsPure; } |
2106 | void setPure(bool P = true); |
2107 | |
2108 | /// Whether this templated function will be late parsed. |
2109 | bool isLateTemplateParsed() const { |
2110 | return FunctionDeclBits.IsLateTemplateParsed; |
2111 | } |
2112 | |
2113 | /// State that this templated function will be late parsed. |
2114 | void setLateTemplateParsed(bool ILT = true) { |
2115 | FunctionDeclBits.IsLateTemplateParsed = ILT; |
2116 | } |
2117 | |
2118 | /// Whether this function is "trivial" in some specialized C++ senses. |
2119 | /// Can only be true for default constructors, copy constructors, |
2120 | /// copy assignment operators, and destructors. Not meaningful until |
2121 | /// the class has been fully built by Sema. |
2122 | bool isTrivial() const { return FunctionDeclBits.IsTrivial; } |
2123 | void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; } |
2124 | |
2125 | bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; } |
2126 | void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; } |
2127 | |
2128 | /// Whether this function is defaulted per C++0x. Only valid for |
2129 | /// special member functions. |
2130 | bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; } |
2131 | void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; } |
2132 | |
2133 | /// Whether this function is explicitly defaulted per C++0x. Only valid |
2134 | /// for special member functions. |
2135 | bool isExplicitlyDefaulted() const { |
2136 | return FunctionDeclBits.IsExplicitlyDefaulted; |
2137 | } |
2138 | |
2139 | /// State that this function is explicitly defaulted per C++0x. Only valid |
2140 | /// for special member functions. |
2141 | void setExplicitlyDefaulted(bool ED = true) { |
2142 | FunctionDeclBits.IsExplicitlyDefaulted = ED; |
2143 | } |
2144 | |
2145 | /// True if this method is user-declared and was not |
2146 | /// deleted or defaulted on its first declaration. |
2147 | bool isUserProvided() const { |
2148 | auto *DeclAsWritten = this; |
2149 | if (FunctionDecl *Pattern = getTemplateInstantiationPattern()) |
2150 | DeclAsWritten = Pattern; |
2151 | return !(DeclAsWritten->isDeleted() || |
2152 | DeclAsWritten->getCanonicalDecl()->isDefaulted()); |
2153 | } |
2154 | |
2155 | /// Whether falling off this function implicitly returns null/zero. |
2156 | /// If a more specific implicit return value is required, front-ends |
2157 | /// should synthesize the appropriate return statements. |
2158 | bool hasImplicitReturnZero() const { |
2159 | return FunctionDeclBits.HasImplicitReturnZero; |
2160 | } |
2161 | |
2162 | /// State that falling off this function implicitly returns null/zero. |
2163 | /// If a more specific implicit return value is required, front-ends |
2164 | /// should synthesize the appropriate return statements. |
2165 | void setHasImplicitReturnZero(bool IRZ) { |
2166 | FunctionDeclBits.HasImplicitReturnZero = IRZ; |
2167 | } |
2168 | |
2169 | /// Whether this function has a prototype, either because one |
2170 | /// was explicitly written or because it was "inherited" by merging |
2171 | /// a declaration without a prototype with a declaration that has a |
2172 | /// prototype. |
2173 | bool hasPrototype() const { |
2174 | return hasWrittenPrototype() || hasInheritedPrototype(); |
2175 | } |
2176 | |
2177 | /// Whether this function has a written prototype. |
2178 | bool hasWrittenPrototype() const { |
2179 | return FunctionDeclBits.HasWrittenPrototype; |
2180 | } |
2181 | |
2182 | /// State that this function has a written prototype. |
2183 | void setHasWrittenPrototype(bool P = true) { |
2184 | FunctionDeclBits.HasWrittenPrototype = P; |
2185 | } |
2186 | |
2187 | /// Whether this function inherited its prototype from a |
2188 | /// previous declaration. |
2189 | bool hasInheritedPrototype() const { |
2190 | return FunctionDeclBits.HasInheritedPrototype; |
2191 | } |
2192 | |
2193 | /// State that this function inherited its prototype from a |
2194 | /// previous declaration. |
2195 | void setHasInheritedPrototype(bool P = true) { |
2196 | FunctionDeclBits.HasInheritedPrototype = P; |
2197 | } |
2198 | |
2199 | /// Whether this is a (C++11) constexpr function or constexpr constructor. |
2200 | bool isConstexpr() const { |
2201 | return FunctionDeclBits.ConstexprKind != CSK_unspecified; |
2202 | } |
2203 | void setConstexprKind(ConstexprSpecKind CSK) { |
2204 | FunctionDeclBits.ConstexprKind = CSK; |
2205 | } |
2206 | ConstexprSpecKind getConstexprKind() const { |
2207 | return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind); |
2208 | } |
2209 | bool isConstexprSpecified() const { |
2210 | return FunctionDeclBits.ConstexprKind == CSK_constexpr; |
2211 | } |
2212 | bool isConsteval() const { |
2213 | return FunctionDeclBits.ConstexprKind == CSK_consteval; |
2214 | } |
2215 | |
2216 | /// Whether the instantiation of this function is pending. |
2217 | /// This bit is set when the decision to instantiate this function is made |
2218 | /// and unset if and when the function body is created. That leaves out |
2219 | /// cases where instantiation did not happen because the template definition |
2220 | /// was not seen in this TU. This bit remains set in those cases, under the |
2221 | /// assumption that the instantiation will happen in some other TU. |
2222 | bool instantiationIsPending() const { |
2223 | return FunctionDeclBits.InstantiationIsPending; |
2224 | } |
2225 | |
2226 | /// State that the instantiation of this function is pending. |
2227 | /// (see instantiationIsPending) |
2228 | void setInstantiationIsPending(bool IC) { |
2229 | FunctionDeclBits.InstantiationIsPending = IC; |
2230 | } |
2231 | |
2232 | /// Indicates the function uses __try. |
2233 | bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; } |
2234 | void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; } |
2235 | |
2236 | /// Indicates the function uses Floating Point constrained intrinsics |
2237 | bool usesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; } |
2238 | void setUsesFPIntrin(bool Val) { FunctionDeclBits.UsesFPIntrin = Val; } |
2239 | |
2240 | /// Whether this function has been deleted. |
2241 | /// |
2242 | /// A function that is "deleted" (via the C++0x "= delete" syntax) |
2243 | /// acts like a normal function, except that it cannot actually be |
2244 | /// called or have its address taken. Deleted functions are |
2245 | /// typically used in C++ overload resolution to attract arguments |
2246 | /// whose type or lvalue/rvalue-ness would permit the use of a |
2247 | /// different overload that would behave incorrectly. For example, |
2248 | /// one might use deleted functions to ban implicit conversion from |
2249 | /// a floating-point number to an Integer type: |
2250 | /// |
2251 | /// @code |
2252 | /// struct Integer { |
2253 | /// Integer(long); // construct from a long |
2254 | /// Integer(double) = delete; // no construction from float or double |
2255 | /// Integer(long double) = delete; // no construction from long double |
2256 | /// }; |
2257 | /// @endcode |
2258 | // If a function is deleted, its first declaration must be. |
2259 | bool isDeleted() const { |
2260 | return getCanonicalDecl()->FunctionDeclBits.IsDeleted; |
2261 | } |
2262 | |
2263 | bool isDeletedAsWritten() const { |
2264 | return FunctionDeclBits.IsDeleted && !isDefaulted(); |
2265 | } |
2266 | |
2267 | void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; } |
2268 | |
2269 | /// Determines whether this function is "main", which is the |
2270 | /// entry point into an executable program. |
2271 | bool isMain() const; |
2272 | |
2273 | /// Determines whether this function is a MSVCRT user defined entry |
2274 | /// point. |
2275 | bool isMSVCRTEntryPoint() const; |
2276 | |
2277 | /// Determines whether this operator new or delete is one |
2278 | /// of the reserved global placement operators: |
2279 | /// void *operator new(size_t, void *); |
2280 | /// void *operator new[](size_t, void *); |
2281 | /// void operator delete(void *, void *); |
2282 | /// void operator delete[](void *, void *); |
2283 | /// These functions have special behavior under [new.delete.placement]: |
2284 | /// These functions are reserved, a C++ program may not define |
2285 | /// functions that displace the versions in the Standard C++ library. |
2286 | /// The provisions of [basic.stc.dynamic] do not apply to these |
2287 | /// reserved placement forms of operator new and operator delete. |
2288 | /// |
2289 | /// This function must be an allocation or deallocation function. |
2290 | bool isReservedGlobalPlacementOperator() const; |
2291 | |
2292 | /// Determines whether this function is one of the replaceable |
2293 | /// global allocation functions: |
2294 | /// void *operator new(size_t); |
2295 | /// void *operator new(size_t, const std::nothrow_t &) noexcept; |
2296 | /// void *operator new[](size_t); |
2297 | /// void *operator new[](size_t, const std::nothrow_t &) noexcept; |
2298 | /// void operator delete(void *) noexcept; |
2299 | /// void operator delete(void *, std::size_t) noexcept; [C++1y] |
2300 | /// void operator delete(void *, const std::nothrow_t &) noexcept; |
2301 | /// void operator delete[](void *) noexcept; |
2302 | /// void operator delete[](void *, std::size_t) noexcept; [C++1y] |
2303 | /// void operator delete[](void *, const std::nothrow_t &) noexcept; |
2304 | /// These functions have special behavior under C++1y [expr.new]: |
2305 | /// An implementation is allowed to omit a call to a replaceable global |
2306 | /// allocation function. [...] |
2307 | /// |
2308 | /// If this function is an aligned allocation/deallocation function, return |
2309 | /// true through IsAligned. |
2310 | bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const; |
2311 | |
2312 | /// Determine if this function provides an inline implementation of a builtin. |
2313 | bool isInlineBuiltinDeclaration() const; |
2314 | |
2315 | /// Determine whether this is a destroying operator delete. |
2316 | bool isDestroyingOperatorDelete() const; |
2317 | |
2318 | /// Compute the language linkage. |
2319 | LanguageLinkage getLanguageLinkage() const; |
2320 | |
2321 | /// Determines whether this function is a function with |
2322 | /// external, C linkage. |
2323 | bool isExternC() const; |
2324 | |
2325 | /// Determines whether this function's context is, or is nested within, |
2326 | /// a C++ extern "C" linkage spec. |
2327 | bool isInExternCContext() const; |
2328 | |
2329 | /// Determines whether this function's context is, or is nested within, |
2330 | /// a C++ extern "C++" linkage spec. |
2331 | bool isInExternCXXContext() const; |
2332 | |
2333 | /// Determines whether this is a global function. |
2334 | bool isGlobal() const; |
2335 | |
2336 | /// Determines whether this function is known to be 'noreturn', through |
2337 | /// an attribute on its declaration or its type. |
2338 | bool isNoReturn() const; |
2339 | |
2340 | /// True if the function was a definition but its body was skipped. |
2341 | bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; } |
2342 | void setHasSkippedBody(bool Skipped = true) { |
2343 | FunctionDeclBits.HasSkippedBody = Skipped; |
2344 | } |
2345 | |
2346 | /// True if this function will eventually have a body, once it's fully parsed. |
2347 | bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; } |
2348 | void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; } |
2349 | |
2350 | /// True if this function is considered a multiversioned function. |
2351 | bool isMultiVersion() const { |
2352 | return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion; |
2353 | } |
2354 | |
2355 | /// Sets the multiversion state for this declaration and all of its |
2356 | /// redeclarations. |
2357 | void setIsMultiVersion(bool V = true) { |
2358 | getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V; |
2359 | } |
2360 | |
2361 | /// Gets the kind of multiversioning attribute this declaration has. Note that |
2362 | /// this can return a value even if the function is not multiversion, such as |
2363 | /// the case of 'target'. |
2364 | MultiVersionKind getMultiVersionKind() const; |
2365 | |
2366 | |
2367 | /// True if this function is a multiversioned dispatch function as a part of |
2368 | /// the cpu_specific/cpu_dispatch functionality. |
2369 | bool isCPUDispatchMultiVersion() const; |
2370 | /// True if this function is a multiversioned processor specific function as a |
2371 | /// part of the cpu_specific/cpu_dispatch functionality. |
2372 | bool isCPUSpecificMultiVersion() const; |
2373 | |
2374 | /// True if this function is a multiversioned dispatch function as a part of |
2375 | /// the target functionality. |
2376 | bool isTargetMultiVersion() const; |
2377 | |
2378 | /// \brief Get the associated-constraints of this function declaration. |
2379 | /// Currently, this will either be a vector of size 1 containing the |
2380 | /// trailing-requires-clause or an empty vector. |
2381 | /// |
2382 | /// Use this instead of getTrailingRequiresClause for concepts APIs that |
2383 | /// accept an ArrayRef of constraint expressions. |
2384 | void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const { |
2385 | if (auto *TRC = getTrailingRequiresClause()) |
2386 | AC.push_back(TRC); |
2387 | } |
2388 | |
2389 | void setPreviousDeclaration(FunctionDecl * PrevDecl); |
2390 | |
2391 | FunctionDecl *getCanonicalDecl() override; |
2392 | const FunctionDecl *getCanonicalDecl() const { |
2393 | return const_cast<FunctionDecl*>(this)->getCanonicalDecl(); |
2394 | } |
2395 | |
2396 | unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const; |
2397 | |
2398 | // ArrayRef interface to parameters. |
2399 | ArrayRef<ParmVarDecl *> parameters() const { |
2400 | return {ParamInfo, getNumParams()}; |
2401 | } |
2402 | MutableArrayRef<ParmVarDecl *> parameters() { |
2403 | return {ParamInfo, getNumParams()}; |
2404 | } |
2405 | |
2406 | // Iterator access to formal parameters. |
2407 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
2408 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
2409 | |
2410 | bool param_empty() const { return parameters().empty(); } |
2411 | param_iterator param_begin() { return parameters().begin(); } |
2412 | param_iterator param_end() { return parameters().end(); } |
2413 | param_const_iterator param_begin() const { return parameters().begin(); } |
2414 | param_const_iterator param_end() const { return parameters().end(); } |
2415 | size_t param_size() const { return parameters().size(); } |
2416 | |
2417 | /// Return the number of parameters this function must have based on its |
2418 | /// FunctionType. This is the length of the ParamInfo array after it has been |
2419 | /// created. |
2420 | unsigned getNumParams() const; |
2421 | |
2422 | const ParmVarDecl *getParamDecl(unsigned i) const { |
2423 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2423, __PRETTY_FUNCTION__)); |
2424 | return ParamInfo[i]; |
2425 | } |
2426 | ParmVarDecl *getParamDecl(unsigned i) { |
2427 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2427, __PRETTY_FUNCTION__)); |
2428 | return ParamInfo[i]; |
2429 | } |
2430 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
2431 | setParams(getASTContext(), NewParamInfo); |
2432 | } |
2433 | |
2434 | /// Returns the minimum number of arguments needed to call this function. This |
2435 | /// may be fewer than the number of function parameters, if some of the |
2436 | /// parameters have default arguments (in C++). |
2437 | unsigned getMinRequiredArguments() const; |
2438 | |
2439 | /// Find the source location information for how the type of this function |
2440 | /// was written. May be absent (for example if the function was declared via |
2441 | /// a typedef) and may contain a different type from that of the function |
2442 | /// (for example if the function type was adjusted by an attribute). |
2443 | FunctionTypeLoc getFunctionTypeLoc() const; |
2444 | |
2445 | QualType getReturnType() const { |
2446 | return getType()->castAs<FunctionType>()->getReturnType(); |
2447 | } |
2448 | |
2449 | /// Attempt to compute an informative source range covering the |
2450 | /// function return type. This may omit qualifiers and other information with |
2451 | /// limited representation in the AST. |
2452 | SourceRange getReturnTypeSourceRange() const; |
2453 | |
2454 | /// Attempt to compute an informative source range covering the |
2455 | /// function parameters, including the ellipsis of a variadic function. |
2456 | /// The source range excludes the parentheses, and is invalid if there are |
2457 | /// no parameters and no ellipsis. |
2458 | SourceRange getParametersSourceRange() const; |
2459 | |
2460 | /// Get the declared return type, which may differ from the actual return |
2461 | /// type if the return type is deduced. |
2462 | QualType getDeclaredReturnType() const { |
2463 | auto *TSI = getTypeSourceInfo(); |
2464 | QualType T = TSI ? TSI->getType() : getType(); |
2465 | return T->castAs<FunctionType>()->getReturnType(); |
2466 | } |
2467 | |
2468 | /// Gets the ExceptionSpecificationType as declared. |
2469 | ExceptionSpecificationType getExceptionSpecType() const { |
2470 | auto *TSI = getTypeSourceInfo(); |
2471 | QualType T = TSI ? TSI->getType() : getType(); |
2472 | const auto *FPT = T->getAs<FunctionProtoType>(); |
2473 | return FPT ? FPT->getExceptionSpecType() : EST_None; |
2474 | } |
2475 | |
2476 | /// Attempt to compute an informative source range covering the |
2477 | /// function exception specification, if any. |
2478 | SourceRange getExceptionSpecSourceRange() const; |
2479 | |
2480 | /// Determine the type of an expression that calls this function. |
2481 | QualType getCallResultType() const { |
2482 | return getType()->castAs<FunctionType>()->getCallResultType( |
2483 | getASTContext()); |
2484 | } |
2485 | |
2486 | /// Returns the storage class as written in the source. For the |
2487 | /// computed linkage of symbol, see getLinkage. |
2488 | StorageClass getStorageClass() const { |
2489 | return static_cast<StorageClass>(FunctionDeclBits.SClass); |
2490 | } |
2491 | |
2492 | /// Sets the storage class as written in the source. |
2493 | void setStorageClass(StorageClass SClass) { |
2494 | FunctionDeclBits.SClass = SClass; |
2495 | } |
2496 | |
2497 | /// Determine whether the "inline" keyword was specified for this |
2498 | /// function. |
2499 | bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; } |
2500 | |
2501 | /// Set whether the "inline" keyword was specified for this function. |
2502 | void setInlineSpecified(bool I) { |
2503 | FunctionDeclBits.IsInlineSpecified = I; |
2504 | FunctionDeclBits.IsInline = I; |
2505 | } |
2506 | |
2507 | /// Flag that this function is implicitly inline. |
2508 | void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; } |
2509 | |
2510 | /// Determine whether this function should be inlined, because it is |
2511 | /// either marked "inline" or "constexpr" or is a member function of a class |
2512 | /// that was defined in the class body. |
2513 | bool isInlined() const { return FunctionDeclBits.IsInline; } |
2514 | |
2515 | bool isInlineDefinitionExternallyVisible() const; |
2516 | |
2517 | bool isMSExternInline() const; |
2518 | |
2519 | bool doesDeclarationForceExternallyVisibleDefinition() const; |
2520 | |
2521 | bool isStatic() const { return getStorageClass() == SC_Static; } |
2522 | |
2523 | /// Whether this function declaration represents an C++ overloaded |
2524 | /// operator, e.g., "operator+". |
2525 | bool isOverloadedOperator() const { |
2526 | return getOverloadedOperator() != OO_None; |
2527 | } |
2528 | |
2529 | OverloadedOperatorKind getOverloadedOperator() const; |
2530 | |
2531 | const IdentifierInfo *getLiteralIdentifier() const; |
2532 | |
2533 | /// If this function is an instantiation of a member function |
2534 | /// of a class template specialization, retrieves the function from |
2535 | /// which it was instantiated. |
2536 | /// |
2537 | /// This routine will return non-NULL for (non-templated) member |
2538 | /// functions of class templates and for instantiations of function |
2539 | /// templates. For example, given: |
2540 | /// |
2541 | /// \code |
2542 | /// template<typename T> |
2543 | /// struct X { |
2544 | /// void f(T); |
2545 | /// }; |
2546 | /// \endcode |
2547 | /// |
2548 | /// The declaration for X<int>::f is a (non-templated) FunctionDecl |
2549 | /// whose parent is the class template specialization X<int>. For |
2550 | /// this declaration, getInstantiatedFromFunction() will return |
2551 | /// the FunctionDecl X<T>::A. When a complete definition of |
2552 | /// X<int>::A is required, it will be instantiated from the |
2553 | /// declaration returned by getInstantiatedFromMemberFunction(). |
2554 | FunctionDecl *getInstantiatedFromMemberFunction() const; |
2555 | |
2556 | /// What kind of templated function this is. |
2557 | TemplatedKind getTemplatedKind() const; |
2558 | |
2559 | /// If this function is an instantiation of a member function of a |
2560 | /// class template specialization, retrieves the member specialization |
2561 | /// information. |
2562 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
2563 | |
2564 | /// Specify that this record is an instantiation of the |
2565 | /// member function FD. |
2566 | void setInstantiationOfMemberFunction(FunctionDecl *FD, |
2567 | TemplateSpecializationKind TSK) { |
2568 | setInstantiationOfMemberFunction(getASTContext(), FD, TSK); |
2569 | } |
2570 | |
2571 | /// Retrieves the function template that is described by this |
2572 | /// function declaration. |
2573 | /// |
2574 | /// Every function template is represented as a FunctionTemplateDecl |
2575 | /// and a FunctionDecl (or something derived from FunctionDecl). The |
2576 | /// former contains template properties (such as the template |
2577 | /// parameter lists) while the latter contains the actual |
2578 | /// description of the template's |
2579 | /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the |
2580 | /// FunctionDecl that describes the function template, |
2581 | /// getDescribedFunctionTemplate() retrieves the |
2582 | /// FunctionTemplateDecl from a FunctionDecl. |
2583 | FunctionTemplateDecl *getDescribedFunctionTemplate() const; |
2584 | |
2585 | void setDescribedFunctionTemplate(FunctionTemplateDecl *Template); |
2586 | |
2587 | /// Determine whether this function is a function template |
2588 | /// specialization. |
2589 | bool isFunctionTemplateSpecialization() const { |
2590 | return getPrimaryTemplate() != nullptr; |
2591 | } |
2592 | |
2593 | /// If this function is actually a function template specialization, |
2594 | /// retrieve information about this function template specialization. |
2595 | /// Otherwise, returns NULL. |
2596 | FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const; |
2597 | |
2598 | /// Determines whether this function is a function template |
2599 | /// specialization or a member of a class template specialization that can |
2600 | /// be implicitly instantiated. |
2601 | bool isImplicitlyInstantiable() const; |
2602 | |
2603 | /// Determines if the given function was instantiated from a |
2604 | /// function template. |
2605 | bool isTemplateInstantiation() const; |
2606 | |
2607 | /// Retrieve the function declaration from which this function could |
2608 | /// be instantiated, if it is an instantiation (rather than a non-template |
2609 | /// or a specialization, for example). |
2610 | FunctionDecl *getTemplateInstantiationPattern() const; |
2611 | |
2612 | /// Retrieve the primary template that this function template |
2613 | /// specialization either specializes or was instantiated from. |
2614 | /// |
2615 | /// If this function declaration is not a function template specialization, |
2616 | /// returns NULL. |
2617 | FunctionTemplateDecl *getPrimaryTemplate() const; |
2618 | |
2619 | /// Retrieve the template arguments used to produce this function |
2620 | /// template specialization from the primary template. |
2621 | /// |
2622 | /// If this function declaration is not a function template specialization, |
2623 | /// returns NULL. |
2624 | const TemplateArgumentList *getTemplateSpecializationArgs() const; |
2625 | |
2626 | /// Retrieve the template argument list as written in the sources, |
2627 | /// if any. |
2628 | /// |
2629 | /// If this function declaration is not a function template specialization |
2630 | /// or if it had no explicit template argument list, returns NULL. |
2631 | /// Note that it an explicit template argument list may be written empty, |
2632 | /// e.g., template<> void foo<>(char* s); |
2633 | const ASTTemplateArgumentListInfo* |
2634 | getTemplateSpecializationArgsAsWritten() const; |
2635 | |
2636 | /// Specify that this function declaration is actually a function |
2637 | /// template specialization. |
2638 | /// |
2639 | /// \param Template the function template that this function template |
2640 | /// specialization specializes. |
2641 | /// |
2642 | /// \param TemplateArgs the template arguments that produced this |
2643 | /// function template specialization from the template. |
2644 | /// |
2645 | /// \param InsertPos If non-NULL, the position in the function template |
2646 | /// specialization set where the function template specialization data will |
2647 | /// be inserted. |
2648 | /// |
2649 | /// \param TSK the kind of template specialization this is. |
2650 | /// |
2651 | /// \param TemplateArgsAsWritten location info of template arguments. |
2652 | /// |
2653 | /// \param PointOfInstantiation point at which the function template |
2654 | /// specialization was first instantiated. |
2655 | void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, |
2656 | const TemplateArgumentList *TemplateArgs, |
2657 | void *InsertPos, |
2658 | TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, |
2659 | const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr, |
2660 | SourceLocation PointOfInstantiation = SourceLocation()) { |
2661 | setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, |
2662 | InsertPos, TSK, TemplateArgsAsWritten, |
2663 | PointOfInstantiation); |
2664 | } |
2665 | |
2666 | /// Specifies that this function declaration is actually a |
2667 | /// dependent function template specialization. |
2668 | void setDependentTemplateSpecialization(ASTContext &Context, |
2669 | const UnresolvedSetImpl &Templates, |
2670 | const TemplateArgumentListInfo &TemplateArgs); |
2671 | |
2672 | DependentFunctionTemplateSpecializationInfo * |
2673 | getDependentSpecializationInfo() const; |
2674 | |
2675 | /// Determine what kind of template instantiation this function |
2676 | /// represents. |
2677 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
2678 | |
2679 | /// Determine the kind of template specialization this function represents |
2680 | /// for the purpose of template instantiation. |
2681 | TemplateSpecializationKind |
2682 | getTemplateSpecializationKindForInstantiation() const; |
2683 | |
2684 | /// Determine what kind of template instantiation this function |
2685 | /// represents. |
2686 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
2687 | SourceLocation PointOfInstantiation = SourceLocation()); |
2688 | |
2689 | /// Retrieve the (first) point of instantiation of a function template |
2690 | /// specialization or a member of a class template specialization. |
2691 | /// |
2692 | /// \returns the first point of instantiation, if this function was |
2693 | /// instantiated from a template; otherwise, returns an invalid source |
2694 | /// location. |
2695 | SourceLocation getPointOfInstantiation() const; |
2696 | |
2697 | /// Determine whether this is or was instantiated from an out-of-line |
2698 | /// definition of a member function. |
2699 | bool isOutOfLine() const override; |
2700 | |
2701 | /// Identify a memory copying or setting function. |
2702 | /// If the given function is a memory copy or setting function, returns |
2703 | /// the corresponding Builtin ID. If the function is not a memory function, |
2704 | /// returns 0. |
2705 | unsigned getMemoryFunctionKind() const; |
2706 | |
2707 | /// Returns ODRHash of the function. This value is calculated and |
2708 | /// stored on first call, then the stored value returned on the other calls. |
2709 | unsigned getODRHash(); |
2710 | |
2711 | /// Returns cached ODRHash of the function. This must have been previously |
2712 | /// computed and stored. |
2713 | unsigned getODRHash() const; |
2714 | |
2715 | // Implement isa/cast/dyncast/etc. |
2716 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2717 | static bool classofKind(Kind K) { |
2718 | return K >= firstFunction && K <= lastFunction; |
2719 | } |
2720 | static DeclContext *castToDeclContext(const FunctionDecl *D) { |
2721 | return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); |
2722 | } |
2723 | static FunctionDecl *castFromDeclContext(const DeclContext *DC) { |
2724 | return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); |
2725 | } |
2726 | }; |
2727 | |
2728 | /// Represents a member of a struct/union/class. |
2729 | class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> { |
2730 | unsigned BitField : 1; |
2731 | unsigned Mutable : 1; |
2732 | mutable unsigned CachedFieldIndex : 30; |
2733 | |
2734 | /// The kinds of value we can store in InitializerOrBitWidth. |
2735 | /// |
2736 | /// Note that this is compatible with InClassInitStyle except for |
2737 | /// ISK_CapturedVLAType. |
2738 | enum InitStorageKind { |
2739 | /// If the pointer is null, there's nothing special. Otherwise, |
2740 | /// this is a bitfield and the pointer is the Expr* storing the |
2741 | /// bit-width. |
2742 | ISK_NoInit = (unsigned) ICIS_NoInit, |
2743 | |
2744 | /// The pointer is an (optional due to delayed parsing) Expr* |
2745 | /// holding the copy-initializer. |
2746 | ISK_InClassCopyInit = (unsigned) ICIS_CopyInit, |
2747 | |
2748 | /// The pointer is an (optional due to delayed parsing) Expr* |
2749 | /// holding the list-initializer. |
2750 | ISK_InClassListInit = (unsigned) ICIS_ListInit, |
2751 | |
2752 | /// The pointer is a VariableArrayType* that's been captured; |
2753 | /// the enclosing context is a lambda or captured statement. |
2754 | ISK_CapturedVLAType, |
2755 | }; |
2756 | |
2757 | /// If this is a bitfield with a default member initializer, this |
2758 | /// structure is used to represent the two expressions. |
2759 | struct InitAndBitWidth { |
2760 | Expr *Init; |
2761 | Expr *BitWidth; |
2762 | }; |
2763 | |
2764 | /// Storage for either the bit-width, the in-class initializer, or |
2765 | /// both (via InitAndBitWidth), or the captured variable length array bound. |
2766 | /// |
2767 | /// If the storage kind is ISK_InClassCopyInit or |
2768 | /// ISK_InClassListInit, but the initializer is null, then this |
2769 | /// field has an in-class initializer that has not yet been parsed |
2770 | /// and attached. |
2771 | // FIXME: Tail-allocate this to reduce the size of FieldDecl in the |
2772 | // overwhelmingly common case that we have none of these things. |
2773 | llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage; |
2774 | |
2775 | protected: |
2776 | FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, |
2777 | SourceLocation IdLoc, IdentifierInfo *Id, |
2778 | QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2779 | InClassInitStyle InitStyle) |
2780 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), |
2781 | BitField(false), Mutable(Mutable), CachedFieldIndex(0), |
2782 | InitStorage(nullptr, (InitStorageKind) InitStyle) { |
2783 | if (BW) |
2784 | setBitWidth(BW); |
2785 | } |
2786 | |
2787 | public: |
2788 | friend class ASTDeclReader; |
2789 | friend class ASTDeclWriter; |
2790 | |
2791 | static FieldDecl *Create(const ASTContext &C, DeclContext *DC, |
2792 | SourceLocation StartLoc, SourceLocation IdLoc, |
2793 | IdentifierInfo *Id, QualType T, |
2794 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2795 | InClassInitStyle InitStyle); |
2796 | |
2797 | static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2798 | |
2799 | /// Returns the index of this field within its record, |
2800 | /// as appropriate for passing to ASTRecordLayout::getFieldOffset. |
2801 | unsigned getFieldIndex() const; |
2802 | |
2803 | /// Determines whether this field is mutable (C++ only). |
2804 | bool isMutable() const { return Mutable; } |
2805 | |
2806 | /// Determines whether this field is a bitfield. |
2807 | bool isBitField() const { return BitField; } |
2808 | |
2809 | /// Determines whether this is an unnamed bitfield. |
2810 | bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } |
2811 | |
2812 | /// Determines whether this field is a |
2813 | /// representative for an anonymous struct or union. Such fields are |
2814 | /// unnamed and are implicitly generated by the implementation to |
2815 | /// store the data for the anonymous union or struct. |
2816 | bool isAnonymousStructOrUnion() const; |
2817 | |
2818 | Expr *getBitWidth() const { |
2819 | if (!BitField) |
2820 | return nullptr; |
2821 | void *Ptr = InitStorage.getPointer(); |
2822 | if (getInClassInitStyle()) |
2823 | return static_cast<InitAndBitWidth*>(Ptr)->BitWidth; |
2824 | return static_cast<Expr*>(Ptr); |
2825 | } |
2826 | |
2827 | unsigned getBitWidthValue(const ASTContext &Ctx) const; |
2828 | |
2829 | /// Set the bit-field width for this member. |
2830 | // Note: used by some clients (i.e., do not remove it). |
2831 | void setBitWidth(Expr *Width) { |
2832 | assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set" ) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2833, __PRETTY_FUNCTION__)) |
2833 | "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set" ) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2833, __PRETTY_FUNCTION__)); |
2834 | assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast< void> (0) : __assert_fail ("Width && \"no bit width specified\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2834, __PRETTY_FUNCTION__)); |
2835 | InitStorage.setPointer( |
2836 | InitStorage.getInt() |
2837 | ? new (getASTContext()) |
2838 | InitAndBitWidth{getInClassInitializer(), Width} |
2839 | : static_cast<void*>(Width)); |
2840 | BitField = true; |
2841 | } |
2842 | |
2843 | /// Remove the bit-field width from this member. |
2844 | // Note: used by some clients (i.e., do not remove it). |
2845 | void removeBitWidth() { |
2846 | assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast <void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2846, __PRETTY_FUNCTION__)); |
2847 | InitStorage.setPointer(getInClassInitializer()); |
2848 | BitField = false; |
2849 | } |
2850 | |
2851 | /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields |
2852 | /// at all and instead act as a separator between contiguous runs of other |
2853 | /// bit-fields. |
2854 | bool isZeroLengthBitField(const ASTContext &Ctx) const; |
2855 | |
2856 | /// Determine if this field is a subobject of zero size, that is, either a |
2857 | /// zero-length bit-field or a field of empty class type with the |
2858 | /// [[no_unique_address]] attribute. |
2859 | bool isZeroSize(const ASTContext &Ctx) const; |
2860 | |
2861 | /// Get the kind of (C++11) default member initializer that this field has. |
2862 | InClassInitStyle getInClassInitStyle() const { |
2863 | InitStorageKind storageKind = InitStorage.getInt(); |
2864 | return (storageKind == ISK_CapturedVLAType |
2865 | ? ICIS_NoInit : (InClassInitStyle) storageKind); |
2866 | } |
2867 | |
2868 | /// Determine whether this member has a C++11 default member initializer. |
2869 | bool hasInClassInitializer() const { |
2870 | return getInClassInitStyle() != ICIS_NoInit; |
2871 | } |
2872 | |
2873 | /// Get the C++11 default member initializer for this member, or null if one |
2874 | /// has not been set. If a valid declaration has a default member initializer, |
2875 | /// but this returns null, then we have not parsed and attached it yet. |
2876 | Expr *getInClassInitializer() const { |
2877 | if (!hasInClassInitializer()) |
2878 | return nullptr; |
2879 | void *Ptr = InitStorage.getPointer(); |
2880 | if (BitField) |
2881 | return static_cast<InitAndBitWidth*>(Ptr)->Init; |
2882 | return static_cast<Expr*>(Ptr); |
2883 | } |
2884 | |
2885 | /// Set the C++11 in-class initializer for this member. |
2886 | void setInClassInitializer(Expr *Init) { |
2887 | assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer() ) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2887, __PRETTY_FUNCTION__)); |
2888 | if (BitField) |
2889 | static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init; |
2890 | else |
2891 | InitStorage.setPointer(Init); |
2892 | } |
2893 | |
2894 | /// Remove the C++11 in-class initializer from this member. |
2895 | void removeInClassInitializer() { |
2896 | assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove" ) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 2896, __PRETTY_FUNCTION__)); |
2897 | InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit); |
2898 | } |
2899 | |
2900 | /// Determine whether this member captures the variable length array |
2901 | /// type. |
2902 | bool hasCapturedVLAType() const { |
2903 | return InitStorage.getInt() == ISK_CapturedVLAType; |
2904 | } |
2905 | |
2906 | /// Get the captured variable length array type. |
2907 | const VariableArrayType *getCapturedVLAType() const { |
2908 | return hasCapturedVLAType() ? static_cast<const VariableArrayType *>( |
2909 | InitStorage.getPointer()) |
2910 | : nullptr; |
2911 | } |
2912 | |
2913 | /// Set the captured variable length array type for this field. |
2914 | void setCapturedVLAType(const VariableArrayType *VLAType); |
2915 | |
2916 | /// Returns the parent of this field declaration, which |
2917 | /// is the struct in which this field is defined. |
2918 | const RecordDecl *getParent() const { |
2919 | return cast<RecordDecl>(getDeclContext()); |
2920 | } |
2921 | |
2922 | RecordDecl *getParent() { |
2923 | return cast<RecordDecl>(getDeclContext()); |
2924 | } |
2925 | |
2926 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2927 | |
2928 | /// Retrieves the canonical declaration of this field. |
2929 | FieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2930 | const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2931 | |
2932 | // Implement isa/cast/dyncast/etc. |
2933 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2934 | static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } |
2935 | }; |
2936 | |
2937 | /// An instance of this object exists for each enum constant |
2938 | /// that is defined. For example, in "enum X {a,b}", each of a/b are |
2939 | /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a |
2940 | /// TagType for the X EnumDecl. |
2941 | class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> { |
2942 | Stmt *Init; // an integer constant expression |
2943 | llvm::APSInt Val; // The value. |
2944 | |
2945 | protected: |
2946 | EnumConstantDecl(DeclContext *DC, SourceLocation L, |
2947 | IdentifierInfo *Id, QualType T, Expr *E, |
2948 | const llvm::APSInt &V) |
2949 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} |
2950 | |
2951 | public: |
2952 | friend class StmtIteratorBase; |
2953 | |
2954 | static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, |
2955 | SourceLocation L, IdentifierInfo *Id, |
2956 | QualType T, Expr *E, |
2957 | const llvm::APSInt &V); |
2958 | static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2959 | |
2960 | const Expr *getInitExpr() const { return (const Expr*) Init; } |
2961 | Expr *getInitExpr() { return (Expr*) Init; } |
2962 | const llvm::APSInt &getInitVal() const { return Val; } |
2963 | |
2964 | void setInitExpr(Expr *E) { Init = (Stmt*) E; } |
2965 | void setInitVal(const llvm::APSInt &V) { Val = V; } |
2966 | |
2967 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2968 | |
2969 | /// Retrieves the canonical declaration of this enumerator. |
2970 | EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2971 | const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2972 | |
2973 | // Implement isa/cast/dyncast/etc. |
2974 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2975 | static bool classofKind(Kind K) { return K == EnumConstant; } |
2976 | }; |
2977 | |
2978 | /// Represents a field injected from an anonymous union/struct into the parent |
2979 | /// scope. These are always implicit. |
2980 | class IndirectFieldDecl : public ValueDecl, |
2981 | public Mergeable<IndirectFieldDecl> { |
2982 | NamedDecl **Chaining; |
2983 | unsigned ChainingSize; |
2984 | |
2985 | IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L, |
2986 | DeclarationName N, QualType T, |
2987 | MutableArrayRef<NamedDecl *> CH); |
2988 | |
2989 | void anchor() override; |
2990 | |
2991 | public: |
2992 | friend class ASTDeclReader; |
2993 | |
2994 | static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, |
2995 | SourceLocation L, IdentifierInfo *Id, |
2996 | QualType T, llvm::MutableArrayRef<NamedDecl *> CH); |
2997 | |
2998 | static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2999 | |
3000 | using chain_iterator = ArrayRef<NamedDecl *>::const_iterator; |
3001 | |
3002 | ArrayRef<NamedDecl *> chain() const { |
3003 | return llvm::makeArrayRef(Chaining, ChainingSize); |
3004 | } |
3005 | chain_iterator chain_begin() const { return chain().begin(); } |
3006 | chain_iterator chain_end() const { return chain().end(); } |
3007 | |
3008 | unsigned getChainingSize() const { return ChainingSize; } |
3009 | |
3010 | FieldDecl *getAnonField() const { |
3011 | assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 3011, __PRETTY_FUNCTION__)); |
3012 | return cast<FieldDecl>(chain().back()); |
3013 | } |
3014 | |
3015 | VarDecl *getVarDecl() const { |
3016 | assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 3016, __PRETTY_FUNCTION__)); |
3017 | return dyn_cast<VarDecl>(chain().front()); |
3018 | } |
3019 | |
3020 | IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3021 | const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3022 | |
3023 | // Implement isa/cast/dyncast/etc. |
3024 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3025 | static bool classofKind(Kind K) { return K == IndirectField; } |
3026 | }; |
3027 | |
3028 | /// Represents a declaration of a type. |
3029 | class TypeDecl : public NamedDecl { |
3030 | friend class ASTContext; |
3031 | |
3032 | /// This indicates the Type object that represents |
3033 | /// this TypeDecl. It is a cache maintained by |
3034 | /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and |
3035 | /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. |
3036 | mutable const Type *TypeForDecl = nullptr; |
3037 | |
3038 | /// The start of the source range for this declaration. |
3039 | SourceLocation LocStart; |
3040 | |
3041 | void anchor() override; |
3042 | |
3043 | protected: |
3044 | TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, |
3045 | SourceLocation StartL = SourceLocation()) |
3046 | : NamedDecl(DK, DC, L, Id), LocStart(StartL) {} |
3047 | |
3048 | public: |
3049 | // Low-level accessor. If you just want the type defined by this node, |
3050 | // check out ASTContext::getTypeDeclType or one of |
3051 | // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you |
3052 | // already know the specific kind of node this is. |
3053 | const Type *getTypeForDecl() const { return TypeForDecl; } |
3054 | void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } |
3055 | |
3056 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
3057 | void setLocStart(SourceLocation L) { LocStart = L; } |
3058 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3059 | if (LocStart.isValid()) |
3060 | return SourceRange(LocStart, getLocation()); |
3061 | else |
3062 | return SourceRange(getLocation()); |
3063 | } |
3064 | |
3065 | // Implement isa/cast/dyncast/etc. |
3066 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3067 | static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } |
3068 | }; |
3069 | |
3070 | /// Base class for declarations which introduce a typedef-name. |
3071 | class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { |
3072 | struct alignas(8) ModedTInfo { |
3073 | TypeSourceInfo *first; |
3074 | QualType second; |
3075 | }; |
3076 | |
3077 | /// If int part is 0, we have not computed IsTransparentTag. |
3078 | /// Otherwise, IsTransparentTag is (getInt() >> 1). |
3079 | mutable llvm::PointerIntPair< |
3080 | llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2> |
3081 | MaybeModedTInfo; |
3082 | |
3083 | void anchor() override; |
3084 | |
3085 | protected: |
3086 | TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC, |
3087 | SourceLocation StartLoc, SourceLocation IdLoc, |
3088 | IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3089 | : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C), |
3090 | MaybeModedTInfo(TInfo, 0) {} |
3091 | |
3092 | using redeclarable_base = Redeclarable<TypedefNameDecl>; |
3093 | |
3094 | TypedefNameDecl *getNextRedeclarationImpl() override { |
3095 | return getNextRedeclaration(); |
3096 | } |
3097 | |
3098 | TypedefNameDecl *getPreviousDeclImpl() override { |
3099 | return getPreviousDecl(); |
3100 | } |
3101 | |
3102 | TypedefNameDecl *getMostRecentDeclImpl() override { |
3103 | return getMostRecentDecl(); |
3104 | } |
3105 | |
3106 | public: |
3107 | using redecl_range = redeclarable_base::redecl_range; |
3108 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3109 | |
3110 | using redeclarable_base::redecls_begin; |
3111 | using redeclarable_base::redecls_end; |
3112 | using redeclarable_base::redecls; |
3113 | using redeclarable_base::getPreviousDecl; |
3114 | using redeclarable_base::getMostRecentDecl; |
3115 | using redeclarable_base::isFirstDecl; |
3116 | |
3117 | bool isModed() const { |
3118 | return MaybeModedTInfo.getPointer().is<ModedTInfo *>(); |
3119 | } |
3120 | |
3121 | TypeSourceInfo *getTypeSourceInfo() const { |
3122 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first |
3123 | : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>(); |
3124 | } |
3125 | |
3126 | QualType getUnderlyingType() const { |
3127 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second |
3128 | : MaybeModedTInfo.getPointer() |
3129 | .get<TypeSourceInfo *>() |
3130 | ->getType(); |
3131 | } |
3132 | |
3133 | void setTypeSourceInfo(TypeSourceInfo *newType) { |
3134 | MaybeModedTInfo.setPointer(newType); |
3135 | } |
3136 | |
3137 | void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) { |
3138 | MaybeModedTInfo.setPointer(new (getASTContext(), 8) |
3139 | ModedTInfo({unmodedTSI, modedTy})); |
3140 | } |
3141 | |
3142 | /// Retrieves the canonical declaration of this typedef-name. |
3143 | TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3144 | const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3145 | |
3146 | /// Retrieves the tag declaration for which this is the typedef name for |
3147 | /// linkage purposes, if any. |
3148 | /// |
3149 | /// \param AnyRedecl Look for the tag declaration in any redeclaration of |
3150 | /// this typedef declaration. |
3151 | TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const; |
3152 | |
3153 | /// Determines if this typedef shares a name and spelling location with its |
3154 | /// underlying tag type, as is the case with the NS_ENUM macro. |
3155 | bool isTransparentTag() const { |
3156 | if (MaybeModedTInfo.getInt()) |
3157 | return MaybeModedTInfo.getInt() & 0x2; |
3158 | return isTransparentTagSlow(); |
3159 | } |
3160 | |
3161 | // Implement isa/cast/dyncast/etc. |
3162 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3163 | static bool classofKind(Kind K) { |
3164 | return K >= firstTypedefName && K <= lastTypedefName; |
3165 | } |
3166 | |
3167 | private: |
3168 | bool isTransparentTagSlow() const; |
3169 | }; |
3170 | |
3171 | /// Represents the declaration of a typedef-name via the 'typedef' |
3172 | /// type specifier. |
3173 | class TypedefDecl : public TypedefNameDecl { |
3174 | TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3175 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3176 | : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {} |
3177 | |
3178 | public: |
3179 | static TypedefDecl *Create(ASTContext &C, DeclContext *DC, |
3180 | SourceLocation StartLoc, SourceLocation IdLoc, |
3181 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
3182 | static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3183 | |
3184 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3185 | |
3186 | // Implement isa/cast/dyncast/etc. |
3187 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3188 | static bool classofKind(Kind K) { return K == Typedef; } |
3189 | }; |
3190 | |
3191 | /// Represents the declaration of a typedef-name via a C++11 |
3192 | /// alias-declaration. |
3193 | class TypeAliasDecl : public TypedefNameDecl { |
3194 | /// The template for which this is the pattern, if any. |
3195 | TypeAliasTemplateDecl *Template; |
3196 | |
3197 | TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3198 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3199 | : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo), |
3200 | Template(nullptr) {} |
3201 | |
3202 | public: |
3203 | static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, |
3204 | SourceLocation StartLoc, SourceLocation IdLoc, |
3205 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
3206 | static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3207 | |
3208 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3209 | |
3210 | TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; } |
3211 | void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; } |
3212 | |
3213 | // Implement isa/cast/dyncast/etc. |
3214 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3215 | static bool classofKind(Kind K) { return K == TypeAlias; } |
3216 | }; |
3217 | |
3218 | /// Represents the declaration of a struct/union/class/enum. |
3219 | class TagDecl : public TypeDecl, |
3220 | public DeclContext, |
3221 | public Redeclarable<TagDecl> { |
3222 | // This class stores some data in DeclContext::TagDeclBits |
3223 | // to save some space. Use the provided accessors to access it. |
3224 | public: |
3225 | // This is really ugly. |
3226 | using TagKind = TagTypeKind; |
3227 | |
3228 | private: |
3229 | SourceRange BraceRange; |
3230 | |
3231 | // A struct representing syntactic qualifier info, |
3232 | // to be used for the (uncommon) case of out-of-line declarations. |
3233 | using ExtInfo = QualifierInfo; |
3234 | |
3235 | /// If the (out-of-line) tag declaration name |
3236 | /// is qualified, it points to the qualifier info (nns and range); |
3237 | /// otherwise, if the tag declaration is anonymous and it is part of |
3238 | /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); |
3239 | /// otherwise, if the tag declaration is anonymous and it is used as a |
3240 | /// declaration specifier for variables, it points to the first VarDecl (used |
3241 | /// for mangling); |
3242 | /// otherwise, it is a null (TypedefNameDecl) pointer. |
3243 | llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier; |
3244 | |
3245 | bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); } |
3246 | ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); } |
3247 | const ExtInfo *getExtInfo() const { |
3248 | return TypedefNameDeclOrQualifier.get<ExtInfo *>(); |
3249 | } |
3250 | |
3251 | protected: |
3252 | TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3253 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
3254 | SourceLocation StartL); |
3255 | |
3256 | using redeclarable_base = Redeclarable<TagDecl>; |
3257 | |
3258 | TagDecl *getNextRedeclarationImpl() override { |
3259 | return getNextRedeclaration(); |
3260 | } |
3261 | |
3262 | TagDecl *getPreviousDeclImpl() override { |
3263 | return getPreviousDecl(); |
3264 | } |
3265 | |
3266 | TagDecl *getMostRecentDeclImpl() override { |
3267 | return getMostRecentDecl(); |
3268 | } |
3269 | |
3270 | /// Completes the definition of this tag declaration. |
3271 | /// |
3272 | /// This is a helper function for derived classes. |
3273 | void completeDefinition(); |
3274 | |
3275 | /// True if this decl is currently being defined. |
3276 | void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; } |
3277 | |
3278 | /// Indicates whether it is possible for declarations of this kind |
3279 | /// to have an out-of-date definition. |
3280 | /// |
3281 | /// This option is only enabled when modules are enabled. |
3282 | void setMayHaveOutOfDateDef(bool V = true) { |
3283 | TagDeclBits.MayHaveOutOfDateDef = V; |
3284 | } |
3285 | |
3286 | public: |
3287 | friend class ASTDeclReader; |
3288 | friend class ASTDeclWriter; |
3289 | |
3290 | using redecl_range = redeclarable_base::redecl_range; |
3291 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3292 | |
3293 | using redeclarable_base::redecls_begin; |
3294 | using redeclarable_base::redecls_end; |
3295 | using redeclarable_base::redecls; |
3296 | using redeclarable_base::getPreviousDecl; |
3297 | using redeclarable_base::getMostRecentDecl; |
3298 | using redeclarable_base::isFirstDecl; |
3299 | |
3300 | SourceRange getBraceRange() const { return BraceRange; } |
3301 | void setBraceRange(SourceRange R) { BraceRange = R; } |
3302 | |
3303 | /// Return SourceLocation representing start of source |
3304 | /// range ignoring outer template declarations. |
3305 | SourceLocation getInnerLocStart() const { return getBeginLoc(); } |
3306 | |
3307 | /// Return SourceLocation representing start of source |
3308 | /// range taking into account any outer template declarations. |
3309 | SourceLocation getOuterLocStart() const; |
3310 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3311 | |
3312 | TagDecl *getCanonicalDecl() override; |
3313 | const TagDecl *getCanonicalDecl() const { |
3314 | return const_cast<TagDecl*>(this)->getCanonicalDecl(); |
3315 | } |
3316 | |
3317 | /// Return true if this declaration is a completion definition of the type. |
3318 | /// Provided for consistency. |
3319 | bool isThisDeclarationADefinition() const { |
3320 | return isCompleteDefinition(); |
3321 | } |
3322 | |
3323 | /// Return true if this decl has its body fully specified. |
3324 | bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; } |
3325 | |
3326 | /// True if this decl has its body fully specified. |
3327 | void setCompleteDefinition(bool V = true) { |
3328 | TagDeclBits.IsCompleteDefinition = V; |
3329 | } |
3330 | |
3331 | /// Return true if this complete decl is |
3332 | /// required to be complete for some existing use. |
3333 | bool isCompleteDefinitionRequired() const { |
3334 | return TagDeclBits.IsCompleteDefinitionRequired; |
3335 | } |
3336 | |
3337 | /// True if this complete decl is |
3338 | /// required to be complete for some existing use. |
3339 | void setCompleteDefinitionRequired(bool V = true) { |
3340 | TagDeclBits.IsCompleteDefinitionRequired = V; |
3341 | } |
3342 | |
3343 | /// Return true if this decl is currently being defined. |
3344 | bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; } |
3345 | |
3346 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
3347 | /// for the very first time) in the syntax of a declarator. |
3348 | bool isEmbeddedInDeclarator() const { |
3349 | return TagDeclBits.IsEmbeddedInDeclarator; |
3350 | } |
3351 | |
3352 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
3353 | /// for the very first time) in the syntax of a declarator. |
3354 | void setEmbeddedInDeclarator(bool isInDeclarator) { |
3355 | TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator; |
3356 | } |
3357 | |
3358 | /// True if this tag is free standing, e.g. "struct foo;". |
3359 | bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; } |
3360 | |
3361 | /// True if this tag is free standing, e.g. "struct foo;". |
3362 | void setFreeStanding(bool isFreeStanding = true) { |
3363 | TagDeclBits.IsFreeStanding = isFreeStanding; |
3364 | } |
3365 | |
3366 | /// Indicates whether it is possible for declarations of this kind |
3367 | /// to have an out-of-date definition. |
3368 | /// |
3369 | /// This option is only enabled when modules are enabled. |
3370 | bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; } |
3371 | |
3372 | /// Whether this declaration declares a type that is |
3373 | /// dependent, i.e., a type that somehow depends on template |
3374 | /// parameters. |
3375 | bool isDependentType() const { return isDependentContext(); } |
3376 | |
3377 | /// Starts the definition of this tag declaration. |
3378 | /// |
3379 | /// This method should be invoked at the beginning of the definition |
3380 | /// of this tag declaration. It will set the tag type into a state |
3381 | /// where it is in the process of being defined. |
3382 | void startDefinition(); |
3383 | |
3384 | /// Returns the TagDecl that actually defines this |
3385 | /// struct/union/class/enum. When determining whether or not a |
3386 | /// struct/union/class/enum has a definition, one should use this |
3387 | /// method as opposed to 'isDefinition'. 'isDefinition' indicates |
3388 | /// whether or not a specific TagDecl is defining declaration, not |
3389 | /// whether or not the struct/union/class/enum type is defined. |
3390 | /// This method returns NULL if there is no TagDecl that defines |
3391 | /// the struct/union/class/enum. |
3392 | TagDecl *getDefinition() const; |
3393 | |
3394 | StringRef getKindName() const { |
3395 | return TypeWithKeyword::getTagTypeKindName(getTagKind()); |
3396 | } |
3397 | |
3398 | TagKind getTagKind() const { |
3399 | return static_cast<TagKind>(TagDeclBits.TagDeclKind); |
3400 | } |
3401 | |
3402 | void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; } |
3403 | |
3404 | bool isStruct() const { return getTagKind() == TTK_Struct; } |
3405 | bool isInterface() const { return getTagKind() == TTK_Interface; } |
3406 | bool isClass() const { return getTagKind() == TTK_Class; } |
3407 | bool isUnion() const { return getTagKind() == TTK_Union; } |
3408 | bool isEnum() const { return getTagKind() == TTK_Enum; } |
3409 | |
3410 | /// Is this tag type named, either directly or via being defined in |
3411 | /// a typedef of this type? |
3412 | /// |
3413 | /// C++11 [basic.link]p8: |
3414 | /// A type is said to have linkage if and only if: |
3415 | /// - it is a class or enumeration type that is named (or has a |
3416 | /// name for linkage purposes) and the name has linkage; ... |
3417 | /// C++11 [dcl.typedef]p9: |
3418 | /// If the typedef declaration defines an unnamed class (or enum), |
3419 | /// the first typedef-name declared by the declaration to be that |
3420 | /// class type (or enum type) is used to denote the class type (or |
3421 | /// enum type) for linkage purposes only. |
3422 | /// |
3423 | /// C does not have an analogous rule, but the same concept is |
3424 | /// nonetheless useful in some places. |
3425 | bool hasNameForLinkage() const { |
3426 | return (getDeclName() || getTypedefNameForAnonDecl()); |
3427 | } |
3428 | |
3429 | TypedefNameDecl *getTypedefNameForAnonDecl() const { |
3430 | return hasExtInfo() ? nullptr |
3431 | : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>(); |
3432 | } |
3433 | |
3434 | void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); |
3435 | |
3436 | /// Retrieve the nested-name-specifier that qualifies the name of this |
3437 | /// declaration, if it was present in the source. |
3438 | NestedNameSpecifier *getQualifier() const { |
3439 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
3440 | : nullptr; |
3441 | } |
3442 | |
3443 | /// Retrieve the nested-name-specifier (with source-location |
3444 | /// information) that qualifies the name of this declaration, if it was |
3445 | /// present in the source. |
3446 | NestedNameSpecifierLoc getQualifierLoc() const { |
3447 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
3448 | : NestedNameSpecifierLoc(); |
3449 | } |
3450 | |
3451 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
3452 | |
3453 | unsigned getNumTemplateParameterLists() const { |
3454 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
3455 | } |
3456 | |
3457 | TemplateParameterList *getTemplateParameterList(unsigned i) const { |
3458 | assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void > (0) : __assert_fail ("i < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 3458, __PRETTY_FUNCTION__)); |
3459 | return getExtInfo()->TemplParamLists[i]; |
3460 | } |
3461 | |
3462 | void setTemplateParameterListsInfo(ASTContext &Context, |
3463 | ArrayRef<TemplateParameterList *> TPLists); |
3464 | |
3465 | // Implement isa/cast/dyncast/etc. |
3466 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3467 | static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } |
3468 | |
3469 | static DeclContext *castToDeclContext(const TagDecl *D) { |
3470 | return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); |
3471 | } |
3472 | |
3473 | static TagDecl *castFromDeclContext(const DeclContext *DC) { |
3474 | return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); |
3475 | } |
3476 | }; |
3477 | |
3478 | /// Represents an enum. In C++11, enums can be forward-declared |
3479 | /// with a fixed underlying type, and in C we allow them to be forward-declared |
3480 | /// with no underlying type as an extension. |
3481 | class EnumDecl : public TagDecl { |
3482 | // This class stores some data in DeclContext::EnumDeclBits |
3483 | // to save some space. Use the provided accessors to access it. |
3484 | |
3485 | /// This represent the integer type that the enum corresponds |
3486 | /// to for code generation purposes. Note that the enumerator constants may |
3487 | /// have a different type than this does. |
3488 | /// |
3489 | /// If the underlying integer type was explicitly stated in the source |
3490 | /// code, this is a TypeSourceInfo* for that type. Otherwise this type |
3491 | /// was automatically deduced somehow, and this is a Type*. |
3492 | /// |
3493 | /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in |
3494 | /// some cases it won't. |
3495 | /// |
3496 | /// The underlying type of an enumeration never has any qualifiers, so |
3497 | /// we can get away with just storing a raw Type*, and thus save an |
3498 | /// extra pointer when TypeSourceInfo is needed. |
3499 | llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType; |
3500 | |
3501 | /// The integer type that values of this type should |
3502 | /// promote to. In C, enumerators are generally of an integer type |
3503 | /// directly, but gcc-style large enumerators (and all enumerators |
3504 | /// in C++) are of the enum type instead. |
3505 | QualType PromotionType; |
3506 | |
3507 | /// If this enumeration is an instantiation of a member enumeration |
3508 | /// of a class template specialization, this is the member specialization |
3509 | /// information. |
3510 | MemberSpecializationInfo *SpecializationInfo = nullptr; |
3511 | |
3512 | /// Store the ODRHash after first calculation. |
3513 | /// The corresponding flag HasODRHash is in EnumDeclBits |
3514 | /// and can be accessed with the provided accessors. |
3515 | unsigned ODRHash; |
3516 | |
3517 | EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3518 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
3519 | bool Scoped, bool ScopedUsingClassTag, bool Fixed); |
3520 | |
3521 | void anchor() override; |
3522 | |
3523 | void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
3524 | TemplateSpecializationKind TSK); |
3525 | |
3526 | /// Sets the width in bits required to store all the |
3527 | /// non-negative enumerators of this enum. |
3528 | void setNumPositiveBits(unsigned Num) { |
3529 | EnumDeclBits.NumPositiveBits = Num; |
3530 | assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount" ) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 3530, __PRETTY_FUNCTION__)); |
3531 | } |
3532 | |
3533 | /// Returns the width in bits required to store all the |
3534 | /// negative enumerators of this enum. (see getNumNegativeBits) |
3535 | void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; } |
3536 | |
3537 | /// True if this tag declaration is a scoped enumeration. Only |
3538 | /// possible in C++11 mode. |
3539 | void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; } |
3540 | |
3541 | /// If this tag declaration is a scoped enum, |
3542 | /// then this is true if the scoped enum was declared using the class |
3543 | /// tag, false if it was declared with the struct tag. No meaning is |
3544 | /// associated if this tag declaration is not a scoped enum. |
3545 | void setScopedUsingClassTag(bool ScopedUCT = true) { |
3546 | EnumDeclBits.IsScopedUsingClassTag = ScopedUCT; |
3547 | } |
3548 | |
3549 | /// True if this is an Objective-C, C++11, or |
3550 | /// Microsoft-style enumeration with a fixed underlying type. |
3551 | void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; } |
3552 | |
3553 | /// True if a valid hash is stored in ODRHash. |
3554 | bool hasODRHash() const { return EnumDeclBits.HasODRHash; } |
3555 | void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; } |
3556 | |
3557 | public: |
3558 | friend class ASTDeclReader; |
3559 | |
3560 | EnumDecl *getCanonicalDecl() override { |
3561 | return cast<EnumDecl>(TagDecl::getCanonicalDecl()); |
3562 | } |
3563 | const EnumDecl *getCanonicalDecl() const { |
3564 | return const_cast<EnumDecl*>(this)->getCanonicalDecl(); |
3565 | } |
3566 | |
3567 | EnumDecl *getPreviousDecl() { |
3568 | return cast_or_null<EnumDecl>( |
3569 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3570 | } |
3571 | const EnumDecl *getPreviousDecl() const { |
3572 | return const_cast<EnumDecl*>(this)->getPreviousDecl(); |
3573 | } |
3574 | |
3575 | EnumDecl *getMostRecentDecl() { |
3576 | return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3577 | } |
3578 | const EnumDecl *getMostRecentDecl() const { |
3579 | return const_cast<EnumDecl*>(this)->getMostRecentDecl(); |
3580 | } |
3581 | |
3582 | EnumDecl *getDefinition() const { |
3583 | return cast_or_null<EnumDecl>(TagDecl::getDefinition()); |
3584 | } |
3585 | |
3586 | static EnumDecl *Create(ASTContext &C, DeclContext *DC, |
3587 | SourceLocation StartLoc, SourceLocation IdLoc, |
3588 | IdentifierInfo *Id, EnumDecl *PrevDecl, |
3589 | bool IsScoped, bool IsScopedUsingClassTag, |
3590 | bool IsFixed); |
3591 | static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3592 | |
3593 | /// When created, the EnumDecl corresponds to a |
3594 | /// forward-declared enum. This method is used to mark the |
3595 | /// declaration as being defined; its enumerators have already been |
3596 | /// added (via DeclContext::addDecl). NewType is the new underlying |
3597 | /// type of the enumeration type. |
3598 | void completeDefinition(QualType NewType, |
3599 | QualType PromotionType, |
3600 | unsigned NumPositiveBits, |
3601 | unsigned NumNegativeBits); |
3602 | |
3603 | // Iterates through the enumerators of this enumeration. |
3604 | using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>; |
3605 | using enumerator_range = |
3606 | llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>; |
3607 | |
3608 | enumerator_range enumerators() const { |
3609 | return enumerator_range(enumerator_begin(), enumerator_end()); |
3610 | } |
3611 | |
3612 | enumerator_iterator enumerator_begin() const { |
3613 | const EnumDecl *E = getDefinition(); |
3614 | if (!E) |
3615 | E = this; |
3616 | return enumerator_iterator(E->decls_begin()); |
3617 | } |
3618 | |
3619 | enumerator_iterator enumerator_end() const { |
3620 | const EnumDecl *E = getDefinition(); |
3621 | if (!E) |
3622 | E = this; |
3623 | return enumerator_iterator(E->decls_end()); |
3624 | } |
3625 | |
3626 | /// Return the integer type that enumerators should promote to. |
3627 | QualType getPromotionType() const { return PromotionType; } |
3628 | |
3629 | /// Set the promotion type. |
3630 | void setPromotionType(QualType T) { PromotionType = T; } |
3631 | |
3632 | /// Return the integer type this enum decl corresponds to. |
3633 | /// This returns a null QualType for an enum forward definition with no fixed |
3634 | /// underlying type. |
3635 | QualType getIntegerType() const { |
3636 | if (!IntegerType) |
3637 | return QualType(); |
3638 | if (const Type *T = IntegerType.dyn_cast<const Type*>()) |
3639 | return QualType(T, 0); |
3640 | return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType(); |
3641 | } |
3642 | |
3643 | /// Set the underlying integer type. |
3644 | void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } |
3645 | |
3646 | /// Set the underlying integer type source info. |
3647 | void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; } |
3648 | |
3649 | /// Return the type source info for the underlying integer type, |
3650 | /// if no type source info exists, return 0. |
3651 | TypeSourceInfo *getIntegerTypeSourceInfo() const { |
3652 | return IntegerType.dyn_cast<TypeSourceInfo*>(); |
3653 | } |
3654 | |
3655 | /// Retrieve the source range that covers the underlying type if |
3656 | /// specified. |
3657 | SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__)); |
3658 | |
3659 | /// Returns the width in bits required to store all the |
3660 | /// non-negative enumerators of this enum. |
3661 | unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; } |
3662 | |
3663 | /// Returns the width in bits required to store all the |
3664 | /// negative enumerators of this enum. These widths include |
3665 | /// the rightmost leading 1; that is: |
3666 | /// |
3667 | /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS |
3668 | /// ------------------------ ------- ----------------- |
3669 | /// -1 1111111 1 |
3670 | /// -10 1110110 5 |
3671 | /// -101 1001011 8 |
3672 | unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; } |
3673 | |
3674 | /// Returns true if this is a C++11 scoped enumeration. |
3675 | bool isScoped() const { return EnumDeclBits.IsScoped; } |
3676 | |
3677 | /// Returns true if this is a C++11 scoped enumeration. |
3678 | bool isScopedUsingClassTag() const { |
3679 | return EnumDeclBits.IsScopedUsingClassTag; |
3680 | } |
3681 | |
3682 | /// Returns true if this is an Objective-C, C++11, or |
3683 | /// Microsoft-style enumeration with a fixed underlying type. |
3684 | bool isFixed() const { return EnumDeclBits.IsFixed; } |
3685 | |
3686 | unsigned getODRHash(); |
3687 | |
3688 | /// Returns true if this can be considered a complete type. |
3689 | bool isComplete() const { |
3690 | // IntegerType is set for fixed type enums and non-fixed but implicitly |
3691 | // int-sized Microsoft enums. |
3692 | return isCompleteDefinition() || IntegerType; |
3693 | } |
3694 | |
3695 | /// Returns true if this enum is either annotated with |
3696 | /// enum_extensibility(closed) or isn't annotated with enum_extensibility. |
3697 | bool isClosed() const; |
3698 | |
3699 | /// Returns true if this enum is annotated with flag_enum and isn't annotated |
3700 | /// with enum_extensibility(open). |
3701 | bool isClosedFlag() const; |
3702 | |
3703 | /// Returns true if this enum is annotated with neither flag_enum nor |
3704 | /// enum_extensibility(open). |
3705 | bool isClosedNonFlag() const; |
3706 | |
3707 | /// Retrieve the enum definition from which this enumeration could |
3708 | /// be instantiated, if it is an instantiation (rather than a non-template). |
3709 | EnumDecl *getTemplateInstantiationPattern() const; |
3710 | |
3711 | /// Returns the enumeration (declared within the template) |
3712 | /// from which this enumeration type was instantiated, or NULL if |
3713 | /// this enumeration was not instantiated from any template. |
3714 | EnumDecl *getInstantiatedFromMemberEnum() const; |
3715 | |
3716 | /// If this enumeration is a member of a specialization of a |
3717 | /// templated class, determine what kind of template specialization |
3718 | /// or instantiation this is. |
3719 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
3720 | |
3721 | /// For an enumeration member that was instantiated from a member |
3722 | /// enumeration of a templated class, set the template specialiation kind. |
3723 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
3724 | SourceLocation PointOfInstantiation = SourceLocation()); |
3725 | |
3726 | /// If this enumeration is an instantiation of a member enumeration of |
3727 | /// a class template specialization, retrieves the member specialization |
3728 | /// information. |
3729 | MemberSpecializationInfo *getMemberSpecializationInfo() const { |
3730 | return SpecializationInfo; |
3731 | } |
3732 | |
3733 | /// Specify that this enumeration is an instantiation of the |
3734 | /// member enumeration ED. |
3735 | void setInstantiationOfMemberEnum(EnumDecl *ED, |
3736 | TemplateSpecializationKind TSK) { |
3737 | setInstantiationOfMemberEnum(getASTContext(), ED, TSK); |
3738 | } |
3739 | |
3740 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3741 | static bool classofKind(Kind K) { return K == Enum; } |
3742 | }; |
3743 | |
3744 | /// Represents a struct/union/class. For example: |
3745 | /// struct X; // Forward declaration, no "body". |
3746 | /// union Y { int A, B; }; // Has body with members A and B (FieldDecls). |
3747 | /// This decl will be marked invalid if *any* members are invalid. |
3748 | class RecordDecl : public TagDecl { |
3749 | // This class stores some data in DeclContext::RecordDeclBits |
3750 | // to save some space. Use the provided accessors to access it. |
3751 | public: |
3752 | friend class DeclContext; |
3753 | /// Enum that represents the different ways arguments are passed to and |
3754 | /// returned from function calls. This takes into account the target-specific |
3755 | /// and version-specific rules along with the rules determined by the |
3756 | /// language. |
3757 | enum ArgPassingKind : unsigned { |
3758 | /// The argument of this type can be passed directly in registers. |
3759 | APK_CanPassInRegs, |
3760 | |
3761 | /// The argument of this type cannot be passed directly in registers. |
3762 | /// Records containing this type as a subobject are not forced to be passed |
3763 | /// indirectly. This value is used only in C++. This value is required by |
3764 | /// C++ because, in uncommon situations, it is possible for a class to have |
3765 | /// only trivial copy/move constructors even when one of its subobjects has |
3766 | /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move |
3767 | /// constructor in the derived class is deleted). |
3768 | APK_CannotPassInRegs, |
3769 | |
3770 | /// The argument of this type cannot be passed directly in registers. |
3771 | /// Records containing this type as a subobject are forced to be passed |
3772 | /// indirectly. |
3773 | APK_CanNeverPassInRegs |
3774 | }; |
3775 | |
3776 | protected: |
3777 | RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3778 | SourceLocation StartLoc, SourceLocation IdLoc, |
3779 | IdentifierInfo *Id, RecordDecl *PrevDecl); |
3780 | |
3781 | public: |
3782 | static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
3783 | SourceLocation StartLoc, SourceLocation IdLoc, |
3784 | IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr); |
3785 | static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
3786 | |
3787 | RecordDecl *getPreviousDecl() { |
3788 | return cast_or_null<RecordDecl>( |
3789 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3790 | } |
3791 | const RecordDecl *getPreviousDecl() const { |
3792 | return const_cast<RecordDecl*>(this)->getPreviousDecl(); |
3793 | } |
3794 | |
3795 | RecordDecl *getMostRecentDecl() { |
3796 | return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3797 | } |
3798 | const RecordDecl *getMostRecentDecl() const { |
3799 | return const_cast<RecordDecl*>(this)->getMostRecentDecl(); |
3800 | } |
3801 | |
3802 | bool hasFlexibleArrayMember() const { |
3803 | return RecordDeclBits.HasFlexibleArrayMember; |
3804 | } |
3805 | |
3806 | void setHasFlexibleArrayMember(bool V) { |
3807 | RecordDeclBits.HasFlexibleArrayMember = V; |
3808 | } |
3809 | |
3810 | /// Whether this is an anonymous struct or union. To be an anonymous |
3811 | /// struct or union, it must have been declared without a name and |
3812 | /// there must be no objects of this type declared, e.g., |
3813 | /// @code |
3814 | /// union { int i; float f; }; |
3815 | /// @endcode |
3816 | /// is an anonymous union but neither of the following are: |
3817 | /// @code |
3818 | /// union X { int i; float f; }; |
3819 | /// union { int i; float f; } obj; |
3820 | /// @endcode |
3821 | bool isAnonymousStructOrUnion() const { |
3822 | return RecordDeclBits.AnonymousStructOrUnion; |
3823 | } |
3824 | |
3825 | void setAnonymousStructOrUnion(bool Anon) { |
3826 | RecordDeclBits.AnonymousStructOrUnion = Anon; |
3827 | } |
3828 | |
3829 | bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; } |
3830 | void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; } |
3831 | |
3832 | bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; } |
3833 | |
3834 | void setHasVolatileMember(bool val) { |
3835 | RecordDeclBits.HasVolatileMember = val; |
3836 | } |
3837 | |
3838 | bool hasLoadedFieldsFromExternalStorage() const { |
3839 | return RecordDeclBits.LoadedFieldsFromExternalStorage; |
3840 | } |
3841 | |
3842 | void setHasLoadedFieldsFromExternalStorage(bool val) const { |
3843 | RecordDeclBits.LoadedFieldsFromExternalStorage = val; |
3844 | } |
3845 | |
3846 | /// Functions to query basic properties of non-trivial C structs. |
3847 | bool isNonTrivialToPrimitiveDefaultInitialize() const { |
3848 | return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize; |
3849 | } |
3850 | |
3851 | void setNonTrivialToPrimitiveDefaultInitialize(bool V) { |
3852 | RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V; |
3853 | } |
3854 | |
3855 | bool isNonTrivialToPrimitiveCopy() const { |
3856 | return RecordDeclBits.NonTrivialToPrimitiveCopy; |
3857 | } |
3858 | |
3859 | void setNonTrivialToPrimitiveCopy(bool V) { |
3860 | RecordDeclBits.NonTrivialToPrimitiveCopy = V; |
3861 | } |
3862 | |
3863 | bool isNonTrivialToPrimitiveDestroy() const { |
3864 | return RecordDeclBits.NonTrivialToPrimitiveDestroy; |
3865 | } |
3866 | |
3867 | void setNonTrivialToPrimitiveDestroy(bool V) { |
3868 | RecordDeclBits.NonTrivialToPrimitiveDestroy = V; |
3869 | } |
3870 | |
3871 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
3872 | return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion; |
3873 | } |
3874 | |
3875 | void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) { |
3876 | RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V; |
3877 | } |
3878 | |
3879 | bool hasNonTrivialToPrimitiveDestructCUnion() const { |
3880 | return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion; |
3881 | } |
3882 | |
3883 | void setHasNonTrivialToPrimitiveDestructCUnion(bool V) { |
3884 | RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V; |
3885 | } |
3886 | |
3887 | bool hasNonTrivialToPrimitiveCopyCUnion() const { |
3888 | return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion; |
3889 | } |
3890 | |
3891 | void setHasNonTrivialToPrimitiveCopyCUnion(bool V) { |
3892 | RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V; |
3893 | } |
3894 | |
3895 | /// Determine whether this class can be passed in registers. In C++ mode, |
3896 | /// it must have at least one trivial, non-deleted copy or move constructor. |
3897 | /// FIXME: This should be set as part of completeDefinition. |
3898 | bool canPassInRegisters() const { |
3899 | return getArgPassingRestrictions() == APK_CanPassInRegs; |
3900 | } |
3901 | |
3902 | ArgPassingKind getArgPassingRestrictions() const { |
3903 | return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions); |
3904 | } |
3905 | |
3906 | void setArgPassingRestrictions(ArgPassingKind Kind) { |
3907 | RecordDeclBits.ArgPassingRestrictions = Kind; |
3908 | } |
3909 | |
3910 | bool isParamDestroyedInCallee() const { |
3911 | return RecordDeclBits.ParamDestroyedInCallee; |
3912 | } |
3913 | |
3914 | void setParamDestroyedInCallee(bool V) { |
3915 | RecordDeclBits.ParamDestroyedInCallee = V; |
3916 | } |
3917 | |
3918 | /// Determines whether this declaration represents the |
3919 | /// injected class name. |
3920 | /// |
3921 | /// The injected class name in C++ is the name of the class that |
3922 | /// appears inside the class itself. For example: |
3923 | /// |
3924 | /// \code |
3925 | /// struct C { |
3926 | /// // C is implicitly declared here as a synonym for the class name. |
3927 | /// }; |
3928 | /// |
3929 | /// C::C c; // same as "C c;" |
3930 | /// \endcode |
3931 | bool isInjectedClassName() const; |
3932 | |
3933 | /// Determine whether this record is a class describing a lambda |
3934 | /// function object. |
3935 | bool isLambda() const; |
3936 | |
3937 | /// Determine whether this record is a record for captured variables in |
3938 | /// CapturedStmt construct. |
3939 | bool isCapturedRecord() const; |
3940 | |
3941 | /// Mark the record as a record for captured variables in CapturedStmt |
3942 | /// construct. |
3943 | void setCapturedRecord(); |
3944 | |
3945 | /// Returns the RecordDecl that actually defines |
3946 | /// this struct/union/class. When determining whether or not a |
3947 | /// struct/union/class is completely defined, one should use this |
3948 | /// method as opposed to 'isCompleteDefinition'. |
3949 | /// 'isCompleteDefinition' indicates whether or not a specific |
3950 | /// RecordDecl is a completed definition, not whether or not the |
3951 | /// record type is defined. This method returns NULL if there is |
3952 | /// no RecordDecl that defines the struct/union/tag. |
3953 | RecordDecl *getDefinition() const { |
3954 | return cast_or_null<RecordDecl>(TagDecl::getDefinition()); |
3955 | } |
3956 | |
3957 | // Iterator access to field members. The field iterator only visits |
3958 | // the non-static data members of this class, ignoring any static |
3959 | // data members, functions, constructors, destructors, etc. |
3960 | using field_iterator = specific_decl_iterator<FieldDecl>; |
3961 | using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>; |
3962 | |
3963 | field_range fields() const { return field_range(field_begin(), field_end()); } |
3964 | field_iterator field_begin() const; |
3965 | |
3966 | field_iterator field_end() const { |
3967 | return field_iterator(decl_iterator()); |
3968 | } |
3969 | |
3970 | // Whether there are any fields (non-static data members) in this record. |
3971 | bool field_empty() const { |
3972 | return field_begin() == field_end(); |
3973 | } |
3974 | |
3975 | /// Note that the definition of this type is now complete. |
3976 | virtual void completeDefinition(); |
3977 | |
3978 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3979 | static bool classofKind(Kind K) { |
3980 | return K >= firstRecord && K <= lastRecord; |
3981 | } |
3982 | |
3983 | /// Get whether or not this is an ms_struct which can |
3984 | /// be turned on with an attribute, pragma, or -mms-bitfields |
3985 | /// commandline option. |
3986 | bool isMsStruct(const ASTContext &C) const; |
3987 | |
3988 | /// Whether we are allowed to insert extra padding between fields. |
3989 | /// These padding are added to help AddressSanitizer detect |
3990 | /// intra-object-overflow bugs. |
3991 | bool mayInsertExtraPadding(bool EmitRemark = false) const; |
3992 | |
3993 | /// Finds the first data member which has a name. |
3994 | /// nullptr is returned if no named data member exists. |
3995 | const FieldDecl *findFirstNamedDataMember() const; |
3996 | |
3997 | private: |
3998 | /// Deserialize just the fields. |
3999 | void LoadFieldsFromExternalStorage() const; |
4000 | }; |
4001 | |
4002 | class FileScopeAsmDecl : public Decl { |
4003 | StringLiteral *AsmString; |
4004 | SourceLocation RParenLoc; |
4005 | |
4006 | FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, |
4007 | SourceLocation StartL, SourceLocation EndL) |
4008 | : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} |
4009 | |
4010 | virtual void anchor(); |
4011 | |
4012 | public: |
4013 | static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, |
4014 | StringLiteral *Str, SourceLocation AsmLoc, |
4015 | SourceLocation RParenLoc); |
4016 | |
4017 | static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4018 | |
4019 | SourceLocation getAsmLoc() const { return getLocation(); } |
4020 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4021 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4022 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4023 | return SourceRange(getAsmLoc(), getRParenLoc()); |
4024 | } |
4025 | |
4026 | const StringLiteral *getAsmString() const { return AsmString; } |
4027 | StringLiteral *getAsmString() { return AsmString; } |
4028 | void setAsmString(StringLiteral *Asm) { AsmString = Asm; } |
4029 | |
4030 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4031 | static bool classofKind(Kind K) { return K == FileScopeAsm; } |
4032 | }; |
4033 | |
4034 | /// Represents a block literal declaration, which is like an |
4035 | /// unnamed FunctionDecl. For example: |
4036 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
4037 | class BlockDecl : public Decl, public DeclContext { |
4038 | // This class stores some data in DeclContext::BlockDeclBits |
4039 | // to save some space. Use the provided accessors to access it. |
4040 | public: |
4041 | /// A class which contains all the information about a particular |
4042 | /// captured value. |
4043 | class Capture { |
4044 | enum { |
4045 | flag_isByRef = 0x1, |
4046 | flag_isNested = 0x2 |
4047 | }; |
4048 | |
4049 | /// The variable being captured. |
4050 | llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; |
4051 | |
4052 | /// The copy expression, expressed in terms of a DeclRef (or |
4053 | /// BlockDeclRef) to the captured variable. Only required if the |
4054 | /// variable has a C++ class type. |
4055 | Expr *CopyExpr; |
4056 | |
4057 | public: |
4058 | Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) |
4059 | : VariableAndFlags(variable, |
4060 | (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), |
4061 | CopyExpr(copy) {} |
4062 | |
4063 | /// The variable being captured. |
4064 | VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } |
4065 | |
4066 | /// Whether this is a "by ref" capture, i.e. a capture of a __block |
4067 | /// variable. |
4068 | bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } |
4069 | |
4070 | bool isEscapingByref() const { |
4071 | return getVariable()->isEscapingByref(); |
4072 | } |
4073 | |
4074 | bool isNonEscapingByref() const { |
4075 | return getVariable()->isNonEscapingByref(); |
4076 | } |
4077 | |
4078 | /// Whether this is a nested capture, i.e. the variable captured |
4079 | /// is not from outside the immediately enclosing function/block. |
4080 | bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } |
4081 | |
4082 | bool hasCopyExpr() const { return CopyExpr != nullptr; } |
4083 | Expr *getCopyExpr() const { return CopyExpr; } |
4084 | void setCopyExpr(Expr *e) { CopyExpr = e; } |
4085 | }; |
4086 | |
4087 | private: |
4088 | /// A new[]'d array of pointers to ParmVarDecls for the formal |
4089 | /// parameters of this function. This is null if a prototype or if there are |
4090 | /// no formals. |
4091 | ParmVarDecl **ParamInfo = nullptr; |
4092 | unsigned NumParams = 0; |
4093 | |
4094 | Stmt *Body = nullptr; |
4095 | TypeSourceInfo *SignatureAsWritten = nullptr; |
4096 | |
4097 | const Capture *Captures = nullptr; |
4098 | unsigned NumCaptures = 0; |
4099 | |
4100 | unsigned ManglingNumber = 0; |
4101 | Decl *ManglingContextDecl = nullptr; |
4102 | |
4103 | protected: |
4104 | BlockDecl(DeclContext *DC, SourceLocation CaretLoc); |
4105 | |
4106 | public: |
4107 | static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); |
4108 | static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4109 | |
4110 | SourceLocation getCaretLocation() const { return getLocation(); } |
4111 | |
4112 | bool isVariadic() const { return BlockDeclBits.IsVariadic; } |
4113 | void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; } |
4114 | |
4115 | CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } |
4116 | Stmt *getBody() const override { return (Stmt*) Body; } |
4117 | void setBody(CompoundStmt *B) { Body = (Stmt*) B; } |
4118 | |
4119 | void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } |
4120 | TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } |
4121 | |
4122 | // ArrayRef access to formal parameters. |
4123 | ArrayRef<ParmVarDecl *> parameters() const { |
4124 | return {ParamInfo, getNumParams()}; |
4125 | } |
4126 | MutableArrayRef<ParmVarDecl *> parameters() { |
4127 | return {ParamInfo, getNumParams()}; |
4128 | } |
4129 | |
4130 | // Iterator access to formal parameters. |
4131 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
4132 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
4133 | |
4134 | bool param_empty() const { return parameters().empty(); } |
4135 | param_iterator param_begin() { return parameters().begin(); } |
4136 | param_iterator param_end() { return parameters().end(); } |
4137 | param_const_iterator param_begin() const { return parameters().begin(); } |
4138 | param_const_iterator param_end() const { return parameters().end(); } |
4139 | size_t param_size() const { return parameters().size(); } |
4140 | |
4141 | unsigned getNumParams() const { return NumParams; } |
4142 | |
4143 | const ParmVarDecl *getParamDecl(unsigned i) const { |
4144 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4144, __PRETTY_FUNCTION__)); |
4145 | return ParamInfo[i]; |
4146 | } |
4147 | ParmVarDecl *getParamDecl(unsigned i) { |
4148 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4148, __PRETTY_FUNCTION__)); |
4149 | return ParamInfo[i]; |
4150 | } |
4151 | |
4152 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); |
4153 | |
4154 | /// True if this block (or its nested blocks) captures |
4155 | /// anything of local storage from its enclosing scopes. |
4156 | bool hasCaptures() const { return NumCaptures || capturesCXXThis(); } |
4157 | |
4158 | /// Returns the number of captured variables. |
4159 | /// Does not include an entry for 'this'. |
4160 | unsigned getNumCaptures() const { return NumCaptures; } |
4161 | |
4162 | using capture_const_iterator = ArrayRef<Capture>::const_iterator; |
4163 | |
4164 | ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; } |
4165 | |
4166 | capture_const_iterator capture_begin() const { return captures().begin(); } |
4167 | capture_const_iterator capture_end() const { return captures().end(); } |
4168 | |
4169 | bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; } |
4170 | void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; } |
4171 | |
4172 | bool blockMissingReturnType() const { |
4173 | return BlockDeclBits.BlockMissingReturnType; |
4174 | } |
4175 | |
4176 | void setBlockMissingReturnType(bool val = true) { |
4177 | BlockDeclBits.BlockMissingReturnType = val; |
4178 | } |
4179 | |
4180 | bool isConversionFromLambda() const { |
4181 | return BlockDeclBits.IsConversionFromLambda; |
4182 | } |
4183 | |
4184 | void setIsConversionFromLambda(bool val = true) { |
4185 | BlockDeclBits.IsConversionFromLambda = val; |
4186 | } |
4187 | |
4188 | bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; } |
4189 | void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; } |
4190 | |
4191 | bool canAvoidCopyToHeap() const { |
4192 | return BlockDeclBits.CanAvoidCopyToHeap; |
4193 | } |
4194 | void setCanAvoidCopyToHeap(bool B = true) { |
4195 | BlockDeclBits.CanAvoidCopyToHeap = B; |
4196 | } |
4197 | |
4198 | bool capturesVariable(const VarDecl *var) const; |
4199 | |
4200 | void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
4201 | bool CapturesCXXThis); |
4202 | |
4203 | unsigned getBlockManglingNumber() const { return ManglingNumber; } |
4204 | |
4205 | Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; } |
4206 | |
4207 | void setBlockMangling(unsigned Number, Decl *Ctx) { |
4208 | ManglingNumber = Number; |
4209 | ManglingContextDecl = Ctx; |
4210 | } |
4211 | |
4212 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4213 | |
4214 | // Implement isa/cast/dyncast/etc. |
4215 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4216 | static bool classofKind(Kind K) { return K == Block; } |
4217 | static DeclContext *castToDeclContext(const BlockDecl *D) { |
4218 | return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); |
4219 | } |
4220 | static BlockDecl *castFromDeclContext(const DeclContext *DC) { |
4221 | return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); |
4222 | } |
4223 | }; |
4224 | |
4225 | /// Represents the body of a CapturedStmt, and serves as its DeclContext. |
4226 | class CapturedDecl final |
4227 | : public Decl, |
4228 | public DeclContext, |
4229 | private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> { |
4230 | protected: |
4231 | size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) { |
4232 | return NumParams; |
4233 | } |
4234 | |
4235 | private: |
4236 | /// The number of parameters to the outlined function. |
4237 | unsigned NumParams; |
4238 | |
4239 | /// The position of context parameter in list of parameters. |
4240 | unsigned ContextParam; |
4241 | |
4242 | /// The body of the outlined function. |
4243 | llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow; |
4244 | |
4245 | explicit CapturedDecl(DeclContext *DC, unsigned NumParams); |
4246 | |
4247 | ImplicitParamDecl *const *getParams() const { |
4248 | return getTrailingObjects<ImplicitParamDecl *>(); |
4249 | } |
4250 | |
4251 | ImplicitParamDecl **getParams() { |
4252 | return getTrailingObjects<ImplicitParamDecl *>(); |
4253 | } |
4254 | |
4255 | public: |
4256 | friend class ASTDeclReader; |
4257 | friend class ASTDeclWriter; |
4258 | friend TrailingObjects; |
4259 | |
4260 | static CapturedDecl *Create(ASTContext &C, DeclContext *DC, |
4261 | unsigned NumParams); |
4262 | static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4263 | unsigned NumParams); |
4264 | |
4265 | Stmt *getBody() const override; |
4266 | void setBody(Stmt *B); |
4267 | |
4268 | bool isNothrow() const; |
4269 | void setNothrow(bool Nothrow = true); |
4270 | |
4271 | unsigned getNumParams() const { return NumParams; } |
4272 | |
4273 | ImplicitParamDecl *getParam(unsigned i) const { |
4274 | assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4274, __PRETTY_FUNCTION__)); |
4275 | return getParams()[i]; |
4276 | } |
4277 | void setParam(unsigned i, ImplicitParamDecl *P) { |
4278 | assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4278, __PRETTY_FUNCTION__)); |
4279 | getParams()[i] = P; |
4280 | } |
4281 | |
4282 | // ArrayRef interface to parameters. |
4283 | ArrayRef<ImplicitParamDecl *> parameters() const { |
4284 | return {getParams(), getNumParams()}; |
4285 | } |
4286 | MutableArrayRef<ImplicitParamDecl *> parameters() { |
4287 | return {getParams(), getNumParams()}; |
4288 | } |
4289 | |
4290 | /// Retrieve the parameter containing captured variables. |
4291 | ImplicitParamDecl *getContextParam() const { |
4292 | assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4292, __PRETTY_FUNCTION__)); |
4293 | return getParam(ContextParam); |
4294 | } |
4295 | void setContextParam(unsigned i, ImplicitParamDecl *P) { |
4296 | assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4296, __PRETTY_FUNCTION__)); |
4297 | ContextParam = i; |
4298 | setParam(i, P); |
4299 | } |
4300 | unsigned getContextParamPosition() const { return ContextParam; } |
4301 | |
4302 | using param_iterator = ImplicitParamDecl *const *; |
4303 | using param_range = llvm::iterator_range<param_iterator>; |
4304 | |
4305 | /// Retrieve an iterator pointing to the first parameter decl. |
4306 | param_iterator param_begin() const { return getParams(); } |
4307 | /// Retrieve an iterator one past the last parameter decl. |
4308 | param_iterator param_end() const { return getParams() + NumParams; } |
4309 | |
4310 | // Implement isa/cast/dyncast/etc. |
4311 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4312 | static bool classofKind(Kind K) { return K == Captured; } |
4313 | static DeclContext *castToDeclContext(const CapturedDecl *D) { |
4314 | return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); |
4315 | } |
4316 | static CapturedDecl *castFromDeclContext(const DeclContext *DC) { |
4317 | return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); |
4318 | } |
4319 | }; |
4320 | |
4321 | /// Describes a module import declaration, which makes the contents |
4322 | /// of the named module visible in the current translation unit. |
4323 | /// |
4324 | /// An import declaration imports the named module (or submodule). For example: |
4325 | /// \code |
4326 | /// @import std.vector; |
4327 | /// \endcode |
4328 | /// |
4329 | /// Import declarations can also be implicitly generated from |
4330 | /// \#include/\#import directives. |
4331 | class ImportDecl final : public Decl, |
4332 | llvm::TrailingObjects<ImportDecl, SourceLocation> { |
4333 | friend class ASTContext; |
4334 | friend class ASTDeclReader; |
4335 | friend class ASTReader; |
4336 | friend TrailingObjects; |
4337 | |
4338 | /// The imported module, along with a bit that indicates whether |
4339 | /// we have source-location information for each identifier in the module |
4340 | /// name. |
4341 | /// |
4342 | /// When the bit is false, we only have a single source location for the |
4343 | /// end of the import declaration. |
4344 | llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete; |
4345 | |
4346 | /// The next import in the list of imports local to the translation |
4347 | /// unit being parsed (not loaded from an AST file). |
4348 | ImportDecl *NextLocalImport = nullptr; |
4349 | |
4350 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4351 | ArrayRef<SourceLocation> IdentifierLocs); |
4352 | |
4353 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4354 | SourceLocation EndLoc); |
4355 | |
4356 | ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} |
4357 | |
4358 | public: |
4359 | /// Create a new module import declaration. |
4360 | static ImportDecl *Create(ASTContext &C, DeclContext *DC, |
4361 | SourceLocation StartLoc, Module *Imported, |
4362 | ArrayRef<SourceLocation> IdentifierLocs); |
4363 | |
4364 | /// Create a new module import declaration for an implicitly-generated |
4365 | /// import. |
4366 | static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, |
4367 | SourceLocation StartLoc, Module *Imported, |
4368 | SourceLocation EndLoc); |
4369 | |
4370 | /// Create a new, deserialized module import declaration. |
4371 | static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4372 | unsigned NumLocations); |
4373 | |
4374 | /// Retrieve the module that was imported by the import declaration. |
4375 | Module *getImportedModule() const { return ImportedAndComplete.getPointer(); } |
4376 | |
4377 | /// Retrieves the locations of each of the identifiers that make up |
4378 | /// the complete module name in the import declaration. |
4379 | /// |
4380 | /// This will return an empty array if the locations of the individual |
4381 | /// identifiers aren't available. |
4382 | ArrayRef<SourceLocation> getIdentifierLocs() const; |
4383 | |
4384 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4385 | |
4386 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4387 | static bool classofKind(Kind K) { return K == Import; } |
4388 | }; |
4389 | |
4390 | /// Represents a C++ Modules TS module export declaration. |
4391 | /// |
4392 | /// For example: |
4393 | /// \code |
4394 | /// export void foo(); |
4395 | /// \endcode |
4396 | class ExportDecl final : public Decl, public DeclContext { |
4397 | virtual void anchor(); |
4398 | |
4399 | private: |
4400 | friend class ASTDeclReader; |
4401 | |
4402 | /// The source location for the right brace (if valid). |
4403 | SourceLocation RBraceLoc; |
4404 | |
4405 | ExportDecl(DeclContext *DC, SourceLocation ExportLoc) |
4406 | : Decl(Export, DC, ExportLoc), DeclContext(Export), |
4407 | RBraceLoc(SourceLocation()) {} |
4408 | |
4409 | public: |
4410 | static ExportDecl *Create(ASTContext &C, DeclContext *DC, |
4411 | SourceLocation ExportLoc); |
4412 | static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4413 | |
4414 | SourceLocation getExportLoc() const { return getLocation(); } |
4415 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4416 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
4417 | |
4418 | bool hasBraces() const { return RBraceLoc.isValid(); } |
4419 | |
4420 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4421 | if (hasBraces()) |
4422 | return RBraceLoc; |
4423 | // No braces: get the end location of the (only) declaration in context |
4424 | // (if present). |
4425 | return decls_empty() ? getLocation() : decls_begin()->getEndLoc(); |
4426 | } |
4427 | |
4428 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4429 | return SourceRange(getLocation(), getEndLoc()); |
4430 | } |
4431 | |
4432 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4433 | static bool classofKind(Kind K) { return K == Export; } |
4434 | static DeclContext *castToDeclContext(const ExportDecl *D) { |
4435 | return static_cast<DeclContext *>(const_cast<ExportDecl*>(D)); |
4436 | } |
4437 | static ExportDecl *castFromDeclContext(const DeclContext *DC) { |
4438 | return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC)); |
4439 | } |
4440 | }; |
4441 | |
4442 | /// Represents an empty-declaration. |
4443 | class EmptyDecl : public Decl { |
4444 | EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {} |
4445 | |
4446 | virtual void anchor(); |
4447 | |
4448 | public: |
4449 | static EmptyDecl *Create(ASTContext &C, DeclContext *DC, |
4450 | SourceLocation L); |
4451 | static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4452 | |
4453 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4454 | static bool classofKind(Kind K) { return K == Empty; } |
4455 | }; |
4456 | |
4457 | /// Insertion operator for diagnostics. This allows sending NamedDecl's |
4458 | /// into a diagnostic with <<. |
4459 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
4460 | const NamedDecl* ND) { |
4461 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4462 | DiagnosticsEngine::ak_nameddecl); |
4463 | return DB; |
4464 | } |
4465 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
4466 | const NamedDecl* ND) { |
4467 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4468 | DiagnosticsEngine::ak_nameddecl); |
4469 | return PD; |
4470 | } |
4471 | |
4472 | template<typename decl_type> |
4473 | void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) { |
4474 | // Note: This routine is implemented here because we need both NamedDecl |
4475 | // and Redeclarable to be defined. |
4476 | assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4477, __PRETTY_FUNCTION__)) |
4477 | "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4477, __PRETTY_FUNCTION__)); |
4478 | |
4479 | if (PrevDecl) { |
4480 | // Point to previous. Make sure that this is actually the most recent |
4481 | // redeclaration, or we can build invalid chains. If the most recent |
4482 | // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. |
4483 | First = PrevDecl->getFirstDecl(); |
4484 | assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first") ? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4484, __PRETTY_FUNCTION__)); |
4485 | decl_type *MostRecent = First->getNextRedeclaration(); |
4486 | RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); |
4487 | |
4488 | // If the declaration was previously visible, a redeclaration of it remains |
4489 | // visible even if it wouldn't be visible by itself. |
4490 | static_cast<decl_type*>(this)->IdentifierNamespace |= |
4491 | MostRecent->getIdentifierNamespace() & |
4492 | (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); |
4493 | } else { |
4494 | // Make this first. |
4495 | First = static_cast<decl_type*>(this); |
4496 | } |
4497 | |
4498 | // First one will point to this one as latest. |
4499 | First->RedeclLink.setLatest(static_cast<decl_type*>(this)); |
4500 | |
4501 | assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))-> isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4502, __PRETTY_FUNCTION__)) |
4502 | cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))-> isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Decl.h" , 4502, __PRETTY_FUNCTION__)); |
4503 | } |
4504 | |
4505 | // Inline function definitions. |
4506 | |
4507 | /// Check if the given decl is complete. |
4508 | /// |
4509 | /// We use this function to break a cycle between the inline definitions in |
4510 | /// Type.h and Decl.h. |
4511 | inline bool IsEnumDeclComplete(EnumDecl *ED) { |
4512 | return ED->isComplete(); |
4513 | } |
4514 | |
4515 | /// Check if the given decl is scoped. |
4516 | /// |
4517 | /// We use this function to break a cycle between the inline definitions in |
4518 | /// Type.h and Decl.h. |
4519 | inline bool IsEnumDeclScoped(EnumDecl *ED) { |
4520 | return ED->isScoped(); |
4521 | } |
4522 | |
4523 | } // namespace clang |
4524 | |
4525 | #endif // LLVM_CLANG_AST_DECL_H |
1 | //===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the Decl and DeclContext interfaces. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_DECLBASE_H |
14 | #define LLVM_CLANG_AST_DECLBASE_H |
15 | |
16 | #include "clang/AST/ASTDumperUtils.h" |
17 | #include "clang/AST/AttrIterator.h" |
18 | #include "clang/AST/DeclarationName.h" |
19 | #include "clang/Basic/IdentifierTable.h" |
20 | #include "clang/Basic/LLVM.h" |
21 | #include "clang/Basic/SourceLocation.h" |
22 | #include "clang/Basic/Specifiers.h" |
23 | #include "llvm/ADT/ArrayRef.h" |
24 | #include "llvm/ADT/PointerIntPair.h" |
25 | #include "llvm/ADT/PointerUnion.h" |
26 | #include "llvm/ADT/iterator.h" |
27 | #include "llvm/ADT/iterator_range.h" |
28 | #include "llvm/Support/Casting.h" |
29 | #include "llvm/Support/Compiler.h" |
30 | #include "llvm/Support/PrettyStackTrace.h" |
31 | #include "llvm/Support/VersionTuple.h" |
32 | #include <algorithm> |
33 | #include <cassert> |
34 | #include <cstddef> |
35 | #include <iterator> |
36 | #include <string> |
37 | #include <type_traits> |
38 | #include <utility> |
39 | |
40 | namespace clang { |
41 | |
42 | class ASTContext; |
43 | class ASTMutationListener; |
44 | class Attr; |
45 | class BlockDecl; |
46 | class DeclContext; |
47 | class ExternalSourceSymbolAttr; |
48 | class FunctionDecl; |
49 | class FunctionType; |
50 | class IdentifierInfo; |
51 | enum Linkage : unsigned char; |
52 | class LinkageSpecDecl; |
53 | class Module; |
54 | class NamedDecl; |
55 | class ObjCCategoryDecl; |
56 | class ObjCCategoryImplDecl; |
57 | class ObjCContainerDecl; |
58 | class ObjCImplDecl; |
59 | class ObjCImplementationDecl; |
60 | class ObjCInterfaceDecl; |
61 | class ObjCMethodDecl; |
62 | class ObjCProtocolDecl; |
63 | struct PrintingPolicy; |
64 | class RecordDecl; |
65 | class SourceManager; |
66 | class Stmt; |
67 | class StoredDeclsMap; |
68 | class TemplateDecl; |
69 | class TranslationUnitDecl; |
70 | class UsingDirectiveDecl; |
71 | |
72 | /// Captures the result of checking the availability of a |
73 | /// declaration. |
74 | enum AvailabilityResult { |
75 | AR_Available = 0, |
76 | AR_NotYetIntroduced, |
77 | AR_Deprecated, |
78 | AR_Unavailable |
79 | }; |
80 | |
81 | /// Decl - This represents one declaration (or definition), e.g. a variable, |
82 | /// typedef, function, struct, etc. |
83 | /// |
84 | /// Note: There are objects tacked on before the *beginning* of Decl |
85 | /// (and its subclasses) in its Decl::operator new(). Proper alignment |
86 | /// of all subclasses (not requiring more than the alignment of Decl) is |
87 | /// asserted in DeclBase.cpp. |
88 | class alignas(8) Decl { |
89 | public: |
90 | /// Lists the kind of concrete classes of Decl. |
91 | enum Kind { |
92 | #define DECL(DERIVED, BASE) DERIVED, |
93 | #define ABSTRACT_DECL(DECL) |
94 | #define DECL_RANGE(BASE, START, END) \ |
95 | first##BASE = START, last##BASE = END, |
96 | #define LAST_DECL_RANGE(BASE, START, END) \ |
97 | first##BASE = START, last##BASE = END |
98 | #include "clang/AST/DeclNodes.inc" |
99 | }; |
100 | |
101 | /// A placeholder type used to construct an empty shell of a |
102 | /// decl-derived type that will be filled in later (e.g., by some |
103 | /// deserialization method). |
104 | struct EmptyShell {}; |
105 | |
106 | /// IdentifierNamespace - The different namespaces in which |
107 | /// declarations may appear. According to C99 6.2.3, there are |
108 | /// four namespaces, labels, tags, members and ordinary |
109 | /// identifiers. C++ describes lookup completely differently: |
110 | /// certain lookups merely "ignore" certain kinds of declarations, |
111 | /// usually based on whether the declaration is of a type, etc. |
112 | /// |
113 | /// These are meant as bitmasks, so that searches in |
114 | /// C++ can look into the "tag" namespace during ordinary lookup. |
115 | /// |
116 | /// Decl currently provides 15 bits of IDNS bits. |
117 | enum IdentifierNamespace { |
118 | /// Labels, declared with 'x:' and referenced with 'goto x'. |
119 | IDNS_Label = 0x0001, |
120 | |
121 | /// Tags, declared with 'struct foo;' and referenced with |
122 | /// 'struct foo'. All tags are also types. This is what |
123 | /// elaborated-type-specifiers look for in C. |
124 | /// This also contains names that conflict with tags in the |
125 | /// same scope but that are otherwise ordinary names (non-type |
126 | /// template parameters and indirect field declarations). |
127 | IDNS_Tag = 0x0002, |
128 | |
129 | /// Types, declared with 'struct foo', typedefs, etc. |
130 | /// This is what elaborated-type-specifiers look for in C++, |
131 | /// but note that it's ill-formed to find a non-tag. |
132 | IDNS_Type = 0x0004, |
133 | |
134 | /// Members, declared with object declarations within tag |
135 | /// definitions. In C, these can only be found by "qualified" |
136 | /// lookup in member expressions. In C++, they're found by |
137 | /// normal lookup. |
138 | IDNS_Member = 0x0008, |
139 | |
140 | /// Namespaces, declared with 'namespace foo {}'. |
141 | /// Lookup for nested-name-specifiers find these. |
142 | IDNS_Namespace = 0x0010, |
143 | |
144 | /// Ordinary names. In C, everything that's not a label, tag, |
145 | /// member, or function-local extern ends up here. |
146 | IDNS_Ordinary = 0x0020, |
147 | |
148 | /// Objective C \@protocol. |
149 | IDNS_ObjCProtocol = 0x0040, |
150 | |
151 | /// This declaration is a friend function. A friend function |
152 | /// declaration is always in this namespace but may also be in |
153 | /// IDNS_Ordinary if it was previously declared. |
154 | IDNS_OrdinaryFriend = 0x0080, |
155 | |
156 | /// This declaration is a friend class. A friend class |
157 | /// declaration is always in this namespace but may also be in |
158 | /// IDNS_Tag|IDNS_Type if it was previously declared. |
159 | IDNS_TagFriend = 0x0100, |
160 | |
161 | /// This declaration is a using declaration. A using declaration |
162 | /// *introduces* a number of other declarations into the current |
163 | /// scope, and those declarations use the IDNS of their targets, |
164 | /// but the actual using declarations go in this namespace. |
165 | IDNS_Using = 0x0200, |
166 | |
167 | /// This declaration is a C++ operator declared in a non-class |
168 | /// context. All such operators are also in IDNS_Ordinary. |
169 | /// C++ lexical operator lookup looks for these. |
170 | IDNS_NonMemberOperator = 0x0400, |
171 | |
172 | /// This declaration is a function-local extern declaration of a |
173 | /// variable or function. This may also be IDNS_Ordinary if it |
174 | /// has been declared outside any function. These act mostly like |
175 | /// invisible friend declarations, but are also visible to unqualified |
176 | /// lookup within the scope of the declaring function. |
177 | IDNS_LocalExtern = 0x0800, |
178 | |
179 | /// This declaration is an OpenMP user defined reduction construction. |
180 | IDNS_OMPReduction = 0x1000, |
181 | |
182 | /// This declaration is an OpenMP user defined mapper. |
183 | IDNS_OMPMapper = 0x2000, |
184 | }; |
185 | |
186 | /// ObjCDeclQualifier - 'Qualifiers' written next to the return and |
187 | /// parameter types in method declarations. Other than remembering |
188 | /// them and mangling them into the method's signature string, these |
189 | /// are ignored by the compiler; they are consumed by certain |
190 | /// remote-messaging frameworks. |
191 | /// |
192 | /// in, inout, and out are mutually exclusive and apply only to |
193 | /// method parameters. bycopy and byref are mutually exclusive and |
194 | /// apply only to method parameters (?). oneway applies only to |
195 | /// results. All of these expect their corresponding parameter to |
196 | /// have a particular type. None of this is currently enforced by |
197 | /// clang. |
198 | /// |
199 | /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier. |
200 | enum ObjCDeclQualifier { |
201 | OBJC_TQ_None = 0x0, |
202 | OBJC_TQ_In = 0x1, |
203 | OBJC_TQ_Inout = 0x2, |
204 | OBJC_TQ_Out = 0x4, |
205 | OBJC_TQ_Bycopy = 0x8, |
206 | OBJC_TQ_Byref = 0x10, |
207 | OBJC_TQ_Oneway = 0x20, |
208 | |
209 | /// The nullability qualifier is set when the nullability of the |
210 | /// result or parameter was expressed via a context-sensitive |
211 | /// keyword. |
212 | OBJC_TQ_CSNullability = 0x40 |
213 | }; |
214 | |
215 | /// The kind of ownership a declaration has, for visibility purposes. |
216 | /// This enumeration is designed such that higher values represent higher |
217 | /// levels of name hiding. |
218 | enum class ModuleOwnershipKind : unsigned { |
219 | /// This declaration is not owned by a module. |
220 | Unowned, |
221 | |
222 | /// This declaration has an owning module, but is globally visible |
223 | /// (typically because its owning module is visible and we know that |
224 | /// modules cannot later become hidden in this compilation). |
225 | /// After serialization and deserialization, this will be converted |
226 | /// to VisibleWhenImported. |
227 | Visible, |
228 | |
229 | /// This declaration has an owning module, and is visible when that |
230 | /// module is imported. |
231 | VisibleWhenImported, |
232 | |
233 | /// This declaration has an owning module, but is only visible to |
234 | /// lookups that occur within that module. |
235 | ModulePrivate |
236 | }; |
237 | |
238 | protected: |
239 | /// The next declaration within the same lexical |
240 | /// DeclContext. These pointers form the linked list that is |
241 | /// traversed via DeclContext's decls_begin()/decls_end(). |
242 | /// |
243 | /// The extra two bits are used for the ModuleOwnershipKind. |
244 | llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits; |
245 | |
246 | private: |
247 | friend class DeclContext; |
248 | |
249 | struct MultipleDC { |
250 | DeclContext *SemanticDC; |
251 | DeclContext *LexicalDC; |
252 | }; |
253 | |
254 | /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. |
255 | /// For declarations that don't contain C++ scope specifiers, it contains |
256 | /// the DeclContext where the Decl was declared. |
257 | /// For declarations with C++ scope specifiers, it contains a MultipleDC* |
258 | /// with the context where it semantically belongs (SemanticDC) and the |
259 | /// context where it was lexically declared (LexicalDC). |
260 | /// e.g.: |
261 | /// |
262 | /// namespace A { |
263 | /// void f(); // SemanticDC == LexicalDC == 'namespace A' |
264 | /// } |
265 | /// void A::f(); // SemanticDC == namespace 'A' |
266 | /// // LexicalDC == global namespace |
267 | llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx; |
268 | |
269 | bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); } |
270 | bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); } |
271 | |
272 | MultipleDC *getMultipleDC() const { |
273 | return DeclCtx.get<MultipleDC*>(); |
274 | } |
275 | |
276 | DeclContext *getSemanticDC() const { |
277 | return DeclCtx.get<DeclContext*>(); |
278 | } |
279 | |
280 | /// Loc - The location of this decl. |
281 | SourceLocation Loc; |
282 | |
283 | /// DeclKind - This indicates which class this is. |
284 | unsigned DeclKind : 7; |
285 | |
286 | /// InvalidDecl - This indicates a semantic error occurred. |
287 | unsigned InvalidDecl : 1; |
288 | |
289 | /// HasAttrs - This indicates whether the decl has attributes or not. |
290 | unsigned HasAttrs : 1; |
291 | |
292 | /// Implicit - Whether this declaration was implicitly generated by |
293 | /// the implementation rather than explicitly written by the user. |
294 | unsigned Implicit : 1; |
295 | |
296 | /// Whether this declaration was "used", meaning that a definition is |
297 | /// required. |
298 | unsigned Used : 1; |
299 | |
300 | /// Whether this declaration was "referenced". |
301 | /// The difference with 'Used' is whether the reference appears in a |
302 | /// evaluated context or not, e.g. functions used in uninstantiated templates |
303 | /// are regarded as "referenced" but not "used". |
304 | unsigned Referenced : 1; |
305 | |
306 | /// Whether this declaration is a top-level declaration (function, |
307 | /// global variable, etc.) that is lexically inside an objc container |
308 | /// definition. |
309 | unsigned TopLevelDeclInObjCContainer : 1; |
310 | |
311 | /// Whether statistic collection is enabled. |
312 | static bool StatisticsEnabled; |
313 | |
314 | protected: |
315 | friend class ASTDeclReader; |
316 | friend class ASTDeclWriter; |
317 | friend class ASTNodeImporter; |
318 | friend class ASTReader; |
319 | friend class CXXClassMemberWrapper; |
320 | friend class LinkageComputer; |
321 | template<typename decl_type> friend class Redeclarable; |
322 | |
323 | /// Access - Used by C++ decls for the access specifier. |
324 | // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum |
325 | unsigned Access : 2; |
326 | |
327 | /// Whether this declaration was loaded from an AST file. |
328 | unsigned FromASTFile : 1; |
329 | |
330 | /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. |
331 | unsigned IdentifierNamespace : 14; |
332 | |
333 | /// If 0, we have not computed the linkage of this declaration. |
334 | /// Otherwise, it is the linkage + 1. |
335 | mutable unsigned CacheValidAndLinkage : 3; |
336 | |
337 | /// Allocate memory for a deserialized declaration. |
338 | /// |
339 | /// This routine must be used to allocate memory for any declaration that is |
340 | /// deserialized from a module file. |
341 | /// |
342 | /// \param Size The size of the allocated object. |
343 | /// \param Ctx The context in which we will allocate memory. |
344 | /// \param ID The global ID of the deserialized declaration. |
345 | /// \param Extra The amount of extra space to allocate after the object. |
346 | void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID, |
347 | std::size_t Extra = 0); |
348 | |
349 | /// Allocate memory for a non-deserialized declaration. |
350 | void *operator new(std::size_t Size, const ASTContext &Ctx, |
351 | DeclContext *Parent, std::size_t Extra = 0); |
352 | |
353 | private: |
354 | bool AccessDeclContextSanity() const; |
355 | |
356 | /// Get the module ownership kind to use for a local lexical child of \p DC, |
357 | /// which may be either a local or (rarely) an imported declaration. |
358 | static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) { |
359 | if (DC) { |
360 | auto *D = cast<Decl>(DC); |
361 | auto MOK = D->getModuleOwnershipKind(); |
362 | if (MOK != ModuleOwnershipKind::Unowned && |
363 | (!D->isFromASTFile() || D->hasLocalOwningModuleStorage())) |
364 | return MOK; |
365 | // If D is not local and we have no local module storage, then we don't |
366 | // need to track module ownership at all. |
367 | } |
368 | return ModuleOwnershipKind::Unowned; |
369 | } |
370 | |
371 | public: |
372 | Decl() = delete; |
373 | Decl(const Decl&) = delete; |
374 | Decl(Decl &&) = delete; |
375 | Decl &operator=(const Decl&) = delete; |
376 | Decl &operator=(Decl&&) = delete; |
377 | |
378 | protected: |
379 | Decl(Kind DK, DeclContext *DC, SourceLocation L) |
380 | : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)), |
381 | DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false), |
382 | Implicit(false), Used(false), Referenced(false), |
383 | TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0), |
384 | IdentifierNamespace(getIdentifierNamespaceForKind(DK)), |
385 | CacheValidAndLinkage(0) { |
386 | if (StatisticsEnabled) add(DK); |
387 | } |
388 | |
389 | Decl(Kind DK, EmptyShell Empty) |
390 | : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false), |
391 | Used(false), Referenced(false), TopLevelDeclInObjCContainer(false), |
392 | Access(AS_none), FromASTFile(0), |
393 | IdentifierNamespace(getIdentifierNamespaceForKind(DK)), |
394 | CacheValidAndLinkage(0) { |
395 | if (StatisticsEnabled) add(DK); |
396 | } |
397 | |
398 | virtual ~Decl(); |
399 | |
400 | /// Update a potentially out-of-date declaration. |
401 | void updateOutOfDate(IdentifierInfo &II) const; |
402 | |
403 | Linkage getCachedLinkage() const { |
404 | return Linkage(CacheValidAndLinkage - 1); |
405 | } |
406 | |
407 | void setCachedLinkage(Linkage L) const { |
408 | CacheValidAndLinkage = L + 1; |
409 | } |
410 | |
411 | bool hasCachedLinkage() const { |
412 | return CacheValidAndLinkage; |
413 | } |
414 | |
415 | public: |
416 | /// Source range that this declaration covers. |
417 | virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
418 | return SourceRange(getLocation(), getLocation()); |
419 | } |
420 | |
421 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
422 | return getSourceRange().getBegin(); |
423 | } |
424 | |
425 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
426 | return getSourceRange().getEnd(); |
427 | } |
428 | |
429 | SourceLocation getLocation() const { return Loc; } |
430 | void setLocation(SourceLocation L) { Loc = L; } |
431 | |
432 | Kind getKind() const { return static_cast<Kind>(DeclKind); } |
433 | const char *getDeclKindName() const; |
434 | |
435 | Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); } |
436 | const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();} |
437 | |
438 | DeclContext *getDeclContext() { |
439 | if (isInSemaDC()) |
440 | return getSemanticDC(); |
441 | return getMultipleDC()->SemanticDC; |
442 | } |
443 | const DeclContext *getDeclContext() const { |
444 | return const_cast<Decl*>(this)->getDeclContext(); |
445 | } |
446 | |
447 | /// Find the innermost non-closure ancestor of this declaration, |
448 | /// walking up through blocks, lambdas, etc. If that ancestor is |
449 | /// not a code context (!isFunctionOrMethod()), returns null. |
450 | /// |
451 | /// A declaration may be its own non-closure context. |
452 | Decl *getNonClosureContext(); |
453 | const Decl *getNonClosureContext() const { |
454 | return const_cast<Decl*>(this)->getNonClosureContext(); |
455 | } |
456 | |
457 | TranslationUnitDecl *getTranslationUnitDecl(); |
458 | const TranslationUnitDecl *getTranslationUnitDecl() const { |
459 | return const_cast<Decl*>(this)->getTranslationUnitDecl(); |
460 | } |
461 | |
462 | bool isInAnonymousNamespace() const; |
463 | |
464 | bool isInStdNamespace() const; |
465 | |
466 | ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__)); |
467 | |
468 | void setAccess(AccessSpecifier AS) { |
469 | Access = AS; |
470 | assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 470, __PRETTY_FUNCTION__)); |
471 | } |
472 | |
473 | AccessSpecifier getAccess() const { |
474 | assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 474, __PRETTY_FUNCTION__)); |
475 | return AccessSpecifier(Access); |
476 | } |
477 | |
478 | /// Retrieve the access specifier for this declaration, even though |
479 | /// it may not yet have been properly set. |
480 | AccessSpecifier getAccessUnsafe() const { |
481 | return AccessSpecifier(Access); |
482 | } |
483 | |
484 | bool hasAttrs() const { return HasAttrs; } |
485 | |
486 | void setAttrs(const AttrVec& Attrs) { |
487 | return setAttrsImpl(Attrs, getASTContext()); |
488 | } |
489 | |
490 | AttrVec &getAttrs() { |
491 | return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs()); |
492 | } |
493 | |
494 | const AttrVec &getAttrs() const; |
495 | void dropAttrs(); |
496 | void addAttr(Attr *A); |
497 | |
498 | using attr_iterator = AttrVec::const_iterator; |
499 | using attr_range = llvm::iterator_range<attr_iterator>; |
500 | |
501 | attr_range attrs() const { |
502 | return attr_range(attr_begin(), attr_end()); |
503 | } |
504 | |
505 | attr_iterator attr_begin() const { |
506 | return hasAttrs() ? getAttrs().begin() : nullptr; |
507 | } |
508 | attr_iterator attr_end() const { |
509 | return hasAttrs() ? getAttrs().end() : nullptr; |
510 | } |
511 | |
512 | template <typename T> |
513 | void dropAttr() { |
514 | if (!HasAttrs) return; |
515 | |
516 | AttrVec &Vec = getAttrs(); |
517 | Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end()); |
518 | |
519 | if (Vec.empty()) |
520 | HasAttrs = false; |
521 | } |
522 | |
523 | template <typename T> |
524 | llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const { |
525 | return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>()); |
526 | } |
527 | |
528 | template <typename T> |
529 | specific_attr_iterator<T> specific_attr_begin() const { |
530 | return specific_attr_iterator<T>(attr_begin()); |
531 | } |
532 | |
533 | template <typename T> |
534 | specific_attr_iterator<T> specific_attr_end() const { |
535 | return specific_attr_iterator<T>(attr_end()); |
536 | } |
537 | |
538 | template<typename T> T *getAttr() const { |
539 | return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr; |
540 | } |
541 | |
542 | template<typename T> bool hasAttr() const { |
543 | return hasAttrs() && hasSpecificAttr<T>(getAttrs()); |
544 | } |
545 | |
546 | /// getMaxAlignment - return the maximum alignment specified by attributes |
547 | /// on this decl, 0 if there are none. |
548 | unsigned getMaxAlignment() const; |
549 | |
550 | /// setInvalidDecl - Indicates the Decl had a semantic error. This |
551 | /// allows for graceful error recovery. |
552 | void setInvalidDecl(bool Invalid = true); |
553 | bool isInvalidDecl() const { return (bool) InvalidDecl; } |
554 | |
555 | /// isImplicit - Indicates whether the declaration was implicitly |
556 | /// generated by the implementation. If false, this declaration |
557 | /// was written explicitly in the source code. |
558 | bool isImplicit() const { return Implicit; } |
559 | void setImplicit(bool I = true) { Implicit = I; } |
560 | |
561 | /// Whether *any* (re-)declaration of the entity was used, meaning that |
562 | /// a definition is required. |
563 | /// |
564 | /// \param CheckUsedAttr When true, also consider the "used" attribute |
565 | /// (in addition to the "used" bit set by \c setUsed()) when determining |
566 | /// whether the function is used. |
567 | bool isUsed(bool CheckUsedAttr = true) const; |
568 | |
569 | /// Set whether the declaration is used, in the sense of odr-use. |
570 | /// |
571 | /// This should only be used immediately after creating a declaration. |
572 | /// It intentionally doesn't notify any listeners. |
573 | void setIsUsed() { getCanonicalDecl()->Used = true; } |
574 | |
575 | /// Mark the declaration used, in the sense of odr-use. |
576 | /// |
577 | /// This notifies any mutation listeners in addition to setting a bit |
578 | /// indicating the declaration is used. |
579 | void markUsed(ASTContext &C); |
580 | |
581 | /// Whether any declaration of this entity was referenced. |
582 | bool isReferenced() const; |
583 | |
584 | /// Whether this declaration was referenced. This should not be relied |
585 | /// upon for anything other than debugging. |
586 | bool isThisDeclarationReferenced() const { return Referenced; } |
587 | |
588 | void setReferenced(bool R = true) { Referenced = R; } |
589 | |
590 | /// Whether this declaration is a top-level declaration (function, |
591 | /// global variable, etc.) that is lexically inside an objc container |
592 | /// definition. |
593 | bool isTopLevelDeclInObjCContainer() const { |
594 | return TopLevelDeclInObjCContainer; |
595 | } |
596 | |
597 | void setTopLevelDeclInObjCContainer(bool V = true) { |
598 | TopLevelDeclInObjCContainer = V; |
599 | } |
600 | |
601 | /// Looks on this and related declarations for an applicable |
602 | /// external source symbol attribute. |
603 | ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const; |
604 | |
605 | /// Whether this declaration was marked as being private to the |
606 | /// module in which it was defined. |
607 | bool isModulePrivate() const { |
608 | return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate; |
609 | } |
610 | |
611 | /// Return true if this declaration has an attribute which acts as |
612 | /// definition of the entity, such as 'alias' or 'ifunc'. |
613 | bool hasDefiningAttr() const; |
614 | |
615 | /// Return this declaration's defining attribute if it has one. |
616 | const Attr *getDefiningAttr() const; |
617 | |
618 | protected: |
619 | /// Specify that this declaration was marked as being private |
620 | /// to the module in which it was defined. |
621 | void setModulePrivate() { |
622 | // The module-private specifier has no effect on unowned declarations. |
623 | // FIXME: We should track this in some way for source fidelity. |
624 | if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned) |
625 | return; |
626 | setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate); |
627 | } |
628 | |
629 | /// Set the owning module ID. |
630 | void setOwningModuleID(unsigned ID) { |
631 | assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration" ) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 631, __PRETTY_FUNCTION__)); |
632 | *((unsigned*)this - 2) = ID; |
633 | } |
634 | |
635 | public: |
636 | /// Determine the availability of the given declaration. |
637 | /// |
638 | /// This routine will determine the most restrictive availability of |
639 | /// the given declaration (e.g., preferring 'unavailable' to |
640 | /// 'deprecated'). |
641 | /// |
642 | /// \param Message If non-NULL and the result is not \c |
643 | /// AR_Available, will be set to a (possibly empty) message |
644 | /// describing why the declaration has not been introduced, is |
645 | /// deprecated, or is unavailable. |
646 | /// |
647 | /// \param EnclosingVersion The version to compare with. If empty, assume the |
648 | /// deployment target version. |
649 | /// |
650 | /// \param RealizedPlatform If non-NULL and the availability result is found |
651 | /// in an available attribute it will set to the platform which is written in |
652 | /// the available attribute. |
653 | AvailabilityResult |
654 | getAvailability(std::string *Message = nullptr, |
655 | VersionTuple EnclosingVersion = VersionTuple(), |
656 | StringRef *RealizedPlatform = nullptr) const; |
657 | |
658 | /// Retrieve the version of the target platform in which this |
659 | /// declaration was introduced. |
660 | /// |
661 | /// \returns An empty version tuple if this declaration has no 'introduced' |
662 | /// availability attributes, or the version tuple that's specified in the |
663 | /// attribute otherwise. |
664 | VersionTuple getVersionIntroduced() const; |
665 | |
666 | /// Determine whether this declaration is marked 'deprecated'. |
667 | /// |
668 | /// \param Message If non-NULL and the declaration is deprecated, |
669 | /// this will be set to the message describing why the declaration |
670 | /// was deprecated (which may be empty). |
671 | bool isDeprecated(std::string *Message = nullptr) const { |
672 | return getAvailability(Message) == AR_Deprecated; |
673 | } |
674 | |
675 | /// Determine whether this declaration is marked 'unavailable'. |
676 | /// |
677 | /// \param Message If non-NULL and the declaration is unavailable, |
678 | /// this will be set to the message describing why the declaration |
679 | /// was made unavailable (which may be empty). |
680 | bool isUnavailable(std::string *Message = nullptr) const { |
681 | return getAvailability(Message) == AR_Unavailable; |
682 | } |
683 | |
684 | /// Determine whether this is a weak-imported symbol. |
685 | /// |
686 | /// Weak-imported symbols are typically marked with the |
687 | /// 'weak_import' attribute, but may also be marked with an |
688 | /// 'availability' attribute where we're targing a platform prior to |
689 | /// the introduction of this feature. |
690 | bool isWeakImported() const; |
691 | |
692 | /// Determines whether this symbol can be weak-imported, |
693 | /// e.g., whether it would be well-formed to add the weak_import |
694 | /// attribute. |
695 | /// |
696 | /// \param IsDefinition Set to \c true to indicate that this |
697 | /// declaration cannot be weak-imported because it has a definition. |
698 | bool canBeWeakImported(bool &IsDefinition) const; |
699 | |
700 | /// Determine whether this declaration came from an AST file (such as |
701 | /// a precompiled header or module) rather than having been parsed. |
702 | bool isFromASTFile() const { return FromASTFile; } |
703 | |
704 | /// Retrieve the global declaration ID associated with this |
705 | /// declaration, which specifies where this Decl was loaded from. |
706 | unsigned getGlobalID() const { |
707 | if (isFromASTFile()) |
708 | return *((const unsigned*)this - 1); |
709 | return 0; |
710 | } |
711 | |
712 | /// Retrieve the global ID of the module that owns this particular |
713 | /// declaration. |
714 | unsigned getOwningModuleID() const { |
715 | if (isFromASTFile()) |
716 | return *((const unsigned*)this - 2); |
717 | return 0; |
718 | } |
719 | |
720 | private: |
721 | Module *getOwningModuleSlow() const; |
722 | |
723 | protected: |
724 | bool hasLocalOwningModuleStorage() const; |
725 | |
726 | public: |
727 | /// Get the imported owning module, if this decl is from an imported |
728 | /// (non-local) module. |
729 | Module *getImportedOwningModule() const { |
730 | if (!isFromASTFile() || !hasOwningModule()) |
731 | return nullptr; |
732 | |
733 | return getOwningModuleSlow(); |
734 | } |
735 | |
736 | /// Get the local owning module, if known. Returns nullptr if owner is |
737 | /// not yet known or declaration is not from a module. |
738 | Module *getLocalOwningModule() const { |
739 | if (isFromASTFile() || !hasOwningModule()) |
740 | return nullptr; |
741 | |
742 | assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage" ) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 743, __PRETTY_FUNCTION__)) |
743 | "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage" ) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 743, __PRETTY_FUNCTION__)); |
744 | return reinterpret_cast<Module *const *>(this)[-1]; |
745 | } |
746 | void setLocalOwningModule(Module *M) { |
747 | assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage () && "should not have a cached owning module") ? static_cast <void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 749, __PRETTY_FUNCTION__)) |
748 | hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage () && "should not have a cached owning module") ? static_cast <void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 749, __PRETTY_FUNCTION__)) |
749 | "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage () && "should not have a cached owning module") ? static_cast <void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 749, __PRETTY_FUNCTION__)); |
750 | reinterpret_cast<Module **>(this)[-1] = M; |
751 | } |
752 | |
753 | /// Is this declaration owned by some module? |
754 | bool hasOwningModule() const { |
755 | return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned; |
756 | } |
757 | |
758 | /// Get the module that owns this declaration (for visibility purposes). |
759 | Module *getOwningModule() const { |
760 | return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule(); |
761 | } |
762 | |
763 | /// Get the module that owns this declaration for linkage purposes. |
764 | /// There only ever is such a module under the C++ Modules TS. |
765 | /// |
766 | /// \param IgnoreLinkage Ignore the linkage of the entity; assume that |
767 | /// all declarations in a global module fragment are unowned. |
768 | Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const; |
769 | |
770 | /// Determine whether this declaration might be hidden from name |
771 | /// lookup. Note that the declaration might be visible even if this returns |
772 | /// \c false, if the owning module is visible within the query context. |
773 | // FIXME: Rename this to make it clearer what it does. |
774 | bool isHidden() const { |
775 | return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible; |
776 | } |
777 | |
778 | /// Set that this declaration is globally visible, even if it came from a |
779 | /// module that is not visible. |
780 | void setVisibleDespiteOwningModule() { |
781 | if (isHidden()) |
782 | setModuleOwnershipKind(ModuleOwnershipKind::Visible); |
783 | } |
784 | |
785 | /// Get the kind of module ownership for this declaration. |
786 | ModuleOwnershipKind getModuleOwnershipKind() const { |
787 | return NextInContextAndBits.getInt(); |
788 | } |
789 | |
790 | /// Set whether this declaration is hidden from name lookup. |
791 | void setModuleOwnershipKind(ModuleOwnershipKind MOK) { |
792 | assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 795, __PRETTY_FUNCTION__)) |
793 | MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 795, __PRETTY_FUNCTION__)) |
794 | !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 795, __PRETTY_FUNCTION__)) |
795 | "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 795, __PRETTY_FUNCTION__)); |
796 | NextInContextAndBits.setInt(MOK); |
797 | } |
798 | |
799 | unsigned getIdentifierNamespace() const { |
800 | return IdentifierNamespace; |
801 | } |
802 | |
803 | bool isInIdentifierNamespace(unsigned NS) const { |
804 | return getIdentifierNamespace() & NS; |
805 | } |
806 | |
807 | static unsigned getIdentifierNamespaceForKind(Kind DK); |
808 | |
809 | bool hasTagIdentifierNamespace() const { |
810 | return isTagIdentifierNamespace(getIdentifierNamespace()); |
811 | } |
812 | |
813 | static bool isTagIdentifierNamespace(unsigned NS) { |
814 | // TagDecls have Tag and Type set and may also have TagFriend. |
815 | return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type); |
816 | } |
817 | |
818 | /// getLexicalDeclContext - The declaration context where this Decl was |
819 | /// lexically declared (LexicalDC). May be different from |
820 | /// getDeclContext() (SemanticDC). |
821 | /// e.g.: |
822 | /// |
823 | /// namespace A { |
824 | /// void f(); // SemanticDC == LexicalDC == 'namespace A' |
825 | /// } |
826 | /// void A::f(); // SemanticDC == namespace 'A' |
827 | /// // LexicalDC == global namespace |
828 | DeclContext *getLexicalDeclContext() { |
829 | if (isInSemaDC()) |
830 | return getSemanticDC(); |
831 | return getMultipleDC()->LexicalDC; |
832 | } |
833 | const DeclContext *getLexicalDeclContext() const { |
834 | return const_cast<Decl*>(this)->getLexicalDeclContext(); |
835 | } |
836 | |
837 | /// Determine whether this declaration is declared out of line (outside its |
838 | /// semantic context). |
839 | virtual bool isOutOfLine() const; |
840 | |
841 | /// setDeclContext - Set both the semantic and lexical DeclContext |
842 | /// to DC. |
843 | void setDeclContext(DeclContext *DC); |
844 | |
845 | void setLexicalDeclContext(DeclContext *DC); |
846 | |
847 | /// Determine whether this declaration is a templated entity (whether it is |
848 | // within the scope of a template parameter). |
849 | bool isTemplated() const; |
850 | |
851 | /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this |
852 | /// scoped decl is defined outside the current function or method. This is |
853 | /// roughly global variables and functions, but also handles enums (which |
854 | /// could be defined inside or outside a function etc). |
855 | bool isDefinedOutsideFunctionOrMethod() const { |
856 | return getParentFunctionOrMethod() == nullptr; |
857 | } |
858 | |
859 | /// Returns true if this declaration lexically is inside a function. |
860 | /// It recognizes non-defining declarations as well as members of local |
861 | /// classes: |
862 | /// \code |
863 | /// void foo() { void bar(); } |
864 | /// void foo2() { class ABC { void bar(); }; } |
865 | /// \endcode |
866 | bool isLexicallyWithinFunctionOrMethod() const; |
867 | |
868 | /// If this decl is defined inside a function/method/block it returns |
869 | /// the corresponding DeclContext, otherwise it returns null. |
870 | const DeclContext *getParentFunctionOrMethod() const; |
871 | DeclContext *getParentFunctionOrMethod() { |
872 | return const_cast<DeclContext*>( |
873 | const_cast<const Decl*>(this)->getParentFunctionOrMethod()); |
874 | } |
875 | |
876 | /// Retrieves the "canonical" declaration of the given declaration. |
877 | virtual Decl *getCanonicalDecl() { return this; } |
878 | const Decl *getCanonicalDecl() const { |
879 | return const_cast<Decl*>(this)->getCanonicalDecl(); |
880 | } |
881 | |
882 | /// Whether this particular Decl is a canonical one. |
883 | bool isCanonicalDecl() const { return getCanonicalDecl() == this; } |
884 | |
885 | protected: |
886 | /// Returns the next redeclaration or itself if this is the only decl. |
887 | /// |
888 | /// Decl subclasses that can be redeclared should override this method so that |
889 | /// Decl::redecl_iterator can iterate over them. |
890 | virtual Decl *getNextRedeclarationImpl() { return this; } |
891 | |
892 | /// Implementation of getPreviousDecl(), to be overridden by any |
893 | /// subclass that has a redeclaration chain. |
894 | virtual Decl *getPreviousDeclImpl() { return nullptr; } |
895 | |
896 | /// Implementation of getMostRecentDecl(), to be overridden by any |
897 | /// subclass that has a redeclaration chain. |
898 | virtual Decl *getMostRecentDeclImpl() { return this; } |
899 | |
900 | public: |
901 | /// Iterates through all the redeclarations of the same decl. |
902 | class redecl_iterator { |
903 | /// Current - The current declaration. |
904 | Decl *Current = nullptr; |
905 | Decl *Starter; |
906 | |
907 | public: |
908 | using value_type = Decl *; |
909 | using reference = const value_type &; |
910 | using pointer = const value_type *; |
911 | using iterator_category = std::forward_iterator_tag; |
912 | using difference_type = std::ptrdiff_t; |
913 | |
914 | redecl_iterator() = default; |
915 | explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {} |
916 | |
917 | reference operator*() const { return Current; } |
918 | value_type operator->() const { return Current; } |
919 | |
920 | redecl_iterator& operator++() { |
921 | assert(Current && "Advancing while iterator has reached end")((Current && "Advancing while iterator has reached end" ) ? static_cast<void> (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 921, __PRETTY_FUNCTION__)); |
922 | // Get either previous decl or latest decl. |
923 | Decl *Next = Current->getNextRedeclarationImpl(); |
924 | assert(Next && "Should return next redeclaration or itself, never null!")((Next && "Should return next redeclaration or itself, never null!" ) ? static_cast<void> (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 924, __PRETTY_FUNCTION__)); |
925 | Current = (Next != Starter) ? Next : nullptr; |
926 | return *this; |
927 | } |
928 | |
929 | redecl_iterator operator++(int) { |
930 | redecl_iterator tmp(*this); |
931 | ++(*this); |
932 | return tmp; |
933 | } |
934 | |
935 | friend bool operator==(redecl_iterator x, redecl_iterator y) { |
936 | return x.Current == y.Current; |
937 | } |
938 | |
939 | friend bool operator!=(redecl_iterator x, redecl_iterator y) { |
940 | return x.Current != y.Current; |
941 | } |
942 | }; |
943 | |
944 | using redecl_range = llvm::iterator_range<redecl_iterator>; |
945 | |
946 | /// Returns an iterator range for all the redeclarations of the same |
947 | /// decl. It will iterate at least once (when this decl is the only one). |
948 | redecl_range redecls() const { |
949 | return redecl_range(redecls_begin(), redecls_end()); |
950 | } |
951 | |
952 | redecl_iterator redecls_begin() const { |
953 | return redecl_iterator(const_cast<Decl *>(this)); |
954 | } |
955 | |
956 | redecl_iterator redecls_end() const { return redecl_iterator(); } |
957 | |
958 | /// Retrieve the previous declaration that declares the same entity |
959 | /// as this declaration, or NULL if there is no previous declaration. |
960 | Decl *getPreviousDecl() { return getPreviousDeclImpl(); } |
961 | |
962 | /// Retrieve the previous declaration that declares the same entity |
963 | /// as this declaration, or NULL if there is no previous declaration. |
964 | const Decl *getPreviousDecl() const { |
965 | return const_cast<Decl *>(this)->getPreviousDeclImpl(); |
966 | } |
967 | |
968 | /// True if this is the first declaration in its redeclaration chain. |
969 | bool isFirstDecl() const { |
970 | return getPreviousDecl() == nullptr; |
971 | } |
972 | |
973 | /// Retrieve the most recent declaration that declares the same entity |
974 | /// as this declaration (which may be this declaration). |
975 | Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); } |
976 | |
977 | /// Retrieve the most recent declaration that declares the same entity |
978 | /// as this declaration (which may be this declaration). |
979 | const Decl *getMostRecentDecl() const { |
980 | return const_cast<Decl *>(this)->getMostRecentDeclImpl(); |
981 | } |
982 | |
983 | /// getBody - If this Decl represents a declaration for a body of code, |
984 | /// such as a function or method definition, this method returns the |
985 | /// top-level Stmt* of that body. Otherwise this method returns null. |
986 | virtual Stmt* getBody() const { return nullptr; } |
987 | |
988 | /// Returns true if this \c Decl represents a declaration for a body of |
989 | /// code, such as a function or method definition. |
990 | /// Note that \c hasBody can also return true if any redeclaration of this |
991 | /// \c Decl represents a declaration for a body of code. |
992 | virtual bool hasBody() const { return getBody() != nullptr; } |
993 | |
994 | /// getBodyRBrace - Gets the right brace of the body, if a body exists. |
995 | /// This works whether the body is a CompoundStmt or a CXXTryStmt. |
996 | SourceLocation getBodyRBrace() const; |
997 | |
998 | // global temp stats (until we have a per-module visitor) |
999 | static void add(Kind k); |
1000 | static void EnableStatistics(); |
1001 | static void PrintStats(); |
1002 | |
1003 | /// isTemplateParameter - Determines whether this declaration is a |
1004 | /// template parameter. |
1005 | bool isTemplateParameter() const; |
1006 | |
1007 | /// isTemplateParameter - Determines whether this declaration is a |
1008 | /// template parameter pack. |
1009 | bool isTemplateParameterPack() const; |
1010 | |
1011 | /// Whether this declaration is a parameter pack. |
1012 | bool isParameterPack() const; |
1013 | |
1014 | /// returns true if this declaration is a template |
1015 | bool isTemplateDecl() const; |
1016 | |
1017 | /// Whether this declaration is a function or function template. |
1018 | bool isFunctionOrFunctionTemplate() const { |
1019 | return (DeclKind >= Decl::firstFunction && |
1020 | DeclKind <= Decl::lastFunction) || |
1021 | DeclKind == FunctionTemplate; |
1022 | } |
1023 | |
1024 | /// If this is a declaration that describes some template, this |
1025 | /// method returns that template declaration. |
1026 | TemplateDecl *getDescribedTemplate() const; |
1027 | |
1028 | /// Returns the function itself, or the templated function if this is a |
1029 | /// function template. |
1030 | FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__)); |
1031 | |
1032 | const FunctionDecl *getAsFunction() const { |
1033 | return const_cast<Decl *>(this)->getAsFunction(); |
1034 | } |
1035 | |
1036 | /// Changes the namespace of this declaration to reflect that it's |
1037 | /// a function-local extern declaration. |
1038 | /// |
1039 | /// These declarations appear in the lexical context of the extern |
1040 | /// declaration, but in the semantic context of the enclosing namespace |
1041 | /// scope. |
1042 | void setLocalExternDecl() { |
1043 | Decl *Prev = getPreviousDecl(); |
1044 | IdentifierNamespace &= ~IDNS_Ordinary; |
1045 | |
1046 | // It's OK for the declaration to still have the "invisible friend" flag or |
1047 | // the "conflicts with tag declarations in this scope" flag for the outer |
1048 | // scope. |
1049 | assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag )) == 0 && "namespace is not ordinary") ? static_cast <void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1050, __PRETTY_FUNCTION__)) |
1050 | "namespace is not ordinary")(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag )) == 0 && "namespace is not ordinary") ? static_cast <void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1050, __PRETTY_FUNCTION__)); |
1051 | |
1052 | IdentifierNamespace |= IDNS_LocalExtern; |
1053 | if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary) |
1054 | IdentifierNamespace |= IDNS_Ordinary; |
1055 | } |
1056 | |
1057 | /// Determine whether this is a block-scope declaration with linkage. |
1058 | /// This will either be a local variable declaration declared 'extern', or a |
1059 | /// local function declaration. |
1060 | bool isLocalExternDecl() { |
1061 | return IdentifierNamespace & IDNS_LocalExtern; |
1062 | } |
1063 | |
1064 | /// Changes the namespace of this declaration to reflect that it's |
1065 | /// the object of a friend declaration. |
1066 | /// |
1067 | /// These declarations appear in the lexical context of the friending |
1068 | /// class, but in the semantic context of the actual entity. This property |
1069 | /// applies only to a specific decl object; other redeclarations of the |
1070 | /// same entity may not (and probably don't) share this property. |
1071 | void setObjectOfFriendDecl(bool PerformFriendInjection = false) { |
1072 | unsigned OldNS = IdentifierNamespace; |
1073 | assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1076, __PRETTY_FUNCTION__)) |
1074 | IDNS_TagFriend | IDNS_OrdinaryFriend |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1076, __PRETTY_FUNCTION__)) |
1075 | IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1076, __PRETTY_FUNCTION__)) |
1076 | "namespace includes neither ordinary nor tag")(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1076, __PRETTY_FUNCTION__)); |
1077 | assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1080, __PRETTY_FUNCTION__)) |
1078 | IDNS_TagFriend | IDNS_OrdinaryFriend |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1080, __PRETTY_FUNCTION__)) |
1079 | IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1080, __PRETTY_FUNCTION__)) |
1080 | "namespace includes other than ordinary or tag")((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1080, __PRETTY_FUNCTION__)); |
1081 | |
1082 | Decl *Prev = getPreviousDecl(); |
1083 | IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type); |
1084 | |
1085 | if (OldNS & (IDNS_Tag | IDNS_TagFriend)) { |
1086 | IdentifierNamespace |= IDNS_TagFriend; |
1087 | if (PerformFriendInjection || |
1088 | (Prev && Prev->getIdentifierNamespace() & IDNS_Tag)) |
1089 | IdentifierNamespace |= IDNS_Tag | IDNS_Type; |
1090 | } |
1091 | |
1092 | if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | |
1093 | IDNS_LocalExtern | IDNS_NonMemberOperator)) { |
1094 | IdentifierNamespace |= IDNS_OrdinaryFriend; |
1095 | if (PerformFriendInjection || |
1096 | (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)) |
1097 | IdentifierNamespace |= IDNS_Ordinary; |
1098 | } |
1099 | } |
1100 | |
1101 | enum FriendObjectKind { |
1102 | FOK_None, ///< Not a friend object. |
1103 | FOK_Declared, ///< A friend of a previously-declared entity. |
1104 | FOK_Undeclared ///< A friend of a previously-undeclared entity. |
1105 | }; |
1106 | |
1107 | /// Determines whether this declaration is the object of a |
1108 | /// friend declaration and, if so, what kind. |
1109 | /// |
1110 | /// There is currently no direct way to find the associated FriendDecl. |
1111 | FriendObjectKind getFriendObjectKind() const { |
1112 | unsigned mask = |
1113 | (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend)); |
1114 | if (!mask) return FOK_None; |
1115 | return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared |
1116 | : FOK_Undeclared); |
1117 | } |
1118 | |
1119 | /// Specifies that this declaration is a C++ overloaded non-member. |
1120 | void setNonMemberOperator() { |
1121 | assert(getKind() == Function || getKind() == FunctionTemplate)((getKind() == Function || getKind() == FunctionTemplate) ? static_cast <void> (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1121, __PRETTY_FUNCTION__)); |
1122 | assert((IdentifierNamespace & IDNS_Ordinary) &&(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace" ) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1123, __PRETTY_FUNCTION__)) |
1123 | "visible non-member operators should be in ordinary namespace")(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace" ) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 1123, __PRETTY_FUNCTION__)); |
1124 | IdentifierNamespace |= IDNS_NonMemberOperator; |
1125 | } |
1126 | |
1127 | static bool classofKind(Kind K) { return true; } |
1128 | static DeclContext *castToDeclContext(const Decl *); |
1129 | static Decl *castFromDeclContext(const DeclContext *); |
1130 | |
1131 | void print(raw_ostream &Out, unsigned Indentation = 0, |
1132 | bool PrintInstantiation = false) const; |
1133 | void print(raw_ostream &Out, const PrintingPolicy &Policy, |
1134 | unsigned Indentation = 0, bool PrintInstantiation = false) const; |
1135 | static void printGroup(Decl** Begin, unsigned NumDecls, |
1136 | raw_ostream &Out, const PrintingPolicy &Policy, |
1137 | unsigned Indentation = 0); |
1138 | |
1139 | // Debuggers don't usually respect default arguments. |
1140 | void dump() const; |
1141 | |
1142 | // Same as dump(), but forces color printing. |
1143 | void dumpColor() const; |
1144 | |
1145 | void dump(raw_ostream &Out, bool Deserialize = false, |
1146 | ASTDumpOutputFormat OutputFormat = ADOF_Default) const; |
1147 | |
1148 | /// \return Unique reproducible object identifier |
1149 | int64_t getID() const; |
1150 | |
1151 | /// Looks through the Decl's underlying type to extract a FunctionType |
1152 | /// when possible. Will return null if the type underlying the Decl does not |
1153 | /// have a FunctionType. |
1154 | const FunctionType *getFunctionType(bool BlocksToo = true) const; |
1155 | |
1156 | private: |
1157 | void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx); |
1158 | void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, |
1159 | ASTContext &Ctx); |
1160 | |
1161 | protected: |
1162 | ASTMutationListener *getASTMutationListener() const; |
1163 | }; |
1164 | |
1165 | /// Determine whether two declarations declare the same entity. |
1166 | inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { |
1167 | if (!D1 || !D2) |
1168 | return false; |
1169 | |
1170 | if (D1 == D2) |
1171 | return true; |
1172 | |
1173 | return D1->getCanonicalDecl() == D2->getCanonicalDecl(); |
1174 | } |
1175 | |
1176 | /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when |
1177 | /// doing something to a specific decl. |
1178 | class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { |
1179 | const Decl *TheDecl; |
1180 | SourceLocation Loc; |
1181 | SourceManager &SM; |
1182 | const char *Message; |
1183 | |
1184 | public: |
1185 | PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L, |
1186 | SourceManager &sm, const char *Msg) |
1187 | : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} |
1188 | |
1189 | void print(raw_ostream &OS) const override; |
1190 | }; |
1191 | |
1192 | /// The results of name lookup within a DeclContext. This is either a |
1193 | /// single result (with no stable storage) or a collection of results (with |
1194 | /// stable storage provided by the lookup table). |
1195 | class DeclContextLookupResult { |
1196 | using ResultTy = ArrayRef<NamedDecl *>; |
1197 | |
1198 | ResultTy Result; |
1199 | |
1200 | // If there is only one lookup result, it would be invalidated by |
1201 | // reallocations of the name table, so store it separately. |
1202 | NamedDecl *Single = nullptr; |
1203 | |
1204 | static NamedDecl *const SingleElementDummyList; |
1205 | |
1206 | public: |
1207 | DeclContextLookupResult() = default; |
1208 | DeclContextLookupResult(ArrayRef<NamedDecl *> Result) |
1209 | : Result(Result) {} |
1210 | DeclContextLookupResult(NamedDecl *Single) |
1211 | : Result(SingleElementDummyList), Single(Single) {} |
1212 | |
1213 | class iterator; |
1214 | |
1215 | using IteratorBase = |
1216 | llvm::iterator_adaptor_base<iterator, ResultTy::iterator, |
1217 | std::random_access_iterator_tag, |
1218 | NamedDecl *const>; |
1219 | |
1220 | class iterator : public IteratorBase { |
1221 | value_type SingleElement; |
1222 | |
1223 | public: |
1224 | explicit iterator(pointer Pos, value_type Single = nullptr) |
1225 | : IteratorBase(Pos), SingleElement(Single) {} |
1226 | |
1227 | reference operator*() const { |
1228 | return SingleElement ? SingleElement : IteratorBase::operator*(); |
1229 | } |
1230 | }; |
1231 | |
1232 | using const_iterator = iterator; |
1233 | using pointer = iterator::pointer; |
1234 | using reference = iterator::reference; |
1235 | |
1236 | iterator begin() const { return iterator(Result.begin(), Single); } |
1237 | iterator end() const { return iterator(Result.end(), Single); } |
1238 | |
1239 | bool empty() const { return Result.empty(); } |
1240 | pointer data() const { return Single ? &Single : Result.data(); } |
1241 | size_t size() const { return Single ? 1 : Result.size(); } |
1242 | reference front() const { return Single ? Single : Result.front(); } |
1243 | reference back() const { return Single ? Single : Result.back(); } |
1244 | reference operator[](size_t N) const { return Single ? Single : Result[N]; } |
1245 | |
1246 | // FIXME: Remove this from the interface |
1247 | DeclContextLookupResult slice(size_t N) const { |
1248 | DeclContextLookupResult Sliced = Result.slice(N); |
1249 | Sliced.Single = Single; |
1250 | return Sliced; |
1251 | } |
1252 | }; |
1253 | |
1254 | /// DeclContext - This is used only as base class of specific decl types that |
1255 | /// can act as declaration contexts. These decls are (only the top classes |
1256 | /// that directly derive from DeclContext are mentioned, not their subclasses): |
1257 | /// |
1258 | /// TranslationUnitDecl |
1259 | /// ExternCContext |
1260 | /// NamespaceDecl |
1261 | /// TagDecl |
1262 | /// OMPDeclareReductionDecl |
1263 | /// OMPDeclareMapperDecl |
1264 | /// FunctionDecl |
1265 | /// ObjCMethodDecl |
1266 | /// ObjCContainerDecl |
1267 | /// LinkageSpecDecl |
1268 | /// ExportDecl |
1269 | /// BlockDecl |
1270 | /// CapturedDecl |
1271 | class DeclContext { |
1272 | /// For makeDeclVisibleInContextImpl |
1273 | friend class ASTDeclReader; |
1274 | /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap, |
1275 | /// hasNeedToReconcileExternalVisibleStorage |
1276 | friend class ExternalASTSource; |
1277 | /// For CreateStoredDeclsMap |
1278 | friend class DependentDiagnostic; |
1279 | /// For hasNeedToReconcileExternalVisibleStorage, |
1280 | /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups |
1281 | friend class ASTWriter; |
1282 | |
1283 | // We use uint64_t in the bit-fields below since some bit-fields |
1284 | // cross the unsigned boundary and this breaks the packing. |
1285 | |
1286 | /// Stores the bits used by DeclContext. |
1287 | /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor |
1288 | /// methods in DeclContext should be updated appropriately. |
1289 | class DeclContextBitfields { |
1290 | friend class DeclContext; |
1291 | /// DeclKind - This indicates which class this is. |
1292 | uint64_t DeclKind : 7; |
1293 | |
1294 | /// Whether this declaration context also has some external |
1295 | /// storage that contains additional declarations that are lexically |
1296 | /// part of this context. |
1297 | mutable uint64_t ExternalLexicalStorage : 1; |
1298 | |
1299 | /// Whether this declaration context also has some external |
1300 | /// storage that contains additional declarations that are visible |
1301 | /// in this context. |
1302 | mutable uint64_t ExternalVisibleStorage : 1; |
1303 | |
1304 | /// Whether this declaration context has had externally visible |
1305 | /// storage added since the last lookup. In this case, \c LookupPtr's |
1306 | /// invariant may not hold and needs to be fixed before we perform |
1307 | /// another lookup. |
1308 | mutable uint64_t NeedToReconcileExternalVisibleStorage : 1; |
1309 | |
1310 | /// If \c true, this context may have local lexical declarations |
1311 | /// that are missing from the lookup table. |
1312 | mutable uint64_t HasLazyLocalLexicalLookups : 1; |
1313 | |
1314 | /// If \c true, the external source may have lexical declarations |
1315 | /// that are missing from the lookup table. |
1316 | mutable uint64_t HasLazyExternalLexicalLookups : 1; |
1317 | |
1318 | /// If \c true, lookups should only return identifier from |
1319 | /// DeclContext scope (for example TranslationUnit). Used in |
1320 | /// LookupQualifiedName() |
1321 | mutable uint64_t UseQualifiedLookup : 1; |
1322 | }; |
1323 | |
1324 | /// Number of bits in DeclContextBitfields. |
1325 | enum { NumDeclContextBits = 13 }; |
1326 | |
1327 | /// Stores the bits used by TagDecl. |
1328 | /// If modified NumTagDeclBits and the accessor |
1329 | /// methods in TagDecl should be updated appropriately. |
1330 | class TagDeclBitfields { |
1331 | friend class TagDecl; |
1332 | /// For the bits in DeclContextBitfields |
1333 | uint64_t : NumDeclContextBits; |
1334 | |
1335 | /// The TagKind enum. |
1336 | uint64_t TagDeclKind : 3; |
1337 | |
1338 | /// True if this is a definition ("struct foo {};"), false if it is a |
1339 | /// declaration ("struct foo;"). It is not considered a definition |
1340 | /// until the definition has been fully processed. |
1341 | uint64_t IsCompleteDefinition : 1; |
1342 | |
1343 | /// True if this is currently being defined. |
1344 | uint64_t IsBeingDefined : 1; |
1345 | |
1346 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
1347 | /// for the very first time) in the syntax of a declarator. |
1348 | uint64_t IsEmbeddedInDeclarator : 1; |
1349 | |
1350 | /// True if this tag is free standing, e.g. "struct foo;". |
1351 | uint64_t IsFreeStanding : 1; |
1352 | |
1353 | /// Indicates whether it is possible for declarations of this kind |
1354 | /// to have an out-of-date definition. |
1355 | /// |
1356 | /// This option is only enabled when modules are enabled. |
1357 | uint64_t MayHaveOutOfDateDef : 1; |
1358 | |
1359 | /// Has the full definition of this type been required by a use somewhere in |
1360 | /// the TU. |
1361 | uint64_t IsCompleteDefinitionRequired : 1; |
1362 | }; |
1363 | |
1364 | /// Number of non-inherited bits in TagDeclBitfields. |
1365 | enum { NumTagDeclBits = 9 }; |
1366 | |
1367 | /// Stores the bits used by EnumDecl. |
1368 | /// If modified NumEnumDeclBit and the accessor |
1369 | /// methods in EnumDecl should be updated appropriately. |
1370 | class EnumDeclBitfields { |
1371 | friend class EnumDecl; |
1372 | /// For the bits in DeclContextBitfields. |
1373 | uint64_t : NumDeclContextBits; |
1374 | /// For the bits in TagDeclBitfields. |
1375 | uint64_t : NumTagDeclBits; |
1376 | |
1377 | /// Width in bits required to store all the non-negative |
1378 | /// enumerators of this enum. |
1379 | uint64_t NumPositiveBits : 8; |
1380 | |
1381 | /// Width in bits required to store all the negative |
1382 | /// enumerators of this enum. |
1383 | uint64_t NumNegativeBits : 8; |
1384 | |
1385 | /// True if this tag declaration is a scoped enumeration. Only |
1386 | /// possible in C++11 mode. |
1387 | uint64_t IsScoped : 1; |
1388 | |
1389 | /// If this tag declaration is a scoped enum, |
1390 | /// then this is true if the scoped enum was declared using the class |
1391 | /// tag, false if it was declared with the struct tag. No meaning is |
1392 | /// associated if this tag declaration is not a scoped enum. |
1393 | uint64_t IsScopedUsingClassTag : 1; |
1394 | |
1395 | /// True if this is an enumeration with fixed underlying type. Only |
1396 | /// possible in C++11, Microsoft extensions, or Objective C mode. |
1397 | uint64_t IsFixed : 1; |
1398 | |
1399 | /// True if a valid hash is stored in ODRHash. |
1400 | uint64_t HasODRHash : 1; |
1401 | }; |
1402 | |
1403 | /// Number of non-inherited bits in EnumDeclBitfields. |
1404 | enum { NumEnumDeclBits = 20 }; |
1405 | |
1406 | /// Stores the bits used by RecordDecl. |
1407 | /// If modified NumRecordDeclBits and the accessor |
1408 | /// methods in RecordDecl should be updated appropriately. |
1409 | class RecordDeclBitfields { |
1410 | friend class RecordDecl; |
1411 | /// For the bits in DeclContextBitfields. |
1412 | uint64_t : NumDeclContextBits; |
1413 | /// For the bits in TagDeclBitfields. |
1414 | uint64_t : NumTagDeclBits; |
1415 | |
1416 | /// This is true if this struct ends with a flexible |
1417 | /// array member (e.g. int X[]) or if this union contains a struct that does. |
1418 | /// If so, this cannot be contained in arrays or other structs as a member. |
1419 | uint64_t HasFlexibleArrayMember : 1; |
1420 | |
1421 | /// Whether this is the type of an anonymous struct or union. |
1422 | uint64_t AnonymousStructOrUnion : 1; |
1423 | |
1424 | /// This is true if this struct has at least one member |
1425 | /// containing an Objective-C object pointer type. |
1426 | uint64_t HasObjectMember : 1; |
1427 | |
1428 | /// This is true if struct has at least one member of |
1429 | /// 'volatile' type. |
1430 | uint64_t HasVolatileMember : 1; |
1431 | |
1432 | /// Whether the field declarations of this record have been loaded |
1433 | /// from external storage. To avoid unnecessary deserialization of |
1434 | /// methods/nested types we allow deserialization of just the fields |
1435 | /// when needed. |
1436 | mutable uint64_t LoadedFieldsFromExternalStorage : 1; |
1437 | |
1438 | /// Basic properties of non-trivial C structs. |
1439 | uint64_t NonTrivialToPrimitiveDefaultInitialize : 1; |
1440 | uint64_t NonTrivialToPrimitiveCopy : 1; |
1441 | uint64_t NonTrivialToPrimitiveDestroy : 1; |
1442 | |
1443 | /// The following bits indicate whether this is or contains a C union that |
1444 | /// is non-trivial to default-initialize, destruct, or copy. These bits |
1445 | /// imply the associated basic non-triviality predicates declared above. |
1446 | uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1; |
1447 | uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1; |
1448 | uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1; |
1449 | |
1450 | /// Indicates whether this struct is destroyed in the callee. |
1451 | uint64_t ParamDestroyedInCallee : 1; |
1452 | |
1453 | /// Represents the way this type is passed to a function. |
1454 | uint64_t ArgPassingRestrictions : 2; |
1455 | }; |
1456 | |
1457 | /// Number of non-inherited bits in RecordDeclBitfields. |
1458 | enum { NumRecordDeclBits = 14 }; |
1459 | |
1460 | /// Stores the bits used by OMPDeclareReductionDecl. |
1461 | /// If modified NumOMPDeclareReductionDeclBits and the accessor |
1462 | /// methods in OMPDeclareReductionDecl should be updated appropriately. |
1463 | class OMPDeclareReductionDeclBitfields { |
1464 | friend class OMPDeclareReductionDecl; |
1465 | /// For the bits in DeclContextBitfields |
1466 | uint64_t : NumDeclContextBits; |
1467 | |
1468 | /// Kind of initializer, |
1469 | /// function call or omp_priv<init_expr> initializtion. |
1470 | uint64_t InitializerKind : 2; |
1471 | }; |
1472 | |
1473 | /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields. |
1474 | enum { NumOMPDeclareReductionDeclBits = 2 }; |
1475 | |
1476 | /// Stores the bits used by FunctionDecl. |
1477 | /// If modified NumFunctionDeclBits and the accessor |
1478 | /// methods in FunctionDecl and CXXDeductionGuideDecl |
1479 | /// (for IsCopyDeductionCandidate) should be updated appropriately. |
1480 | class FunctionDeclBitfields { |
1481 | friend class FunctionDecl; |
1482 | /// For IsCopyDeductionCandidate |
1483 | friend class CXXDeductionGuideDecl; |
1484 | /// For the bits in DeclContextBitfields. |
1485 | uint64_t : NumDeclContextBits; |
1486 | |
1487 | uint64_t SClass : 3; |
1488 | uint64_t IsInline : 1; |
1489 | uint64_t IsInlineSpecified : 1; |
1490 | |
1491 | uint64_t IsVirtualAsWritten : 1; |
1492 | uint64_t IsPure : 1; |
1493 | uint64_t HasInheritedPrototype : 1; |
1494 | uint64_t HasWrittenPrototype : 1; |
1495 | uint64_t IsDeleted : 1; |
1496 | /// Used by CXXMethodDecl |
1497 | uint64_t IsTrivial : 1; |
1498 | |
1499 | /// This flag indicates whether this function is trivial for the purpose of |
1500 | /// calls. This is meaningful only when this function is a copy/move |
1501 | /// constructor or a destructor. |
1502 | uint64_t IsTrivialForCall : 1; |
1503 | |
1504 | uint64_t IsDefaulted : 1; |
1505 | uint64_t IsExplicitlyDefaulted : 1; |
1506 | uint64_t HasDefaultedFunctionInfo : 1; |
1507 | uint64_t HasImplicitReturnZero : 1; |
1508 | uint64_t IsLateTemplateParsed : 1; |
1509 | |
1510 | /// Kind of contexpr specifier as defined by ConstexprSpecKind. |
1511 | uint64_t ConstexprKind : 2; |
1512 | uint64_t InstantiationIsPending : 1; |
1513 | |
1514 | /// Indicates if the function uses __try. |
1515 | uint64_t UsesSEHTry : 1; |
1516 | |
1517 | /// Indicates if the function was a definition |
1518 | /// but its body was skipped. |
1519 | uint64_t HasSkippedBody : 1; |
1520 | |
1521 | /// Indicates if the function declaration will |
1522 | /// have a body, once we're done parsing it. |
1523 | uint64_t WillHaveBody : 1; |
1524 | |
1525 | /// Indicates that this function is a multiversioned |
1526 | /// function using attribute 'target'. |
1527 | uint64_t IsMultiVersion : 1; |
1528 | |
1529 | /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that |
1530 | /// the Deduction Guide is the implicitly generated 'copy |
1531 | /// deduction candidate' (is used during overload resolution). |
1532 | uint64_t IsCopyDeductionCandidate : 1; |
1533 | |
1534 | /// Store the ODRHash after first calculation. |
1535 | uint64_t HasODRHash : 1; |
1536 | |
1537 | /// Indicates if the function uses Floating Point Constrained Intrinsics |
1538 | uint64_t UsesFPIntrin : 1; |
1539 | }; |
1540 | |
1541 | /// Number of non-inherited bits in FunctionDeclBitfields. |
1542 | enum { NumFunctionDeclBits = 27 }; |
1543 | |
1544 | /// Stores the bits used by CXXConstructorDecl. If modified |
1545 | /// NumCXXConstructorDeclBits and the accessor |
1546 | /// methods in CXXConstructorDecl should be updated appropriately. |
1547 | class CXXConstructorDeclBitfields { |
1548 | friend class CXXConstructorDecl; |
1549 | /// For the bits in DeclContextBitfields. |
1550 | uint64_t : NumDeclContextBits; |
1551 | /// For the bits in FunctionDeclBitfields. |
1552 | uint64_t : NumFunctionDeclBits; |
1553 | |
1554 | /// 24 bits to fit in the remaining available space. |
1555 | /// Note that this makes CXXConstructorDeclBitfields take |
1556 | /// exactly 64 bits and thus the width of NumCtorInitializers |
1557 | /// will need to be shrunk if some bit is added to NumDeclContextBitfields, |
1558 | /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields. |
1559 | uint64_t NumCtorInitializers : 21; |
1560 | uint64_t IsInheritingConstructor : 1; |
1561 | |
1562 | /// Whether this constructor has a trail-allocated explicit specifier. |
1563 | uint64_t HasTrailingExplicitSpecifier : 1; |
1564 | /// If this constructor does't have a trail-allocated explicit specifier. |
1565 | /// Whether this constructor is explicit specified. |
1566 | uint64_t IsSimpleExplicit : 1; |
1567 | }; |
1568 | |
1569 | /// Number of non-inherited bits in CXXConstructorDeclBitfields. |
1570 | enum { |
1571 | NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits |
1572 | }; |
1573 | |
1574 | /// Stores the bits used by ObjCMethodDecl. |
1575 | /// If modified NumObjCMethodDeclBits and the accessor |
1576 | /// methods in ObjCMethodDecl should be updated appropriately. |
1577 | class ObjCMethodDeclBitfields { |
1578 | friend class ObjCMethodDecl; |
1579 | |
1580 | /// For the bits in DeclContextBitfields. |
1581 | uint64_t : NumDeclContextBits; |
1582 | |
1583 | /// The conventional meaning of this method; an ObjCMethodFamily. |
1584 | /// This is not serialized; instead, it is computed on demand and |
1585 | /// cached. |
1586 | mutable uint64_t Family : ObjCMethodFamilyBitWidth; |
1587 | |
1588 | /// instance (true) or class (false) method. |
1589 | uint64_t IsInstance : 1; |
1590 | uint64_t IsVariadic : 1; |
1591 | |
1592 | /// True if this method is the getter or setter for an explicit property. |
1593 | uint64_t IsPropertyAccessor : 1; |
1594 | |
1595 | /// True if this method is a synthesized property accessor stub. |
1596 | uint64_t IsSynthesizedAccessorStub : 1; |
1597 | |
1598 | /// Method has a definition. |
1599 | uint64_t IsDefined : 1; |
1600 | |
1601 | /// Method redeclaration in the same interface. |
1602 | uint64_t IsRedeclaration : 1; |
1603 | |
1604 | /// Is redeclared in the same interface. |
1605 | mutable uint64_t HasRedeclaration : 1; |
1606 | |
1607 | /// \@required/\@optional |
1608 | uint64_t DeclImplementation : 2; |
1609 | |
1610 | /// in, inout, etc. |
1611 | uint64_t objcDeclQualifier : 7; |
1612 | |
1613 | /// Indicates whether this method has a related result type. |
1614 | uint64_t RelatedResultType : 1; |
1615 | |
1616 | /// Whether the locations of the selector identifiers are in a |
1617 | /// "standard" position, a enum SelectorLocationsKind. |
1618 | uint64_t SelLocsKind : 2; |
1619 | |
1620 | /// Whether this method overrides any other in the class hierarchy. |
1621 | /// |
1622 | /// A method is said to override any method in the class's |
1623 | /// base classes, its protocols, or its categories' protocols, that has |
1624 | /// the same selector and is of the same kind (class or instance). |
1625 | /// A method in an implementation is not considered as overriding the same |
1626 | /// method in the interface or its categories. |
1627 | uint64_t IsOverriding : 1; |
1628 | |
1629 | /// Indicates if the method was a definition but its body was skipped. |
1630 | uint64_t HasSkippedBody : 1; |
1631 | }; |
1632 | |
1633 | /// Number of non-inherited bits in ObjCMethodDeclBitfields. |
1634 | enum { NumObjCMethodDeclBits = 24 }; |
1635 | |
1636 | /// Stores the bits used by ObjCContainerDecl. |
1637 | /// If modified NumObjCContainerDeclBits and the accessor |
1638 | /// methods in ObjCContainerDecl should be updated appropriately. |
1639 | class ObjCContainerDeclBitfields { |
1640 | friend class ObjCContainerDecl; |
1641 | /// For the bits in DeclContextBitfields |
1642 | uint32_t : NumDeclContextBits; |
1643 | |
1644 | // Not a bitfield but this saves space. |
1645 | // Note that ObjCContainerDeclBitfields is full. |
1646 | SourceLocation AtStart; |
1647 | }; |
1648 | |
1649 | /// Number of non-inherited bits in ObjCContainerDeclBitfields. |
1650 | /// Note that here we rely on the fact that SourceLocation is 32 bits |
1651 | /// wide. We check this with the static_assert in the ctor of DeclContext. |
1652 | enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits }; |
1653 | |
1654 | /// Stores the bits used by LinkageSpecDecl. |
1655 | /// If modified NumLinkageSpecDeclBits and the accessor |
1656 | /// methods in LinkageSpecDecl should be updated appropriately. |
1657 | class LinkageSpecDeclBitfields { |
1658 | friend class LinkageSpecDecl; |
1659 | /// For the bits in DeclContextBitfields. |
1660 | uint64_t : NumDeclContextBits; |
1661 | |
1662 | /// The language for this linkage specification with values |
1663 | /// in the enum LinkageSpecDecl::LanguageIDs. |
1664 | uint64_t Language : 3; |
1665 | |
1666 | /// True if this linkage spec has braces. |
1667 | /// This is needed so that hasBraces() returns the correct result while the |
1668 | /// linkage spec body is being parsed. Once RBraceLoc has been set this is |
1669 | /// not used, so it doesn't need to be serialized. |
1670 | uint64_t HasBraces : 1; |
1671 | }; |
1672 | |
1673 | /// Number of non-inherited bits in LinkageSpecDeclBitfields. |
1674 | enum { NumLinkageSpecDeclBits = 4 }; |
1675 | |
1676 | /// Stores the bits used by BlockDecl. |
1677 | /// If modified NumBlockDeclBits and the accessor |
1678 | /// methods in BlockDecl should be updated appropriately. |
1679 | class BlockDeclBitfields { |
1680 | friend class BlockDecl; |
1681 | /// For the bits in DeclContextBitfields. |
1682 | uint64_t : NumDeclContextBits; |
1683 | |
1684 | uint64_t IsVariadic : 1; |
1685 | uint64_t CapturesCXXThis : 1; |
1686 | uint64_t BlockMissingReturnType : 1; |
1687 | uint64_t IsConversionFromLambda : 1; |
1688 | |
1689 | /// A bit that indicates this block is passed directly to a function as a |
1690 | /// non-escaping parameter. |
1691 | uint64_t DoesNotEscape : 1; |
1692 | |
1693 | /// A bit that indicates whether it's possible to avoid coying this block to |
1694 | /// the heap when it initializes or is assigned to a local variable with |
1695 | /// automatic storage. |
1696 | uint64_t CanAvoidCopyToHeap : 1; |
1697 | }; |
1698 | |
1699 | /// Number of non-inherited bits in BlockDeclBitfields. |
1700 | enum { NumBlockDeclBits = 5 }; |
1701 | |
1702 | /// Pointer to the data structure used to lookup declarations |
1703 | /// within this context (or a DependentStoredDeclsMap if this is a |
1704 | /// dependent context). We maintain the invariant that, if the map |
1705 | /// contains an entry for a DeclarationName (and we haven't lazily |
1706 | /// omitted anything), then it contains all relevant entries for that |
1707 | /// name (modulo the hasExternalDecls() flag). |
1708 | mutable StoredDeclsMap *LookupPtr = nullptr; |
1709 | |
1710 | protected: |
1711 | /// This anonymous union stores the bits belonging to DeclContext and classes |
1712 | /// deriving from it. The goal is to use otherwise wasted |
1713 | /// space in DeclContext to store data belonging to derived classes. |
1714 | /// The space saved is especially significient when pointers are aligned |
1715 | /// to 8 bytes. In this case due to alignment requirements we have a |
1716 | /// little less than 8 bytes free in DeclContext which we can use. |
1717 | /// We check that none of the classes in this union is larger than |
1718 | /// 8 bytes with static_asserts in the ctor of DeclContext. |
1719 | union { |
1720 | DeclContextBitfields DeclContextBits; |
1721 | TagDeclBitfields TagDeclBits; |
1722 | EnumDeclBitfields EnumDeclBits; |
1723 | RecordDeclBitfields RecordDeclBits; |
1724 | OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits; |
1725 | FunctionDeclBitfields FunctionDeclBits; |
1726 | CXXConstructorDeclBitfields CXXConstructorDeclBits; |
1727 | ObjCMethodDeclBitfields ObjCMethodDeclBits; |
1728 | ObjCContainerDeclBitfields ObjCContainerDeclBits; |
1729 | LinkageSpecDeclBitfields LinkageSpecDeclBits; |
1730 | BlockDeclBitfields BlockDeclBits; |
1731 | |
1732 | static_assert(sizeof(DeclContextBitfields) <= 8, |
1733 | "DeclContextBitfields is larger than 8 bytes!"); |
1734 | static_assert(sizeof(TagDeclBitfields) <= 8, |
1735 | "TagDeclBitfields is larger than 8 bytes!"); |
1736 | static_assert(sizeof(EnumDeclBitfields) <= 8, |
1737 | "EnumDeclBitfields is larger than 8 bytes!"); |
1738 | static_assert(sizeof(RecordDeclBitfields) <= 8, |
1739 | "RecordDeclBitfields is larger than 8 bytes!"); |
1740 | static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8, |
1741 | "OMPDeclareReductionDeclBitfields is larger than 8 bytes!"); |
1742 | static_assert(sizeof(FunctionDeclBitfields) <= 8, |
1743 | "FunctionDeclBitfields is larger than 8 bytes!"); |
1744 | static_assert(sizeof(CXXConstructorDeclBitfields) <= 8, |
1745 | "CXXConstructorDeclBitfields is larger than 8 bytes!"); |
1746 | static_assert(sizeof(ObjCMethodDeclBitfields) <= 8, |
1747 | "ObjCMethodDeclBitfields is larger than 8 bytes!"); |
1748 | static_assert(sizeof(ObjCContainerDeclBitfields) <= 8, |
1749 | "ObjCContainerDeclBitfields is larger than 8 bytes!"); |
1750 | static_assert(sizeof(LinkageSpecDeclBitfields) <= 8, |
1751 | "LinkageSpecDeclBitfields is larger than 8 bytes!"); |
1752 | static_assert(sizeof(BlockDeclBitfields) <= 8, |
1753 | "BlockDeclBitfields is larger than 8 bytes!"); |
1754 | }; |
1755 | |
1756 | /// FirstDecl - The first declaration stored within this declaration |
1757 | /// context. |
1758 | mutable Decl *FirstDecl = nullptr; |
1759 | |
1760 | /// LastDecl - The last declaration stored within this declaration |
1761 | /// context. FIXME: We could probably cache this value somewhere |
1762 | /// outside of the DeclContext, to reduce the size of DeclContext by |
1763 | /// another pointer. |
1764 | mutable Decl *LastDecl = nullptr; |
1765 | |
1766 | /// Build up a chain of declarations. |
1767 | /// |
1768 | /// \returns the first/last pair of declarations. |
1769 | static std::pair<Decl *, Decl *> |
1770 | BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded); |
1771 | |
1772 | DeclContext(Decl::Kind K); |
1773 | |
1774 | public: |
1775 | ~DeclContext(); |
1776 | |
1777 | Decl::Kind getDeclKind() const { |
1778 | return static_cast<Decl::Kind>(DeclContextBits.DeclKind); |
1779 | } |
1780 | |
1781 | const char *getDeclKindName() const; |
1782 | |
1783 | /// getParent - Returns the containing DeclContext. |
1784 | DeclContext *getParent() { |
1785 | return cast<Decl>(this)->getDeclContext(); |
1786 | } |
1787 | const DeclContext *getParent() const { |
1788 | return const_cast<DeclContext*>(this)->getParent(); |
1789 | } |
1790 | |
1791 | /// getLexicalParent - Returns the containing lexical DeclContext. May be |
1792 | /// different from getParent, e.g.: |
1793 | /// |
1794 | /// namespace A { |
1795 | /// struct S; |
1796 | /// } |
1797 | /// struct A::S {}; // getParent() == namespace 'A' |
1798 | /// // getLexicalParent() == translation unit |
1799 | /// |
1800 | DeclContext *getLexicalParent() { |
1801 | return cast<Decl>(this)->getLexicalDeclContext(); |
1802 | } |
1803 | const DeclContext *getLexicalParent() const { |
1804 | return const_cast<DeclContext*>(this)->getLexicalParent(); |
1805 | } |
1806 | |
1807 | DeclContext *getLookupParent(); |
1808 | |
1809 | const DeclContext *getLookupParent() const { |
1810 | return const_cast<DeclContext*>(this)->getLookupParent(); |
1811 | } |
1812 | |
1813 | ASTContext &getParentASTContext() const { |
1814 | return cast<Decl>(this)->getASTContext(); |
1815 | } |
1816 | |
1817 | bool isClosure() const { return getDeclKind() == Decl::Block; } |
1818 | |
1819 | /// Return this DeclContext if it is a BlockDecl. Otherwise, return the |
1820 | /// innermost enclosing BlockDecl or null if there are no enclosing blocks. |
1821 | const BlockDecl *getInnermostBlockDecl() const; |
1822 | |
1823 | bool isObjCContainer() const { |
1824 | switch (getDeclKind()) { |
1825 | case Decl::ObjCCategory: |
1826 | case Decl::ObjCCategoryImpl: |
1827 | case Decl::ObjCImplementation: |
1828 | case Decl::ObjCInterface: |
1829 | case Decl::ObjCProtocol: |
1830 | return true; |
1831 | default: |
1832 | return false; |
1833 | } |
1834 | } |
1835 | |
1836 | bool isFunctionOrMethod() const { |
1837 | switch (getDeclKind()) { |
1838 | case Decl::Block: |
1839 | case Decl::Captured: |
1840 | case Decl::ObjCMethod: |
1841 | return true; |
1842 | default: |
1843 | return getDeclKind() >= Decl::firstFunction && |
1844 | getDeclKind() <= Decl::lastFunction; |
1845 | } |
1846 | } |
1847 | |
1848 | /// Test whether the context supports looking up names. |
1849 | bool isLookupContext() const { |
1850 | return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec && |
1851 | getDeclKind() != Decl::Export; |
1852 | } |
1853 | |
1854 | bool isFileContext() const { |
1855 | return getDeclKind() == Decl::TranslationUnit || |
1856 | getDeclKind() == Decl::Namespace; |
1857 | } |
1858 | |
1859 | bool isTranslationUnit() const { |
1860 | return getDeclKind() == Decl::TranslationUnit; |
1861 | } |
1862 | |
1863 | bool isRecord() const { |
1864 | return getDeclKind() >= Decl::firstRecord && |
1865 | getDeclKind() <= Decl::lastRecord; |
1866 | } |
1867 | |
1868 | bool isNamespace() const { return getDeclKind() == Decl::Namespace; } |
1869 | |
1870 | bool isStdNamespace() const; |
1871 | |
1872 | bool isInlineNamespace() const; |
1873 | |
1874 | /// Determines whether this context is dependent on a |
1875 | /// template parameter. |
1876 | bool isDependentContext() const; |
1877 | |
1878 | /// isTransparentContext - Determines whether this context is a |
1879 | /// "transparent" context, meaning that the members declared in this |
1880 | /// context are semantically declared in the nearest enclosing |
1881 | /// non-transparent (opaque) context but are lexically declared in |
1882 | /// this context. For example, consider the enumerators of an |
1883 | /// enumeration type: |
1884 | /// @code |
1885 | /// enum E { |
1886 | /// Val1 |
1887 | /// }; |
1888 | /// @endcode |
1889 | /// Here, E is a transparent context, so its enumerator (Val1) will |
1890 | /// appear (semantically) that it is in the same context of E. |
1891 | /// Examples of transparent contexts include: enumerations (except for |
1892 | /// C++0x scoped enums), and C++ linkage specifications. |
1893 | bool isTransparentContext() const; |
1894 | |
1895 | /// Determines whether this context or some of its ancestors is a |
1896 | /// linkage specification context that specifies C linkage. |
1897 | bool isExternCContext() const; |
1898 | |
1899 | /// Retrieve the nearest enclosing C linkage specification context. |
1900 | const LinkageSpecDecl *getExternCContext() const; |
1901 | |
1902 | /// Determines whether this context or some of its ancestors is a |
1903 | /// linkage specification context that specifies C++ linkage. |
1904 | bool isExternCXXContext() const; |
1905 | |
1906 | /// Determine whether this declaration context is equivalent |
1907 | /// to the declaration context DC. |
1908 | bool Equals(const DeclContext *DC) const { |
1909 | return DC && this->getPrimaryContext() == DC->getPrimaryContext(); |
1910 | } |
1911 | |
1912 | /// Determine whether this declaration context encloses the |
1913 | /// declaration context DC. |
1914 | bool Encloses(const DeclContext *DC) const; |
1915 | |
1916 | /// Find the nearest non-closure ancestor of this context, |
1917 | /// i.e. the innermost semantic parent of this context which is not |
1918 | /// a closure. A context may be its own non-closure ancestor. |
1919 | Decl *getNonClosureAncestor(); |
1920 | const Decl *getNonClosureAncestor() const { |
1921 | return const_cast<DeclContext*>(this)->getNonClosureAncestor(); |
1922 | } |
1923 | |
1924 | /// getPrimaryContext - There may be many different |
1925 | /// declarations of the same entity (including forward declarations |
1926 | /// of classes, multiple definitions of namespaces, etc.), each with |
1927 | /// a different set of declarations. This routine returns the |
1928 | /// "primary" DeclContext structure, which will contain the |
1929 | /// information needed to perform name lookup into this context. |
1930 | DeclContext *getPrimaryContext(); |
1931 | const DeclContext *getPrimaryContext() const { |
1932 | return const_cast<DeclContext*>(this)->getPrimaryContext(); |
1933 | } |
1934 | |
1935 | /// getRedeclContext - Retrieve the context in which an entity conflicts with |
1936 | /// other entities of the same name, or where it is a redeclaration if the |
1937 | /// two entities are compatible. This skips through transparent contexts. |
1938 | DeclContext *getRedeclContext(); |
1939 | const DeclContext *getRedeclContext() const { |
1940 | return const_cast<DeclContext *>(this)->getRedeclContext(); |
1941 | } |
1942 | |
1943 | /// Retrieve the nearest enclosing namespace context. |
1944 | DeclContext *getEnclosingNamespaceContext(); |
1945 | const DeclContext *getEnclosingNamespaceContext() const { |
1946 | return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext(); |
1947 | } |
1948 | |
1949 | /// Retrieve the outermost lexically enclosing record context. |
1950 | RecordDecl *getOuterLexicalRecordContext(); |
1951 | const RecordDecl *getOuterLexicalRecordContext() const { |
1952 | return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext(); |
1953 | } |
1954 | |
1955 | /// Test if this context is part of the enclosing namespace set of |
1956 | /// the context NS, as defined in C++0x [namespace.def]p9. If either context |
1957 | /// isn't a namespace, this is equivalent to Equals(). |
1958 | /// |
1959 | /// The enclosing namespace set of a namespace is the namespace and, if it is |
1960 | /// inline, its enclosing namespace, recursively. |
1961 | bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; |
1962 | |
1963 | /// Collects all of the declaration contexts that are semantically |
1964 | /// connected to this declaration context. |
1965 | /// |
1966 | /// For declaration contexts that have multiple semantically connected but |
1967 | /// syntactically distinct contexts, such as C++ namespaces, this routine |
1968 | /// retrieves the complete set of such declaration contexts in source order. |
1969 | /// For example, given: |
1970 | /// |
1971 | /// \code |
1972 | /// namespace N { |
1973 | /// int x; |
1974 | /// } |
1975 | /// namespace N { |
1976 | /// int y; |
1977 | /// } |
1978 | /// \endcode |
1979 | /// |
1980 | /// The \c Contexts parameter will contain both definitions of N. |
1981 | /// |
1982 | /// \param Contexts Will be cleared and set to the set of declaration |
1983 | /// contexts that are semanticaly connected to this declaration context, |
1984 | /// in source order, including this context (which may be the only result, |
1985 | /// for non-namespace contexts). |
1986 | void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts); |
1987 | |
1988 | /// decl_iterator - Iterates through the declarations stored |
1989 | /// within this context. |
1990 | class decl_iterator { |
1991 | /// Current - The current declaration. |
1992 | Decl *Current = nullptr; |
1993 | |
1994 | public: |
1995 | using value_type = Decl *; |
1996 | using reference = const value_type &; |
1997 | using pointer = const value_type *; |
1998 | using iterator_category = std::forward_iterator_tag; |
1999 | using difference_type = std::ptrdiff_t; |
2000 | |
2001 | decl_iterator() = default; |
2002 | explicit decl_iterator(Decl *C) : Current(C) {} |
2003 | |
2004 | reference operator*() const { return Current; } |
2005 | |
2006 | // This doesn't meet the iterator requirements, but it's convenient |
2007 | value_type operator->() const { return Current; } |
2008 | |
2009 | decl_iterator& operator++() { |
2010 | Current = Current->getNextDeclInContext(); |
2011 | return *this; |
2012 | } |
2013 | |
2014 | decl_iterator operator++(int) { |
2015 | decl_iterator tmp(*this); |
2016 | ++(*this); |
2017 | return tmp; |
2018 | } |
2019 | |
2020 | friend bool operator==(decl_iterator x, decl_iterator y) { |
2021 | return x.Current == y.Current; |
2022 | } |
2023 | |
2024 | friend bool operator!=(decl_iterator x, decl_iterator y) { |
2025 | return x.Current != y.Current; |
2026 | } |
2027 | }; |
2028 | |
2029 | using decl_range = llvm::iterator_range<decl_iterator>; |
2030 | |
2031 | /// decls_begin/decls_end - Iterate over the declarations stored in |
2032 | /// this context. |
2033 | decl_range decls() const { return decl_range(decls_begin(), decls_end()); } |
2034 | decl_iterator decls_begin() const; |
2035 | decl_iterator decls_end() const { return decl_iterator(); } |
2036 | bool decls_empty() const; |
2037 | |
2038 | /// noload_decls_begin/end - Iterate over the declarations stored in this |
2039 | /// context that are currently loaded; don't attempt to retrieve anything |
2040 | /// from an external source. |
2041 | decl_range noload_decls() const { |
2042 | return decl_range(noload_decls_begin(), noload_decls_end()); |
2043 | } |
2044 | decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); } |
2045 | decl_iterator noload_decls_end() const { return decl_iterator(); } |
2046 | |
2047 | /// specific_decl_iterator - Iterates over a subrange of |
2048 | /// declarations stored in a DeclContext, providing only those that |
2049 | /// are of type SpecificDecl (or a class derived from it). This |
2050 | /// iterator is used, for example, to provide iteration over just |
2051 | /// the fields within a RecordDecl (with SpecificDecl = FieldDecl). |
2052 | template<typename SpecificDecl> |
2053 | class specific_decl_iterator { |
2054 | /// Current - The current, underlying declaration iterator, which |
2055 | /// will either be NULL or will point to a declaration of |
2056 | /// type SpecificDecl. |
2057 | DeclContext::decl_iterator Current; |
2058 | |
2059 | /// SkipToNextDecl - Advances the current position up to the next |
2060 | /// declaration of type SpecificDecl that also meets the criteria |
2061 | /// required by Acceptable. |
2062 | void SkipToNextDecl() { |
2063 | while (*Current && !isa<SpecificDecl>(*Current)) |
2064 | ++Current; |
2065 | } |
2066 | |
2067 | public: |
2068 | using value_type = SpecificDecl *; |
2069 | // TODO: Add reference and pointer types (with some appropriate proxy type) |
2070 | // if we ever have a need for them. |
2071 | using reference = void; |
2072 | using pointer = void; |
2073 | using difference_type = |
2074 | std::iterator_traits<DeclContext::decl_iterator>::difference_type; |
2075 | using iterator_category = std::forward_iterator_tag; |
2076 | |
2077 | specific_decl_iterator() = default; |
2078 | |
2079 | /// specific_decl_iterator - Construct a new iterator over a |
2080 | /// subset of the declarations the range [C, |
2081 | /// end-of-declarations). If A is non-NULL, it is a pointer to a |
2082 | /// member function of SpecificDecl that should return true for |
2083 | /// all of the SpecificDecl instances that will be in the subset |
2084 | /// of iterators. For example, if you want Objective-C instance |
2085 | /// methods, SpecificDecl will be ObjCMethodDecl and A will be |
2086 | /// &ObjCMethodDecl::isInstanceMethod. |
2087 | explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) { |
2088 | SkipToNextDecl(); |
2089 | } |
2090 | |
2091 | value_type operator*() const { return cast<SpecificDecl>(*Current); } |
2092 | |
2093 | // This doesn't meet the iterator requirements, but it's convenient |
2094 | value_type operator->() const { return **this; } |
2095 | |
2096 | specific_decl_iterator& operator++() { |
2097 | ++Current; |
2098 | SkipToNextDecl(); |
2099 | return *this; |
2100 | } |
2101 | |
2102 | specific_decl_iterator operator++(int) { |
2103 | specific_decl_iterator tmp(*this); |
2104 | ++(*this); |
2105 | return tmp; |
2106 | } |
2107 | |
2108 | friend bool operator==(const specific_decl_iterator& x, |
2109 | const specific_decl_iterator& y) { |
2110 | return x.Current == y.Current; |
2111 | } |
2112 | |
2113 | friend bool operator!=(const specific_decl_iterator& x, |
2114 | const specific_decl_iterator& y) { |
2115 | return x.Current != y.Current; |
2116 | } |
2117 | }; |
2118 | |
2119 | /// Iterates over a filtered subrange of declarations stored |
2120 | /// in a DeclContext. |
2121 | /// |
2122 | /// This iterator visits only those declarations that are of type |
2123 | /// SpecificDecl (or a class derived from it) and that meet some |
2124 | /// additional run-time criteria. This iterator is used, for |
2125 | /// example, to provide access to the instance methods within an |
2126 | /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and |
2127 | /// Acceptable = ObjCMethodDecl::isInstanceMethod). |
2128 | template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const> |
2129 | class filtered_decl_iterator { |
2130 | /// Current - The current, underlying declaration iterator, which |
2131 | /// will either be NULL or will point to a declaration of |
2132 | /// type SpecificDecl. |
2133 | DeclContext::decl_iterator Current; |
2134 | |
2135 | /// SkipToNextDecl - Advances the current position up to the next |
2136 | /// declaration of type SpecificDecl that also meets the criteria |
2137 | /// required by Acceptable. |
2138 | void SkipToNextDecl() { |
2139 | while (*Current && |
2140 | (!isa<SpecificDecl>(*Current) || |
2141 | (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)()))) |
2142 | ++Current; |
2143 | } |
2144 | |
2145 | public: |
2146 | using value_type = SpecificDecl *; |
2147 | // TODO: Add reference and pointer types (with some appropriate proxy type) |
2148 | // if we ever have a need for them. |
2149 | using reference = void; |
2150 | using pointer = void; |
2151 | using difference_type = |
2152 | std::iterator_traits<DeclContext::decl_iterator>::difference_type; |
2153 | using iterator_category = std::forward_iterator_tag; |
2154 | |
2155 | filtered_decl_iterator() = default; |
2156 | |
2157 | /// filtered_decl_iterator - Construct a new iterator over a |
2158 | /// subset of the declarations the range [C, |
2159 | /// end-of-declarations). If A is non-NULL, it is a pointer to a |
2160 | /// member function of SpecificDecl that should return true for |
2161 | /// all of the SpecificDecl instances that will be in the subset |
2162 | /// of iterators. For example, if you want Objective-C instance |
2163 | /// methods, SpecificDecl will be ObjCMethodDecl and A will be |
2164 | /// &ObjCMethodDecl::isInstanceMethod. |
2165 | explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) { |
2166 | SkipToNextDecl(); |
2167 | } |
2168 | |
2169 | value_type operator*() const { return cast<SpecificDecl>(*Current); } |
2170 | value_type operator->() const { return cast<SpecificDecl>(*Current); } |
2171 | |
2172 | filtered_decl_iterator& operator++() { |
2173 | ++Current; |
2174 | SkipToNextDecl(); |
2175 | return *this; |
2176 | } |
2177 | |
2178 | filtered_decl_iterator operator++(int) { |
2179 | filtered_decl_iterator tmp(*this); |
2180 | ++(*this); |
2181 | return tmp; |
2182 | } |
2183 | |
2184 | friend bool operator==(const filtered_decl_iterator& x, |
2185 | const filtered_decl_iterator& y) { |
2186 | return x.Current == y.Current; |
2187 | } |
2188 | |
2189 | friend bool operator!=(const filtered_decl_iterator& x, |
2190 | const filtered_decl_iterator& y) { |
2191 | return x.Current != y.Current; |
2192 | } |
2193 | }; |
2194 | |
2195 | /// Add the declaration D into this context. |
2196 | /// |
2197 | /// This routine should be invoked when the declaration D has first |
2198 | /// been declared, to place D into the context where it was |
2199 | /// (lexically) defined. Every declaration must be added to one |
2200 | /// (and only one!) context, where it can be visited via |
2201 | /// [decls_begin(), decls_end()). Once a declaration has been added |
2202 | /// to its lexical context, the corresponding DeclContext owns the |
2203 | /// declaration. |
2204 | /// |
2205 | /// If D is also a NamedDecl, it will be made visible within its |
2206 | /// semantic context via makeDeclVisibleInContext. |
2207 | void addDecl(Decl *D); |
2208 | |
2209 | /// Add the declaration D into this context, but suppress |
2210 | /// searches for external declarations with the same name. |
2211 | /// |
2212 | /// Although analogous in function to addDecl, this removes an |
2213 | /// important check. This is only useful if the Decl is being |
2214 | /// added in response to an external search; in all other cases, |
2215 | /// addDecl() is the right function to use. |
2216 | /// See the ASTImporter for use cases. |
2217 | void addDeclInternal(Decl *D); |
2218 | |
2219 | /// Add the declaration D to this context without modifying |
2220 | /// any lookup tables. |
2221 | /// |
2222 | /// This is useful for some operations in dependent contexts where |
2223 | /// the semantic context might not be dependent; this basically |
2224 | /// only happens with friends. |
2225 | void addHiddenDecl(Decl *D); |
2226 | |
2227 | /// Removes a declaration from this context. |
2228 | void removeDecl(Decl *D); |
2229 | |
2230 | /// Checks whether a declaration is in this context. |
2231 | bool containsDecl(Decl *D) const; |
2232 | |
2233 | /// Checks whether a declaration is in this context. |
2234 | /// This also loads the Decls from the external source before the check. |
2235 | bool containsDeclAndLoad(Decl *D) const; |
2236 | |
2237 | using lookup_result = DeclContextLookupResult; |
2238 | using lookup_iterator = lookup_result::iterator; |
2239 | |
2240 | /// lookup - Find the declarations (if any) with the given Name in |
2241 | /// this context. Returns a range of iterators that contains all of |
2242 | /// the declarations with this name, with object, function, member, |
2243 | /// and enumerator names preceding any tag name. Note that this |
2244 | /// routine will not look into parent contexts. |
2245 | lookup_result lookup(DeclarationName Name) const; |
2246 | |
2247 | /// Find the declarations with the given name that are visible |
2248 | /// within this context; don't attempt to retrieve anything from an |
2249 | /// external source. |
2250 | lookup_result noload_lookup(DeclarationName Name); |
2251 | |
2252 | /// A simplistic name lookup mechanism that performs name lookup |
2253 | /// into this declaration context without consulting the external source. |
2254 | /// |
2255 | /// This function should almost never be used, because it subverts the |
2256 | /// usual relationship between a DeclContext and the external source. |
2257 | /// See the ASTImporter for the (few, but important) use cases. |
2258 | /// |
2259 | /// FIXME: This is very inefficient; replace uses of it with uses of |
2260 | /// noload_lookup. |
2261 | void localUncachedLookup(DeclarationName Name, |
2262 | SmallVectorImpl<NamedDecl *> &Results); |
2263 | |
2264 | /// Makes a declaration visible within this context. |
2265 | /// |
2266 | /// This routine makes the declaration D visible to name lookup |
2267 | /// within this context and, if this is a transparent context, |
2268 | /// within its parent contexts up to the first enclosing |
2269 | /// non-transparent context. Making a declaration visible within a |
2270 | /// context does not transfer ownership of a declaration, and a |
2271 | /// declaration can be visible in many contexts that aren't its |
2272 | /// lexical context. |
2273 | /// |
2274 | /// If D is a redeclaration of an existing declaration that is |
2275 | /// visible from this context, as determined by |
2276 | /// NamedDecl::declarationReplaces, the previous declaration will be |
2277 | /// replaced with D. |
2278 | void makeDeclVisibleInContext(NamedDecl *D); |
2279 | |
2280 | /// all_lookups_iterator - An iterator that provides a view over the results |
2281 | /// of looking up every possible name. |
2282 | class all_lookups_iterator; |
2283 | |
2284 | using lookups_range = llvm::iterator_range<all_lookups_iterator>; |
2285 | |
2286 | lookups_range lookups() const; |
2287 | // Like lookups(), but avoids loading external declarations. |
2288 | // If PreserveInternalState, avoids building lookup data structures too. |
2289 | lookups_range noload_lookups(bool PreserveInternalState) const; |
2290 | |
2291 | /// Iterators over all possible lookups within this context. |
2292 | all_lookups_iterator lookups_begin() const; |
2293 | all_lookups_iterator lookups_end() const; |
2294 | |
2295 | /// Iterators over all possible lookups within this context that are |
2296 | /// currently loaded; don't attempt to retrieve anything from an external |
2297 | /// source. |
2298 | all_lookups_iterator noload_lookups_begin() const; |
2299 | all_lookups_iterator noload_lookups_end() const; |
2300 | |
2301 | struct udir_iterator; |
2302 | |
2303 | using udir_iterator_base = |
2304 | llvm::iterator_adaptor_base<udir_iterator, lookup_iterator, |
2305 | std::random_access_iterator_tag, |
2306 | UsingDirectiveDecl *>; |
2307 | |
2308 | struct udir_iterator : udir_iterator_base { |
2309 | udir_iterator(lookup_iterator I) : udir_iterator_base(I) {} |
2310 | |
2311 | UsingDirectiveDecl *operator*() const; |
2312 | }; |
2313 | |
2314 | using udir_range = llvm::iterator_range<udir_iterator>; |
2315 | |
2316 | udir_range using_directives() const; |
2317 | |
2318 | // These are all defined in DependentDiagnostic.h. |
2319 | class ddiag_iterator; |
2320 | |
2321 | using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>; |
2322 | |
2323 | inline ddiag_range ddiags() const; |
2324 | |
2325 | // Low-level accessors |
2326 | |
2327 | /// Mark that there are external lexical declarations that we need |
2328 | /// to include in our lookup table (and that are not available as external |
2329 | /// visible lookups). These extra lookup results will be found by walking |
2330 | /// the lexical declarations of this context. This should be used only if |
2331 | /// setHasExternalLexicalStorage() has been called on any decl context for |
2332 | /// which this is the primary context. |
2333 | void setMustBuildLookupTable() { |
2334 | assert(this == getPrimaryContext() &&((this == getPrimaryContext() && "should only be called on primary context" ) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 2335, __PRETTY_FUNCTION__)) |
2335 | "should only be called on primary context")((this == getPrimaryContext() && "should only be called on primary context" ) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclBase.h" , 2335, __PRETTY_FUNCTION__)); |
2336 | DeclContextBits.HasLazyExternalLexicalLookups = true; |
2337 | } |
2338 | |
2339 | /// Retrieve the internal representation of the lookup structure. |
2340 | /// This may omit some names if we are lazily building the structure. |
2341 | StoredDeclsMap *getLookupPtr() const { return LookupPtr; } |
2342 | |
2343 | /// Ensure the lookup structure is fully-built and return it. |
2344 | StoredDeclsMap *buildLookup(); |
2345 | |
2346 | /// Whether this DeclContext has external storage containing |
2347 | /// additional declarations that are lexically in this context. |
2348 | bool hasExternalLexicalStorage() const { |
2349 | return DeclContextBits.ExternalLexicalStorage; |
2350 | } |
2351 | |
2352 | /// State whether this DeclContext has external storage for |
2353 | /// declarations lexically in this context. |
2354 | void setHasExternalLexicalStorage(bool ES = true) const { |
2355 | DeclContextBits.ExternalLexicalStorage = ES; |
2356 | } |
2357 | |
2358 | /// Whether this DeclContext has external storage containing |
2359 | /// additional declarations that are visible in this context. |
2360 | bool hasExternalVisibleStorage() const { |
2361 | return DeclContextBits.ExternalVisibleStorage; |
2362 | } |
2363 | |
2364 | /// State whether this DeclContext has external storage for |
2365 | /// declarations visible in this context. |
2366 | void setHasExternalVisibleStorage(bool ES = true) const { |
2367 | DeclContextBits.ExternalVisibleStorage = ES; |
2368 | if (ES && LookupPtr) |
2369 | DeclContextBits.NeedToReconcileExternalVisibleStorage = true; |
2370 | } |
2371 | |
2372 | /// Determine whether the given declaration is stored in the list of |
2373 | /// declarations lexically within this context. |
2374 | bool isDeclInLexicalTraversal(const Decl *D) const { |
2375 | return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || |
2376 | D == LastDecl); |
2377 | } |
2378 | |
2379 | bool setUseQualifiedLookup(bool use = true) const { |
2380 | bool old_value = DeclContextBits.UseQualifiedLookup; |
2381 | DeclContextBits.UseQualifiedLookup = use; |
2382 | return old_value; |
2383 | } |
2384 | |
2385 | bool shouldUseQualifiedLookup() const { |
2386 | return DeclContextBits.UseQualifiedLookup; |
2387 | } |
2388 | |
2389 | static bool classof(const Decl *D); |
2390 | static bool classof(const DeclContext *D) { return true; } |
2391 | |
2392 | void dumpDeclContext() const; |
2393 | void dumpLookups() const; |
2394 | void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false, |
2395 | bool Deserialize = false) const; |
2396 | |
2397 | private: |
2398 | /// Whether this declaration context has had externally visible |
2399 | /// storage added since the last lookup. In this case, \c LookupPtr's |
2400 | /// invariant may not hold and needs to be fixed before we perform |
2401 | /// another lookup. |
2402 | bool hasNeedToReconcileExternalVisibleStorage() const { |
2403 | return DeclContextBits.NeedToReconcileExternalVisibleStorage; |
2404 | } |
2405 | |
2406 | /// State that this declaration context has had externally visible |
2407 | /// storage added since the last lookup. In this case, \c LookupPtr's |
2408 | /// invariant may not hold and needs to be fixed before we perform |
2409 | /// another lookup. |
2410 | void setNeedToReconcileExternalVisibleStorage(bool Need = true) const { |
2411 | DeclContextBits.NeedToReconcileExternalVisibleStorage = Need; |
2412 | } |
2413 | |
2414 | /// If \c true, this context may have local lexical declarations |
2415 | /// that are missing from the lookup table. |
2416 | bool hasLazyLocalLexicalLookups() const { |
2417 | return DeclContextBits.HasLazyLocalLexicalLookups; |
2418 | } |
2419 | |
2420 | /// If \c true, this context may have local lexical declarations |
2421 | /// that are missing from the lookup table. |
2422 | void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const { |
2423 | DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL; |
2424 | } |
2425 | |
2426 | /// If \c true, the external source may have lexical declarations |
2427 | /// that are missing from the lookup table. |
2428 | bool hasLazyExternalLexicalLookups() const { |
2429 | return DeclContextBits.HasLazyExternalLexicalLookups; |
2430 | } |
2431 | |
2432 | /// If \c true, the external source may have lexical declarations |
2433 | /// that are missing from the lookup table. |
2434 | void setHasLazyExternalLexicalLookups(bool HasLELL = true) const { |
2435 | DeclContextBits.HasLazyExternalLexicalLookups = HasLELL; |
2436 | } |
2437 | |
2438 | void reconcileExternalVisibleStorage() const; |
2439 | bool LoadLexicalDeclsFromExternalStorage() const; |
2440 | |
2441 | /// Makes a declaration visible within this context, but |
2442 | /// suppresses searches for external declarations with the same |
2443 | /// name. |
2444 | /// |
2445 | /// Analogous to makeDeclVisibleInContext, but for the exclusive |
2446 | /// use of addDeclInternal(). |
2447 | void makeDeclVisibleInContextInternal(NamedDecl *D); |
2448 | |
2449 | StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; |
2450 | |
2451 | void loadLazyLocalLexicalLookups(); |
2452 | void buildLookupImpl(DeclContext *DCtx, bool Internal); |
2453 | void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, |
2454 | bool Rediscoverable); |
2455 | void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal); |
2456 | }; |
2457 | |
2458 | inline bool Decl::isTemplateParameter() const { |
2459 | return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm || |
2460 | getKind() == TemplateTemplateParm; |
2461 | } |
2462 | |
2463 | // Specialization selected when ToTy is not a known subclass of DeclContext. |
2464 | template <class ToTy, |
2465 | bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value> |
2466 | struct cast_convert_decl_context { |
2467 | static const ToTy *doit(const DeclContext *Val) { |
2468 | return static_cast<const ToTy*>(Decl::castFromDeclContext(Val)); |
2469 | } |
2470 | |
2471 | static ToTy *doit(DeclContext *Val) { |
2472 | return static_cast<ToTy*>(Decl::castFromDeclContext(Val)); |
2473 | } |
2474 | }; |
2475 | |
2476 | // Specialization selected when ToTy is a known subclass of DeclContext. |
2477 | template <class ToTy> |
2478 | struct cast_convert_decl_context<ToTy, true> { |
2479 | static const ToTy *doit(const DeclContext *Val) { |
2480 | return static_cast<const ToTy*>(Val); |
2481 | } |
2482 | |
2483 | static ToTy *doit(DeclContext *Val) { |
2484 | return static_cast<ToTy*>(Val); |
2485 | } |
2486 | }; |
2487 | |
2488 | } // namespace clang |
2489 | |
2490 | namespace llvm { |
2491 | |
2492 | /// isa<T>(DeclContext*) |
2493 | template <typename To> |
2494 | struct isa_impl<To, ::clang::DeclContext> { |
2495 | static bool doit(const ::clang::DeclContext &Val) { |
2496 | return To::classofKind(Val.getDeclKind()); |
2497 | } |
2498 | }; |
2499 | |
2500 | /// cast<T>(DeclContext*) |
2501 | template<class ToTy> |
2502 | struct cast_convert_val<ToTy, |
2503 | const ::clang::DeclContext,const ::clang::DeclContext> { |
2504 | static const ToTy &doit(const ::clang::DeclContext &Val) { |
2505 | return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); |
2506 | } |
2507 | }; |
2508 | |
2509 | template<class ToTy> |
2510 | struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> { |
2511 | static ToTy &doit(::clang::DeclContext &Val) { |
2512 | return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); |
2513 | } |
2514 | }; |
2515 | |
2516 | template<class ToTy> |
2517 | struct cast_convert_val<ToTy, |
2518 | const ::clang::DeclContext*, const ::clang::DeclContext*> { |
2519 | static const ToTy *doit(const ::clang::DeclContext *Val) { |
2520 | return ::clang::cast_convert_decl_context<ToTy>::doit(Val); |
2521 | } |
2522 | }; |
2523 | |
2524 | template<class ToTy> |
2525 | struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> { |
2526 | static ToTy *doit(::clang::DeclContext *Val) { |
2527 | return ::clang::cast_convert_decl_context<ToTy>::doit(Val); |
2528 | } |
2529 | }; |
2530 | |
2531 | /// Implement cast_convert_val for Decl -> DeclContext conversions. |
2532 | template<class FromTy> |
2533 | struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> { |
2534 | static ::clang::DeclContext &doit(const FromTy &Val) { |
2535 | return *FromTy::castToDeclContext(&Val); |
2536 | } |
2537 | }; |
2538 | |
2539 | template<class FromTy> |
2540 | struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> { |
2541 | static ::clang::DeclContext *doit(const FromTy *Val) { |
2542 | return FromTy::castToDeclContext(Val); |
2543 | } |
2544 | }; |
2545 | |
2546 | template<class FromTy> |
2547 | struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> { |
2548 | static const ::clang::DeclContext &doit(const FromTy &Val) { |
2549 | return *FromTy::castToDeclContext(&Val); |
2550 | } |
2551 | }; |
2552 | |
2553 | template<class FromTy> |
2554 | struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> { |
2555 | static const ::clang::DeclContext *doit(const FromTy *Val) { |
2556 | return FromTy::castToDeclContext(Val); |
2557 | } |
2558 | }; |
2559 | |
2560 | } // namespace llvm |
2561 | |
2562 | #endif // LLVM_CLANG_AST_DECLBASE_H |