File: | src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaDecl.cpp |
Warning: | line 9892, column 19 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/Expr.h" |
25 | #include "clang/AST/ExprCXX.h" |
26 | #include "clang/AST/NonTrivialTypeVisitor.h" |
27 | #include "clang/AST/StmtCXX.h" |
28 | #include "clang/Basic/Builtins.h" |
29 | #include "clang/Basic/PartialDiagnostic.h" |
30 | #include "clang/Basic/SourceManager.h" |
31 | #include "clang/Basic/TargetInfo.h" |
32 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex |
33 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. |
34 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex |
35 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() |
36 | #include "clang/Sema/CXXFieldCollector.h" |
37 | #include "clang/Sema/DeclSpec.h" |
38 | #include "clang/Sema/DelayedDiagnostic.h" |
39 | #include "clang/Sema/Initialization.h" |
40 | #include "clang/Sema/Lookup.h" |
41 | #include "clang/Sema/ParsedTemplate.h" |
42 | #include "clang/Sema/Scope.h" |
43 | #include "clang/Sema/ScopeInfo.h" |
44 | #include "clang/Sema/SemaInternal.h" |
45 | #include "clang/Sema/Template.h" |
46 | #include "llvm/ADT/SmallString.h" |
47 | #include "llvm/ADT/Triple.h" |
48 | #include <algorithm> |
49 | #include <cstring> |
50 | #include <functional> |
51 | #include <unordered_map> |
52 | |
53 | using namespace clang; |
54 | using namespace sema; |
55 | |
56 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { |
57 | if (OwnedType) { |
58 | Decl *Group[2] = { OwnedType, Ptr }; |
59 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); |
60 | } |
61 | |
62 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); |
63 | } |
64 | |
65 | namespace { |
66 | |
67 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { |
68 | public: |
69 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, |
70 | bool AllowTemplates = false, |
71 | bool AllowNonTemplates = true) |
72 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), |
73 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { |
74 | WantExpressionKeywords = false; |
75 | WantCXXNamedCasts = false; |
76 | WantRemainingKeywords = false; |
77 | } |
78 | |
79 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
80 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { |
81 | if (!AllowInvalidDecl && ND->isInvalidDecl()) |
82 | return false; |
83 | |
84 | if (getAsTypeTemplateDecl(ND)) |
85 | return AllowTemplates; |
86 | |
87 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); |
88 | if (!IsType) |
89 | return false; |
90 | |
91 | if (AllowNonTemplates) |
92 | return true; |
93 | |
94 | // An injected-class-name of a class template (specialization) is valid |
95 | // as a template or as a non-template. |
96 | if (AllowTemplates) { |
97 | auto *RD = dyn_cast<CXXRecordDecl>(ND); |
98 | if (!RD || !RD->isInjectedClassName()) |
99 | return false; |
100 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); |
101 | return RD->getDescribedClassTemplate() || |
102 | isa<ClassTemplateSpecializationDecl>(RD); |
103 | } |
104 | |
105 | return false; |
106 | } |
107 | |
108 | return !WantClassName && candidate.isKeyword(); |
109 | } |
110 | |
111 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
112 | return std::make_unique<TypeNameValidatorCCC>(*this); |
113 | } |
114 | |
115 | private: |
116 | bool AllowInvalidDecl; |
117 | bool WantClassName; |
118 | bool AllowTemplates; |
119 | bool AllowNonTemplates; |
120 | }; |
121 | |
122 | } // end anonymous namespace |
123 | |
124 | /// Determine whether the token kind starts a simple-type-specifier. |
125 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { |
126 | switch (Kind) { |
127 | // FIXME: Take into account the current language when deciding whether a |
128 | // token kind is a valid type specifier |
129 | case tok::kw_short: |
130 | case tok::kw_long: |
131 | case tok::kw___int64: |
132 | case tok::kw___int128: |
133 | case tok::kw_signed: |
134 | case tok::kw_unsigned: |
135 | case tok::kw_void: |
136 | case tok::kw_char: |
137 | case tok::kw_int: |
138 | case tok::kw_half: |
139 | case tok::kw_float: |
140 | case tok::kw_double: |
141 | case tok::kw___bf16: |
142 | case tok::kw__Float16: |
143 | case tok::kw___float128: |
144 | case tok::kw_wchar_t: |
145 | case tok::kw_bool: |
146 | case tok::kw___underlying_type: |
147 | case tok::kw___auto_type: |
148 | return true; |
149 | |
150 | case tok::annot_typename: |
151 | case tok::kw_char16_t: |
152 | case tok::kw_char32_t: |
153 | case tok::kw_typeof: |
154 | case tok::annot_decltype: |
155 | case tok::kw_decltype: |
156 | return getLangOpts().CPlusPlus; |
157 | |
158 | case tok::kw_char8_t: |
159 | return getLangOpts().Char8; |
160 | |
161 | default: |
162 | break; |
163 | } |
164 | |
165 | return false; |
166 | } |
167 | |
168 | namespace { |
169 | enum class UnqualifiedTypeNameLookupResult { |
170 | NotFound, |
171 | FoundNonType, |
172 | FoundType |
173 | }; |
174 | } // end anonymous namespace |
175 | |
176 | /// Tries to perform unqualified lookup of the type decls in bases for |
177 | /// dependent class. |
178 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a |
179 | /// type decl, \a FoundType if only type decls are found. |
180 | static UnqualifiedTypeNameLookupResult |
181 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, |
182 | SourceLocation NameLoc, |
183 | const CXXRecordDecl *RD) { |
184 | if (!RD->hasDefinition()) |
185 | return UnqualifiedTypeNameLookupResult::NotFound; |
186 | // Look for type decls in base classes. |
187 | UnqualifiedTypeNameLookupResult FoundTypeDecl = |
188 | UnqualifiedTypeNameLookupResult::NotFound; |
189 | for (const auto &Base : RD->bases()) { |
190 | const CXXRecordDecl *BaseRD = nullptr; |
191 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) |
192 | BaseRD = BaseTT->getAsCXXRecordDecl(); |
193 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { |
194 | // Look for type decls in dependent base classes that have known primary |
195 | // templates. |
196 | if (!TST || !TST->isDependentType()) |
197 | continue; |
198 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); |
199 | if (!TD) |
200 | continue; |
201 | if (auto *BasePrimaryTemplate = |
202 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { |
203 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) |
204 | BaseRD = BasePrimaryTemplate; |
205 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { |
206 | if (const ClassTemplatePartialSpecializationDecl *PS = |
207 | CTD->findPartialSpecialization(Base.getType())) |
208 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) |
209 | BaseRD = PS; |
210 | } |
211 | } |
212 | } |
213 | if (BaseRD) { |
214 | for (NamedDecl *ND : BaseRD->lookup(&II)) { |
215 | if (!isa<TypeDecl>(ND)) |
216 | return UnqualifiedTypeNameLookupResult::FoundNonType; |
217 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; |
218 | } |
219 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { |
220 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { |
221 | case UnqualifiedTypeNameLookupResult::FoundNonType: |
222 | return UnqualifiedTypeNameLookupResult::FoundNonType; |
223 | case UnqualifiedTypeNameLookupResult::FoundType: |
224 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; |
225 | break; |
226 | case UnqualifiedTypeNameLookupResult::NotFound: |
227 | break; |
228 | } |
229 | } |
230 | } |
231 | } |
232 | |
233 | return FoundTypeDecl; |
234 | } |
235 | |
236 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, |
237 | const IdentifierInfo &II, |
238 | SourceLocation NameLoc) { |
239 | // Lookup in the parent class template context, if any. |
240 | const CXXRecordDecl *RD = nullptr; |
241 | UnqualifiedTypeNameLookupResult FoundTypeDecl = |
242 | UnqualifiedTypeNameLookupResult::NotFound; |
243 | for (DeclContext *DC = S.CurContext; |
244 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; |
245 | DC = DC->getParent()) { |
246 | // Look for type decls in dependent base classes that have known primary |
247 | // templates. |
248 | RD = dyn_cast<CXXRecordDecl>(DC); |
249 | if (RD && RD->getDescribedClassTemplate()) |
250 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); |
251 | } |
252 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) |
253 | return nullptr; |
254 | |
255 | // We found some types in dependent base classes. Recover as if the user |
256 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the |
257 | // lookup during template instantiation. |
258 | S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; |
259 | |
260 | ASTContext &Context = S.Context; |
261 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, |
262 | cast<Type>(Context.getRecordType(RD))); |
263 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); |
264 | |
265 | CXXScopeSpec SS; |
266 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
267 | |
268 | TypeLocBuilder Builder; |
269 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); |
270 | DepTL.setNameLoc(NameLoc); |
271 | DepTL.setElaboratedKeywordLoc(SourceLocation()); |
272 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
273 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
274 | } |
275 | |
276 | /// If the identifier refers to a type name within this scope, |
277 | /// return the declaration of that type. |
278 | /// |
279 | /// This routine performs ordinary name lookup of the identifier II |
280 | /// within the given scope, with optional C++ scope specifier SS, to |
281 | /// determine whether the name refers to a type. If so, returns an |
282 | /// opaque pointer (actually a QualType) corresponding to that |
283 | /// type. Otherwise, returns NULL. |
284 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, |
285 | Scope *S, CXXScopeSpec *SS, |
286 | bool isClassName, bool HasTrailingDot, |
287 | ParsedType ObjectTypePtr, |
288 | bool IsCtorOrDtorName, |
289 | bool WantNontrivialTypeSourceInfo, |
290 | bool IsClassTemplateDeductionContext, |
291 | IdentifierInfo **CorrectedII) { |
292 | // FIXME: Consider allowing this outside C++1z mode as an extension. |
293 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && |
294 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && |
295 | !isClassName && !HasTrailingDot; |
296 | |
297 | // Determine where we will perform name lookup. |
298 | DeclContext *LookupCtx = nullptr; |
299 | if (ObjectTypePtr) { |
300 | QualType ObjectType = ObjectTypePtr.get(); |
301 | if (ObjectType->isRecordType()) |
302 | LookupCtx = computeDeclContext(ObjectType); |
303 | } else if (SS && SS->isNotEmpty()) { |
304 | LookupCtx = computeDeclContext(*SS, false); |
305 | |
306 | if (!LookupCtx) { |
307 | if (isDependentScopeSpecifier(*SS)) { |
308 | // C++ [temp.res]p3: |
309 | // A qualified-id that refers to a type and in which the |
310 | // nested-name-specifier depends on a template-parameter (14.6.2) |
311 | // shall be prefixed by the keyword typename to indicate that the |
312 | // qualified-id denotes a type, forming an |
313 | // elaborated-type-specifier (7.1.5.3). |
314 | // |
315 | // We therefore do not perform any name lookup if the result would |
316 | // refer to a member of an unknown specialization. |
317 | if (!isClassName && !IsCtorOrDtorName) |
318 | return nullptr; |
319 | |
320 | // We know from the grammar that this name refers to a type, |
321 | // so build a dependent node to describe the type. |
322 | if (WantNontrivialTypeSourceInfo) |
323 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); |
324 | |
325 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); |
326 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, |
327 | II, NameLoc); |
328 | return ParsedType::make(T); |
329 | } |
330 | |
331 | return nullptr; |
332 | } |
333 | |
334 | if (!LookupCtx->isDependentContext() && |
335 | RequireCompleteDeclContext(*SS, LookupCtx)) |
336 | return nullptr; |
337 | } |
338 | |
339 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of |
340 | // lookup for class-names. |
341 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : |
342 | LookupOrdinaryName; |
343 | LookupResult Result(*this, &II, NameLoc, Kind); |
344 | if (LookupCtx) { |
345 | // Perform "qualified" name lookup into the declaration context we |
346 | // computed, which is either the type of the base of a member access |
347 | // expression or the declaration context associated with a prior |
348 | // nested-name-specifier. |
349 | LookupQualifiedName(Result, LookupCtx); |
350 | |
351 | if (ObjectTypePtr && Result.empty()) { |
352 | // C++ [basic.lookup.classref]p3: |
353 | // If the unqualified-id is ~type-name, the type-name is looked up |
354 | // in the context of the entire postfix-expression. If the type T of |
355 | // the object expression is of a class type C, the type-name is also |
356 | // looked up in the scope of class C. At least one of the lookups shall |
357 | // find a name that refers to (possibly cv-qualified) T. |
358 | LookupName(Result, S); |
359 | } |
360 | } else { |
361 | // Perform unqualified name lookup. |
362 | LookupName(Result, S); |
363 | |
364 | // For unqualified lookup in a class template in MSVC mode, look into |
365 | // dependent base classes where the primary class template is known. |
366 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { |
367 | if (ParsedType TypeInBase = |
368 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) |
369 | return TypeInBase; |
370 | } |
371 | } |
372 | |
373 | NamedDecl *IIDecl = nullptr; |
374 | switch (Result.getResultKind()) { |
375 | case LookupResult::NotFound: |
376 | case LookupResult::NotFoundInCurrentInstantiation: |
377 | if (CorrectedII) { |
378 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, |
379 | AllowDeducedTemplate); |
380 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, |
381 | S, SS, CCC, CTK_ErrorRecovery); |
382 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); |
383 | TemplateTy Template; |
384 | bool MemberOfUnknownSpecialization; |
385 | UnqualifiedId TemplateName; |
386 | TemplateName.setIdentifier(NewII, NameLoc); |
387 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); |
388 | CXXScopeSpec NewSS, *NewSSPtr = SS; |
389 | if (SS && NNS) { |
390 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
391 | NewSSPtr = &NewSS; |
392 | } |
393 | if (Correction && (NNS || NewII != &II) && |
394 | // Ignore a correction to a template type as the to-be-corrected |
395 | // identifier is not a template (typo correction for template names |
396 | // is handled elsewhere). |
397 | !(getLangOpts().CPlusPlus && NewSSPtr && |
398 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, |
399 | Template, MemberOfUnknownSpecialization))) { |
400 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, |
401 | isClassName, HasTrailingDot, ObjectTypePtr, |
402 | IsCtorOrDtorName, |
403 | WantNontrivialTypeSourceInfo, |
404 | IsClassTemplateDeductionContext); |
405 | if (Ty) { |
406 | diagnoseTypo(Correction, |
407 | PDiag(diag::err_unknown_type_or_class_name_suggest) |
408 | << Result.getLookupName() << isClassName); |
409 | if (SS && NNS) |
410 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
411 | *CorrectedII = NewII; |
412 | return Ty; |
413 | } |
414 | } |
415 | } |
416 | // If typo correction failed or was not performed, fall through |
417 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; |
418 | case LookupResult::FoundOverloaded: |
419 | case LookupResult::FoundUnresolvedValue: |
420 | Result.suppressDiagnostics(); |
421 | return nullptr; |
422 | |
423 | case LookupResult::Ambiguous: |
424 | // Recover from type-hiding ambiguities by hiding the type. We'll |
425 | // do the lookup again when looking for an object, and we can |
426 | // diagnose the error then. If we don't do this, then the error |
427 | // about hiding the type will be immediately followed by an error |
428 | // that only makes sense if the identifier was treated like a type. |
429 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { |
430 | Result.suppressDiagnostics(); |
431 | return nullptr; |
432 | } |
433 | |
434 | // Look to see if we have a type anywhere in the list of results. |
435 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); |
436 | Res != ResEnd; ++Res) { |
437 | NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); |
438 | if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( |
439 | RealRes) || |
440 | (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { |
441 | if (!IIDecl || |
442 | // Make the selection of the recovery decl deterministic. |
443 | RealRes->getLocation() < IIDecl->getLocation()) |
444 | IIDecl = RealRes; |
445 | } |
446 | } |
447 | |
448 | if (!IIDecl) { |
449 | // None of the entities we found is a type, so there is no way |
450 | // to even assume that the result is a type. In this case, don't |
451 | // complain about the ambiguity. The parser will either try to |
452 | // perform this lookup again (e.g., as an object name), which |
453 | // will produce the ambiguity, or will complain that it expected |
454 | // a type name. |
455 | Result.suppressDiagnostics(); |
456 | return nullptr; |
457 | } |
458 | |
459 | // We found a type within the ambiguous lookup; diagnose the |
460 | // ambiguity and then return that type. This might be the right |
461 | // answer, or it might not be, but it suppresses any attempt to |
462 | // perform the name lookup again. |
463 | break; |
464 | |
465 | case LookupResult::Found: |
466 | IIDecl = Result.getFoundDecl(); |
467 | break; |
468 | } |
469 | |
470 | assert(IIDecl && "Didn't find decl")((void)0); |
471 | |
472 | QualType T; |
473 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { |
474 | // C++ [class.qual]p2: A lookup that would find the injected-class-name |
475 | // instead names the constructors of the class, except when naming a class. |
476 | // This is ill-formed when we're not actually forming a ctor or dtor name. |
477 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); |
478 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); |
479 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && |
480 | FoundRD->isInjectedClassName() && |
481 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) |
482 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) |
483 | << &II << /*Type*/1; |
484 | |
485 | DiagnoseUseOfDecl(IIDecl, NameLoc); |
486 | |
487 | T = Context.getTypeDeclType(TD); |
488 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); |
489 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { |
490 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); |
491 | if (!HasTrailingDot) |
492 | T = Context.getObjCInterfaceType(IDecl); |
493 | } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { |
494 | (void)DiagnoseUseOfDecl(UD, NameLoc); |
495 | // Recover with 'int' |
496 | T = Context.IntTy; |
497 | } else if (AllowDeducedTemplate) { |
498 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) |
499 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), |
500 | QualType(), false); |
501 | } |
502 | |
503 | if (T.isNull()) { |
504 | // If it's not plausibly a type, suppress diagnostics. |
505 | Result.suppressDiagnostics(); |
506 | return nullptr; |
507 | } |
508 | |
509 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a |
510 | // constructor or destructor name (in such a case, the scope specifier |
511 | // will be attached to the enclosing Expr or Decl node). |
512 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && |
513 | !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { |
514 | if (WantNontrivialTypeSourceInfo) { |
515 | // Construct a type with type-source information. |
516 | TypeLocBuilder Builder; |
517 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); |
518 | |
519 | T = getElaboratedType(ETK_None, *SS, T); |
520 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); |
521 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
522 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); |
523 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
524 | } else { |
525 | T = getElaboratedType(ETK_None, *SS, T); |
526 | } |
527 | } |
528 | |
529 | return ParsedType::make(T); |
530 | } |
531 | |
532 | // Builds a fake NNS for the given decl context. |
533 | static NestedNameSpecifier * |
534 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { |
535 | for (;; DC = DC->getLookupParent()) { |
536 | DC = DC->getPrimaryContext(); |
537 | auto *ND = dyn_cast<NamespaceDecl>(DC); |
538 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) |
539 | return NestedNameSpecifier::Create(Context, nullptr, ND); |
540 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) |
541 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), |
542 | RD->getTypeForDecl()); |
543 | else if (isa<TranslationUnitDecl>(DC)) |
544 | return NestedNameSpecifier::GlobalSpecifier(Context); |
545 | } |
546 | llvm_unreachable("something isn't in TU scope?")__builtin_unreachable(); |
547 | } |
548 | |
549 | /// Find the parent class with dependent bases of the innermost enclosing method |
550 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end |
551 | /// up allowing unqualified dependent type names at class-level, which MSVC |
552 | /// correctly rejects. |
553 | static const CXXRecordDecl * |
554 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { |
555 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { |
556 | DC = DC->getPrimaryContext(); |
557 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) |
558 | if (MD->getParent()->hasAnyDependentBases()) |
559 | return MD->getParent(); |
560 | } |
561 | return nullptr; |
562 | } |
563 | |
564 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, |
565 | SourceLocation NameLoc, |
566 | bool IsTemplateTypeArg) { |
567 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((void)0); |
568 | |
569 | NestedNameSpecifier *NNS = nullptr; |
570 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { |
571 | // If we weren't able to parse a default template argument, delay lookup |
572 | // until instantiation time by making a non-dependent DependentTypeName. We |
573 | // pretend we saw a NestedNameSpecifier referring to the current scope, and |
574 | // lookup is retried. |
575 | // FIXME: This hurts our diagnostic quality, since we get errors like "no |
576 | // type named 'Foo' in 'current_namespace'" when the user didn't write any |
577 | // name specifiers. |
578 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); |
579 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; |
580 | } else if (const CXXRecordDecl *RD = |
581 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { |
582 | // Build a DependentNameType that will perform lookup into RD at |
583 | // instantiation time. |
584 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), |
585 | RD->getTypeForDecl()); |
586 | |
587 | // Diagnose that this identifier was undeclared, and retry the lookup during |
588 | // template instantiation. |
589 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II |
590 | << RD; |
591 | } else { |
592 | // This is not a situation that we should recover from. |
593 | return ParsedType(); |
594 | } |
595 | |
596 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); |
597 | |
598 | // Build type location information. We synthesized the qualifier, so we have |
599 | // to build a fake NestedNameSpecifierLoc. |
600 | NestedNameSpecifierLocBuilder NNSLocBuilder; |
601 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
602 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); |
603 | |
604 | TypeLocBuilder Builder; |
605 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); |
606 | DepTL.setNameLoc(NameLoc); |
607 | DepTL.setElaboratedKeywordLoc(SourceLocation()); |
608 | DepTL.setQualifierLoc(QualifierLoc); |
609 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
610 | } |
611 | |
612 | /// isTagName() - This method is called *for error recovery purposes only* |
613 | /// to determine if the specified name is a valid tag name ("struct foo"). If |
614 | /// so, this returns the TST for the tag corresponding to it (TST_enum, |
615 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose |
616 | /// cases in C where the user forgot to specify the tag. |
617 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { |
618 | // Do a tag name lookup in this scope. |
619 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); |
620 | LookupName(R, S, false); |
621 | R.suppressDiagnostics(); |
622 | if (R.getResultKind() == LookupResult::Found) |
623 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { |
624 | switch (TD->getTagKind()) { |
625 | case TTK_Struct: return DeclSpec::TST_struct; |
626 | case TTK_Interface: return DeclSpec::TST_interface; |
627 | case TTK_Union: return DeclSpec::TST_union; |
628 | case TTK_Class: return DeclSpec::TST_class; |
629 | case TTK_Enum: return DeclSpec::TST_enum; |
630 | } |
631 | } |
632 | |
633 | return DeclSpec::TST_unspecified; |
634 | } |
635 | |
636 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, |
637 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes |
638 | /// then downgrade the missing typename error to a warning. |
639 | /// This is needed for MSVC compatibility; Example: |
640 | /// @code |
641 | /// template<class T> class A { |
642 | /// public: |
643 | /// typedef int TYPE; |
644 | /// }; |
645 | /// template<class T> class B : public A<T> { |
646 | /// public: |
647 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. |
648 | /// }; |
649 | /// @endcode |
650 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { |
651 | if (CurContext->isRecord()) { |
652 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) |
653 | return true; |
654 | |
655 | const Type *Ty = SS->getScopeRep()->getAsType(); |
656 | |
657 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); |
658 | for (const auto &Base : RD->bases()) |
659 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) |
660 | return true; |
661 | return S->isFunctionPrototypeScope(); |
662 | } |
663 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); |
664 | } |
665 | |
666 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, |
667 | SourceLocation IILoc, |
668 | Scope *S, |
669 | CXXScopeSpec *SS, |
670 | ParsedType &SuggestedType, |
671 | bool IsTemplateName) { |
672 | // Don't report typename errors for editor placeholders. |
673 | if (II->isEditorPlaceholder()) |
674 | return; |
675 | // We don't have anything to suggest (yet). |
676 | SuggestedType = nullptr; |
677 | |
678 | // There may have been a typo in the name of the type. Look up typo |
679 | // results, in case we have something that we can suggest. |
680 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, |
681 | /*AllowTemplates=*/IsTemplateName, |
682 | /*AllowNonTemplates=*/!IsTemplateName); |
683 | if (TypoCorrection Corrected = |
684 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, |
685 | CCC, CTK_ErrorRecovery)) { |
686 | // FIXME: Support error recovery for the template-name case. |
687 | bool CanRecover = !IsTemplateName; |
688 | if (Corrected.isKeyword()) { |
689 | // We corrected to a keyword. |
690 | diagnoseTypo(Corrected, |
691 | PDiag(IsTemplateName ? diag::err_no_template_suggest |
692 | : diag::err_unknown_typename_suggest) |
693 | << II); |
694 | II = Corrected.getCorrectionAsIdentifierInfo(); |
695 | } else { |
696 | // We found a similarly-named type or interface; suggest that. |
697 | if (!SS || !SS->isSet()) { |
698 | diagnoseTypo(Corrected, |
699 | PDiag(IsTemplateName ? diag::err_no_template_suggest |
700 | : diag::err_unknown_typename_suggest) |
701 | << II, CanRecover); |
702 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { |
703 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
704 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
705 | II->getName().equals(CorrectedStr); |
706 | diagnoseTypo(Corrected, |
707 | PDiag(IsTemplateName |
708 | ? diag::err_no_member_template_suggest |
709 | : diag::err_unknown_nested_typename_suggest) |
710 | << II << DC << DroppedSpecifier << SS->getRange(), |
711 | CanRecover); |
712 | } else { |
713 | llvm_unreachable("could not have corrected a typo here")__builtin_unreachable(); |
714 | } |
715 | |
716 | if (!CanRecover) |
717 | return; |
718 | |
719 | CXXScopeSpec tmpSS; |
720 | if (Corrected.getCorrectionSpecifier()) |
721 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), |
722 | SourceRange(IILoc)); |
723 | // FIXME: Support class template argument deduction here. |
724 | SuggestedType = |
725 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, |
726 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, |
727 | /*IsCtorOrDtorName=*/false, |
728 | /*WantNontrivialTypeSourceInfo=*/true); |
729 | } |
730 | return; |
731 | } |
732 | |
733 | if (getLangOpts().CPlusPlus && !IsTemplateName) { |
734 | // See if II is a class template that the user forgot to pass arguments to. |
735 | UnqualifiedId Name; |
736 | Name.setIdentifier(II, IILoc); |
737 | CXXScopeSpec EmptySS; |
738 | TemplateTy TemplateResult; |
739 | bool MemberOfUnknownSpecialization; |
740 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, |
741 | Name, nullptr, true, TemplateResult, |
742 | MemberOfUnknownSpecialization) == TNK_Type_template) { |
743 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); |
744 | return; |
745 | } |
746 | } |
747 | |
748 | // FIXME: Should we move the logic that tries to recover from a missing tag |
749 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? |
750 | |
751 | if (!SS || (!SS->isSet() && !SS->isInvalid())) |
752 | Diag(IILoc, IsTemplateName ? diag::err_no_template |
753 | : diag::err_unknown_typename) |
754 | << II; |
755 | else if (DeclContext *DC = computeDeclContext(*SS, false)) |
756 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template |
757 | : diag::err_typename_nested_not_found) |
758 | << II << DC << SS->getRange(); |
759 | else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { |
760 | SuggestedType = |
761 | ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); |
762 | } else if (isDependentScopeSpecifier(*SS)) { |
763 | unsigned DiagID = diag::err_typename_missing; |
764 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) |
765 | DiagID = diag::ext_typename_missing; |
766 | |
767 | Diag(SS->getRange().getBegin(), DiagID) |
768 | << SS->getScopeRep() << II->getName() |
769 | << SourceRange(SS->getRange().getBegin(), IILoc) |
770 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); |
771 | SuggestedType = ActOnTypenameType(S, SourceLocation(), |
772 | *SS, *II, IILoc).get(); |
773 | } else { |
774 | assert(SS && SS->isInvalid() &&((void)0) |
775 | "Invalid scope specifier has already been diagnosed")((void)0); |
776 | } |
777 | } |
778 | |
779 | /// Determine whether the given result set contains either a type name |
780 | /// or |
781 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { |
782 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && |
783 | NextToken.is(tok::less); |
784 | |
785 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { |
786 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) |
787 | return true; |
788 | |
789 | if (CheckTemplate && isa<TemplateDecl>(*I)) |
790 | return true; |
791 | } |
792 | |
793 | return false; |
794 | } |
795 | |
796 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, |
797 | Scope *S, CXXScopeSpec &SS, |
798 | IdentifierInfo *&Name, |
799 | SourceLocation NameLoc) { |
800 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); |
801 | SemaRef.LookupParsedName(R, S, &SS); |
802 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { |
803 | StringRef FixItTagName; |
804 | switch (Tag->getTagKind()) { |
805 | case TTK_Class: |
806 | FixItTagName = "class "; |
807 | break; |
808 | |
809 | case TTK_Enum: |
810 | FixItTagName = "enum "; |
811 | break; |
812 | |
813 | case TTK_Struct: |
814 | FixItTagName = "struct "; |
815 | break; |
816 | |
817 | case TTK_Interface: |
818 | FixItTagName = "__interface "; |
819 | break; |
820 | |
821 | case TTK_Union: |
822 | FixItTagName = "union "; |
823 | break; |
824 | } |
825 | |
826 | StringRef TagName = FixItTagName.drop_back(); |
827 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) |
828 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus |
829 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); |
830 | |
831 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); |
832 | I != IEnd; ++I) |
833 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) |
834 | << Name << TagName; |
835 | |
836 | // Replace lookup results with just the tag decl. |
837 | Result.clear(Sema::LookupTagName); |
838 | SemaRef.LookupParsedName(Result, S, &SS); |
839 | return true; |
840 | } |
841 | |
842 | return false; |
843 | } |
844 | |
845 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. |
846 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, |
847 | QualType T, SourceLocation NameLoc) { |
848 | ASTContext &Context = S.Context; |
849 | |
850 | TypeLocBuilder Builder; |
851 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); |
852 | |
853 | T = S.getElaboratedType(ETK_None, SS, T); |
854 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); |
855 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
856 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
857 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
858 | } |
859 | |
860 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, |
861 | IdentifierInfo *&Name, |
862 | SourceLocation NameLoc, |
863 | const Token &NextToken, |
864 | CorrectionCandidateCallback *CCC) { |
865 | DeclarationNameInfo NameInfo(Name, NameLoc); |
866 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); |
867 | |
868 | assert(NextToken.isNot(tok::coloncolon) &&((void)0) |
869 | "parse nested name specifiers before calling ClassifyName")((void)0); |
870 | if (getLangOpts().CPlusPlus && SS.isSet() && |
871 | isCurrentClassName(*Name, S, &SS)) { |
872 | // Per [class.qual]p2, this names the constructors of SS, not the |
873 | // injected-class-name. We don't have a classification for that. |
874 | // There's not much point caching this result, since the parser |
875 | // will reject it later. |
876 | return NameClassification::Unknown(); |
877 | } |
878 | |
879 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); |
880 | LookupParsedName(Result, S, &SS, !CurMethod); |
881 | |
882 | if (SS.isInvalid()) |
883 | return NameClassification::Error(); |
884 | |
885 | // For unqualified lookup in a class template in MSVC mode, look into |
886 | // dependent base classes where the primary class template is known. |
887 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { |
888 | if (ParsedType TypeInBase = |
889 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) |
890 | return TypeInBase; |
891 | } |
892 | |
893 | // Perform lookup for Objective-C instance variables (including automatically |
894 | // synthesized instance variables), if we're in an Objective-C method. |
895 | // FIXME: This lookup really, really needs to be folded in to the normal |
896 | // unqualified lookup mechanism. |
897 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { |
898 | DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); |
899 | if (Ivar.isInvalid()) |
900 | return NameClassification::Error(); |
901 | if (Ivar.isUsable()) |
902 | return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); |
903 | |
904 | // We defer builtin creation until after ivar lookup inside ObjC methods. |
905 | if (Result.empty()) |
906 | LookupBuiltin(Result); |
907 | } |
908 | |
909 | bool SecondTry = false; |
910 | bool IsFilteredTemplateName = false; |
911 | |
912 | Corrected: |
913 | switch (Result.getResultKind()) { |
914 | case LookupResult::NotFound: |
915 | // If an unqualified-id is followed by a '(', then we have a function |
916 | // call. |
917 | if (SS.isEmpty() && NextToken.is(tok::l_paren)) { |
918 | // In C++, this is an ADL-only call. |
919 | // FIXME: Reference? |
920 | if (getLangOpts().CPlusPlus) |
921 | return NameClassification::UndeclaredNonType(); |
922 | |
923 | // C90 6.3.2.2: |
924 | // If the expression that precedes the parenthesized argument list in a |
925 | // function call consists solely of an identifier, and if no |
926 | // declaration is visible for this identifier, the identifier is |
927 | // implicitly declared exactly as if, in the innermost block containing |
928 | // the function call, the declaration |
929 | // |
930 | // extern int identifier (); |
931 | // |
932 | // appeared. |
933 | // |
934 | // We also allow this in C99 as an extension. |
935 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) |
936 | return NameClassification::NonType(D); |
937 | } |
938 | |
939 | if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { |
940 | // In C++20 onwards, this could be an ADL-only call to a function |
941 | // template, and we're required to assume that this is a template name. |
942 | // |
943 | // FIXME: Find a way to still do typo correction in this case. |
944 | TemplateName Template = |
945 | Context.getAssumedTemplateName(NameInfo.getName()); |
946 | return NameClassification::UndeclaredTemplate(Template); |
947 | } |
948 | |
949 | // In C, we first see whether there is a tag type by the same name, in |
950 | // which case it's likely that the user just forgot to write "enum", |
951 | // "struct", or "union". |
952 | if (!getLangOpts().CPlusPlus && !SecondTry && |
953 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { |
954 | break; |
955 | } |
956 | |
957 | // Perform typo correction to determine if there is another name that is |
958 | // close to this name. |
959 | if (!SecondTry && CCC) { |
960 | SecondTry = true; |
961 | if (TypoCorrection Corrected = |
962 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, |
963 | &SS, *CCC, CTK_ErrorRecovery)) { |
964 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; |
965 | unsigned QualifiedDiag = diag::err_no_member_suggest; |
966 | |
967 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); |
968 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); |
969 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && |
970 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { |
971 | UnqualifiedDiag = diag::err_no_template_suggest; |
972 | QualifiedDiag = diag::err_no_member_template_suggest; |
973 | } else if (UnderlyingFirstDecl && |
974 | (isa<TypeDecl>(UnderlyingFirstDecl) || |
975 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || |
976 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { |
977 | UnqualifiedDiag = diag::err_unknown_typename_suggest; |
978 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; |
979 | } |
980 | |
981 | if (SS.isEmpty()) { |
982 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); |
983 | } else {// FIXME: is this even reachable? Test it. |
984 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
985 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
986 | Name->getName().equals(CorrectedStr); |
987 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) |
988 | << Name << computeDeclContext(SS, false) |
989 | << DroppedSpecifier << SS.getRange()); |
990 | } |
991 | |
992 | // Update the name, so that the caller has the new name. |
993 | Name = Corrected.getCorrectionAsIdentifierInfo(); |
994 | |
995 | // Typo correction corrected to a keyword. |
996 | if (Corrected.isKeyword()) |
997 | return Name; |
998 | |
999 | // Also update the LookupResult... |
1000 | // FIXME: This should probably go away at some point |
1001 | Result.clear(); |
1002 | Result.setLookupName(Corrected.getCorrection()); |
1003 | if (FirstDecl) |
1004 | Result.addDecl(FirstDecl); |
1005 | |
1006 | // If we found an Objective-C instance variable, let |
1007 | // LookupInObjCMethod build the appropriate expression to |
1008 | // reference the ivar. |
1009 | // FIXME: This is a gross hack. |
1010 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { |
1011 | DeclResult R = |
1012 | LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); |
1013 | if (R.isInvalid()) |
1014 | return NameClassification::Error(); |
1015 | if (R.isUsable()) |
1016 | return NameClassification::NonType(Ivar); |
1017 | } |
1018 | |
1019 | goto Corrected; |
1020 | } |
1021 | } |
1022 | |
1023 | // We failed to correct; just fall through and let the parser deal with it. |
1024 | Result.suppressDiagnostics(); |
1025 | return NameClassification::Unknown(); |
1026 | |
1027 | case LookupResult::NotFoundInCurrentInstantiation: { |
1028 | // We performed name lookup into the current instantiation, and there were |
1029 | // dependent bases, so we treat this result the same way as any other |
1030 | // dependent nested-name-specifier. |
1031 | |
1032 | // C++ [temp.res]p2: |
1033 | // A name used in a template declaration or definition and that is |
1034 | // dependent on a template-parameter is assumed not to name a type |
1035 | // unless the applicable name lookup finds a type name or the name is |
1036 | // qualified by the keyword typename. |
1037 | // |
1038 | // FIXME: If the next token is '<', we might want to ask the parser to |
1039 | // perform some heroics to see if we actually have a |
1040 | // template-argument-list, which would indicate a missing 'template' |
1041 | // keyword here. |
1042 | return NameClassification::DependentNonType(); |
1043 | } |
1044 | |
1045 | case LookupResult::Found: |
1046 | case LookupResult::FoundOverloaded: |
1047 | case LookupResult::FoundUnresolvedValue: |
1048 | break; |
1049 | |
1050 | case LookupResult::Ambiguous: |
1051 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && |
1052 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, |
1053 | /*AllowDependent=*/false)) { |
1054 | // C++ [temp.local]p3: |
1055 | // A lookup that finds an injected-class-name (10.2) can result in an |
1056 | // ambiguity in certain cases (for example, if it is found in more than |
1057 | // one base class). If all of the injected-class-names that are found |
1058 | // refer to specializations of the same class template, and if the name |
1059 | // is followed by a template-argument-list, the reference refers to the |
1060 | // class template itself and not a specialization thereof, and is not |
1061 | // ambiguous. |
1062 | // |
1063 | // This filtering can make an ambiguous result into an unambiguous one, |
1064 | // so try again after filtering out template names. |
1065 | FilterAcceptableTemplateNames(Result); |
1066 | if (!Result.isAmbiguous()) { |
1067 | IsFilteredTemplateName = true; |
1068 | break; |
1069 | } |
1070 | } |
1071 | |
1072 | // Diagnose the ambiguity and return an error. |
1073 | return NameClassification::Error(); |
1074 | } |
1075 | |
1076 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && |
1077 | (IsFilteredTemplateName || |
1078 | hasAnyAcceptableTemplateNames( |
1079 | Result, /*AllowFunctionTemplates=*/true, |
1080 | /*AllowDependent=*/false, |
1081 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && |
1082 | getLangOpts().CPlusPlus20))) { |
1083 | // C++ [temp.names]p3: |
1084 | // After name lookup (3.4) finds that a name is a template-name or that |
1085 | // an operator-function-id or a literal- operator-id refers to a set of |
1086 | // overloaded functions any member of which is a function template if |
1087 | // this is followed by a <, the < is always taken as the delimiter of a |
1088 | // template-argument-list and never as the less-than operator. |
1089 | // C++2a [temp.names]p2: |
1090 | // A name is also considered to refer to a template if it is an |
1091 | // unqualified-id followed by a < and name lookup finds either one |
1092 | // or more functions or finds nothing. |
1093 | if (!IsFilteredTemplateName) |
1094 | FilterAcceptableTemplateNames(Result); |
1095 | |
1096 | bool IsFunctionTemplate; |
1097 | bool IsVarTemplate; |
1098 | TemplateName Template; |
1099 | if (Result.end() - Result.begin() > 1) { |
1100 | IsFunctionTemplate = true; |
1101 | Template = Context.getOverloadedTemplateName(Result.begin(), |
1102 | Result.end()); |
1103 | } else if (!Result.empty()) { |
1104 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( |
1105 | *Result.begin(), /*AllowFunctionTemplates=*/true, |
1106 | /*AllowDependent=*/false)); |
1107 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); |
1108 | IsVarTemplate = isa<VarTemplateDecl>(TD); |
1109 | |
1110 | if (SS.isNotEmpty()) |
1111 | Template = |
1112 | Context.getQualifiedTemplateName(SS.getScopeRep(), |
1113 | /*TemplateKeyword=*/false, TD); |
1114 | else |
1115 | Template = TemplateName(TD); |
1116 | } else { |
1117 | // All results were non-template functions. This is a function template |
1118 | // name. |
1119 | IsFunctionTemplate = true; |
1120 | Template = Context.getAssumedTemplateName(NameInfo.getName()); |
1121 | } |
1122 | |
1123 | if (IsFunctionTemplate) { |
1124 | // Function templates always go through overload resolution, at which |
1125 | // point we'll perform the various checks (e.g., accessibility) we need |
1126 | // to based on which function we selected. |
1127 | Result.suppressDiagnostics(); |
1128 | |
1129 | return NameClassification::FunctionTemplate(Template); |
1130 | } |
1131 | |
1132 | return IsVarTemplate ? NameClassification::VarTemplate(Template) |
1133 | : NameClassification::TypeTemplate(Template); |
1134 | } |
1135 | |
1136 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); |
1137 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { |
1138 | DiagnoseUseOfDecl(Type, NameLoc); |
1139 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); |
1140 | QualType T = Context.getTypeDeclType(Type); |
1141 | if (SS.isNotEmpty()) |
1142 | return buildNestedType(*this, SS, T, NameLoc); |
1143 | return ParsedType::make(T); |
1144 | } |
1145 | |
1146 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); |
1147 | if (!Class) { |
1148 | // FIXME: It's unfortunate that we don't have a Type node for handling this. |
1149 | if (ObjCCompatibleAliasDecl *Alias = |
1150 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) |
1151 | Class = Alias->getClassInterface(); |
1152 | } |
1153 | |
1154 | if (Class) { |
1155 | DiagnoseUseOfDecl(Class, NameLoc); |
1156 | |
1157 | if (NextToken.is(tok::period)) { |
1158 | // Interface. <something> is parsed as a property reference expression. |
1159 | // Just return "unknown" as a fall-through for now. |
1160 | Result.suppressDiagnostics(); |
1161 | return NameClassification::Unknown(); |
1162 | } |
1163 | |
1164 | QualType T = Context.getObjCInterfaceType(Class); |
1165 | return ParsedType::make(T); |
1166 | } |
1167 | |
1168 | if (isa<ConceptDecl>(FirstDecl)) |
1169 | return NameClassification::Concept( |
1170 | TemplateName(cast<TemplateDecl>(FirstDecl))); |
1171 | |
1172 | if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { |
1173 | (void)DiagnoseUseOfDecl(EmptyD, NameLoc); |
1174 | return NameClassification::Error(); |
1175 | } |
1176 | |
1177 | // We can have a type template here if we're classifying a template argument. |
1178 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && |
1179 | !isa<VarTemplateDecl>(FirstDecl)) |
1180 | return NameClassification::TypeTemplate( |
1181 | TemplateName(cast<TemplateDecl>(FirstDecl))); |
1182 | |
1183 | // Check for a tag type hidden by a non-type decl in a few cases where it |
1184 | // seems likely a type is wanted instead of the non-type that was found. |
1185 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); |
1186 | if ((NextToken.is(tok::identifier) || |
1187 | (NextIsOp && |
1188 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && |
1189 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { |
1190 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); |
1191 | DiagnoseUseOfDecl(Type, NameLoc); |
1192 | QualType T = Context.getTypeDeclType(Type); |
1193 | if (SS.isNotEmpty()) |
1194 | return buildNestedType(*this, SS, T, NameLoc); |
1195 | return ParsedType::make(T); |
1196 | } |
1197 | |
1198 | // If we already know which single declaration is referenced, just annotate |
1199 | // that declaration directly. Defer resolving even non-overloaded class |
1200 | // member accesses, as we need to defer certain access checks until we know |
1201 | // the context. |
1202 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); |
1203 | if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) |
1204 | return NameClassification::NonType(Result.getRepresentativeDecl()); |
1205 | |
1206 | // Otherwise, this is an overload set that we will need to resolve later. |
1207 | Result.suppressDiagnostics(); |
1208 | return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( |
1209 | Context, Result.getNamingClass(), SS.getWithLocInContext(Context), |
1210 | Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), |
1211 | Result.begin(), Result.end())); |
1212 | } |
1213 | |
1214 | ExprResult |
1215 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, |
1216 | SourceLocation NameLoc) { |
1217 | assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((void)0); |
1218 | CXXScopeSpec SS; |
1219 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); |
1220 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); |
1221 | } |
1222 | |
1223 | ExprResult |
1224 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, |
1225 | IdentifierInfo *Name, |
1226 | SourceLocation NameLoc, |
1227 | bool IsAddressOfOperand) { |
1228 | DeclarationNameInfo NameInfo(Name, NameLoc); |
1229 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), |
1230 | NameInfo, IsAddressOfOperand, |
1231 | /*TemplateArgs=*/nullptr); |
1232 | } |
1233 | |
1234 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, |
1235 | NamedDecl *Found, |
1236 | SourceLocation NameLoc, |
1237 | const Token &NextToken) { |
1238 | if (getCurMethodDecl() && SS.isEmpty()) |
1239 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) |
1240 | return BuildIvarRefExpr(S, NameLoc, Ivar); |
1241 | |
1242 | // Reconstruct the lookup result. |
1243 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); |
1244 | Result.addDecl(Found); |
1245 | Result.resolveKind(); |
1246 | |
1247 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); |
1248 | return BuildDeclarationNameExpr(SS, Result, ADL); |
1249 | } |
1250 | |
1251 | ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { |
1252 | // For an implicit class member access, transform the result into a member |
1253 | // access expression if necessary. |
1254 | auto *ULE = cast<UnresolvedLookupExpr>(E); |
1255 | if ((*ULE->decls_begin())->isCXXClassMember()) { |
1256 | CXXScopeSpec SS; |
1257 | SS.Adopt(ULE->getQualifierLoc()); |
1258 | |
1259 | // Reconstruct the lookup result. |
1260 | LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), |
1261 | LookupOrdinaryName); |
1262 | Result.setNamingClass(ULE->getNamingClass()); |
1263 | for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) |
1264 | Result.addDecl(*I, I.getAccess()); |
1265 | Result.resolveKind(); |
1266 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, |
1267 | nullptr, S); |
1268 | } |
1269 | |
1270 | // Otherwise, this is already in the form we needed, and no further checks |
1271 | // are necessary. |
1272 | return ULE; |
1273 | } |
1274 | |
1275 | Sema::TemplateNameKindForDiagnostics |
1276 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { |
1277 | auto *TD = Name.getAsTemplateDecl(); |
1278 | if (!TD) |
1279 | return TemplateNameKindForDiagnostics::DependentTemplate; |
1280 | if (isa<ClassTemplateDecl>(TD)) |
1281 | return TemplateNameKindForDiagnostics::ClassTemplate; |
1282 | if (isa<FunctionTemplateDecl>(TD)) |
1283 | return TemplateNameKindForDiagnostics::FunctionTemplate; |
1284 | if (isa<VarTemplateDecl>(TD)) |
1285 | return TemplateNameKindForDiagnostics::VarTemplate; |
1286 | if (isa<TypeAliasTemplateDecl>(TD)) |
1287 | return TemplateNameKindForDiagnostics::AliasTemplate; |
1288 | if (isa<TemplateTemplateParmDecl>(TD)) |
1289 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; |
1290 | if (isa<ConceptDecl>(TD)) |
1291 | return TemplateNameKindForDiagnostics::Concept; |
1292 | return TemplateNameKindForDiagnostics::DependentTemplate; |
1293 | } |
1294 | |
1295 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { |
1296 | assert(DC->getLexicalParent() == CurContext &&((void)0) |
1297 | "The next DeclContext should be lexically contained in the current one.")((void)0); |
1298 | CurContext = DC; |
1299 | S->setEntity(DC); |
1300 | } |
1301 | |
1302 | void Sema::PopDeclContext() { |
1303 | assert(CurContext && "DeclContext imbalance!")((void)0); |
1304 | |
1305 | CurContext = CurContext->getLexicalParent(); |
1306 | assert(CurContext && "Popped translation unit!")((void)0); |
1307 | } |
1308 | |
1309 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, |
1310 | Decl *D) { |
1311 | // Unlike PushDeclContext, the context to which we return is not necessarily |
1312 | // the containing DC of TD, because the new context will be some pre-existing |
1313 | // TagDecl definition instead of a fresh one. |
1314 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); |
1315 | CurContext = cast<TagDecl>(D)->getDefinition(); |
1316 | assert(CurContext && "skipping definition of undefined tag")((void)0); |
1317 | // Start lookups from the parent of the current context; we don't want to look |
1318 | // into the pre-existing complete definition. |
1319 | S->setEntity(CurContext->getLookupParent()); |
1320 | return Result; |
1321 | } |
1322 | |
1323 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { |
1324 | CurContext = static_cast<decltype(CurContext)>(Context); |
1325 | } |
1326 | |
1327 | /// EnterDeclaratorContext - Used when we must lookup names in the context |
1328 | /// of a declarator's nested name specifier. |
1329 | /// |
1330 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { |
1331 | // C++0x [basic.lookup.unqual]p13: |
1332 | // A name used in the definition of a static data member of class |
1333 | // X (after the qualified-id of the static member) is looked up as |
1334 | // if the name was used in a member function of X. |
1335 | // C++0x [basic.lookup.unqual]p14: |
1336 | // If a variable member of a namespace is defined outside of the |
1337 | // scope of its namespace then any name used in the definition of |
1338 | // the variable member (after the declarator-id) is looked up as |
1339 | // if the definition of the variable member occurred in its |
1340 | // namespace. |
1341 | // Both of these imply that we should push a scope whose context |
1342 | // is the semantic context of the declaration. We can't use |
1343 | // PushDeclContext here because that context is not necessarily |
1344 | // lexically contained in the current context. Fortunately, |
1345 | // the containing scope should have the appropriate information. |
1346 | |
1347 | assert(!S->getEntity() && "scope already has entity")((void)0); |
1348 | |
1349 | #ifndef NDEBUG1 |
1350 | Scope *Ancestor = S->getParent(); |
1351 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); |
1352 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((void)0); |
1353 | #endif |
1354 | |
1355 | CurContext = DC; |
1356 | S->setEntity(DC); |
1357 | |
1358 | if (S->getParent()->isTemplateParamScope()) { |
1359 | // Also set the corresponding entities for all immediately-enclosing |
1360 | // template parameter scopes. |
1361 | EnterTemplatedContext(S->getParent(), DC); |
1362 | } |
1363 | } |
1364 | |
1365 | void Sema::ExitDeclaratorContext(Scope *S) { |
1366 | assert(S->getEntity() == CurContext && "Context imbalance!")((void)0); |
1367 | |
1368 | // Switch back to the lexical context. The safety of this is |
1369 | // enforced by an assert in EnterDeclaratorContext. |
1370 | Scope *Ancestor = S->getParent(); |
1371 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); |
1372 | CurContext = Ancestor->getEntity(); |
1373 | |
1374 | // We don't need to do anything with the scope, which is going to |
1375 | // disappear. |
1376 | } |
1377 | |
1378 | void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { |
1379 | assert(S->isTemplateParamScope() &&((void)0) |
1380 | "expected to be initializing a template parameter scope")((void)0); |
1381 | |
1382 | // C++20 [temp.local]p7: |
1383 | // In the definition of a member of a class template that appears outside |
1384 | // of the class template definition, the name of a member of the class |
1385 | // template hides the name of a template-parameter of any enclosing class |
1386 | // templates (but not a template-parameter of the member if the member is a |
1387 | // class or function template). |
1388 | // C++20 [temp.local]p9: |
1389 | // In the definition of a class template or in the definition of a member |
1390 | // of such a template that appears outside of the template definition, for |
1391 | // each non-dependent base class (13.8.2.1), if the name of the base class |
1392 | // or the name of a member of the base class is the same as the name of a |
1393 | // template-parameter, the base class name or member name hides the |
1394 | // template-parameter name (6.4.10). |
1395 | // |
1396 | // This means that a template parameter scope should be searched immediately |
1397 | // after searching the DeclContext for which it is a template parameter |
1398 | // scope. For example, for |
1399 | // template<typename T> template<typename U> template<typename V> |
1400 | // void N::A<T>::B<U>::f(...) |
1401 | // we search V then B<U> (and base classes) then U then A<T> (and base |
1402 | // classes) then T then N then ::. |
1403 | unsigned ScopeDepth = getTemplateDepth(S); |
1404 | for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { |
1405 | DeclContext *SearchDCAfterScope = DC; |
1406 | for (; DC; DC = DC->getLookupParent()) { |
1407 | if (const TemplateParameterList *TPL = |
1408 | cast<Decl>(DC)->getDescribedTemplateParams()) { |
1409 | unsigned DCDepth = TPL->getDepth() + 1; |
1410 | if (DCDepth > ScopeDepth) |
1411 | continue; |
1412 | if (ScopeDepth == DCDepth) |
1413 | SearchDCAfterScope = DC = DC->getLookupParent(); |
1414 | break; |
1415 | } |
1416 | } |
1417 | S->setLookupEntity(SearchDCAfterScope); |
1418 | } |
1419 | } |
1420 | |
1421 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { |
1422 | // We assume that the caller has already called |
1423 | // ActOnReenterTemplateScope so getTemplatedDecl() works. |
1424 | FunctionDecl *FD = D->getAsFunction(); |
1425 | if (!FD) |
1426 | return; |
1427 | |
1428 | // Same implementation as PushDeclContext, but enters the context |
1429 | // from the lexical parent, rather than the top-level class. |
1430 | assert(CurContext == FD->getLexicalParent() &&((void)0) |
1431 | "The next DeclContext should be lexically contained in the current one.")((void)0); |
1432 | CurContext = FD; |
1433 | S->setEntity(CurContext); |
1434 | |
1435 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { |
1436 | ParmVarDecl *Param = FD->getParamDecl(P); |
1437 | // If the parameter has an identifier, then add it to the scope |
1438 | if (Param->getIdentifier()) { |
1439 | S->AddDecl(Param); |
1440 | IdResolver.AddDecl(Param); |
1441 | } |
1442 | } |
1443 | } |
1444 | |
1445 | void Sema::ActOnExitFunctionContext() { |
1446 | // Same implementation as PopDeclContext, but returns to the lexical parent, |
1447 | // rather than the top-level class. |
1448 | assert(CurContext && "DeclContext imbalance!")((void)0); |
1449 | CurContext = CurContext->getLexicalParent(); |
1450 | assert(CurContext && "Popped translation unit!")((void)0); |
1451 | } |
1452 | |
1453 | /// Determine whether we allow overloading of the function |
1454 | /// PrevDecl with another declaration. |
1455 | /// |
1456 | /// This routine determines whether overloading is possible, not |
1457 | /// whether some new function is actually an overload. It will return |
1458 | /// true in C++ (where we can always provide overloads) or, as an |
1459 | /// extension, in C when the previous function is already an |
1460 | /// overloaded function declaration or has the "overloadable" |
1461 | /// attribute. |
1462 | static bool AllowOverloadingOfFunction(LookupResult &Previous, |
1463 | ASTContext &Context, |
1464 | const FunctionDecl *New) { |
1465 | if (Context.getLangOpts().CPlusPlus) |
1466 | return true; |
1467 | |
1468 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) |
1469 | return true; |
1470 | |
1471 | return Previous.getResultKind() == LookupResult::Found && |
1472 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || |
1473 | New->hasAttr<OverloadableAttr>()); |
1474 | } |
1475 | |
1476 | /// Add this decl to the scope shadowed decl chains. |
1477 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { |
1478 | // Move up the scope chain until we find the nearest enclosing |
1479 | // non-transparent context. The declaration will be introduced into this |
1480 | // scope. |
1481 | while (S->getEntity() && S->getEntity()->isTransparentContext()) |
1482 | S = S->getParent(); |
1483 | |
1484 | // Add scoped declarations into their context, so that they can be |
1485 | // found later. Declarations without a context won't be inserted |
1486 | // into any context. |
1487 | if (AddToContext) |
1488 | CurContext->addDecl(D); |
1489 | |
1490 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they |
1491 | // are function-local declarations. |
1492 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) |
1493 | return; |
1494 | |
1495 | // Template instantiations should also not be pushed into scope. |
1496 | if (isa<FunctionDecl>(D) && |
1497 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) |
1498 | return; |
1499 | |
1500 | // If this replaces anything in the current scope, |
1501 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), |
1502 | IEnd = IdResolver.end(); |
1503 | for (; I != IEnd; ++I) { |
1504 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { |
1505 | S->RemoveDecl(*I); |
1506 | IdResolver.RemoveDecl(*I); |
1507 | |
1508 | // Should only need to replace one decl. |
1509 | break; |
1510 | } |
1511 | } |
1512 | |
1513 | S->AddDecl(D); |
1514 | |
1515 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { |
1516 | // Implicitly-generated labels may end up getting generated in an order that |
1517 | // isn't strictly lexical, which breaks name lookup. Be careful to insert |
1518 | // the label at the appropriate place in the identifier chain. |
1519 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { |
1520 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); |
1521 | if (IDC == CurContext) { |
1522 | if (!S->isDeclScope(*I)) |
1523 | continue; |
1524 | } else if (IDC->Encloses(CurContext)) |
1525 | break; |
1526 | } |
1527 | |
1528 | IdResolver.InsertDeclAfter(I, D); |
1529 | } else { |
1530 | IdResolver.AddDecl(D); |
1531 | } |
1532 | warnOnReservedIdentifier(D); |
1533 | } |
1534 | |
1535 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, |
1536 | bool AllowInlineNamespace) { |
1537 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); |
1538 | } |
1539 | |
1540 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { |
1541 | DeclContext *TargetDC = DC->getPrimaryContext(); |
1542 | do { |
1543 | if (DeclContext *ScopeDC = S->getEntity()) |
1544 | if (ScopeDC->getPrimaryContext() == TargetDC) |
1545 | return S; |
1546 | } while ((S = S->getParent())); |
1547 | |
1548 | return nullptr; |
1549 | } |
1550 | |
1551 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, |
1552 | DeclContext*, |
1553 | ASTContext&); |
1554 | |
1555 | /// Filters out lookup results that don't fall within the given scope |
1556 | /// as determined by isDeclInScope. |
1557 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, |
1558 | bool ConsiderLinkage, |
1559 | bool AllowInlineNamespace) { |
1560 | LookupResult::Filter F = R.makeFilter(); |
1561 | while (F.hasNext()) { |
1562 | NamedDecl *D = F.next(); |
1563 | |
1564 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) |
1565 | continue; |
1566 | |
1567 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) |
1568 | continue; |
1569 | |
1570 | F.erase(); |
1571 | } |
1572 | |
1573 | F.done(); |
1574 | } |
1575 | |
1576 | /// We've determined that \p New is a redeclaration of \p Old. Check that they |
1577 | /// have compatible owning modules. |
1578 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { |
1579 | // FIXME: The Modules TS is not clear about how friend declarations are |
1580 | // to be treated. It's not meaningful to have different owning modules for |
1581 | // linkage in redeclarations of the same entity, so for now allow the |
1582 | // redeclaration and change the owning modules to match. |
1583 | if (New->getFriendObjectKind() && |
1584 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { |
1585 | New->setLocalOwningModule(Old->getOwningModule()); |
1586 | makeMergedDefinitionVisible(New); |
1587 | return false; |
1588 | } |
1589 | |
1590 | Module *NewM = New->getOwningModule(); |
1591 | Module *OldM = Old->getOwningModule(); |
1592 | |
1593 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) |
1594 | NewM = NewM->Parent; |
1595 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) |
1596 | OldM = OldM->Parent; |
1597 | |
1598 | if (NewM == OldM) |
1599 | return false; |
1600 | |
1601 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); |
1602 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); |
1603 | if (NewIsModuleInterface || OldIsModuleInterface) { |
1604 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: |
1605 | // if a declaration of D [...] appears in the purview of a module, all |
1606 | // other such declarations shall appear in the purview of the same module |
1607 | Diag(New->getLocation(), diag::err_mismatched_owning_module) |
1608 | << New |
1609 | << NewIsModuleInterface |
1610 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") |
1611 | << OldIsModuleInterface |
1612 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); |
1613 | Diag(Old->getLocation(), diag::note_previous_declaration); |
1614 | New->setInvalidDecl(); |
1615 | return true; |
1616 | } |
1617 | |
1618 | return false; |
1619 | } |
1620 | |
1621 | static bool isUsingDecl(NamedDecl *D) { |
1622 | return isa<UsingShadowDecl>(D) || |
1623 | isa<UnresolvedUsingTypenameDecl>(D) || |
1624 | isa<UnresolvedUsingValueDecl>(D); |
1625 | } |
1626 | |
1627 | /// Removes using shadow declarations from the lookup results. |
1628 | static void RemoveUsingDecls(LookupResult &R) { |
1629 | LookupResult::Filter F = R.makeFilter(); |
1630 | while (F.hasNext()) |
1631 | if (isUsingDecl(F.next())) |
1632 | F.erase(); |
1633 | |
1634 | F.done(); |
1635 | } |
1636 | |
1637 | /// Check for this common pattern: |
1638 | /// @code |
1639 | /// class S { |
1640 | /// S(const S&); // DO NOT IMPLEMENT |
1641 | /// void operator=(const S&); // DO NOT IMPLEMENT |
1642 | /// }; |
1643 | /// @endcode |
1644 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { |
1645 | // FIXME: Should check for private access too but access is set after we get |
1646 | // the decl here. |
1647 | if (D->doesThisDeclarationHaveABody()) |
1648 | return false; |
1649 | |
1650 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) |
1651 | return CD->isCopyConstructor(); |
1652 | return D->isCopyAssignmentOperator(); |
1653 | } |
1654 | |
1655 | // We need this to handle |
1656 | // |
1657 | // typedef struct { |
1658 | // void *foo() { return 0; } |
1659 | // } A; |
1660 | // |
1661 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' |
1662 | // for example. If 'A', foo will have external linkage. If we have '*A', |
1663 | // foo will have no linkage. Since we can't know until we get to the end |
1664 | // of the typedef, this function finds out if D might have non-external linkage. |
1665 | // Callers should verify at the end of the TU if it D has external linkage or |
1666 | // not. |
1667 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { |
1668 | const DeclContext *DC = D->getDeclContext(); |
1669 | while (!DC->isTranslationUnit()) { |
1670 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ |
1671 | if (!RD->hasNameForLinkage()) |
1672 | return true; |
1673 | } |
1674 | DC = DC->getParent(); |
1675 | } |
1676 | |
1677 | return !D->isExternallyVisible(); |
1678 | } |
1679 | |
1680 | // FIXME: This needs to be refactored; some other isInMainFile users want |
1681 | // these semantics. |
1682 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { |
1683 | if (S.TUKind != TU_Complete) |
1684 | return false; |
1685 | return S.SourceMgr.isInMainFile(Loc); |
1686 | } |
1687 | |
1688 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { |
1689 | assert(D)((void)0); |
1690 | |
1691 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) |
1692 | return false; |
1693 | |
1694 | // Ignore all entities declared within templates, and out-of-line definitions |
1695 | // of members of class templates. |
1696 | if (D->getDeclContext()->isDependentContext() || |
1697 | D->getLexicalDeclContext()->isDependentContext()) |
1698 | return false; |
1699 | |
1700 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
1701 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
1702 | return false; |
1703 | // A non-out-of-line declaration of a member specialization was implicitly |
1704 | // instantiated; it's the out-of-line declaration that we're interested in. |
1705 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
1706 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) |
1707 | return false; |
1708 | |
1709 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { |
1710 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) |
1711 | return false; |
1712 | } else { |
1713 | // 'static inline' functions are defined in headers; don't warn. |
1714 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) |
1715 | return false; |
1716 | } |
1717 | |
1718 | if (FD->doesThisDeclarationHaveABody() && |
1719 | Context.DeclMustBeEmitted(FD)) |
1720 | return false; |
1721 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1722 | // Constants and utility variables are defined in headers with internal |
1723 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker |
1724 | // like "inline".) |
1725 | if (!isMainFileLoc(*this, VD->getLocation())) |
1726 | return false; |
1727 | |
1728 | if (Context.DeclMustBeEmitted(VD)) |
1729 | return false; |
1730 | |
1731 | if (VD->isStaticDataMember() && |
1732 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
1733 | return false; |
1734 | if (VD->isStaticDataMember() && |
1735 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
1736 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) |
1737 | return false; |
1738 | |
1739 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) |
1740 | return false; |
1741 | } else { |
1742 | return false; |
1743 | } |
1744 | |
1745 | // Only warn for unused decls internal to the translation unit. |
1746 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function |
1747 | // for inline functions defined in the main source file, for instance. |
1748 | return mightHaveNonExternalLinkage(D); |
1749 | } |
1750 | |
1751 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { |
1752 | if (!D) |
1753 | return; |
1754 | |
1755 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
1756 | const FunctionDecl *First = FD->getFirstDecl(); |
1757 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) |
1758 | return; // First should already be in the vector. |
1759 | } |
1760 | |
1761 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1762 | const VarDecl *First = VD->getFirstDecl(); |
1763 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) |
1764 | return; // First should already be in the vector. |
1765 | } |
1766 | |
1767 | if (ShouldWarnIfUnusedFileScopedDecl(D)) |
1768 | UnusedFileScopedDecls.push_back(D); |
1769 | } |
1770 | |
1771 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { |
1772 | if (D->isInvalidDecl()) |
1773 | return false; |
1774 | |
1775 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { |
1776 | // For a decomposition declaration, warn if none of the bindings are |
1777 | // referenced, instead of if the variable itself is referenced (which |
1778 | // it is, by the bindings' expressions). |
1779 | for (auto *BD : DD->bindings()) |
1780 | if (BD->isReferenced()) |
1781 | return false; |
1782 | } else if (!D->getDeclName()) { |
1783 | return false; |
1784 | } else if (D->isReferenced() || D->isUsed()) { |
1785 | return false; |
1786 | } |
1787 | |
1788 | if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) |
1789 | return false; |
1790 | |
1791 | if (isa<LabelDecl>(D)) |
1792 | return true; |
1793 | |
1794 | // Except for labels, we only care about unused decls that are local to |
1795 | // functions. |
1796 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); |
1797 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) |
1798 | // For dependent types, the diagnostic is deferred. |
1799 | WithinFunction = |
1800 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); |
1801 | if (!WithinFunction) |
1802 | return false; |
1803 | |
1804 | if (isa<TypedefNameDecl>(D)) |
1805 | return true; |
1806 | |
1807 | // White-list anything that isn't a local variable. |
1808 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) |
1809 | return false; |
1810 | |
1811 | // Types of valid local variables should be complete, so this should succeed. |
1812 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1813 | |
1814 | // White-list anything with an __attribute__((unused)) type. |
1815 | const auto *Ty = VD->getType().getTypePtr(); |
1816 | |
1817 | // Only look at the outermost level of typedef. |
1818 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { |
1819 | if (TT->getDecl()->hasAttr<UnusedAttr>()) |
1820 | return false; |
1821 | } |
1822 | |
1823 | // If we failed to complete the type for some reason, or if the type is |
1824 | // dependent, don't diagnose the variable. |
1825 | if (Ty->isIncompleteType() || Ty->isDependentType()) |
1826 | return false; |
1827 | |
1828 | // Look at the element type to ensure that the warning behaviour is |
1829 | // consistent for both scalars and arrays. |
1830 | Ty = Ty->getBaseElementTypeUnsafe(); |
1831 | |
1832 | if (const TagType *TT = Ty->getAs<TagType>()) { |
1833 | const TagDecl *Tag = TT->getDecl(); |
1834 | if (Tag->hasAttr<UnusedAttr>()) |
1835 | return false; |
1836 | |
1837 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { |
1838 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) |
1839 | return false; |
1840 | |
1841 | if (const Expr *Init = VD->getInit()) { |
1842 | if (const ExprWithCleanups *Cleanups = |
1843 | dyn_cast<ExprWithCleanups>(Init)) |
1844 | Init = Cleanups->getSubExpr(); |
1845 | const CXXConstructExpr *Construct = |
1846 | dyn_cast<CXXConstructExpr>(Init); |
1847 | if (Construct && !Construct->isElidable()) { |
1848 | CXXConstructorDecl *CD = Construct->getConstructor(); |
1849 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && |
1850 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) |
1851 | return false; |
1852 | } |
1853 | |
1854 | // Suppress the warning if we don't know how this is constructed, and |
1855 | // it could possibly be non-trivial constructor. |
1856 | if (Init->isTypeDependent()) |
1857 | for (const CXXConstructorDecl *Ctor : RD->ctors()) |
1858 | if (!Ctor->isTrivial()) |
1859 | return false; |
1860 | } |
1861 | } |
1862 | } |
1863 | |
1864 | // TODO: __attribute__((unused)) templates? |
1865 | } |
1866 | |
1867 | return true; |
1868 | } |
1869 | |
1870 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, |
1871 | FixItHint &Hint) { |
1872 | if (isa<LabelDecl>(D)) { |
1873 | SourceLocation AfterColon = Lexer::findLocationAfterToken( |
1874 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), |
1875 | true); |
1876 | if (AfterColon.isInvalid()) |
1877 | return; |
1878 | Hint = FixItHint::CreateRemoval( |
1879 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); |
1880 | } |
1881 | } |
1882 | |
1883 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { |
1884 | if (D->getTypeForDecl()->isDependentType()) |
1885 | return; |
1886 | |
1887 | for (auto *TmpD : D->decls()) { |
1888 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) |
1889 | DiagnoseUnusedDecl(T); |
1890 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) |
1891 | DiagnoseUnusedNestedTypedefs(R); |
1892 | } |
1893 | } |
1894 | |
1895 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used |
1896 | /// unless they are marked attr(unused). |
1897 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { |
1898 | if (!ShouldDiagnoseUnusedDecl(D)) |
1899 | return; |
1900 | |
1901 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { |
1902 | // typedefs can be referenced later on, so the diagnostics are emitted |
1903 | // at end-of-translation-unit. |
1904 | UnusedLocalTypedefNameCandidates.insert(TD); |
1905 | return; |
1906 | } |
1907 | |
1908 | FixItHint Hint; |
1909 | GenerateFixForUnusedDecl(D, Context, Hint); |
1910 | |
1911 | unsigned DiagID; |
1912 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) |
1913 | DiagID = diag::warn_unused_exception_param; |
1914 | else if (isa<LabelDecl>(D)) |
1915 | DiagID = diag::warn_unused_label; |
1916 | else |
1917 | DiagID = diag::warn_unused_variable; |
1918 | |
1919 | Diag(D->getLocation(), DiagID) << D << Hint; |
1920 | } |
1921 | |
1922 | void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { |
1923 | // If it's not referenced, it can't be set. |
1924 | if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>()) |
1925 | return; |
1926 | |
1927 | const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); |
1928 | |
1929 | if (Ty->isReferenceType() || Ty->isDependentType()) |
1930 | return; |
1931 | |
1932 | if (const TagType *TT = Ty->getAs<TagType>()) { |
1933 | const TagDecl *Tag = TT->getDecl(); |
1934 | if (Tag->hasAttr<UnusedAttr>()) |
1935 | return; |
1936 | // In C++, don't warn for record types that don't have WarnUnusedAttr, to |
1937 | // mimic gcc's behavior. |
1938 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { |
1939 | if (!RD->hasAttr<WarnUnusedAttr>()) |
1940 | return; |
1941 | } |
1942 | } |
1943 | |
1944 | auto iter = RefsMinusAssignments.find(VD); |
1945 | if (iter == RefsMinusAssignments.end()) |
1946 | return; |
1947 | |
1948 | assert(iter->getSecond() >= 0 &&((void)0) |
1949 | "Found a negative number of references to a VarDecl")((void)0); |
1950 | if (iter->getSecond() != 0) |
1951 | return; |
1952 | unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter |
1953 | : diag::warn_unused_but_set_variable; |
1954 | Diag(VD->getLocation(), DiagID) << VD; |
1955 | } |
1956 | |
1957 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { |
1958 | // Verify that we have no forward references left. If so, there was a goto |
1959 | // or address of a label taken, but no definition of it. Label fwd |
1960 | // definitions are indicated with a null substmt which is also not a resolved |
1961 | // MS inline assembly label name. |
1962 | bool Diagnose = false; |
1963 | if (L->isMSAsmLabel()) |
1964 | Diagnose = !L->isResolvedMSAsmLabel(); |
1965 | else |
1966 | Diagnose = L->getStmt() == nullptr; |
1967 | if (Diagnose) |
1968 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; |
1969 | } |
1970 | |
1971 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { |
1972 | S->mergeNRVOIntoParent(); |
1973 | |
1974 | if (S->decl_empty()) return; |
1975 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&((void)0) |
1976 | "Scope shouldn't contain decls!")((void)0); |
1977 | |
1978 | for (auto *TmpD : S->decls()) { |
1979 | assert(TmpD && "This decl didn't get pushed??")((void)0); |
1980 | |
1981 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((void)0); |
1982 | NamedDecl *D = cast<NamedDecl>(TmpD); |
1983 | |
1984 | // Diagnose unused variables in this scope. |
1985 | if (!S->hasUnrecoverableErrorOccurred()) { |
1986 | DiagnoseUnusedDecl(D); |
1987 | if (const auto *RD = dyn_cast<RecordDecl>(D)) |
1988 | DiagnoseUnusedNestedTypedefs(RD); |
1989 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1990 | DiagnoseUnusedButSetDecl(VD); |
1991 | RefsMinusAssignments.erase(VD); |
1992 | } |
1993 | } |
1994 | |
1995 | if (!D->getDeclName()) continue; |
1996 | |
1997 | // If this was a forward reference to a label, verify it was defined. |
1998 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) |
1999 | CheckPoppedLabel(LD, *this); |
2000 | |
2001 | // Remove this name from our lexical scope, and warn on it if we haven't |
2002 | // already. |
2003 | IdResolver.RemoveDecl(D); |
2004 | auto ShadowI = ShadowingDecls.find(D); |
2005 | if (ShadowI != ShadowingDecls.end()) { |
2006 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { |
2007 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) |
2008 | << D << FD << FD->getParent(); |
2009 | Diag(FD->getLocation(), diag::note_previous_declaration); |
2010 | } |
2011 | ShadowingDecls.erase(ShadowI); |
2012 | } |
2013 | } |
2014 | } |
2015 | |
2016 | /// Look for an Objective-C class in the translation unit. |
2017 | /// |
2018 | /// \param Id The name of the Objective-C class we're looking for. If |
2019 | /// typo-correction fixes this name, the Id will be updated |
2020 | /// to the fixed name. |
2021 | /// |
2022 | /// \param IdLoc The location of the name in the translation unit. |
2023 | /// |
2024 | /// \param DoTypoCorrection If true, this routine will attempt typo correction |
2025 | /// if there is no class with the given name. |
2026 | /// |
2027 | /// \returns The declaration of the named Objective-C class, or NULL if the |
2028 | /// class could not be found. |
2029 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, |
2030 | SourceLocation IdLoc, |
2031 | bool DoTypoCorrection) { |
2032 | // The third "scope" argument is 0 since we aren't enabling lazy built-in |
2033 | // creation from this context. |
2034 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); |
2035 | |
2036 | if (!IDecl && DoTypoCorrection) { |
2037 | // Perform typo correction at the given location, but only if we |
2038 | // find an Objective-C class name. |
2039 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; |
2040 | if (TypoCorrection C = |
2041 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, |
2042 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { |
2043 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); |
2044 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); |
2045 | Id = IDecl->getIdentifier(); |
2046 | } |
2047 | } |
2048 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); |
2049 | // This routine must always return a class definition, if any. |
2050 | if (Def && Def->getDefinition()) |
2051 | Def = Def->getDefinition(); |
2052 | return Def; |
2053 | } |
2054 | |
2055 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting |
2056 | /// from S, where a non-field would be declared. This routine copes |
2057 | /// with the difference between C and C++ scoping rules in structs and |
2058 | /// unions. For example, the following code is well-formed in C but |
2059 | /// ill-formed in C++: |
2060 | /// @code |
2061 | /// struct S6 { |
2062 | /// enum { BAR } e; |
2063 | /// }; |
2064 | /// |
2065 | /// void test_S6() { |
2066 | /// struct S6 a; |
2067 | /// a.e = BAR; |
2068 | /// } |
2069 | /// @endcode |
2070 | /// For the declaration of BAR, this routine will return a different |
2071 | /// scope. The scope S will be the scope of the unnamed enumeration |
2072 | /// within S6. In C++, this routine will return the scope associated |
2073 | /// with S6, because the enumeration's scope is a transparent |
2074 | /// context but structures can contain non-field names. In C, this |
2075 | /// routine will return the translation unit scope, since the |
2076 | /// enumeration's scope is a transparent context and structures cannot |
2077 | /// contain non-field names. |
2078 | Scope *Sema::getNonFieldDeclScope(Scope *S) { |
2079 | while (((S->getFlags() & Scope::DeclScope) == 0) || |
2080 | (S->getEntity() && S->getEntity()->isTransparentContext()) || |
2081 | (S->isClassScope() && !getLangOpts().CPlusPlus)) |
2082 | S = S->getParent(); |
2083 | return S; |
2084 | } |
2085 | |
2086 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, |
2087 | ASTContext::GetBuiltinTypeError Error) { |
2088 | switch (Error) { |
2089 | case ASTContext::GE_None: |
2090 | return ""; |
2091 | case ASTContext::GE_Missing_type: |
2092 | return BuiltinInfo.getHeaderName(ID); |
2093 | case ASTContext::GE_Missing_stdio: |
2094 | return "stdio.h"; |
2095 | case ASTContext::GE_Missing_setjmp: |
2096 | return "setjmp.h"; |
2097 | case ASTContext::GE_Missing_ucontext: |
2098 | return "ucontext.h"; |
2099 | } |
2100 | llvm_unreachable("unhandled error kind")__builtin_unreachable(); |
2101 | } |
2102 | |
2103 | FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, |
2104 | unsigned ID, SourceLocation Loc) { |
2105 | DeclContext *Parent = Context.getTranslationUnitDecl(); |
2106 | |
2107 | if (getLangOpts().CPlusPlus) { |
2108 | LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( |
2109 | Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); |
2110 | CLinkageDecl->setImplicit(); |
2111 | Parent->addDecl(CLinkageDecl); |
2112 | Parent = CLinkageDecl; |
2113 | } |
2114 | |
2115 | FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, |
2116 | /*TInfo=*/nullptr, SC_Extern, false, |
2117 | Type->isFunctionProtoType()); |
2118 | New->setImplicit(); |
2119 | New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); |
2120 | |
2121 | // Create Decl objects for each parameter, adding them to the |
2122 | // FunctionDecl. |
2123 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { |
2124 | SmallVector<ParmVarDecl *, 16> Params; |
2125 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
2126 | ParmVarDecl *parm = ParmVarDecl::Create( |
2127 | Context, New, SourceLocation(), SourceLocation(), nullptr, |
2128 | FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); |
2129 | parm->setScopeInfo(0, i); |
2130 | Params.push_back(parm); |
2131 | } |
2132 | New->setParams(Params); |
2133 | } |
2134 | |
2135 | AddKnownFunctionAttributes(New); |
2136 | return New; |
2137 | } |
2138 | |
2139 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at |
2140 | /// file scope. lazily create a decl for it. ForRedeclaration is true |
2141 | /// if we're creating this built-in in anticipation of redeclaring the |
2142 | /// built-in. |
2143 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, |
2144 | Scope *S, bool ForRedeclaration, |
2145 | SourceLocation Loc) { |
2146 | LookupNecessaryTypesForBuiltin(S, ID); |
2147 | |
2148 | ASTContext::GetBuiltinTypeError Error; |
2149 | QualType R = Context.GetBuiltinType(ID, Error); |
2150 | if (Error) { |
2151 | if (!ForRedeclaration) |
2152 | return nullptr; |
2153 | |
2154 | // If we have a builtin without an associated type we should not emit a |
2155 | // warning when we were not able to find a type for it. |
2156 | if (Error == ASTContext::GE_Missing_type || |
2157 | Context.BuiltinInfo.allowTypeMismatch(ID)) |
2158 | return nullptr; |
2159 | |
2160 | // If we could not find a type for setjmp it is because the jmp_buf type was |
2161 | // not defined prior to the setjmp declaration. |
2162 | if (Error == ASTContext::GE_Missing_setjmp) { |
2163 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) |
2164 | << Context.BuiltinInfo.getName(ID); |
2165 | return nullptr; |
2166 | } |
2167 | |
2168 | // Generally, we emit a warning that the declaration requires the |
2169 | // appropriate header. |
2170 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) |
2171 | << getHeaderName(Context.BuiltinInfo, ID, Error) |
2172 | << Context.BuiltinInfo.getName(ID); |
2173 | return nullptr; |
2174 | } |
2175 | |
2176 | if (!ForRedeclaration && |
2177 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || |
2178 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { |
2179 | Diag(Loc, diag::ext_implicit_lib_function_decl) |
2180 | << Context.BuiltinInfo.getName(ID) << R; |
2181 | if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) |
2182 | Diag(Loc, diag::note_include_header_or_declare) |
2183 | << Header << Context.BuiltinInfo.getName(ID); |
2184 | } |
2185 | |
2186 | if (R.isNull()) |
2187 | return nullptr; |
2188 | |
2189 | FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); |
2190 | RegisterLocallyScopedExternCDecl(New, S); |
2191 | |
2192 | // TUScope is the translation-unit scope to insert this function into. |
2193 | // FIXME: This is hideous. We need to teach PushOnScopeChains to |
2194 | // relate Scopes to DeclContexts, and probably eliminate CurContext |
2195 | // entirely, but we're not there yet. |
2196 | DeclContext *SavedContext = CurContext; |
2197 | CurContext = New->getDeclContext(); |
2198 | PushOnScopeChains(New, TUScope); |
2199 | CurContext = SavedContext; |
2200 | return New; |
2201 | } |
2202 | |
2203 | /// Typedef declarations don't have linkage, but they still denote the same |
2204 | /// entity if their types are the same. |
2205 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's |
2206 | /// isSameEntity. |
2207 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, |
2208 | TypedefNameDecl *Decl, |
2209 | LookupResult &Previous) { |
2210 | // This is only interesting when modules are enabled. |
2211 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) |
2212 | return; |
2213 | |
2214 | // Empty sets are uninteresting. |
2215 | if (Previous.empty()) |
2216 | return; |
2217 | |
2218 | LookupResult::Filter Filter = Previous.makeFilter(); |
2219 | while (Filter.hasNext()) { |
2220 | NamedDecl *Old = Filter.next(); |
2221 | |
2222 | // Non-hidden declarations are never ignored. |
2223 | if (S.isVisible(Old)) |
2224 | continue; |
2225 | |
2226 | // Declarations of the same entity are not ignored, even if they have |
2227 | // different linkages. |
2228 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { |
2229 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), |
2230 | Decl->getUnderlyingType())) |
2231 | continue; |
2232 | |
2233 | // If both declarations give a tag declaration a typedef name for linkage |
2234 | // purposes, then they declare the same entity. |
2235 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && |
2236 | Decl->getAnonDeclWithTypedefName()) |
2237 | continue; |
2238 | } |
2239 | |
2240 | Filter.erase(); |
2241 | } |
2242 | |
2243 | Filter.done(); |
2244 | } |
2245 | |
2246 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { |
2247 | QualType OldType; |
2248 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) |
2249 | OldType = OldTypedef->getUnderlyingType(); |
2250 | else |
2251 | OldType = Context.getTypeDeclType(Old); |
2252 | QualType NewType = New->getUnderlyingType(); |
2253 | |
2254 | if (NewType->isVariablyModifiedType()) { |
2255 | // Must not redefine a typedef with a variably-modified type. |
2256 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; |
2257 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) |
2258 | << Kind << NewType; |
2259 | if (Old->getLocation().isValid()) |
2260 | notePreviousDefinition(Old, New->getLocation()); |
2261 | New->setInvalidDecl(); |
2262 | return true; |
2263 | } |
2264 | |
2265 | if (OldType != NewType && |
2266 | !OldType->isDependentType() && |
2267 | !NewType->isDependentType() && |
2268 | !Context.hasSameType(OldType, NewType)) { |
2269 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; |
2270 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) |
2271 | << Kind << NewType << OldType; |
2272 | if (Old->getLocation().isValid()) |
2273 | notePreviousDefinition(Old, New->getLocation()); |
2274 | New->setInvalidDecl(); |
2275 | return true; |
2276 | } |
2277 | return false; |
2278 | } |
2279 | |
2280 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the |
2281 | /// same name and scope as a previous declaration 'Old'. Figure out |
2282 | /// how to resolve this situation, merging decls or emitting |
2283 | /// diagnostics as appropriate. If there was an error, set New to be invalid. |
2284 | /// |
2285 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, |
2286 | LookupResult &OldDecls) { |
2287 | // If the new decl is known invalid already, don't bother doing any |
2288 | // merging checks. |
2289 | if (New->isInvalidDecl()) return; |
2290 | |
2291 | // Allow multiple definitions for ObjC built-in typedefs. |
2292 | // FIXME: Verify the underlying types are equivalent! |
2293 | if (getLangOpts().ObjC) { |
2294 | const IdentifierInfo *TypeID = New->getIdentifier(); |
2295 | switch (TypeID->getLength()) { |
2296 | default: break; |
2297 | case 2: |
2298 | { |
2299 | if (!TypeID->isStr("id")) |
2300 | break; |
2301 | QualType T = New->getUnderlyingType(); |
2302 | if (!T->isPointerType()) |
2303 | break; |
2304 | if (!T->isVoidPointerType()) { |
2305 | QualType PT = T->castAs<PointerType>()->getPointeeType(); |
2306 | if (!PT->isStructureType()) |
2307 | break; |
2308 | } |
2309 | Context.setObjCIdRedefinitionType(T); |
2310 | // Install the built-in type for 'id', ignoring the current definition. |
2311 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); |
2312 | return; |
2313 | } |
2314 | case 5: |
2315 | if (!TypeID->isStr("Class")) |
2316 | break; |
2317 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); |
2318 | // Install the built-in type for 'Class', ignoring the current definition. |
2319 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); |
2320 | return; |
2321 | case 3: |
2322 | if (!TypeID->isStr("SEL")) |
2323 | break; |
2324 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); |
2325 | // Install the built-in type for 'SEL', ignoring the current definition. |
2326 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); |
2327 | return; |
2328 | } |
2329 | // Fall through - the typedef name was not a builtin type. |
2330 | } |
2331 | |
2332 | // Verify the old decl was also a type. |
2333 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); |
2334 | if (!Old) { |
2335 | Diag(New->getLocation(), diag::err_redefinition_different_kind) |
2336 | << New->getDeclName(); |
2337 | |
2338 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); |
2339 | if (OldD->getLocation().isValid()) |
2340 | notePreviousDefinition(OldD, New->getLocation()); |
2341 | |
2342 | return New->setInvalidDecl(); |
2343 | } |
2344 | |
2345 | // If the old declaration is invalid, just give up here. |
2346 | if (Old->isInvalidDecl()) |
2347 | return New->setInvalidDecl(); |
2348 | |
2349 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { |
2350 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); |
2351 | auto *NewTag = New->getAnonDeclWithTypedefName(); |
2352 | NamedDecl *Hidden = nullptr; |
2353 | if (OldTag && NewTag && |
2354 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && |
2355 | !hasVisibleDefinition(OldTag, &Hidden)) { |
2356 | // There is a definition of this tag, but it is not visible. Use it |
2357 | // instead of our tag. |
2358 | New->setTypeForDecl(OldTD->getTypeForDecl()); |
2359 | if (OldTD->isModed()) |
2360 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), |
2361 | OldTD->getUnderlyingType()); |
2362 | else |
2363 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); |
2364 | |
2365 | // Make the old tag definition visible. |
2366 | makeMergedDefinitionVisible(Hidden); |
2367 | |
2368 | // If this was an unscoped enumeration, yank all of its enumerators |
2369 | // out of the scope. |
2370 | if (isa<EnumDecl>(NewTag)) { |
2371 | Scope *EnumScope = getNonFieldDeclScope(S); |
2372 | for (auto *D : NewTag->decls()) { |
2373 | auto *ED = cast<EnumConstantDecl>(D); |
2374 | assert(EnumScope->isDeclScope(ED))((void)0); |
2375 | EnumScope->RemoveDecl(ED); |
2376 | IdResolver.RemoveDecl(ED); |
2377 | ED->getLexicalDeclContext()->removeDecl(ED); |
2378 | } |
2379 | } |
2380 | } |
2381 | } |
2382 | |
2383 | // If the typedef types are not identical, reject them in all languages and |
2384 | // with any extensions enabled. |
2385 | if (isIncompatibleTypedef(Old, New)) |
2386 | return; |
2387 | |
2388 | // The types match. Link up the redeclaration chain and merge attributes if |
2389 | // the old declaration was a typedef. |
2390 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { |
2391 | New->setPreviousDecl(Typedef); |
2392 | mergeDeclAttributes(New, Old); |
2393 | } |
2394 | |
2395 | if (getLangOpts().MicrosoftExt) |
2396 | return; |
2397 | |
2398 | if (getLangOpts().CPlusPlus) { |
2399 | // C++ [dcl.typedef]p2: |
2400 | // In a given non-class scope, a typedef specifier can be used to |
2401 | // redefine the name of any type declared in that scope to refer |
2402 | // to the type to which it already refers. |
2403 | if (!isa<CXXRecordDecl>(CurContext)) |
2404 | return; |
2405 | |
2406 | // C++0x [dcl.typedef]p4: |
2407 | // In a given class scope, a typedef specifier can be used to redefine |
2408 | // any class-name declared in that scope that is not also a typedef-name |
2409 | // to refer to the type to which it already refers. |
2410 | // |
2411 | // This wording came in via DR424, which was a correction to the |
2412 | // wording in DR56, which accidentally banned code like: |
2413 | // |
2414 | // struct S { |
2415 | // typedef struct A { } A; |
2416 | // }; |
2417 | // |
2418 | // in the C++03 standard. We implement the C++0x semantics, which |
2419 | // allow the above but disallow |
2420 | // |
2421 | // struct S { |
2422 | // typedef int I; |
2423 | // typedef int I; |
2424 | // }; |
2425 | // |
2426 | // since that was the intent of DR56. |
2427 | if (!isa<TypedefNameDecl>(Old)) |
2428 | return; |
2429 | |
2430 | Diag(New->getLocation(), diag::err_redefinition) |
2431 | << New->getDeclName(); |
2432 | notePreviousDefinition(Old, New->getLocation()); |
2433 | return New->setInvalidDecl(); |
2434 | } |
2435 | |
2436 | // Modules always permit redefinition of typedefs, as does C11. |
2437 | if (getLangOpts().Modules || getLangOpts().C11) |
2438 | return; |
2439 | |
2440 | // If we have a redefinition of a typedef in C, emit a warning. This warning |
2441 | // is normally mapped to an error, but can be controlled with |
2442 | // -Wtypedef-redefinition. If either the original or the redefinition is |
2443 | // in a system header, don't emit this for compatibility with GCC. |
2444 | if (getDiagnostics().getSuppressSystemWarnings() && |
2445 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). |
2446 | (Old->isImplicit() || |
2447 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || |
2448 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) |
2449 | return; |
2450 | |
2451 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) |
2452 | << New->getDeclName(); |
2453 | notePreviousDefinition(Old, New->getLocation()); |
2454 | } |
2455 | |
2456 | /// DeclhasAttr - returns true if decl Declaration already has the target |
2457 | /// attribute. |
2458 | static bool DeclHasAttr(const Decl *D, const Attr *A) { |
2459 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); |
2460 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); |
2461 | for (const auto *i : D->attrs()) |
2462 | if (i->getKind() == A->getKind()) { |
2463 | if (Ann) { |
2464 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) |
2465 | return true; |
2466 | continue; |
2467 | } |
2468 | // FIXME: Don't hardcode this check |
2469 | if (OA && isa<OwnershipAttr>(i)) |
2470 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); |
2471 | return true; |
2472 | } |
2473 | |
2474 | return false; |
2475 | } |
2476 | |
2477 | static bool isAttributeTargetADefinition(Decl *D) { |
2478 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) |
2479 | return VD->isThisDeclarationADefinition(); |
2480 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) |
2481 | return TD->isCompleteDefinition() || TD->isBeingDefined(); |
2482 | return true; |
2483 | } |
2484 | |
2485 | /// Merge alignment attributes from \p Old to \p New, taking into account the |
2486 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. |
2487 | /// |
2488 | /// \return \c true if any attributes were added to \p New. |
2489 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { |
2490 | // Look for alignas attributes on Old, and pick out whichever attribute |
2491 | // specifies the strictest alignment requirement. |
2492 | AlignedAttr *OldAlignasAttr = nullptr; |
2493 | AlignedAttr *OldStrictestAlignAttr = nullptr; |
2494 | unsigned OldAlign = 0; |
2495 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { |
2496 | // FIXME: We have no way of representing inherited dependent alignments |
2497 | // in a case like: |
2498 | // template<int A, int B> struct alignas(A) X; |
2499 | // template<int A, int B> struct alignas(B) X {}; |
2500 | // For now, we just ignore any alignas attributes which are not on the |
2501 | // definition in such a case. |
2502 | if (I->isAlignmentDependent()) |
2503 | return false; |
2504 | |
2505 | if (I->isAlignas()) |
2506 | OldAlignasAttr = I; |
2507 | |
2508 | unsigned Align = I->getAlignment(S.Context); |
2509 | if (Align > OldAlign) { |
2510 | OldAlign = Align; |
2511 | OldStrictestAlignAttr = I; |
2512 | } |
2513 | } |
2514 | |
2515 | // Look for alignas attributes on New. |
2516 | AlignedAttr *NewAlignasAttr = nullptr; |
2517 | unsigned NewAlign = 0; |
2518 | for (auto *I : New->specific_attrs<AlignedAttr>()) { |
2519 | if (I->isAlignmentDependent()) |
2520 | return false; |
2521 | |
2522 | if (I->isAlignas()) |
2523 | NewAlignasAttr = I; |
2524 | |
2525 | unsigned Align = I->getAlignment(S.Context); |
2526 | if (Align > NewAlign) |
2527 | NewAlign = Align; |
2528 | } |
2529 | |
2530 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { |
2531 | // Both declarations have 'alignas' attributes. We require them to match. |
2532 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but |
2533 | // fall short. (If two declarations both have alignas, they must both match |
2534 | // every definition, and so must match each other if there is a definition.) |
2535 | |
2536 | // If either declaration only contains 'alignas(0)' specifiers, then it |
2537 | // specifies the natural alignment for the type. |
2538 | if (OldAlign == 0 || NewAlign == 0) { |
2539 | QualType Ty; |
2540 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) |
2541 | Ty = VD->getType(); |
2542 | else |
2543 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); |
2544 | |
2545 | if (OldAlign == 0) |
2546 | OldAlign = S.Context.getTypeAlign(Ty); |
2547 | if (NewAlign == 0) |
2548 | NewAlign = S.Context.getTypeAlign(Ty); |
2549 | } |
2550 | |
2551 | if (OldAlign != NewAlign) { |
2552 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) |
2553 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() |
2554 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); |
2555 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); |
2556 | } |
2557 | } |
2558 | |
2559 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { |
2560 | // C++11 [dcl.align]p6: |
2561 | // if any declaration of an entity has an alignment-specifier, |
2562 | // every defining declaration of that entity shall specify an |
2563 | // equivalent alignment. |
2564 | // C11 6.7.5/7: |
2565 | // If the definition of an object does not have an alignment |
2566 | // specifier, any other declaration of that object shall also |
2567 | // have no alignment specifier. |
2568 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) |
2569 | << OldAlignasAttr; |
2570 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) |
2571 | << OldAlignasAttr; |
2572 | } |
2573 | |
2574 | bool AnyAdded = false; |
2575 | |
2576 | // Ensure we have an attribute representing the strictest alignment. |
2577 | if (OldAlign > NewAlign) { |
2578 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); |
2579 | Clone->setInherited(true); |
2580 | New->addAttr(Clone); |
2581 | AnyAdded = true; |
2582 | } |
2583 | |
2584 | // Ensure we have an alignas attribute if the old declaration had one. |
2585 | if (OldAlignasAttr && !NewAlignasAttr && |
2586 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { |
2587 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); |
2588 | Clone->setInherited(true); |
2589 | New->addAttr(Clone); |
2590 | AnyAdded = true; |
2591 | } |
2592 | |
2593 | return AnyAdded; |
2594 | } |
2595 | |
2596 | #define WANT_DECL_MERGE_LOGIC |
2597 | #include "clang/Sema/AttrParsedAttrImpl.inc" |
2598 | #undef WANT_DECL_MERGE_LOGIC |
2599 | |
2600 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, |
2601 | const InheritableAttr *Attr, |
2602 | Sema::AvailabilityMergeKind AMK) { |
2603 | // Diagnose any mutual exclusions between the attribute that we want to add |
2604 | // and attributes that already exist on the declaration. |
2605 | if (!DiagnoseMutualExclusions(S, D, Attr)) |
2606 | return false; |
2607 | |
2608 | // This function copies an attribute Attr from a previous declaration to the |
2609 | // new declaration D if the new declaration doesn't itself have that attribute |
2610 | // yet or if that attribute allows duplicates. |
2611 | // If you're adding a new attribute that requires logic different from |
2612 | // "use explicit attribute on decl if present, else use attribute from |
2613 | // previous decl", for example if the attribute needs to be consistent |
2614 | // between redeclarations, you need to call a custom merge function here. |
2615 | InheritableAttr *NewAttr = nullptr; |
2616 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) |
2617 | NewAttr = S.mergeAvailabilityAttr( |
2618 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), |
2619 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), |
2620 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, |
2621 | AA->getPriority()); |
2622 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) |
2623 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); |
2624 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) |
2625 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); |
2626 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) |
2627 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); |
2628 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) |
2629 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); |
2630 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) |
2631 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), |
2632 | FA->getFirstArg()); |
2633 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) |
2634 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); |
2635 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) |
2636 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); |
2637 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) |
2638 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), |
2639 | IA->getInheritanceModel()); |
2640 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) |
2641 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, |
2642 | &S.Context.Idents.get(AA->getSpelling())); |
2643 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && |
2644 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || |
2645 | isa<CUDAGlobalAttr>(Attr))) { |
2646 | // CUDA target attributes are part of function signature for |
2647 | // overloading purposes and must not be merged. |
2648 | return false; |
2649 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) |
2650 | NewAttr = S.mergeMinSizeAttr(D, *MA); |
2651 | else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) |
2652 | NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); |
2653 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) |
2654 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); |
2655 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) |
2656 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); |
2657 | else if (isa<AlignedAttr>(Attr)) |
2658 | // AlignedAttrs are handled separately, because we need to handle all |
2659 | // such attributes on a declaration at the same time. |
2660 | NewAttr = nullptr; |
2661 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && |
2662 | (AMK == Sema::AMK_Override || |
2663 | AMK == Sema::AMK_ProtocolImplementation || |
2664 | AMK == Sema::AMK_OptionalProtocolImplementation)) |
2665 | NewAttr = nullptr; |
2666 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) |
2667 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); |
2668 | else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) |
2669 | NewAttr = S.mergeImportModuleAttr(D, *IMA); |
2670 | else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) |
2671 | NewAttr = S.mergeImportNameAttr(D, *INA); |
2672 | else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) |
2673 | NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); |
2674 | else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) |
2675 | NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); |
2676 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) |
2677 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); |
2678 | |
2679 | if (NewAttr) { |
2680 | NewAttr->setInherited(true); |
2681 | D->addAttr(NewAttr); |
2682 | if (isa<MSInheritanceAttr>(NewAttr)) |
2683 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); |
2684 | return true; |
2685 | } |
2686 | |
2687 | return false; |
2688 | } |
2689 | |
2690 | static const NamedDecl *getDefinition(const Decl *D) { |
2691 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) |
2692 | return TD->getDefinition(); |
2693 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
2694 | const VarDecl *Def = VD->getDefinition(); |
2695 | if (Def) |
2696 | return Def; |
2697 | return VD->getActingDefinition(); |
2698 | } |
2699 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
2700 | const FunctionDecl *Def = nullptr; |
2701 | if (FD->isDefined(Def, true)) |
2702 | return Def; |
2703 | } |
2704 | return nullptr; |
2705 | } |
2706 | |
2707 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { |
2708 | for (const auto *Attribute : D->attrs()) |
2709 | if (Attribute->getKind() == Kind) |
2710 | return true; |
2711 | return false; |
2712 | } |
2713 | |
2714 | /// checkNewAttributesAfterDef - If we already have a definition, check that |
2715 | /// there are no new attributes in this declaration. |
2716 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { |
2717 | if (!New->hasAttrs()) |
2718 | return; |
2719 | |
2720 | const NamedDecl *Def = getDefinition(Old); |
2721 | if (!Def || Def == New) |
2722 | return; |
2723 | |
2724 | AttrVec &NewAttributes = New->getAttrs(); |
2725 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { |
2726 | const Attr *NewAttribute = NewAttributes[I]; |
2727 | |
2728 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { |
2729 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { |
2730 | Sema::SkipBodyInfo SkipBody; |
2731 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); |
2732 | |
2733 | // If we're skipping this definition, drop the "alias" attribute. |
2734 | if (SkipBody.ShouldSkip) { |
2735 | NewAttributes.erase(NewAttributes.begin() + I); |
2736 | --E; |
2737 | continue; |
2738 | } |
2739 | } else { |
2740 | VarDecl *VD = cast<VarDecl>(New); |
2741 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == |
2742 | VarDecl::TentativeDefinition |
2743 | ? diag::err_alias_after_tentative |
2744 | : diag::err_redefinition; |
2745 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); |
2746 | if (Diag == diag::err_redefinition) |
2747 | S.notePreviousDefinition(Def, VD->getLocation()); |
2748 | else |
2749 | S.Diag(Def->getLocation(), diag::note_previous_definition); |
2750 | VD->setInvalidDecl(); |
2751 | } |
2752 | ++I; |
2753 | continue; |
2754 | } |
2755 | |
2756 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { |
2757 | // Tentative definitions are only interesting for the alias check above. |
2758 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { |
2759 | ++I; |
2760 | continue; |
2761 | } |
2762 | } |
2763 | |
2764 | if (hasAttribute(Def, NewAttribute->getKind())) { |
2765 | ++I; |
2766 | continue; // regular attr merging will take care of validating this. |
2767 | } |
2768 | |
2769 | if (isa<C11NoReturnAttr>(NewAttribute)) { |
2770 | // C's _Noreturn is allowed to be added to a function after it is defined. |
2771 | ++I; |
2772 | continue; |
2773 | } else if (isa<UuidAttr>(NewAttribute)) { |
2774 | // msvc will allow a subsequent definition to add an uuid to a class |
2775 | ++I; |
2776 | continue; |
2777 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { |
2778 | if (AA->isAlignas()) { |
2779 | // C++11 [dcl.align]p6: |
2780 | // if any declaration of an entity has an alignment-specifier, |
2781 | // every defining declaration of that entity shall specify an |
2782 | // equivalent alignment. |
2783 | // C11 6.7.5/7: |
2784 | // If the definition of an object does not have an alignment |
2785 | // specifier, any other declaration of that object shall also |
2786 | // have no alignment specifier. |
2787 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) |
2788 | << AA; |
2789 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) |
2790 | << AA; |
2791 | NewAttributes.erase(NewAttributes.begin() + I); |
2792 | --E; |
2793 | continue; |
2794 | } |
2795 | } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { |
2796 | // If there is a C definition followed by a redeclaration with this |
2797 | // attribute then there are two different definitions. In C++, prefer the |
2798 | // standard diagnostics. |
2799 | if (!S.getLangOpts().CPlusPlus) { |
2800 | S.Diag(NewAttribute->getLocation(), |
2801 | diag::err_loader_uninitialized_redeclaration); |
2802 | S.Diag(Def->getLocation(), diag::note_previous_definition); |
2803 | NewAttributes.erase(NewAttributes.begin() + I); |
2804 | --E; |
2805 | continue; |
2806 | } |
2807 | } else if (isa<SelectAnyAttr>(NewAttribute) && |
2808 | cast<VarDecl>(New)->isInline() && |
2809 | !cast<VarDecl>(New)->isInlineSpecified()) { |
2810 | // Don't warn about applying selectany to implicitly inline variables. |
2811 | // Older compilers and language modes would require the use of selectany |
2812 | // to make such variables inline, and it would have no effect if we |
2813 | // honored it. |
2814 | ++I; |
2815 | continue; |
2816 | } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { |
2817 | // We allow to add OMP[Begin]DeclareVariantAttr to be added to |
2818 | // declarations after defintions. |
2819 | ++I; |
2820 | continue; |
2821 | } |
2822 | |
2823 | S.Diag(NewAttribute->getLocation(), |
2824 | diag::warn_attribute_precede_definition); |
2825 | S.Diag(Def->getLocation(), diag::note_previous_definition); |
2826 | NewAttributes.erase(NewAttributes.begin() + I); |
2827 | --E; |
2828 | } |
2829 | } |
2830 | |
2831 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, |
2832 | const ConstInitAttr *CIAttr, |
2833 | bool AttrBeforeInit) { |
2834 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); |
2835 | |
2836 | // Figure out a good way to write this specifier on the old declaration. |
2837 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve |
2838 | // enough of the attribute list spelling information to extract that without |
2839 | // heroics. |
2840 | std::string SuitableSpelling; |
2841 | if (S.getLangOpts().CPlusPlus20) |
2842 | SuitableSpelling = std::string( |
2843 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); |
2844 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) |
2845 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( |
2846 | InsertLoc, {tok::l_square, tok::l_square, |
2847 | S.PP.getIdentifierInfo("clang"), tok::coloncolon, |
2848 | S.PP.getIdentifierInfo("require_constant_initialization"), |
2849 | tok::r_square, tok::r_square})); |
2850 | if (SuitableSpelling.empty()) |
2851 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( |
2852 | InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, |
2853 | S.PP.getIdentifierInfo("require_constant_initialization"), |
2854 | tok::r_paren, tok::r_paren})); |
2855 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) |
2856 | SuitableSpelling = "constinit"; |
2857 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) |
2858 | SuitableSpelling = "[[clang::require_constant_initialization]]"; |
2859 | if (SuitableSpelling.empty()) |
2860 | SuitableSpelling = "__attribute__((require_constant_initialization))"; |
2861 | SuitableSpelling += " "; |
2862 | |
2863 | if (AttrBeforeInit) { |
2864 | // extern constinit int a; |
2865 | // int a = 0; // error (missing 'constinit'), accepted as extension |
2866 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((void)0); |
2867 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) |
2868 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); |
2869 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); |
2870 | } else { |
2871 | // int a = 0; |
2872 | // constinit extern int a; // error (missing 'constinit') |
2873 | S.Diag(CIAttr->getLocation(), |
2874 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late |
2875 | : diag::warn_require_const_init_added_too_late) |
2876 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); |
2877 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) |
2878 | << CIAttr->isConstinit() |
2879 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); |
2880 | } |
2881 | } |
2882 | |
2883 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. |
2884 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, |
2885 | AvailabilityMergeKind AMK) { |
2886 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { |
2887 | UsedAttr *NewAttr = OldAttr->clone(Context); |
2888 | NewAttr->setInherited(true); |
2889 | New->addAttr(NewAttr); |
2890 | } |
2891 | if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { |
2892 | RetainAttr *NewAttr = OldAttr->clone(Context); |
2893 | NewAttr->setInherited(true); |
2894 | New->addAttr(NewAttr); |
2895 | } |
2896 | |
2897 | if (!Old->hasAttrs() && !New->hasAttrs()) |
2898 | return; |
2899 | |
2900 | // [dcl.constinit]p1: |
2901 | // If the [constinit] specifier is applied to any declaration of a |
2902 | // variable, it shall be applied to the initializing declaration. |
2903 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); |
2904 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); |
2905 | if (bool(OldConstInit) != bool(NewConstInit)) { |
2906 | const auto *OldVD = cast<VarDecl>(Old); |
2907 | auto *NewVD = cast<VarDecl>(New); |
2908 | |
2909 | // Find the initializing declaration. Note that we might not have linked |
2910 | // the new declaration into the redeclaration chain yet. |
2911 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); |
2912 | if (!InitDecl && |
2913 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) |
2914 | InitDecl = NewVD; |
2915 | |
2916 | if (InitDecl == NewVD) { |
2917 | // This is the initializing declaration. If it would inherit 'constinit', |
2918 | // that's ill-formed. (Note that we do not apply this to the attribute |
2919 | // form). |
2920 | if (OldConstInit && OldConstInit->isConstinit()) |
2921 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, |
2922 | /*AttrBeforeInit=*/true); |
2923 | } else if (NewConstInit) { |
2924 | // This is the first time we've been told that this declaration should |
2925 | // have a constant initializer. If we already saw the initializing |
2926 | // declaration, this is too late. |
2927 | if (InitDecl && InitDecl != NewVD) { |
2928 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, |
2929 | /*AttrBeforeInit=*/false); |
2930 | NewVD->dropAttr<ConstInitAttr>(); |
2931 | } |
2932 | } |
2933 | } |
2934 | |
2935 | // Attributes declared post-definition are currently ignored. |
2936 | checkNewAttributesAfterDef(*this, New, Old); |
2937 | |
2938 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { |
2939 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { |
2940 | if (!OldA->isEquivalent(NewA)) { |
2941 | // This redeclaration changes __asm__ label. |
2942 | Diag(New->getLocation(), diag::err_different_asm_label); |
2943 | Diag(OldA->getLocation(), diag::note_previous_declaration); |
2944 | } |
2945 | } else if (Old->isUsed()) { |
2946 | // This redeclaration adds an __asm__ label to a declaration that has |
2947 | // already been ODR-used. |
2948 | Diag(New->getLocation(), diag::err_late_asm_label_name) |
2949 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); |
2950 | } |
2951 | } |
2952 | |
2953 | // Re-declaration cannot add abi_tag's. |
2954 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { |
2955 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { |
2956 | for (const auto &NewTag : NewAbiTagAttr->tags()) { |
2957 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), |
2958 | NewTag) == OldAbiTagAttr->tags_end()) { |
2959 | Diag(NewAbiTagAttr->getLocation(), |
2960 | diag::err_new_abi_tag_on_redeclaration) |
2961 | << NewTag; |
2962 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); |
2963 | } |
2964 | } |
2965 | } else { |
2966 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); |
2967 | Diag(Old->getLocation(), diag::note_previous_declaration); |
2968 | } |
2969 | } |
2970 | |
2971 | // This redeclaration adds a section attribute. |
2972 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { |
2973 | if (auto *VD = dyn_cast<VarDecl>(New)) { |
2974 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { |
2975 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); |
2976 | Diag(Old->getLocation(), diag::note_previous_declaration); |
2977 | } |
2978 | } |
2979 | } |
2980 | |
2981 | // Redeclaration adds code-seg attribute. |
2982 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); |
2983 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && |
2984 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { |
2985 | Diag(New->getLocation(), diag::warn_mismatched_section) |
2986 | << 0 /*codeseg*/; |
2987 | Diag(Old->getLocation(), diag::note_previous_declaration); |
2988 | } |
2989 | |
2990 | if (!Old->hasAttrs()) |
2991 | return; |
2992 | |
2993 | bool foundAny = New->hasAttrs(); |
2994 | |
2995 | // Ensure that any moving of objects within the allocated map is done before |
2996 | // we process them. |
2997 | if (!foundAny) New->setAttrs(AttrVec()); |
2998 | |
2999 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { |
3000 | // Ignore deprecated/unavailable/availability attributes if requested. |
3001 | AvailabilityMergeKind LocalAMK = AMK_None; |
3002 | if (isa<DeprecatedAttr>(I) || |
3003 | isa<UnavailableAttr>(I) || |
3004 | isa<AvailabilityAttr>(I)) { |
3005 | switch (AMK) { |
3006 | case AMK_None: |
3007 | continue; |
3008 | |
3009 | case AMK_Redeclaration: |
3010 | case AMK_Override: |
3011 | case AMK_ProtocolImplementation: |
3012 | case AMK_OptionalProtocolImplementation: |
3013 | LocalAMK = AMK; |
3014 | break; |
3015 | } |
3016 | } |
3017 | |
3018 | // Already handled. |
3019 | if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) |
3020 | continue; |
3021 | |
3022 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) |
3023 | foundAny = true; |
3024 | } |
3025 | |
3026 | if (mergeAlignedAttrs(*this, New, Old)) |
3027 | foundAny = true; |
3028 | |
3029 | if (!foundAny) New->dropAttrs(); |
3030 | } |
3031 | |
3032 | /// mergeParamDeclAttributes - Copy attributes from the old parameter |
3033 | /// to the new one. |
3034 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, |
3035 | const ParmVarDecl *oldDecl, |
3036 | Sema &S) { |
3037 | // C++11 [dcl.attr.depend]p2: |
3038 | // The first declaration of a function shall specify the |
3039 | // carries_dependency attribute for its declarator-id if any declaration |
3040 | // of the function specifies the carries_dependency attribute. |
3041 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); |
3042 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { |
3043 | S.Diag(CDA->getLocation(), |
3044 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; |
3045 | // Find the first declaration of the parameter. |
3046 | // FIXME: Should we build redeclaration chains for function parameters? |
3047 | const FunctionDecl *FirstFD = |
3048 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); |
3049 | const ParmVarDecl *FirstVD = |
3050 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); |
3051 | S.Diag(FirstVD->getLocation(), |
3052 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; |
3053 | } |
3054 | |
3055 | if (!oldDecl->hasAttrs()) |
3056 | return; |
3057 | |
3058 | bool foundAny = newDecl->hasAttrs(); |
3059 | |
3060 | // Ensure that any moving of objects within the allocated map is |
3061 | // done before we process them. |
3062 | if (!foundAny) newDecl->setAttrs(AttrVec()); |
3063 | |
3064 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { |
3065 | if (!DeclHasAttr(newDecl, I)) { |
3066 | InheritableAttr *newAttr = |
3067 | cast<InheritableParamAttr>(I->clone(S.Context)); |
3068 | newAttr->setInherited(true); |
3069 | newDecl->addAttr(newAttr); |
3070 | foundAny = true; |
3071 | } |
3072 | } |
3073 | |
3074 | if (!foundAny) newDecl->dropAttrs(); |
3075 | } |
3076 | |
3077 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, |
3078 | const ParmVarDecl *OldParam, |
3079 | Sema &S) { |
3080 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { |
3081 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { |
3082 | if (*Oldnullability != *Newnullability) { |
3083 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) |
3084 | << DiagNullabilityKind( |
3085 | *Newnullability, |
3086 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
3087 | != 0)) |
3088 | << DiagNullabilityKind( |
3089 | *Oldnullability, |
3090 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
3091 | != 0)); |
3092 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); |
3093 | } |
3094 | } else { |
3095 | QualType NewT = NewParam->getType(); |
3096 | NewT = S.Context.getAttributedType( |
3097 | AttributedType::getNullabilityAttrKind(*Oldnullability), |
3098 | NewT, NewT); |
3099 | NewParam->setType(NewT); |
3100 | } |
3101 | } |
3102 | } |
3103 | |
3104 | namespace { |
3105 | |
3106 | /// Used in MergeFunctionDecl to keep track of function parameters in |
3107 | /// C. |
3108 | struct GNUCompatibleParamWarning { |
3109 | ParmVarDecl *OldParm; |
3110 | ParmVarDecl *NewParm; |
3111 | QualType PromotedType; |
3112 | }; |
3113 | |
3114 | } // end anonymous namespace |
3115 | |
3116 | // Determine whether the previous declaration was a definition, implicit |
3117 | // declaration, or a declaration. |
3118 | template <typename T> |
3119 | static std::pair<diag::kind, SourceLocation> |
3120 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { |
3121 | diag::kind PrevDiag; |
3122 | SourceLocation OldLocation = Old->getLocation(); |
3123 | if (Old->isThisDeclarationADefinition()) |
3124 | PrevDiag = diag::note_previous_definition; |
3125 | else if (Old->isImplicit()) { |
3126 | PrevDiag = diag::note_previous_implicit_declaration; |
3127 | if (OldLocation.isInvalid()) |
3128 | OldLocation = New->getLocation(); |
3129 | } else |
3130 | PrevDiag = diag::note_previous_declaration; |
3131 | return std::make_pair(PrevDiag, OldLocation); |
3132 | } |
3133 | |
3134 | /// canRedefineFunction - checks if a function can be redefined. Currently, |
3135 | /// only extern inline functions can be redefined, and even then only in |
3136 | /// GNU89 mode. |
3137 | static bool canRedefineFunction(const FunctionDecl *FD, |
3138 | const LangOptions& LangOpts) { |
3139 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && |
3140 | !LangOpts.CPlusPlus && |
3141 | FD->isInlineSpecified() && |
3142 | FD->getStorageClass() == SC_Extern); |
3143 | } |
3144 | |
3145 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { |
3146 | const AttributedType *AT = T->getAs<AttributedType>(); |
3147 | while (AT && !AT->isCallingConv()) |
3148 | AT = AT->getModifiedType()->getAs<AttributedType>(); |
3149 | return AT; |
3150 | } |
3151 | |
3152 | template <typename T> |
3153 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { |
3154 | const DeclContext *DC = Old->getDeclContext(); |
3155 | if (DC->isRecord()) |
3156 | return false; |
3157 | |
3158 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); |
3159 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) |
3160 | return true; |
3161 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) |
3162 | return true; |
3163 | return false; |
3164 | } |
3165 | |
3166 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } |
3167 | static bool isExternC(VarTemplateDecl *) { return false; } |
3168 | static bool isExternC(FunctionTemplateDecl *) { return false; } |
3169 | |
3170 | /// Check whether a redeclaration of an entity introduced by a |
3171 | /// using-declaration is valid, given that we know it's not an overload |
3172 | /// (nor a hidden tag declaration). |
3173 | template<typename ExpectedDecl> |
3174 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, |
3175 | ExpectedDecl *New) { |
3176 | // C++11 [basic.scope.declarative]p4: |
3177 | // Given a set of declarations in a single declarative region, each of |
3178 | // which specifies the same unqualified name, |
3179 | // -- they shall all refer to the same entity, or all refer to functions |
3180 | // and function templates; or |
3181 | // -- exactly one declaration shall declare a class name or enumeration |
3182 | // name that is not a typedef name and the other declarations shall all |
3183 | // refer to the same variable or enumerator, or all refer to functions |
3184 | // and function templates; in this case the class name or enumeration |
3185 | // name is hidden (3.3.10). |
3186 | |
3187 | // C++11 [namespace.udecl]p14: |
3188 | // If a function declaration in namespace scope or block scope has the |
3189 | // same name and the same parameter-type-list as a function introduced |
3190 | // by a using-declaration, and the declarations do not declare the same |
3191 | // function, the program is ill-formed. |
3192 | |
3193 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); |
3194 | if (Old && |
3195 | !Old->getDeclContext()->getRedeclContext()->Equals( |
3196 | New->getDeclContext()->getRedeclContext()) && |
3197 | !(isExternC(Old) && isExternC(New))) |
3198 | Old = nullptr; |
3199 | |
3200 | if (!Old) { |
3201 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); |
3202 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); |
3203 | S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; |
3204 | return true; |
3205 | } |
3206 | return false; |
3207 | } |
3208 | |
3209 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, |
3210 | const FunctionDecl *B) { |
3211 | assert(A->getNumParams() == B->getNumParams())((void)0); |
3212 | |
3213 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { |
3214 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); |
3215 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); |
3216 | if (AttrA == AttrB) |
3217 | return true; |
3218 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && |
3219 | AttrA->isDynamic() == AttrB->isDynamic(); |
3220 | }; |
3221 | |
3222 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); |
3223 | } |
3224 | |
3225 | /// If necessary, adjust the semantic declaration context for a qualified |
3226 | /// declaration to name the correct inline namespace within the qualifier. |
3227 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, |
3228 | DeclaratorDecl *OldD) { |
3229 | // The only case where we need to update the DeclContext is when |
3230 | // redeclaration lookup for a qualified name finds a declaration |
3231 | // in an inline namespace within the context named by the qualifier: |
3232 | // |
3233 | // inline namespace N { int f(); } |
3234 | // int ::f(); // Sema DC needs adjusting from :: to N::. |
3235 | // |
3236 | // For unqualified declarations, the semantic context *can* change |
3237 | // along the redeclaration chain (for local extern declarations, |
3238 | // extern "C" declarations, and friend declarations in particular). |
3239 | if (!NewD->getQualifier()) |
3240 | return; |
3241 | |
3242 | // NewD is probably already in the right context. |
3243 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); |
3244 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); |
3245 | if (NamedDC->Equals(SemaDC)) |
3246 | return; |
3247 | |
3248 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||((void)0) |
3249 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&((void)0) |
3250 | "unexpected context for redeclaration")((void)0); |
3251 | |
3252 | auto *LexDC = NewD->getLexicalDeclContext(); |
3253 | auto FixSemaDC = [=](NamedDecl *D) { |
3254 | if (!D) |
3255 | return; |
3256 | D->setDeclContext(SemaDC); |
3257 | D->setLexicalDeclContext(LexDC); |
3258 | }; |
3259 | |
3260 | FixSemaDC(NewD); |
3261 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) |
3262 | FixSemaDC(FD->getDescribedFunctionTemplate()); |
3263 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) |
3264 | FixSemaDC(VD->getDescribedVarTemplate()); |
3265 | } |
3266 | |
3267 | /// MergeFunctionDecl - We just parsed a function 'New' from |
3268 | /// declarator D which has the same name and scope as a previous |
3269 | /// declaration 'Old'. Figure out how to resolve this situation, |
3270 | /// merging decls or emitting diagnostics as appropriate. |
3271 | /// |
3272 | /// In C++, New and Old must be declarations that are not |
3273 | /// overloaded. Use IsOverload to determine whether New and Old are |
3274 | /// overloaded, and to select the Old declaration that New should be |
3275 | /// merged with. |
3276 | /// |
3277 | /// Returns true if there was an error, false otherwise. |
3278 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, |
3279 | Scope *S, bool MergeTypeWithOld) { |
3280 | // Verify the old decl was also a function. |
3281 | FunctionDecl *Old = OldD->getAsFunction(); |
3282 | if (!Old) { |
3283 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { |
3284 | if (New->getFriendObjectKind()) { |
3285 | Diag(New->getLocation(), diag::err_using_decl_friend); |
3286 | Diag(Shadow->getTargetDecl()->getLocation(), |
3287 | diag::note_using_decl_target); |
3288 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) |
3289 | << 0; |
3290 | return true; |
3291 | } |
3292 | |
3293 | // Check whether the two declarations might declare the same function or |
3294 | // function template. |
3295 | if (FunctionTemplateDecl *NewTemplate = |
3296 | New->getDescribedFunctionTemplate()) { |
3297 | if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, |
3298 | NewTemplate)) |
3299 | return true; |
3300 | OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) |
3301 | ->getAsFunction(); |
3302 | } else { |
3303 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) |
3304 | return true; |
3305 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); |
3306 | } |
3307 | } else { |
3308 | Diag(New->getLocation(), diag::err_redefinition_different_kind) |
3309 | << New->getDeclName(); |
3310 | notePreviousDefinition(OldD, New->getLocation()); |
3311 | return true; |
3312 | } |
3313 | } |
3314 | |
3315 | // If the old declaration was found in an inline namespace and the new |
3316 | // declaration was qualified, update the DeclContext to match. |
3317 | adjustDeclContextForDeclaratorDecl(New, Old); |
3318 | |
3319 | // If the old declaration is invalid, just give up here. |
3320 | if (Old->isInvalidDecl()) |
3321 | return true; |
3322 | |
3323 | // Disallow redeclaration of some builtins. |
3324 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { |
3325 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); |
3326 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) |
3327 | << Old << Old->getType(); |
3328 | return true; |
3329 | } |
3330 | |
3331 | diag::kind PrevDiag; |
3332 | SourceLocation OldLocation; |
3333 | std::tie(PrevDiag, OldLocation) = |
3334 | getNoteDiagForInvalidRedeclaration(Old, New); |
3335 | |
3336 | // Don't complain about this if we're in GNU89 mode and the old function |
3337 | // is an extern inline function. |
3338 | // Don't complain about specializations. They are not supposed to have |
3339 | // storage classes. |
3340 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && |
3341 | New->getStorageClass() == SC_Static && |
3342 | Old->hasExternalFormalLinkage() && |
3343 | !New->getTemplateSpecializationInfo() && |
3344 | !canRedefineFunction(Old, getLangOpts())) { |
3345 | if (getLangOpts().MicrosoftExt) { |
3346 | Diag(New->getLocation(), diag::ext_static_non_static) << New; |
3347 | Diag(OldLocation, PrevDiag); |
3348 | } else { |
3349 | Diag(New->getLocation(), diag::err_static_non_static) << New; |
3350 | Diag(OldLocation, PrevDiag); |
3351 | return true; |
3352 | } |
3353 | } |
3354 | |
3355 | if (New->hasAttr<InternalLinkageAttr>() && |
3356 | !Old->hasAttr<InternalLinkageAttr>()) { |
3357 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) |
3358 | << New->getDeclName(); |
3359 | notePreviousDefinition(Old, New->getLocation()); |
3360 | New->dropAttr<InternalLinkageAttr>(); |
3361 | } |
3362 | |
3363 | if (CheckRedeclarationModuleOwnership(New, Old)) |
3364 | return true; |
3365 | |
3366 | if (!getLangOpts().CPlusPlus) { |
3367 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); |
3368 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { |
3369 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) |
3370 | << New << OldOvl; |
3371 | |
3372 | // Try our best to find a decl that actually has the overloadable |
3373 | // attribute for the note. In most cases (e.g. programs with only one |
3374 | // broken declaration/definition), this won't matter. |
3375 | // |
3376 | // FIXME: We could do this if we juggled some extra state in |
3377 | // OverloadableAttr, rather than just removing it. |
3378 | const Decl *DiagOld = Old; |
3379 | if (OldOvl) { |
3380 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { |
3381 | const auto *A = D->getAttr<OverloadableAttr>(); |
3382 | return A && !A->isImplicit(); |
3383 | }); |
3384 | // If we've implicitly added *all* of the overloadable attrs to this |
3385 | // chain, emitting a "previous redecl" note is pointless. |
3386 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; |
3387 | } |
3388 | |
3389 | if (DiagOld) |
3390 | Diag(DiagOld->getLocation(), |
3391 | diag::note_attribute_overloadable_prev_overload) |
3392 | << OldOvl; |
3393 | |
3394 | if (OldOvl) |
3395 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); |
3396 | else |
3397 | New->dropAttr<OverloadableAttr>(); |
3398 | } |
3399 | } |
3400 | |
3401 | // If a function is first declared with a calling convention, but is later |
3402 | // declared or defined without one, all following decls assume the calling |
3403 | // convention of the first. |
3404 | // |
3405 | // It's OK if a function is first declared without a calling convention, |
3406 | // but is later declared or defined with the default calling convention. |
3407 | // |
3408 | // To test if either decl has an explicit calling convention, we look for |
3409 | // AttributedType sugar nodes on the type as written. If they are missing or |
3410 | // were canonicalized away, we assume the calling convention was implicit. |
3411 | // |
3412 | // Note also that we DO NOT return at this point, because we still have |
3413 | // other tests to run. |
3414 | QualType OldQType = Context.getCanonicalType(Old->getType()); |
3415 | QualType NewQType = Context.getCanonicalType(New->getType()); |
3416 | const FunctionType *OldType = cast<FunctionType>(OldQType); |
3417 | const FunctionType *NewType = cast<FunctionType>(NewQType); |
3418 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); |
3419 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); |
3420 | bool RequiresAdjustment = false; |
3421 | |
3422 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { |
3423 | FunctionDecl *First = Old->getFirstDecl(); |
3424 | const FunctionType *FT = |
3425 | First->getType().getCanonicalType()->castAs<FunctionType>(); |
3426 | FunctionType::ExtInfo FI = FT->getExtInfo(); |
3427 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); |
3428 | if (!NewCCExplicit) { |
3429 | // Inherit the CC from the previous declaration if it was specified |
3430 | // there but not here. |
3431 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); |
3432 | RequiresAdjustment = true; |
3433 | } else if (Old->getBuiltinID()) { |
3434 | // Builtin attribute isn't propagated to the new one yet at this point, |
3435 | // so we check if the old one is a builtin. |
3436 | |
3437 | // Calling Conventions on a Builtin aren't really useful and setting a |
3438 | // default calling convention and cdecl'ing some builtin redeclarations is |
3439 | // common, so warn and ignore the calling convention on the redeclaration. |
3440 | Diag(New->getLocation(), diag::warn_cconv_unsupported) |
3441 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) |
3442 | << (int)CallingConventionIgnoredReason::BuiltinFunction; |
3443 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); |
3444 | RequiresAdjustment = true; |
3445 | } else { |
3446 | // Calling conventions aren't compatible, so complain. |
3447 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); |
3448 | Diag(New->getLocation(), diag::err_cconv_change) |
3449 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) |
3450 | << !FirstCCExplicit |
3451 | << (!FirstCCExplicit ? "" : |
3452 | FunctionType::getNameForCallConv(FI.getCC())); |
3453 | |
3454 | // Put the note on the first decl, since it is the one that matters. |
3455 | Diag(First->getLocation(), diag::note_previous_declaration); |
3456 | return true; |
3457 | } |
3458 | } |
3459 | |
3460 | // FIXME: diagnose the other way around? |
3461 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { |
3462 | NewTypeInfo = NewTypeInfo.withNoReturn(true); |
3463 | RequiresAdjustment = true; |
3464 | } |
3465 | |
3466 | // Merge regparm attribute. |
3467 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || |
3468 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { |
3469 | if (NewTypeInfo.getHasRegParm()) { |
3470 | Diag(New->getLocation(), diag::err_regparm_mismatch) |
3471 | << NewType->getRegParmType() |
3472 | << OldType->getRegParmType(); |
3473 | Diag(OldLocation, diag::note_previous_declaration); |
3474 | return true; |
3475 | } |
3476 | |
3477 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); |
3478 | RequiresAdjustment = true; |
3479 | } |
3480 | |
3481 | // Merge ns_returns_retained attribute. |
3482 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { |
3483 | if (NewTypeInfo.getProducesResult()) { |
3484 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) |
3485 | << "'ns_returns_retained'"; |
3486 | Diag(OldLocation, diag::note_previous_declaration); |
3487 | return true; |
3488 | } |
3489 | |
3490 | NewTypeInfo = NewTypeInfo.withProducesResult(true); |
3491 | RequiresAdjustment = true; |
3492 | } |
3493 | |
3494 | if (OldTypeInfo.getNoCallerSavedRegs() != |
3495 | NewTypeInfo.getNoCallerSavedRegs()) { |
3496 | if (NewTypeInfo.getNoCallerSavedRegs()) { |
3497 | AnyX86NoCallerSavedRegistersAttr *Attr = |
3498 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); |
3499 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; |
3500 | Diag(OldLocation, diag::note_previous_declaration); |
3501 | return true; |
3502 | } |
3503 | |
3504 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); |
3505 | RequiresAdjustment = true; |
3506 | } |
3507 | |
3508 | if (RequiresAdjustment) { |
3509 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); |
3510 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); |
3511 | New->setType(QualType(AdjustedType, 0)); |
3512 | NewQType = Context.getCanonicalType(New->getType()); |
3513 | } |
3514 | |
3515 | // If this redeclaration makes the function inline, we may need to add it to |
3516 | // UndefinedButUsed. |
3517 | if (!Old->isInlined() && New->isInlined() && |
3518 | !New->hasAttr<GNUInlineAttr>() && |
3519 | !getLangOpts().GNUInline && |
3520 | Old->isUsed(false) && |
3521 | !Old->isDefined() && !New->isThisDeclarationADefinition()) |
3522 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), |
3523 | SourceLocation())); |
3524 | |
3525 | // If this redeclaration makes it newly gnu_inline, we don't want to warn |
3526 | // about it. |
3527 | if (New->hasAttr<GNUInlineAttr>() && |
3528 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { |
3529 | UndefinedButUsed.erase(Old->getCanonicalDecl()); |
3530 | } |
3531 | |
3532 | // If pass_object_size params don't match up perfectly, this isn't a valid |
3533 | // redeclaration. |
3534 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && |
3535 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { |
3536 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) |
3537 | << New->getDeclName(); |
3538 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3539 | return true; |
3540 | } |
3541 | |
3542 | if (getLangOpts().CPlusPlus) { |
3543 | // C++1z [over.load]p2 |
3544 | // Certain function declarations cannot be overloaded: |
3545 | // -- Function declarations that differ only in the return type, |
3546 | // the exception specification, or both cannot be overloaded. |
3547 | |
3548 | // Check the exception specifications match. This may recompute the type of |
3549 | // both Old and New if it resolved exception specifications, so grab the |
3550 | // types again after this. Because this updates the type, we do this before |
3551 | // any of the other checks below, which may update the "de facto" NewQType |
3552 | // but do not necessarily update the type of New. |
3553 | if (CheckEquivalentExceptionSpec(Old, New)) |
3554 | return true; |
3555 | OldQType = Context.getCanonicalType(Old->getType()); |
3556 | NewQType = Context.getCanonicalType(New->getType()); |
3557 | |
3558 | // Go back to the type source info to compare the declared return types, |
3559 | // per C++1y [dcl.type.auto]p13: |
3560 | // Redeclarations or specializations of a function or function template |
3561 | // with a declared return type that uses a placeholder type shall also |
3562 | // use that placeholder, not a deduced type. |
3563 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); |
3564 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); |
3565 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && |
3566 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, |
3567 | OldDeclaredReturnType)) { |
3568 | QualType ResQT; |
3569 | if (NewDeclaredReturnType->isObjCObjectPointerType() && |
3570 | OldDeclaredReturnType->isObjCObjectPointerType()) |
3571 | // FIXME: This does the wrong thing for a deduced return type. |
3572 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); |
3573 | if (ResQT.isNull()) { |
3574 | if (New->isCXXClassMember() && New->isOutOfLine()) |
3575 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) |
3576 | << New << New->getReturnTypeSourceRange(); |
3577 | else |
3578 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) |
3579 | << New->getReturnTypeSourceRange(); |
3580 | Diag(OldLocation, PrevDiag) << Old << Old->getType() |
3581 | << Old->getReturnTypeSourceRange(); |
3582 | return true; |
3583 | } |
3584 | else |
3585 | NewQType = ResQT; |
3586 | } |
3587 | |
3588 | QualType OldReturnType = OldType->getReturnType(); |
3589 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); |
3590 | if (OldReturnType != NewReturnType) { |
3591 | // If this function has a deduced return type and has already been |
3592 | // defined, copy the deduced value from the old declaration. |
3593 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); |
3594 | if (OldAT && OldAT->isDeduced()) { |
3595 | New->setType( |
3596 | SubstAutoType(New->getType(), |
3597 | OldAT->isDependentType() ? Context.DependentTy |
3598 | : OldAT->getDeducedType())); |
3599 | NewQType = Context.getCanonicalType( |
3600 | SubstAutoType(NewQType, |
3601 | OldAT->isDependentType() ? Context.DependentTy |
3602 | : OldAT->getDeducedType())); |
3603 | } |
3604 | } |
3605 | |
3606 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); |
3607 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); |
3608 | if (OldMethod && NewMethod) { |
3609 | // Preserve triviality. |
3610 | NewMethod->setTrivial(OldMethod->isTrivial()); |
3611 | |
3612 | // MSVC allows explicit template specialization at class scope: |
3613 | // 2 CXXMethodDecls referring to the same function will be injected. |
3614 | // We don't want a redeclaration error. |
3615 | bool IsClassScopeExplicitSpecialization = |
3616 | OldMethod->isFunctionTemplateSpecialization() && |
3617 | NewMethod->isFunctionTemplateSpecialization(); |
3618 | bool isFriend = NewMethod->getFriendObjectKind(); |
3619 | |
3620 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && |
3621 | !IsClassScopeExplicitSpecialization) { |
3622 | // -- Member function declarations with the same name and the |
3623 | // same parameter types cannot be overloaded if any of them |
3624 | // is a static member function declaration. |
3625 | if (OldMethod->isStatic() != NewMethod->isStatic()) { |
3626 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); |
3627 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3628 | return true; |
3629 | } |
3630 | |
3631 | // C++ [class.mem]p1: |
3632 | // [...] A member shall not be declared twice in the |
3633 | // member-specification, except that a nested class or member |
3634 | // class template can be declared and then later defined. |
3635 | if (!inTemplateInstantiation()) { |
3636 | unsigned NewDiag; |
3637 | if (isa<CXXConstructorDecl>(OldMethod)) |
3638 | NewDiag = diag::err_constructor_redeclared; |
3639 | else if (isa<CXXDestructorDecl>(NewMethod)) |
3640 | NewDiag = diag::err_destructor_redeclared; |
3641 | else if (isa<CXXConversionDecl>(NewMethod)) |
3642 | NewDiag = diag::err_conv_function_redeclared; |
3643 | else |
3644 | NewDiag = diag::err_member_redeclared; |
3645 | |
3646 | Diag(New->getLocation(), NewDiag); |
3647 | } else { |
3648 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) |
3649 | << New << New->getType(); |
3650 | } |
3651 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3652 | return true; |
3653 | |
3654 | // Complain if this is an explicit declaration of a special |
3655 | // member that was initially declared implicitly. |
3656 | // |
3657 | // As an exception, it's okay to befriend such methods in order |
3658 | // to permit the implicit constructor/destructor/operator calls. |
3659 | } else if (OldMethod->isImplicit()) { |
3660 | if (isFriend) { |
3661 | NewMethod->setImplicit(); |
3662 | } else { |
3663 | Diag(NewMethod->getLocation(), |
3664 | diag::err_definition_of_implicitly_declared_member) |
3665 | << New << getSpecialMember(OldMethod); |
3666 | return true; |
3667 | } |
3668 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { |
3669 | Diag(NewMethod->getLocation(), |
3670 | diag::err_definition_of_explicitly_defaulted_member) |
3671 | << getSpecialMember(OldMethod); |
3672 | return true; |
3673 | } |
3674 | } |
3675 | |
3676 | // C++11 [dcl.attr.noreturn]p1: |
3677 | // The first declaration of a function shall specify the noreturn |
3678 | // attribute if any declaration of that function specifies the noreturn |
3679 | // attribute. |
3680 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); |
3681 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { |
3682 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); |
3683 | Diag(Old->getFirstDecl()->getLocation(), |
3684 | diag::note_noreturn_missing_first_decl); |
3685 | } |
3686 | |
3687 | // C++11 [dcl.attr.depend]p2: |
3688 | // The first declaration of a function shall specify the |
3689 | // carries_dependency attribute for its declarator-id if any declaration |
3690 | // of the function specifies the carries_dependency attribute. |
3691 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); |
3692 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { |
3693 | Diag(CDA->getLocation(), |
3694 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; |
3695 | Diag(Old->getFirstDecl()->getLocation(), |
3696 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; |
3697 | } |
3698 | |
3699 | // (C++98 8.3.5p3): |
3700 | // All declarations for a function shall agree exactly in both the |
3701 | // return type and the parameter-type-list. |
3702 | // We also want to respect all the extended bits except noreturn. |
3703 | |
3704 | // noreturn should now match unless the old type info didn't have it. |
3705 | QualType OldQTypeForComparison = OldQType; |
3706 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { |
3707 | auto *OldType = OldQType->castAs<FunctionProtoType>(); |
3708 | const FunctionType *OldTypeForComparison |
3709 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); |
3710 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); |
3711 | assert(OldQTypeForComparison.isCanonical())((void)0); |
3712 | } |
3713 | |
3714 | if (haveIncompatibleLanguageLinkages(Old, New)) { |
3715 | // As a special case, retain the language linkage from previous |
3716 | // declarations of a friend function as an extension. |
3717 | // |
3718 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC |
3719 | // and is useful because there's otherwise no way to specify language |
3720 | // linkage within class scope. |
3721 | // |
3722 | // Check cautiously as the friend object kind isn't yet complete. |
3723 | if (New->getFriendObjectKind() != Decl::FOK_None) { |
3724 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; |
3725 | Diag(OldLocation, PrevDiag); |
3726 | } else { |
3727 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; |
3728 | Diag(OldLocation, PrevDiag); |
3729 | return true; |
3730 | } |
3731 | } |
3732 | |
3733 | // If the function types are compatible, merge the declarations. Ignore the |
3734 | // exception specifier because it was already checked above in |
3735 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics |
3736 | // about incompatible types under -fms-compatibility. |
3737 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, |
3738 | NewQType)) |
3739 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
3740 | |
3741 | // If the types are imprecise (due to dependent constructs in friends or |
3742 | // local extern declarations), it's OK if they differ. We'll check again |
3743 | // during instantiation. |
3744 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) |
3745 | return false; |
3746 | |
3747 | // Fall through for conflicting redeclarations and redefinitions. |
3748 | } |
3749 | |
3750 | // C: Function types need to be compatible, not identical. This handles |
3751 | // duplicate function decls like "void f(int); void f(enum X);" properly. |
3752 | if (!getLangOpts().CPlusPlus && |
3753 | Context.typesAreCompatible(OldQType, NewQType)) { |
3754 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); |
3755 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); |
3756 | const FunctionProtoType *OldProto = nullptr; |
3757 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && |
3758 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { |
3759 | // The old declaration provided a function prototype, but the |
3760 | // new declaration does not. Merge in the prototype. |
3761 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((void)0); |
3762 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); |
3763 | NewQType = |
3764 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, |
3765 | OldProto->getExtProtoInfo()); |
3766 | New->setType(NewQType); |
3767 | New->setHasInheritedPrototype(); |
3768 | |
3769 | // Synthesize parameters with the same types. |
3770 | SmallVector<ParmVarDecl*, 16> Params; |
3771 | for (const auto &ParamType : OldProto->param_types()) { |
3772 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), |
3773 | SourceLocation(), nullptr, |
3774 | ParamType, /*TInfo=*/nullptr, |
3775 | SC_None, nullptr); |
3776 | Param->setScopeInfo(0, Params.size()); |
3777 | Param->setImplicit(); |
3778 | Params.push_back(Param); |
3779 | } |
3780 | |
3781 | New->setParams(Params); |
3782 | } |
3783 | |
3784 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
3785 | } |
3786 | |
3787 | // Check if the function types are compatible when pointer size address |
3788 | // spaces are ignored. |
3789 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) |
3790 | return false; |
3791 | |
3792 | // GNU C permits a K&R definition to follow a prototype declaration |
3793 | // if the declared types of the parameters in the K&R definition |
3794 | // match the types in the prototype declaration, even when the |
3795 | // promoted types of the parameters from the K&R definition differ |
3796 | // from the types in the prototype. GCC then keeps the types from |
3797 | // the prototype. |
3798 | // |
3799 | // If a variadic prototype is followed by a non-variadic K&R definition, |
3800 | // the K&R definition becomes variadic. This is sort of an edge case, but |
3801 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and |
3802 | // C99 6.9.1p8. |
3803 | if (!getLangOpts().CPlusPlus && |
3804 | Old->hasPrototype() && !New->hasPrototype() && |
3805 | New->getType()->getAs<FunctionProtoType>() && |
3806 | Old->getNumParams() == New->getNumParams()) { |
3807 | SmallVector<QualType, 16> ArgTypes; |
3808 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; |
3809 | const FunctionProtoType *OldProto |
3810 | = Old->getType()->getAs<FunctionProtoType>(); |
3811 | const FunctionProtoType *NewProto |
3812 | = New->getType()->getAs<FunctionProtoType>(); |
3813 | |
3814 | // Determine whether this is the GNU C extension. |
3815 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), |
3816 | NewProto->getReturnType()); |
3817 | bool LooseCompatible = !MergedReturn.isNull(); |
3818 | for (unsigned Idx = 0, End = Old->getNumParams(); |
3819 | LooseCompatible && Idx != End; ++Idx) { |
3820 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); |
3821 | ParmVarDecl *NewParm = New->getParamDecl(Idx); |
3822 | if (Context.typesAreCompatible(OldParm->getType(), |
3823 | NewProto->getParamType(Idx))) { |
3824 | ArgTypes.push_back(NewParm->getType()); |
3825 | } else if (Context.typesAreCompatible(OldParm->getType(), |
3826 | NewParm->getType(), |
3827 | /*CompareUnqualified=*/true)) { |
3828 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, |
3829 | NewProto->getParamType(Idx) }; |
3830 | Warnings.push_back(Warn); |
3831 | ArgTypes.push_back(NewParm->getType()); |
3832 | } else |
3833 | LooseCompatible = false; |
3834 | } |
3835 | |
3836 | if (LooseCompatible) { |
3837 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { |
3838 | Diag(Warnings[Warn].NewParm->getLocation(), |
3839 | diag::ext_param_promoted_not_compatible_with_prototype) |
3840 | << Warnings[Warn].PromotedType |
3841 | << Warnings[Warn].OldParm->getType(); |
3842 | if (Warnings[Warn].OldParm->getLocation().isValid()) |
3843 | Diag(Warnings[Warn].OldParm->getLocation(), |
3844 | diag::note_previous_declaration); |
3845 | } |
3846 | |
3847 | if (MergeTypeWithOld) |
3848 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, |
3849 | OldProto->getExtProtoInfo())); |
3850 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
3851 | } |
3852 | |
3853 | // Fall through to diagnose conflicting types. |
3854 | } |
3855 | |
3856 | // A function that has already been declared has been redeclared or |
3857 | // defined with a different type; show an appropriate diagnostic. |
3858 | |
3859 | // If the previous declaration was an implicitly-generated builtin |
3860 | // declaration, then at the very least we should use a specialized note. |
3861 | unsigned BuiltinID; |
3862 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { |
3863 | // If it's actually a library-defined builtin function like 'malloc' |
3864 | // or 'printf', just warn about the incompatible redeclaration. |
3865 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { |
3866 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; |
3867 | Diag(OldLocation, diag::note_previous_builtin_declaration) |
3868 | << Old << Old->getType(); |
3869 | return false; |
3870 | } |
3871 | |
3872 | PrevDiag = diag::note_previous_builtin_declaration; |
3873 | } |
3874 | |
3875 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); |
3876 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3877 | return true; |
3878 | } |
3879 | |
3880 | /// Completes the merge of two function declarations that are |
3881 | /// known to be compatible. |
3882 | /// |
3883 | /// This routine handles the merging of attributes and other |
3884 | /// properties of function declarations from the old declaration to |
3885 | /// the new declaration, once we know that New is in fact a |
3886 | /// redeclaration of Old. |
3887 | /// |
3888 | /// \returns false |
3889 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, |
3890 | Scope *S, bool MergeTypeWithOld) { |
3891 | // Merge the attributes |
3892 | mergeDeclAttributes(New, Old); |
3893 | |
3894 | // Merge "pure" flag. |
3895 | if (Old->isPure()) |
3896 | New->setPure(); |
3897 | |
3898 | // Merge "used" flag. |
3899 | if (Old->getMostRecentDecl()->isUsed(false)) |
3900 | New->setIsUsed(); |
3901 | |
3902 | // Merge attributes from the parameters. These can mismatch with K&R |
3903 | // declarations. |
3904 | if (New->getNumParams() == Old->getNumParams()) |
3905 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { |
3906 | ParmVarDecl *NewParam = New->getParamDecl(i); |
3907 | ParmVarDecl *OldParam = Old->getParamDecl(i); |
3908 | mergeParamDeclAttributes(NewParam, OldParam, *this); |
3909 | mergeParamDeclTypes(NewParam, OldParam, *this); |
3910 | } |
3911 | |
3912 | if (getLangOpts().CPlusPlus) |
3913 | return MergeCXXFunctionDecl(New, Old, S); |
3914 | |
3915 | // Merge the function types so the we get the composite types for the return |
3916 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl |
3917 | // was visible. |
3918 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); |
3919 | if (!Merged.isNull() && MergeTypeWithOld) |
3920 | New->setType(Merged); |
3921 | |
3922 | return false; |
3923 | } |
3924 | |
3925 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, |
3926 | ObjCMethodDecl *oldMethod) { |
3927 | // Merge the attributes, including deprecated/unavailable |
3928 | AvailabilityMergeKind MergeKind = |
3929 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) |
3930 | ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation |
3931 | : AMK_ProtocolImplementation) |
3932 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration |
3933 | : AMK_Override; |
3934 | |
3935 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); |
3936 | |
3937 | // Merge attributes from the parameters. |
3938 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), |
3939 | oe = oldMethod->param_end(); |
3940 | for (ObjCMethodDecl::param_iterator |
3941 | ni = newMethod->param_begin(), ne = newMethod->param_end(); |
3942 | ni != ne && oi != oe; ++ni, ++oi) |
3943 | mergeParamDeclAttributes(*ni, *oi, *this); |
3944 | |
3945 | CheckObjCMethodOverride(newMethod, oldMethod); |
3946 | } |
3947 | |
3948 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { |
3949 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))((void)0); |
3950 | |
3951 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() |
3952 | ? diag::err_redefinition_different_type |
3953 | : diag::err_redeclaration_different_type) |
3954 | << New->getDeclName() << New->getType() << Old->getType(); |
3955 | |
3956 | diag::kind PrevDiag; |
3957 | SourceLocation OldLocation; |
3958 | std::tie(PrevDiag, OldLocation) |
3959 | = getNoteDiagForInvalidRedeclaration(Old, New); |
3960 | S.Diag(OldLocation, PrevDiag); |
3961 | New->setInvalidDecl(); |
3962 | } |
3963 | |
3964 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and |
3965 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, |
3966 | /// emitting diagnostics as appropriate. |
3967 | /// |
3968 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back |
3969 | /// to here in AddInitializerToDecl. We can't check them before the initializer |
3970 | /// is attached. |
3971 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, |
3972 | bool MergeTypeWithOld) { |
3973 | if (New->isInvalidDecl() || Old->isInvalidDecl()) |
3974 | return; |
3975 | |
3976 | QualType MergedT; |
3977 | if (getLangOpts().CPlusPlus) { |
3978 | if (New->getType()->isUndeducedType()) { |
3979 | // We don't know what the new type is until the initializer is attached. |
3980 | return; |
3981 | } else if (Context.hasSameType(New->getType(), Old->getType())) { |
3982 | // These could still be something that needs exception specs checked. |
3983 | return MergeVarDeclExceptionSpecs(New, Old); |
3984 | } |
3985 | // C++ [basic.link]p10: |
3986 | // [...] the types specified by all declarations referring to a given |
3987 | // object or function shall be identical, except that declarations for an |
3988 | // array object can specify array types that differ by the presence or |
3989 | // absence of a major array bound (8.3.4). |
3990 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { |
3991 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); |
3992 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); |
3993 | |
3994 | // We are merging a variable declaration New into Old. If it has an array |
3995 | // bound, and that bound differs from Old's bound, we should diagnose the |
3996 | // mismatch. |
3997 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { |
3998 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; |
3999 | PrevVD = PrevVD->getPreviousDecl()) { |
4000 | QualType PrevVDTy = PrevVD->getType(); |
4001 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) |
4002 | continue; |
4003 | |
4004 | if (!Context.hasSameType(New->getType(), PrevVDTy)) |
4005 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); |
4006 | } |
4007 | } |
4008 | |
4009 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { |
4010 | if (Context.hasSameType(OldArray->getElementType(), |
4011 | NewArray->getElementType())) |
4012 | MergedT = New->getType(); |
4013 | } |
4014 | // FIXME: Check visibility. New is hidden but has a complete type. If New |
4015 | // has no array bound, it should not inherit one from Old, if Old is not |
4016 | // visible. |
4017 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { |
4018 | if (Context.hasSameType(OldArray->getElementType(), |
4019 | NewArray->getElementType())) |
4020 | MergedT = Old->getType(); |
4021 | } |
4022 | } |
4023 | else if (New->getType()->isObjCObjectPointerType() && |
4024 | Old->getType()->isObjCObjectPointerType()) { |
4025 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), |
4026 | Old->getType()); |
4027 | } |
4028 | } else { |
4029 | // C 6.2.7p2: |
4030 | // All declarations that refer to the same object or function shall have |
4031 | // compatible type. |
4032 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); |
4033 | } |
4034 | if (MergedT.isNull()) { |
4035 | // It's OK if we couldn't merge types if either type is dependent, for a |
4036 | // block-scope variable. In other cases (static data members of class |
4037 | // templates, variable templates, ...), we require the types to be |
4038 | // equivalent. |
4039 | // FIXME: The C++ standard doesn't say anything about this. |
4040 | if ((New->getType()->isDependentType() || |
4041 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { |
4042 | // If the old type was dependent, we can't merge with it, so the new type |
4043 | // becomes dependent for now. We'll reproduce the original type when we |
4044 | // instantiate the TypeSourceInfo for the variable. |
4045 | if (!New->getType()->isDependentType() && MergeTypeWithOld) |
4046 | New->setType(Context.DependentTy); |
4047 | return; |
4048 | } |
4049 | return diagnoseVarDeclTypeMismatch(*this, New, Old); |
4050 | } |
4051 | |
4052 | // Don't actually update the type on the new declaration if the old |
4053 | // declaration was an extern declaration in a different scope. |
4054 | if (MergeTypeWithOld) |
4055 | New->setType(MergedT); |
4056 | } |
4057 | |
4058 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, |
4059 | LookupResult &Previous) { |
4060 | // C11 6.2.7p4: |
4061 | // For an identifier with internal or external linkage declared |
4062 | // in a scope in which a prior declaration of that identifier is |
4063 | // visible, if the prior declaration specifies internal or |
4064 | // external linkage, the type of the identifier at the later |
4065 | // declaration becomes the composite type. |
4066 | // |
4067 | // If the variable isn't visible, we do not merge with its type. |
4068 | if (Previous.isShadowed()) |
4069 | return false; |
4070 | |
4071 | if (S.getLangOpts().CPlusPlus) { |
4072 | // C++11 [dcl.array]p3: |
4073 | // If there is a preceding declaration of the entity in the same |
4074 | // scope in which the bound was specified, an omitted array bound |
4075 | // is taken to be the same as in that earlier declaration. |
4076 | return NewVD->isPreviousDeclInSameBlockScope() || |
4077 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && |
4078 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); |
4079 | } else { |
4080 | // If the old declaration was function-local, don't merge with its |
4081 | // type unless we're in the same function. |
4082 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || |
4083 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); |
4084 | } |
4085 | } |
4086 | |
4087 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name |
4088 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this |
4089 | /// situation, merging decls or emitting diagnostics as appropriate. |
4090 | /// |
4091 | /// Tentative definition rules (C99 6.9.2p2) are checked by |
4092 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative |
4093 | /// definitions here, since the initializer hasn't been attached. |
4094 | /// |
4095 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { |
4096 | // If the new decl is already invalid, don't do any other checking. |
4097 | if (New->isInvalidDecl()) |
4098 | return; |
4099 | |
4100 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) |
4101 | return; |
4102 | |
4103 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); |
4104 | |
4105 | // Verify the old decl was also a variable or variable template. |
4106 | VarDecl *Old = nullptr; |
4107 | VarTemplateDecl *OldTemplate = nullptr; |
4108 | if (Previous.isSingleResult()) { |
4109 | if (NewTemplate) { |
4110 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); |
4111 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; |
4112 | |
4113 | if (auto *Shadow = |
4114 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) |
4115 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) |
4116 | return New->setInvalidDecl(); |
4117 | } else { |
4118 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); |
4119 | |
4120 | if (auto *Shadow = |
4121 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) |
4122 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) |
4123 | return New->setInvalidDecl(); |
4124 | } |
4125 | } |
4126 | if (!Old) { |
4127 | Diag(New->getLocation(), diag::err_redefinition_different_kind) |
4128 | << New->getDeclName(); |
4129 | notePreviousDefinition(Previous.getRepresentativeDecl(), |
4130 | New->getLocation()); |
4131 | return New->setInvalidDecl(); |
4132 | } |
4133 | |
4134 | // If the old declaration was found in an inline namespace and the new |
4135 | // declaration was qualified, update the DeclContext to match. |
4136 | adjustDeclContextForDeclaratorDecl(New, Old); |
4137 | |
4138 | // Ensure the template parameters are compatible. |
4139 | if (NewTemplate && |
4140 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), |
4141 | OldTemplate->getTemplateParameters(), |
4142 | /*Complain=*/true, TPL_TemplateMatch)) |
4143 | return New->setInvalidDecl(); |
4144 | |
4145 | // C++ [class.mem]p1: |
4146 | // A member shall not be declared twice in the member-specification [...] |
4147 | // |
4148 | // Here, we need only consider static data members. |
4149 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { |
4150 | Diag(New->getLocation(), diag::err_duplicate_member) |
4151 | << New->getIdentifier(); |
4152 | Diag(Old->getLocation(), diag::note_previous_declaration); |
4153 | New->setInvalidDecl(); |
4154 | } |
4155 | |
4156 | mergeDeclAttributes(New, Old); |
4157 | // Warn if an already-declared variable is made a weak_import in a subsequent |
4158 | // declaration |
4159 | if (New->hasAttr<WeakImportAttr>() && |
4160 | Old->getStorageClass() == SC_None && |
4161 | !Old->hasAttr<WeakImportAttr>()) { |
4162 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); |
4163 | notePreviousDefinition(Old, New->getLocation()); |
4164 | // Remove weak_import attribute on new declaration. |
4165 | New->dropAttr<WeakImportAttr>(); |
4166 | } |
4167 | |
4168 | if (New->hasAttr<InternalLinkageAttr>() && |
4169 | !Old->hasAttr<InternalLinkageAttr>()) { |
4170 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) |
4171 | << New->getDeclName(); |
4172 | notePreviousDefinition(Old, New->getLocation()); |
4173 | New->dropAttr<InternalLinkageAttr>(); |
4174 | } |
4175 | |
4176 | // Merge the types. |
4177 | VarDecl *MostRecent = Old->getMostRecentDecl(); |
4178 | if (MostRecent != Old) { |
4179 | MergeVarDeclTypes(New, MostRecent, |
4180 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); |
4181 | if (New->isInvalidDecl()) |
4182 | return; |
4183 | } |
4184 | |
4185 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); |
4186 | if (New->isInvalidDecl()) |
4187 | return; |
4188 | |
4189 | diag::kind PrevDiag; |
4190 | SourceLocation OldLocation; |
4191 | std::tie(PrevDiag, OldLocation) = |
4192 | getNoteDiagForInvalidRedeclaration(Old, New); |
4193 | |
4194 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. |
4195 | if (New->getStorageClass() == SC_Static && |
4196 | !New->isStaticDataMember() && |
4197 | Old->hasExternalFormalLinkage()) { |
4198 | if (getLangOpts().MicrosoftExt) { |
4199 | Diag(New->getLocation(), diag::ext_static_non_static) |
4200 | << New->getDeclName(); |
4201 | Diag(OldLocation, PrevDiag); |
4202 | } else { |
4203 | Diag(New->getLocation(), diag::err_static_non_static) |
4204 | << New->getDeclName(); |
4205 | Diag(OldLocation, PrevDiag); |
4206 | return New->setInvalidDecl(); |
4207 | } |
4208 | } |
4209 | // C99 6.2.2p4: |
4210 | // For an identifier declared with the storage-class specifier |
4211 | // extern in a scope in which a prior declaration of that |
4212 | // identifier is visible,23) if the prior declaration specifies |
4213 | // internal or external linkage, the linkage of the identifier at |
4214 | // the later declaration is the same as the linkage specified at |
4215 | // the prior declaration. If no prior declaration is visible, or |
4216 | // if the prior declaration specifies no linkage, then the |
4217 | // identifier has external linkage. |
4218 | if (New->hasExternalStorage() && Old->hasLinkage()) |
4219 | /* Okay */; |
4220 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && |
4221 | !New->isStaticDataMember() && |
4222 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { |
4223 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); |
4224 | Diag(OldLocation, PrevDiag); |
4225 | return New->setInvalidDecl(); |
4226 | } |
4227 | |
4228 | // Check if extern is followed by non-extern and vice-versa. |
4229 | if (New->hasExternalStorage() && |
4230 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { |
4231 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); |
4232 | Diag(OldLocation, PrevDiag); |
4233 | return New->setInvalidDecl(); |
4234 | } |
4235 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && |
4236 | !New->hasExternalStorage()) { |
4237 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); |
4238 | Diag(OldLocation, PrevDiag); |
4239 | return New->setInvalidDecl(); |
4240 | } |
4241 | |
4242 | if (CheckRedeclarationModuleOwnership(New, Old)) |
4243 | return; |
4244 | |
4245 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. |
4246 | |
4247 | // FIXME: The test for external storage here seems wrong? We still |
4248 | // need to check for mismatches. |
4249 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && |
4250 | // Don't complain about out-of-line definitions of static members. |
4251 | !(Old->getLexicalDeclContext()->isRecord() && |
4252 | !New->getLexicalDeclContext()->isRecord())) { |
4253 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); |
4254 | Diag(OldLocation, PrevDiag); |
4255 | return New->setInvalidDecl(); |
4256 | } |
4257 | |
4258 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { |
4259 | if (VarDecl *Def = Old->getDefinition()) { |
4260 | // C++1z [dcl.fcn.spec]p4: |
4261 | // If the definition of a variable appears in a translation unit before |
4262 | // its first declaration as inline, the program is ill-formed. |
4263 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; |
4264 | Diag(Def->getLocation(), diag::note_previous_definition); |
4265 | } |
4266 | } |
4267 | |
4268 | // If this redeclaration makes the variable inline, we may need to add it to |
4269 | // UndefinedButUsed. |
4270 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && |
4271 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) |
4272 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), |
4273 | SourceLocation())); |
4274 | |
4275 | if (New->getTLSKind() != Old->getTLSKind()) { |
4276 | if (!Old->getTLSKind()) { |
4277 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); |
4278 | Diag(OldLocation, PrevDiag); |
4279 | } else if (!New->getTLSKind()) { |
4280 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); |
4281 | Diag(OldLocation, PrevDiag); |
4282 | } else { |
4283 | // Do not allow redeclaration to change the variable between requiring |
4284 | // static and dynamic initialization. |
4285 | // FIXME: GCC allows this, but uses the TLS keyword on the first |
4286 | // declaration to determine the kind. Do we need to be compatible here? |
4287 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) |
4288 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); |
4289 | Diag(OldLocation, PrevDiag); |
4290 | } |
4291 | } |
4292 | |
4293 | // C++ doesn't have tentative definitions, so go right ahead and check here. |
4294 | if (getLangOpts().CPlusPlus && |
4295 | New->isThisDeclarationADefinition() == VarDecl::Definition) { |
4296 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && |
4297 | Old->getCanonicalDecl()->isConstexpr()) { |
4298 | // This definition won't be a definition any more once it's been merged. |
4299 | Diag(New->getLocation(), |
4300 | diag::warn_deprecated_redundant_constexpr_static_def); |
4301 | } else if (VarDecl *Def = Old->getDefinition()) { |
4302 | if (checkVarDeclRedefinition(Def, New)) |
4303 | return; |
4304 | } |
4305 | } |
4306 | |
4307 | if (haveIncompatibleLanguageLinkages(Old, New)) { |
4308 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; |
4309 | Diag(OldLocation, PrevDiag); |
4310 | New->setInvalidDecl(); |
4311 | return; |
4312 | } |
4313 | |
4314 | // Merge "used" flag. |
4315 | if (Old->getMostRecentDecl()->isUsed(false)) |
4316 | New->setIsUsed(); |
4317 | |
4318 | // Keep a chain of previous declarations. |
4319 | New->setPreviousDecl(Old); |
4320 | if (NewTemplate) |
4321 | NewTemplate->setPreviousDecl(OldTemplate); |
4322 | |
4323 | // Inherit access appropriately. |
4324 | New->setAccess(Old->getAccess()); |
4325 | if (NewTemplate) |
4326 | NewTemplate->setAccess(New->getAccess()); |
4327 | |
4328 | if (Old->isInline()) |
4329 | New->setImplicitlyInline(); |
4330 | } |
4331 | |
4332 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { |
4333 | SourceManager &SrcMgr = getSourceManager(); |
4334 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); |
4335 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); |
4336 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); |
4337 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); |
4338 | auto &HSI = PP.getHeaderSearchInfo(); |
4339 | StringRef HdrFilename = |
4340 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); |
4341 | |
4342 | auto noteFromModuleOrInclude = [&](Module *Mod, |
4343 | SourceLocation IncLoc) -> bool { |
4344 | // Redefinition errors with modules are common with non modular mapped |
4345 | // headers, example: a non-modular header H in module A that also gets |
4346 | // included directly in a TU. Pointing twice to the same header/definition |
4347 | // is confusing, try to get better diagnostics when modules is on. |
4348 | if (IncLoc.isValid()) { |
4349 | if (Mod) { |
4350 | Diag(IncLoc, diag::note_redefinition_modules_same_file) |
4351 | << HdrFilename.str() << Mod->getFullModuleName(); |
4352 | if (!Mod->DefinitionLoc.isInvalid()) |
4353 | Diag(Mod->DefinitionLoc, diag::note_defined_here) |
4354 | << Mod->getFullModuleName(); |
4355 | } else { |
4356 | Diag(IncLoc, diag::note_redefinition_include_same_file) |
4357 | << HdrFilename.str(); |
4358 | } |
4359 | return true; |
4360 | } |
4361 | |
4362 | return false; |
4363 | }; |
4364 | |
4365 | // Is it the same file and same offset? Provide more information on why |
4366 | // this leads to a redefinition error. |
4367 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { |
4368 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); |
4369 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); |
4370 | bool EmittedDiag = |
4371 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); |
4372 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); |
4373 | |
4374 | // If the header has no guards, emit a note suggesting one. |
4375 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) |
4376 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); |
4377 | |
4378 | if (EmittedDiag) |
4379 | return; |
4380 | } |
4381 | |
4382 | // Redefinition coming from different files or couldn't do better above. |
4383 | if (Old->getLocation().isValid()) |
4384 | Diag(Old->getLocation(), diag::note_previous_definition); |
4385 | } |
4386 | |
4387 | /// We've just determined that \p Old and \p New both appear to be definitions |
4388 | /// of the same variable. Either diagnose or fix the problem. |
4389 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { |
4390 | if (!hasVisibleDefinition(Old) && |
4391 | (New->getFormalLinkage() == InternalLinkage || |
4392 | New->isInline() || |
4393 | New->getDescribedVarTemplate() || |
4394 | New->getNumTemplateParameterLists() || |
4395 | New->getDeclContext()->isDependentContext())) { |
4396 | // The previous definition is hidden, and multiple definitions are |
4397 | // permitted (in separate TUs). Demote this to a declaration. |
4398 | New->demoteThisDefinitionToDeclaration(); |
4399 | |
4400 | // Make the canonical definition visible. |
4401 | if (auto *OldTD = Old->getDescribedVarTemplate()) |
4402 | makeMergedDefinitionVisible(OldTD); |
4403 | makeMergedDefinitionVisible(Old); |
4404 | return false; |
4405 | } else { |
4406 | Diag(New->getLocation(), diag::err_redefinition) << New; |
4407 | notePreviousDefinition(Old, New->getLocation()); |
4408 | New->setInvalidDecl(); |
4409 | return true; |
4410 | } |
4411 | } |
4412 | |
4413 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with |
4414 | /// no declarator (e.g. "struct foo;") is parsed. |
4415 | Decl * |
4416 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
4417 | RecordDecl *&AnonRecord) { |
4418 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, |
4419 | AnonRecord); |
4420 | } |
4421 | |
4422 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to |
4423 | // disambiguate entities defined in different scopes. |
4424 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks |
4425 | // compatibility. |
4426 | // We will pick our mangling number depending on which version of MSVC is being |
4427 | // targeted. |
4428 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { |
4429 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) |
4430 | ? S->getMSCurManglingNumber() |
4431 | : S->getMSLastManglingNumber(); |
4432 | } |
4433 | |
4434 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { |
4435 | if (!Context.getLangOpts().CPlusPlus) |
4436 | return; |
4437 | |
4438 | if (isa<CXXRecordDecl>(Tag->getParent())) { |
4439 | // If this tag is the direct child of a class, number it if |
4440 | // it is anonymous. |
4441 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) |
4442 | return; |
4443 | MangleNumberingContext &MCtx = |
4444 | Context.getManglingNumberContext(Tag->getParent()); |
4445 | Context.setManglingNumber( |
4446 | Tag, MCtx.getManglingNumber( |
4447 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); |
4448 | return; |
4449 | } |
4450 | |
4451 | // If this tag isn't a direct child of a class, number it if it is local. |
4452 | MangleNumberingContext *MCtx; |
4453 | Decl *ManglingContextDecl; |
4454 | std::tie(MCtx, ManglingContextDecl) = |
4455 | getCurrentMangleNumberContext(Tag->getDeclContext()); |
4456 | if (MCtx) { |
4457 | Context.setManglingNumber( |
4458 | Tag, MCtx->getManglingNumber( |
4459 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); |
4460 | } |
4461 | } |
4462 | |
4463 | namespace { |
4464 | struct NonCLikeKind { |
4465 | enum { |
4466 | None, |
4467 | BaseClass, |
4468 | DefaultMemberInit, |
4469 | Lambda, |
4470 | Friend, |
4471 | OtherMember, |
4472 | Invalid, |
4473 | } Kind = None; |
4474 | SourceRange Range; |
4475 | |
4476 | explicit operator bool() { return Kind != None; } |
4477 | }; |
4478 | } |
4479 | |
4480 | /// Determine whether a class is C-like, according to the rules of C++ |
4481 | /// [dcl.typedef] for anonymous classes with typedef names for linkage. |
4482 | static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { |
4483 | if (RD->isInvalidDecl()) |
4484 | return {NonCLikeKind::Invalid, {}}; |
4485 | |
4486 | // C++ [dcl.typedef]p9: [P1766R1] |
4487 | // An unnamed class with a typedef name for linkage purposes shall not |
4488 | // |
4489 | // -- have any base classes |
4490 | if (RD->getNumBases()) |
4491 | return {NonCLikeKind::BaseClass, |
4492 | SourceRange(RD->bases_begin()->getBeginLoc(), |
4493 | RD->bases_end()[-1].getEndLoc())}; |
4494 | bool Invalid = false; |
4495 | for (Decl *D : RD->decls()) { |
4496 | // Don't complain about things we already diagnosed. |
4497 | if (D->isInvalidDecl()) { |
4498 | Invalid = true; |
4499 | continue; |
4500 | } |
4501 | |
4502 | // -- have any [...] default member initializers |
4503 | if (auto *FD = dyn_cast<FieldDecl>(D)) { |
4504 | if (FD->hasInClassInitializer()) { |
4505 | auto *Init = FD->getInClassInitializer(); |
4506 | return {NonCLikeKind::DefaultMemberInit, |
4507 | Init ? Init->getSourceRange() : D->getSourceRange()}; |
4508 | } |
4509 | continue; |
4510 | } |
4511 | |
4512 | // FIXME: We don't allow friend declarations. This violates the wording of |
4513 | // P1766, but not the intent. |
4514 | if (isa<FriendDecl>(D)) |
4515 | return {NonCLikeKind::Friend, D->getSourceRange()}; |
4516 | |
4517 | // -- declare any members other than non-static data members, member |
4518 | // enumerations, or member classes, |
4519 | if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || |
4520 | isa<EnumDecl>(D)) |
4521 | continue; |
4522 | auto *MemberRD = dyn_cast<CXXRecordDecl>(D); |
4523 | if (!MemberRD) { |
4524 | if (D->isImplicit()) |
4525 | continue; |
4526 | return {NonCLikeKind::OtherMember, D->getSourceRange()}; |
4527 | } |
4528 | |
4529 | // -- contain a lambda-expression, |
4530 | if (MemberRD->isLambda()) |
4531 | return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; |
4532 | |
4533 | // and all member classes shall also satisfy these requirements |
4534 | // (recursively). |
4535 | if (MemberRD->isThisDeclarationADefinition()) { |
4536 | if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) |
4537 | return Kind; |
4538 | } |
4539 | } |
4540 | |
4541 | return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; |
4542 | } |
4543 | |
4544 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, |
4545 | TypedefNameDecl *NewTD) { |
4546 | if (TagFromDeclSpec->isInvalidDecl()) |
4547 | return; |
4548 | |
4549 | // Do nothing if the tag already has a name for linkage purposes. |
4550 | if (TagFromDeclSpec->hasNameForLinkage()) |
4551 | return; |
4552 | |
4553 | // A well-formed anonymous tag must always be a TUK_Definition. |
4554 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((void)0); |
4555 | |
4556 | // The type must match the tag exactly; no qualifiers allowed. |
4557 | if (!Context.hasSameType(NewTD->getUnderlyingType(), |
4558 | Context.getTagDeclType(TagFromDeclSpec))) { |
4559 | if (getLangOpts().CPlusPlus) |
4560 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); |
4561 | return; |
4562 | } |
4563 | |
4564 | // C++ [dcl.typedef]p9: [P1766R1, applied as DR] |
4565 | // An unnamed class with a typedef name for linkage purposes shall [be |
4566 | // C-like]. |
4567 | // |
4568 | // FIXME: Also diagnose if we've already computed the linkage. That ideally |
4569 | // shouldn't happen, but there are constructs that the language rule doesn't |
4570 | // disallow for which we can't reasonably avoid computing linkage early. |
4571 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); |
4572 | NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) |
4573 | : NonCLikeKind(); |
4574 | bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); |
4575 | if (NonCLike || ChangesLinkage) { |
4576 | if (NonCLike.Kind == NonCLikeKind::Invalid) |
4577 | return; |
4578 | |
4579 | unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; |
4580 | if (ChangesLinkage) { |
4581 | // If the linkage changes, we can't accept this as an extension. |
4582 | if (NonCLike.Kind == NonCLikeKind::None) |
4583 | DiagID = diag::err_typedef_changes_linkage; |
4584 | else |
4585 | DiagID = diag::err_non_c_like_anon_struct_in_typedef; |
4586 | } |
4587 | |
4588 | SourceLocation FixitLoc = |
4589 | getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); |
4590 | llvm::SmallString<40> TextToInsert; |
4591 | TextToInsert += ' '; |
4592 | TextToInsert += NewTD->getIdentifier()->getName(); |
4593 | |
4594 | Diag(FixitLoc, DiagID) |
4595 | << isa<TypeAliasDecl>(NewTD) |
4596 | << FixItHint::CreateInsertion(FixitLoc, TextToInsert); |
4597 | if (NonCLike.Kind != NonCLikeKind::None) { |
4598 | Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) |
4599 | << NonCLike.Kind - 1 << NonCLike.Range; |
4600 | } |
4601 | Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) |
4602 | << NewTD << isa<TypeAliasDecl>(NewTD); |
4603 | |
4604 | if (ChangesLinkage) |
4605 | return; |
4606 | } |
4607 | |
4608 | // Otherwise, set this as the anon-decl typedef for the tag. |
4609 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); |
4610 | } |
4611 | |
4612 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { |
4613 | switch (T) { |
4614 | case DeclSpec::TST_class: |
4615 | return 0; |
4616 | case DeclSpec::TST_struct: |
4617 | return 1; |
4618 | case DeclSpec::TST_interface: |
4619 | return 2; |
4620 | case DeclSpec::TST_union: |
4621 | return 3; |
4622 | case DeclSpec::TST_enum: |
4623 | return 4; |
4624 | default: |
4625 | llvm_unreachable("unexpected type specifier")__builtin_unreachable(); |
4626 | } |
4627 | } |
4628 | |
4629 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with |
4630 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template |
4631 | /// parameters to cope with template friend declarations. |
4632 | Decl * |
4633 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
4634 | MultiTemplateParamsArg TemplateParams, |
4635 | bool IsExplicitInstantiation, |
4636 | RecordDecl *&AnonRecord) { |
4637 | Decl *TagD = nullptr; |
4638 | TagDecl *Tag = nullptr; |
4639 | if (DS.getTypeSpecType() == DeclSpec::TST_class || |
4640 | DS.getTypeSpecType() == DeclSpec::TST_struct || |
4641 | DS.getTypeSpecType() == DeclSpec::TST_interface || |
4642 | DS.getTypeSpecType() == DeclSpec::TST_union || |
4643 | DS.getTypeSpecType() == DeclSpec::TST_enum) { |
4644 | TagD = DS.getRepAsDecl(); |
4645 | |
4646 | if (!TagD) // We probably had an error |
4647 | return nullptr; |
4648 | |
4649 | // Note that the above type specs guarantee that the |
4650 | // type rep is a Decl, whereas in many of the others |
4651 | // it's a Type. |
4652 | if (isa<TagDecl>(TagD)) |
4653 | Tag = cast<TagDecl>(TagD); |
4654 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) |
4655 | Tag = CTD->getTemplatedDecl(); |
4656 | } |
4657 | |
4658 | if (Tag) { |
4659 | handleTagNumbering(Tag, S); |
4660 | Tag->setFreeStanding(); |
4661 | if (Tag->isInvalidDecl()) |
4662 | return Tag; |
4663 | } |
4664 | |
4665 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { |
4666 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object |
4667 | // or incomplete types shall not be restrict-qualified." |
4668 | if (TypeQuals & DeclSpec::TQ_restrict) |
4669 | Diag(DS.getRestrictSpecLoc(), |
4670 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) |
4671 | << DS.getSourceRange(); |
4672 | } |
4673 | |
4674 | if (DS.isInlineSpecified()) |
4675 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) |
4676 | << getLangOpts().CPlusPlus17; |
4677 | |
4678 | if (DS.hasConstexprSpecifier()) { |
4679 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations |
4680 | // and definitions of functions and variables. |
4681 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to |
4682 | // the declaration of a function or function template |
4683 | if (Tag) |
4684 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) |
4685 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) |
4686 | << static_cast<int>(DS.getConstexprSpecifier()); |
4687 | else |
4688 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) |
4689 | << static_cast<int>(DS.getConstexprSpecifier()); |
4690 | // Don't emit warnings after this error. |
4691 | return TagD; |
4692 | } |
4693 | |
4694 | DiagnoseFunctionSpecifiers(DS); |
4695 | |
4696 | if (DS.isFriendSpecified()) { |
4697 | // If we're dealing with a decl but not a TagDecl, assume that |
4698 | // whatever routines created it handled the friendship aspect. |
4699 | if (TagD && !Tag) |
4700 | return nullptr; |
4701 | return ActOnFriendTypeDecl(S, DS, TemplateParams); |
4702 | } |
4703 | |
4704 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); |
4705 | bool IsExplicitSpecialization = |
4706 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; |
4707 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && |
4708 | !IsExplicitInstantiation && !IsExplicitSpecialization && |
4709 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { |
4710 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a |
4711 | // nested-name-specifier unless it is an explicit instantiation |
4712 | // or an explicit specialization. |
4713 | // |
4714 | // FIXME: We allow class template partial specializations here too, per the |
4715 | // obvious intent of DR1819. |
4716 | // |
4717 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. |
4718 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) |
4719 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); |
4720 | return nullptr; |
4721 | } |
4722 | |
4723 | // Track whether this decl-specifier declares anything. |
4724 | bool DeclaresAnything = true; |
4725 | |
4726 | // Handle anonymous struct definitions. |
4727 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { |
4728 | if (!Record->getDeclName() && Record->isCompleteDefinition() && |
4729 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { |
4730 | if (getLangOpts().CPlusPlus || |
4731 | Record->getDeclContext()->isRecord()) { |
4732 | // If CurContext is a DeclContext that can contain statements, |
4733 | // RecursiveASTVisitor won't visit the decls that |
4734 | // BuildAnonymousStructOrUnion() will put into CurContext. |
4735 | // Also store them here so that they can be part of the |
4736 | // DeclStmt that gets created in this case. |
4737 | // FIXME: Also return the IndirectFieldDecls created by |
4738 | // BuildAnonymousStructOr union, for the same reason? |
4739 | if (CurContext->isFunctionOrMethod()) |
4740 | AnonRecord = Record; |
4741 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, |
4742 | Context.getPrintingPolicy()); |
4743 | } |
4744 | |
4745 | DeclaresAnything = false; |
4746 | } |
4747 | } |
4748 | |
4749 | // C11 6.7.2.1p2: |
4750 | // A struct-declaration that does not declare an anonymous structure or |
4751 | // anonymous union shall contain a struct-declarator-list. |
4752 | // |
4753 | // This rule also existed in C89 and C99; the grammar for struct-declaration |
4754 | // did not permit a struct-declaration without a struct-declarator-list. |
4755 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && |
4756 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { |
4757 | // Check for Microsoft C extension: anonymous struct/union member. |
4758 | // Handle 2 kinds of anonymous struct/union: |
4759 | // struct STRUCT; |
4760 | // union UNION; |
4761 | // and |
4762 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. |
4763 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. |
4764 | if ((Tag && Tag->getDeclName()) || |
4765 | DS.getTypeSpecType() == DeclSpec::TST_typename) { |
4766 | RecordDecl *Record = nullptr; |
4767 | if (Tag) |
4768 | Record = dyn_cast<RecordDecl>(Tag); |
4769 | else if (const RecordType *RT = |
4770 | DS.getRepAsType().get()->getAsStructureType()) |
4771 | Record = RT->getDecl(); |
4772 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) |
4773 | Record = UT->getDecl(); |
4774 | |
4775 | if (Record && getLangOpts().MicrosoftExt) { |
4776 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) |
4777 | << Record->isUnion() << DS.getSourceRange(); |
4778 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); |
4779 | } |
4780 | |
4781 | DeclaresAnything = false; |
4782 | } |
4783 | } |
4784 | |
4785 | // Skip all the checks below if we have a type error. |
4786 | if (DS.getTypeSpecType() == DeclSpec::TST_error || |
4787 | (TagD && TagD->isInvalidDecl())) |
4788 | return TagD; |
4789 | |
4790 | if (getLangOpts().CPlusPlus && |
4791 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) |
4792 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) |
4793 | if (Enum->enumerator_begin() == Enum->enumerator_end() && |
4794 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) |
4795 | DeclaresAnything = false; |
4796 | |
4797 | if (!DS.isMissingDeclaratorOk()) { |
4798 | // Customize diagnostic for a typedef missing a name. |
4799 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) |
4800 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) |
4801 | << DS.getSourceRange(); |
4802 | else |
4803 | DeclaresAnything = false; |
4804 | } |
4805 | |
4806 | if (DS.isModulePrivateSpecified() && |
4807 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) |
4808 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) |
4809 | << Tag->getTagKind() |
4810 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); |
4811 | |
4812 | ActOnDocumentableDecl(TagD); |
4813 | |
4814 | // C 6.7/2: |
4815 | // A declaration [...] shall declare at least a declarator [...], a tag, |
4816 | // or the members of an enumeration. |
4817 | // C++ [dcl.dcl]p3: |
4818 | // [If there are no declarators], and except for the declaration of an |
4819 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more |
4820 | // names into the program, or shall redeclare a name introduced by a |
4821 | // previous declaration. |
4822 | if (!DeclaresAnything) { |
4823 | // In C, we allow this as a (popular) extension / bug. Don't bother |
4824 | // producing further diagnostics for redundant qualifiers after this. |
4825 | Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) |
4826 | ? diag::err_no_declarators |
4827 | : diag::ext_no_declarators) |
4828 | << DS.getSourceRange(); |
4829 | return TagD; |
4830 | } |
4831 | |
4832 | // C++ [dcl.stc]p1: |
4833 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the |
4834 | // init-declarator-list of the declaration shall not be empty. |
4835 | // C++ [dcl.fct.spec]p1: |
4836 | // If a cv-qualifier appears in a decl-specifier-seq, the |
4837 | // init-declarator-list of the declaration shall not be empty. |
4838 | // |
4839 | // Spurious qualifiers here appear to be valid in C. |
4840 | unsigned DiagID = diag::warn_standalone_specifier; |
4841 | if (getLangOpts().CPlusPlus) |
4842 | DiagID = diag::ext_standalone_specifier; |
4843 | |
4844 | // Note that a linkage-specification sets a storage class, but |
4845 | // 'extern "C" struct foo;' is actually valid and not theoretically |
4846 | // useless. |
4847 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { |
4848 | if (SCS == DeclSpec::SCS_mutable) |
4849 | // Since mutable is not a viable storage class specifier in C, there is |
4850 | // no reason to treat it as an extension. Instead, diagnose as an error. |
4851 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); |
4852 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) |
4853 | Diag(DS.getStorageClassSpecLoc(), DiagID) |
4854 | << DeclSpec::getSpecifierName(SCS); |
4855 | } |
4856 | |
4857 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) |
4858 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) |
4859 | << DeclSpec::getSpecifierName(TSCS); |
4860 | if (DS.getTypeQualifiers()) { |
4861 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
4862 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; |
4863 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
4864 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; |
4865 | // Restrict is covered above. |
4866 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
4867 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; |
4868 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
4869 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; |
4870 | } |
4871 | |
4872 | // Warn about ignored type attributes, for example: |
4873 | // __attribute__((aligned)) struct A; |
4874 | // Attributes should be placed after tag to apply to type declaration. |
4875 | if (!DS.getAttributes().empty()) { |
4876 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); |
4877 | if (TypeSpecType == DeclSpec::TST_class || |
4878 | TypeSpecType == DeclSpec::TST_struct || |
4879 | TypeSpecType == DeclSpec::TST_interface || |
4880 | TypeSpecType == DeclSpec::TST_union || |
4881 | TypeSpecType == DeclSpec::TST_enum) { |
4882 | for (const ParsedAttr &AL : DS.getAttributes()) |
4883 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) |
4884 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); |
4885 | } |
4886 | } |
4887 | |
4888 | return TagD; |
4889 | } |
4890 | |
4891 | /// We are trying to inject an anonymous member into the given scope; |
4892 | /// check if there's an existing declaration that can't be overloaded. |
4893 | /// |
4894 | /// \return true if this is a forbidden redeclaration |
4895 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, |
4896 | Scope *S, |
4897 | DeclContext *Owner, |
4898 | DeclarationName Name, |
4899 | SourceLocation NameLoc, |
4900 | bool IsUnion) { |
4901 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, |
4902 | Sema::ForVisibleRedeclaration); |
4903 | if (!SemaRef.LookupName(R, S)) return false; |
4904 | |
4905 | // Pick a representative declaration. |
4906 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); |
4907 | assert(PrevDecl && "Expected a non-null Decl")((void)0); |
4908 | |
4909 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) |
4910 | return false; |
4911 | |
4912 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) |
4913 | << IsUnion << Name; |
4914 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); |
4915 | |
4916 | return true; |
4917 | } |
4918 | |
4919 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the |
4920 | /// anonymous struct or union AnonRecord into the owning context Owner |
4921 | /// and scope S. This routine will be invoked just after we realize |
4922 | /// that an unnamed union or struct is actually an anonymous union or |
4923 | /// struct, e.g., |
4924 | /// |
4925 | /// @code |
4926 | /// union { |
4927 | /// int i; |
4928 | /// float f; |
4929 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and |
4930 | /// // f into the surrounding scope.x |
4931 | /// @endcode |
4932 | /// |
4933 | /// This routine is recursive, injecting the names of nested anonymous |
4934 | /// structs/unions into the owning context and scope as well. |
4935 | static bool |
4936 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, |
4937 | RecordDecl *AnonRecord, AccessSpecifier AS, |
4938 | SmallVectorImpl<NamedDecl *> &Chaining) { |
4939 | bool Invalid = false; |
4940 | |
4941 | // Look every FieldDecl and IndirectFieldDecl with a name. |
4942 | for (auto *D : AnonRecord->decls()) { |
4943 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && |
4944 | cast<NamedDecl>(D)->getDeclName()) { |
4945 | ValueDecl *VD = cast<ValueDecl>(D); |
4946 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), |
4947 | VD->getLocation(), |
4948 | AnonRecord->isUnion())) { |
4949 | // C++ [class.union]p2: |
4950 | // The names of the members of an anonymous union shall be |
4951 | // distinct from the names of any other entity in the |
4952 | // scope in which the anonymous union is declared. |
4953 | Invalid = true; |
4954 | } else { |
4955 | // C++ [class.union]p2: |
4956 | // For the purpose of name lookup, after the anonymous union |
4957 | // definition, the members of the anonymous union are |
4958 | // considered to have been defined in the scope in which the |
4959 | // anonymous union is declared. |
4960 | unsigned OldChainingSize = Chaining.size(); |
4961 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) |
4962 | Chaining.append(IF->chain_begin(), IF->chain_end()); |
4963 | else |
4964 | Chaining.push_back(VD); |
4965 | |
4966 | assert(Chaining.size() >= 2)((void)0); |
4967 | NamedDecl **NamedChain = |
4968 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; |
4969 | for (unsigned i = 0; i < Chaining.size(); i++) |
4970 | NamedChain[i] = Chaining[i]; |
4971 | |
4972 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( |
4973 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), |
4974 | VD->getType(), {NamedChain, Chaining.size()}); |
4975 | |
4976 | for (const auto *Attr : VD->attrs()) |
4977 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); |
4978 | |
4979 | IndirectField->setAccess(AS); |
4980 | IndirectField->setImplicit(); |
4981 | SemaRef.PushOnScopeChains(IndirectField, S); |
4982 | |
4983 | // That includes picking up the appropriate access specifier. |
4984 | if (AS != AS_none) IndirectField->setAccess(AS); |
4985 | |
4986 | Chaining.resize(OldChainingSize); |
4987 | } |
4988 | } |
4989 | } |
4990 | |
4991 | return Invalid; |
4992 | } |
4993 | |
4994 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to |
4995 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: |
4996 | /// illegal input values are mapped to SC_None. |
4997 | static StorageClass |
4998 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { |
4999 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); |
5000 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&((void)0) |
5001 | "Parser allowed 'typedef' as storage class VarDecl.")((void)0); |
5002 | switch (StorageClassSpec) { |
5003 | case DeclSpec::SCS_unspecified: return SC_None; |
5004 | case DeclSpec::SCS_extern: |
5005 | if (DS.isExternInLinkageSpec()) |
5006 | return SC_None; |
5007 | return SC_Extern; |
5008 | case DeclSpec::SCS_static: return SC_Static; |
5009 | case DeclSpec::SCS_auto: return SC_Auto; |
5010 | case DeclSpec::SCS_register: return SC_Register; |
5011 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; |
5012 | // Illegal SCSs map to None: error reporting is up to the caller. |
5013 | case DeclSpec::SCS_mutable: // Fall through. |
5014 | case DeclSpec::SCS_typedef: return SC_None; |
5015 | } |
5016 | llvm_unreachable("unknown storage class specifier")__builtin_unreachable(); |
5017 | } |
5018 | |
5019 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { |
5020 | assert(Record->hasInClassInitializer())((void)0); |
5021 | |
5022 | for (const auto *I : Record->decls()) { |
5023 | const auto *FD = dyn_cast<FieldDecl>(I); |
5024 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) |
5025 | FD = IFD->getAnonField(); |
5026 | if (FD && FD->hasInClassInitializer()) |
5027 | return FD->getLocation(); |
5028 | } |
5029 | |
5030 | llvm_unreachable("couldn't find in-class initializer")__builtin_unreachable(); |
5031 | } |
5032 | |
5033 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, |
5034 | SourceLocation DefaultInitLoc) { |
5035 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) |
5036 | return; |
5037 | |
5038 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); |
5039 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; |
5040 | } |
5041 | |
5042 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, |
5043 | CXXRecordDecl *AnonUnion) { |
5044 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) |
5045 | return; |
5046 | |
5047 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); |
5048 | } |
5049 | |
5050 | /// BuildAnonymousStructOrUnion - Handle the declaration of an |
5051 | /// anonymous structure or union. Anonymous unions are a C++ feature |
5052 | /// (C++ [class.union]) and a C11 feature; anonymous structures |
5053 | /// are a C11 feature and GNU C++ extension. |
5054 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, |
5055 | AccessSpecifier AS, |
5056 | RecordDecl *Record, |
5057 | const PrintingPolicy &Policy) { |
5058 | DeclContext *Owner = Record->getDeclContext(); |
5059 | |
5060 | // Diagnose whether this anonymous struct/union is an extension. |
5061 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) |
5062 | Diag(Record->getLocation(), diag::ext_anonymous_union); |
5063 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) |
5064 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); |
5065 | else if (!Record->isUnion() && !getLangOpts().C11) |
5066 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); |
5067 | |
5068 | // C and C++ require different kinds of checks for anonymous |
5069 | // structs/unions. |
5070 | bool Invalid = false; |
5071 | if (getLangOpts().CPlusPlus) { |
5072 | const char *PrevSpec = nullptr; |
5073 | if (Record->isUnion()) { |
5074 | // C++ [class.union]p6: |
5075 | // C++17 [class.union.anon]p2: |
5076 | // Anonymous unions declared in a named namespace or in the |
5077 | // global namespace shall be declared static. |
5078 | unsigned DiagID; |
5079 | DeclContext *OwnerScope = Owner->getRedeclContext(); |
5080 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && |
5081 | (OwnerScope->isTranslationUnit() || |
5082 | (OwnerScope->isNamespace() && |
5083 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { |
5084 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) |
5085 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); |
5086 | |
5087 | // Recover by adding 'static'. |
5088 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), |
5089 | PrevSpec, DiagID, Policy); |
5090 | } |
5091 | // C++ [class.union]p6: |
5092 | // A storage class is not allowed in a declaration of an |
5093 | // anonymous union in a class scope. |
5094 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && |
5095 | isa<RecordDecl>(Owner)) { |
5096 | Diag(DS.getStorageClassSpecLoc(), |
5097 | diag::err_anonymous_union_with_storage_spec) |
5098 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); |
5099 | |
5100 | // Recover by removing the storage specifier. |
5101 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, |
5102 | SourceLocation(), |
5103 | PrevSpec, DiagID, Context.getPrintingPolicy()); |
5104 | } |
5105 | } |
5106 | |
5107 | // Ignore const/volatile/restrict qualifiers. |
5108 | if (DS.getTypeQualifiers()) { |
5109 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
5110 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) |
5111 | << Record->isUnion() << "const" |
5112 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); |
5113 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
5114 | Diag(DS.getVolatileSpecLoc(), |
5115 | diag::ext_anonymous_struct_union_qualified) |
5116 | << Record->isUnion() << "volatile" |
5117 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); |
5118 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) |
5119 | Diag(DS.getRestrictSpecLoc(), |
5120 | diag::ext_anonymous_struct_union_qualified) |
5121 | << Record->isUnion() << "restrict" |
5122 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); |
5123 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
5124 | Diag(DS.getAtomicSpecLoc(), |
5125 | diag::ext_anonymous_struct_union_qualified) |
5126 | << Record->isUnion() << "_Atomic" |
5127 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); |
5128 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
5129 | Diag(DS.getUnalignedSpecLoc(), |
5130 | diag::ext_anonymous_struct_union_qualified) |
5131 | << Record->isUnion() << "__unaligned" |
5132 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); |
5133 | |
5134 | DS.ClearTypeQualifiers(); |
5135 | } |
5136 | |
5137 | // C++ [class.union]p2: |
5138 | // The member-specification of an anonymous union shall only |
5139 | // define non-static data members. [Note: nested types and |
5140 | // functions cannot be declared within an anonymous union. ] |
5141 | for (auto *Mem : Record->decls()) { |
5142 | // Ignore invalid declarations; we already diagnosed them. |
5143 | if (Mem->isInvalidDecl()) |
5144 | continue; |
5145 | |
5146 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { |
5147 | // C++ [class.union]p3: |
5148 | // An anonymous union shall not have private or protected |
5149 | // members (clause 11). |
5150 | assert(FD->getAccess() != AS_none)((void)0); |
5151 | if (FD->getAccess() != AS_public) { |
5152 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) |
5153 | << Record->isUnion() << (FD->getAccess() == AS_protected); |
5154 | Invalid = true; |
5155 | } |
5156 | |
5157 | // C++ [class.union]p1 |
5158 | // An object of a class with a non-trivial constructor, a non-trivial |
5159 | // copy constructor, a non-trivial destructor, or a non-trivial copy |
5160 | // assignment operator cannot be a member of a union, nor can an |
5161 | // array of such objects. |
5162 | if (CheckNontrivialField(FD)) |
5163 | Invalid = true; |
5164 | } else if (Mem->isImplicit()) { |
5165 | // Any implicit members are fine. |
5166 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { |
5167 | // This is a type that showed up in an |
5168 | // elaborated-type-specifier inside the anonymous struct or |
5169 | // union, but which actually declares a type outside of the |
5170 | // anonymous struct or union. It's okay. |
5171 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { |
5172 | if (!MemRecord->isAnonymousStructOrUnion() && |
5173 | MemRecord->getDeclName()) { |
5174 | // Visual C++ allows type definition in anonymous struct or union. |
5175 | if (getLangOpts().MicrosoftExt) |
5176 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) |
5177 | << Record->isUnion(); |
5178 | else { |
5179 | // This is a nested type declaration. |
5180 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) |
5181 | << Record->isUnion(); |
5182 | Invalid = true; |
5183 | } |
5184 | } else { |
5185 | // This is an anonymous type definition within another anonymous type. |
5186 | // This is a popular extension, provided by Plan9, MSVC and GCC, but |
5187 | // not part of standard C++. |
5188 | Diag(MemRecord->getLocation(), |
5189 | diag::ext_anonymous_record_with_anonymous_type) |
5190 | << Record->isUnion(); |
5191 | } |
5192 | } else if (isa<AccessSpecDecl>(Mem)) { |
5193 | // Any access specifier is fine. |
5194 | } else if (isa<StaticAssertDecl>(Mem)) { |
5195 | // In C++1z, static_assert declarations are also fine. |
5196 | } else { |
5197 | // We have something that isn't a non-static data |
5198 | // member. Complain about it. |
5199 | unsigned DK = diag::err_anonymous_record_bad_member; |
5200 | if (isa<TypeDecl>(Mem)) |
5201 | DK = diag::err_anonymous_record_with_type; |
5202 | else if (isa<FunctionDecl>(Mem)) |
5203 | DK = diag::err_anonymous_record_with_function; |
5204 | else if (isa<VarDecl>(Mem)) |
5205 | DK = diag::err_anonymous_record_with_static; |
5206 | |
5207 | // Visual C++ allows type definition in anonymous struct or union. |
5208 | if (getLangOpts().MicrosoftExt && |
5209 | DK == diag::err_anonymous_record_with_type) |
5210 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) |
5211 | << Record->isUnion(); |
5212 | else { |
5213 | Diag(Mem->getLocation(), DK) << Record->isUnion(); |
5214 | Invalid = true; |
5215 | } |
5216 | } |
5217 | } |
5218 | |
5219 | // C++11 [class.union]p8 (DR1460): |
5220 | // At most one variant member of a union may have a |
5221 | // brace-or-equal-initializer. |
5222 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && |
5223 | Owner->isRecord()) |
5224 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), |
5225 | cast<CXXRecordDecl>(Record)); |
5226 | } |
5227 | |
5228 | if (!Record->isUnion() && !Owner->isRecord()) { |
5229 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) |
5230 | << getLangOpts().CPlusPlus; |
5231 | Invalid = true; |
5232 | } |
5233 | |
5234 | // C++ [dcl.dcl]p3: |
5235 | // [If there are no declarators], and except for the declaration of an |
5236 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more |
5237 | // names into the program |
5238 | // C++ [class.mem]p2: |
5239 | // each such member-declaration shall either declare at least one member |
5240 | // name of the class or declare at least one unnamed bit-field |
5241 | // |
5242 | // For C this is an error even for a named struct, and is diagnosed elsewhere. |
5243 | if (getLangOpts().CPlusPlus && Record->field_empty()) |
5244 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); |
5245 | |
5246 | // Mock up a declarator. |
5247 | Declarator Dc(DS, DeclaratorContext::Member); |
5248 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); |
5249 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")((void)0); |
5250 | |
5251 | // Create a declaration for this anonymous struct/union. |
5252 | NamedDecl *Anon = nullptr; |
5253 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { |
5254 | Anon = FieldDecl::Create( |
5255 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), |
5256 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, |
5257 | /*BitWidth=*/nullptr, /*Mutable=*/false, |
5258 | /*InitStyle=*/ICIS_NoInit); |
5259 | Anon->setAccess(AS); |
5260 | ProcessDeclAttributes(S, Anon, Dc); |
5261 | |
5262 | if (getLangOpts().CPlusPlus) |
5263 | FieldCollector->Add(cast<FieldDecl>(Anon)); |
5264 | } else { |
5265 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); |
5266 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); |
5267 | if (SCSpec == DeclSpec::SCS_mutable) { |
5268 | // mutable can only appear on non-static class members, so it's always |
5269 | // an error here |
5270 | Diag(Record->getLocation(), diag::err_mutable_nonmember); |
5271 | Invalid = true; |
5272 | SC = SC_None; |
5273 | } |
5274 | |
5275 | assert(DS.getAttributes().empty() && "No attribute expected")((void)0); |
5276 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), |
5277 | Record->getLocation(), /*IdentifierInfo=*/nullptr, |
5278 | Context.getTypeDeclType(Record), TInfo, SC); |
5279 | |
5280 | // Default-initialize the implicit variable. This initialization will be |
5281 | // trivial in almost all cases, except if a union member has an in-class |
5282 | // initializer: |
5283 | // union { int n = 0; }; |
5284 | if (!Invalid) |
5285 | ActOnUninitializedDecl(Anon); |
5286 | } |
5287 | Anon->setImplicit(); |
5288 | |
5289 | // Mark this as an anonymous struct/union type. |
5290 | Record->setAnonymousStructOrUnion(true); |
5291 | |
5292 | // Add the anonymous struct/union object to the current |
5293 | // context. We'll be referencing this object when we refer to one of |
5294 | // its members. |
5295 | Owner->addDecl(Anon); |
5296 | |
5297 | // Inject the members of the anonymous struct/union into the owning |
5298 | // context and into the identifier resolver chain for name lookup |
5299 | // purposes. |
5300 | SmallVector<NamedDecl*, 2> Chain; |
5301 | Chain.push_back(Anon); |
5302 | |
5303 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) |
5304 | Invalid = true; |
5305 | |
5306 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { |
5307 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { |
5308 | MangleNumberingContext *MCtx; |
5309 | Decl *ManglingContextDecl; |
5310 | std::tie(MCtx, ManglingContextDecl) = |
5311 | getCurrentMangleNumberContext(NewVD->getDeclContext()); |
5312 | if (MCtx) { |
5313 | Context.setManglingNumber( |
5314 | NewVD, MCtx->getManglingNumber( |
5315 | NewVD, getMSManglingNumber(getLangOpts(), S))); |
5316 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); |
5317 | } |
5318 | } |
5319 | } |
5320 | |
5321 | if (Invalid) |
5322 | Anon->setInvalidDecl(); |
5323 | |
5324 | return Anon; |
5325 | } |
5326 | |
5327 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an |
5328 | /// Microsoft C anonymous structure. |
5329 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx |
5330 | /// Example: |
5331 | /// |
5332 | /// struct A { int a; }; |
5333 | /// struct B { struct A; int b; }; |
5334 | /// |
5335 | /// void foo() { |
5336 | /// B var; |
5337 | /// var.a = 3; |
5338 | /// } |
5339 | /// |
5340 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, |
5341 | RecordDecl *Record) { |
5342 | assert(Record && "expected a record!")((void)0); |
5343 | |
5344 | // Mock up a declarator. |
5345 | Declarator Dc(DS, DeclaratorContext::TypeName); |
5346 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); |
5347 | assert(TInfo && "couldn't build declarator info for anonymous struct")((void)0); |
5348 | |
5349 | auto *ParentDecl = cast<RecordDecl>(CurContext); |
5350 | QualType RecTy = Context.getTypeDeclType(Record); |
5351 | |
5352 | // Create a declaration for this anonymous struct. |
5353 | NamedDecl *Anon = |
5354 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), |
5355 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, |
5356 | /*BitWidth=*/nullptr, /*Mutable=*/false, |
5357 | /*InitStyle=*/ICIS_NoInit); |
5358 | Anon->setImplicit(); |
5359 | |
5360 | // Add the anonymous struct object to the current context. |
5361 | CurContext->addDecl(Anon); |
5362 | |
5363 | // Inject the members of the anonymous struct into the current |
5364 | // context and into the identifier resolver chain for name lookup |
5365 | // purposes. |
5366 | SmallVector<NamedDecl*, 2> Chain; |
5367 | Chain.push_back(Anon); |
5368 | |
5369 | RecordDecl *RecordDef = Record->getDefinition(); |
5370 | if (RequireCompleteSizedType(Anon->getLocation(), RecTy, |
5371 | diag::err_field_incomplete_or_sizeless) || |
5372 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, |
5373 | AS_none, Chain)) { |
5374 | Anon->setInvalidDecl(); |
5375 | ParentDecl->setInvalidDecl(); |
5376 | } |
5377 | |
5378 | return Anon; |
5379 | } |
5380 | |
5381 | /// GetNameForDeclarator - Determine the full declaration name for the |
5382 | /// given Declarator. |
5383 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { |
5384 | return GetNameFromUnqualifiedId(D.getName()); |
5385 | } |
5386 | |
5387 | /// Retrieves the declaration name from a parsed unqualified-id. |
5388 | DeclarationNameInfo |
5389 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { |
5390 | DeclarationNameInfo NameInfo; |
5391 | NameInfo.setLoc(Name.StartLocation); |
5392 | |
5393 | switch (Name.getKind()) { |
5394 | |
5395 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
5396 | case UnqualifiedIdKind::IK_Identifier: |
5397 | NameInfo.setName(Name.Identifier); |
5398 | return NameInfo; |
5399 | |
5400 | case UnqualifiedIdKind::IK_DeductionGuideName: { |
5401 | // C++ [temp.deduct.guide]p3: |
5402 | // The simple-template-id shall name a class template specialization. |
5403 | // The template-name shall be the same identifier as the template-name |
5404 | // of the simple-template-id. |
5405 | // These together intend to imply that the template-name shall name a |
5406 | // class template. |
5407 | // FIXME: template<typename T> struct X {}; |
5408 | // template<typename T> using Y = X<T>; |
5409 | // Y(int) -> Y<int>; |
5410 | // satisfies these rules but does not name a class template. |
5411 | TemplateName TN = Name.TemplateName.get().get(); |
5412 | auto *Template = TN.getAsTemplateDecl(); |
5413 | if (!Template || !isa<ClassTemplateDecl>(Template)) { |
5414 | Diag(Name.StartLocation, |
5415 | diag::err_deduction_guide_name_not_class_template) |
5416 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; |
5417 | if (Template) |
5418 | Diag(Template->getLocation(), diag::note_template_decl_here); |
5419 | return DeclarationNameInfo(); |
5420 | } |
5421 | |
5422 | NameInfo.setName( |
5423 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); |
5424 | return NameInfo; |
5425 | } |
5426 | |
5427 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
5428 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( |
5429 | Name.OperatorFunctionId.Operator)); |
5430 | NameInfo.setCXXOperatorNameRange(SourceRange( |
5431 | Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); |
5432 | return NameInfo; |
5433 | |
5434 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
5435 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( |
5436 | Name.Identifier)); |
5437 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); |
5438 | return NameInfo; |
5439 | |
5440 | case UnqualifiedIdKind::IK_ConversionFunctionId: { |
5441 | TypeSourceInfo *TInfo; |
5442 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); |
5443 | if (Ty.isNull()) |
5444 | return DeclarationNameInfo(); |
5445 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( |
5446 | Context.getCanonicalType(Ty))); |
5447 | NameInfo.setNamedTypeInfo(TInfo); |
5448 | return NameInfo; |
5449 | } |
5450 | |
5451 | case UnqualifiedIdKind::IK_ConstructorName: { |
5452 | TypeSourceInfo *TInfo; |
5453 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); |
5454 | if (Ty.isNull()) |
5455 | return DeclarationNameInfo(); |
5456 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( |
5457 | Context.getCanonicalType(Ty))); |
5458 | NameInfo.setNamedTypeInfo(TInfo); |
5459 | return NameInfo; |
5460 | } |
5461 | |
5462 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { |
5463 | // In well-formed code, we can only have a constructor |
5464 | // template-id that refers to the current context, so go there |
5465 | // to find the actual type being constructed. |
5466 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); |
5467 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) |
5468 | return DeclarationNameInfo(); |
5469 | |
5470 | // Determine the type of the class being constructed. |
5471 | QualType CurClassType = Context.getTypeDeclType(CurClass); |
5472 | |
5473 | // FIXME: Check two things: that the template-id names the same type as |
5474 | // CurClassType, and that the template-id does not occur when the name |
5475 | // was qualified. |
5476 | |
5477 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( |
5478 | Context.getCanonicalType(CurClassType))); |
5479 | // FIXME: should we retrieve TypeSourceInfo? |
5480 | NameInfo.setNamedTypeInfo(nullptr); |
5481 | return NameInfo; |
5482 | } |
5483 | |
5484 | case UnqualifiedIdKind::IK_DestructorName: { |
5485 | TypeSourceInfo *TInfo; |
5486 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); |
5487 | if (Ty.isNull()) |
5488 | return DeclarationNameInfo(); |
5489 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( |
5490 | Context.getCanonicalType(Ty))); |
5491 | NameInfo.setNamedTypeInfo(TInfo); |
5492 | return NameInfo; |
5493 | } |
5494 | |
5495 | case UnqualifiedIdKind::IK_TemplateId: { |
5496 | TemplateName TName = Name.TemplateId->Template.get(); |
5497 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; |
5498 | return Context.getNameForTemplate(TName, TNameLoc); |
5499 | } |
5500 | |
5501 | } // switch (Name.getKind()) |
5502 | |
5503 | llvm_unreachable("Unknown name kind")__builtin_unreachable(); |
5504 | } |
5505 | |
5506 | static QualType getCoreType(QualType Ty) { |
5507 | do { |
5508 | if (Ty->isPointerType() || Ty->isReferenceType()) |
5509 | Ty = Ty->getPointeeType(); |
5510 | else if (Ty->isArrayType()) |
5511 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); |
5512 | else |
5513 | return Ty.withoutLocalFastQualifiers(); |
5514 | } while (true); |
5515 | } |
5516 | |
5517 | /// hasSimilarParameters - Determine whether the C++ functions Declaration |
5518 | /// and Definition have "nearly" matching parameters. This heuristic is |
5519 | /// used to improve diagnostics in the case where an out-of-line function |
5520 | /// definition doesn't match any declaration within the class or namespace. |
5521 | /// Also sets Params to the list of indices to the parameters that differ |
5522 | /// between the declaration and the definition. If hasSimilarParameters |
5523 | /// returns true and Params is empty, then all of the parameters match. |
5524 | static bool hasSimilarParameters(ASTContext &Context, |
5525 | FunctionDecl *Declaration, |
5526 | FunctionDecl *Definition, |
5527 | SmallVectorImpl<unsigned> &Params) { |
5528 | Params.clear(); |
5529 | if (Declaration->param_size() != Definition->param_size()) |
5530 | return false; |
5531 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { |
5532 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); |
5533 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); |
5534 | |
5535 | // The parameter types are identical |
5536 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) |
5537 | continue; |
5538 | |
5539 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); |
5540 | QualType DefParamBaseTy = getCoreType(DefParamTy); |
5541 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); |
5542 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); |
5543 | |
5544 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || |
5545 | (DeclTyName && DeclTyName == DefTyName)) |
5546 | Params.push_back(Idx); |
5547 | else // The two parameters aren't even close |
5548 | return false; |
5549 | } |
5550 | |
5551 | return true; |
5552 | } |
5553 | |
5554 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given |
5555 | /// declarator needs to be rebuilt in the current instantiation. |
5556 | /// Any bits of declarator which appear before the name are valid for |
5557 | /// consideration here. That's specifically the type in the decl spec |
5558 | /// and the base type in any member-pointer chunks. |
5559 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, |
5560 | DeclarationName Name) { |
5561 | // The types we specifically need to rebuild are: |
5562 | // - typenames, typeofs, and decltypes |
5563 | // - types which will become injected class names |
5564 | // Of course, we also need to rebuild any type referencing such a |
5565 | // type. It's safest to just say "dependent", but we call out a |
5566 | // few cases here. |
5567 | |
5568 | DeclSpec &DS = D.getMutableDeclSpec(); |
5569 | switch (DS.getTypeSpecType()) { |
5570 | case DeclSpec::TST_typename: |
5571 | case DeclSpec::TST_typeofType: |
5572 | case DeclSpec::TST_underlyingType: |
5573 | case DeclSpec::TST_atomic: { |
5574 | // Grab the type from the parser. |
5575 | TypeSourceInfo *TSI = nullptr; |
5576 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); |
5577 | if (T.isNull() || !T->isInstantiationDependentType()) break; |
5578 | |
5579 | // Make sure there's a type source info. This isn't really much |
5580 | // of a waste; most dependent types should have type source info |
5581 | // attached already. |
5582 | if (!TSI) |
5583 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); |
5584 | |
5585 | // Rebuild the type in the current instantiation. |
5586 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); |
5587 | if (!TSI) return true; |
5588 | |
5589 | // Store the new type back in the decl spec. |
5590 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); |
5591 | DS.UpdateTypeRep(LocType); |
5592 | break; |
5593 | } |
5594 | |
5595 | case DeclSpec::TST_decltype: |
5596 | case DeclSpec::TST_typeofExpr: { |
5597 | Expr *E = DS.getRepAsExpr(); |
5598 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); |
5599 | if (Result.isInvalid()) return true; |
5600 | DS.UpdateExprRep(Result.get()); |
5601 | break; |
5602 | } |
5603 | |
5604 | default: |
5605 | // Nothing to do for these decl specs. |
5606 | break; |
5607 | } |
5608 | |
5609 | // It doesn't matter what order we do this in. |
5610 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { |
5611 | DeclaratorChunk &Chunk = D.getTypeObject(I); |
5612 | |
5613 | // The only type information in the declarator which can come |
5614 | // before the declaration name is the base type of a member |
5615 | // pointer. |
5616 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) |
5617 | continue; |
5618 | |
5619 | // Rebuild the scope specifier in-place. |
5620 | CXXScopeSpec &SS = Chunk.Mem.Scope(); |
5621 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) |
5622 | return true; |
5623 | } |
5624 | |
5625 | return false; |
5626 | } |
5627 | |
5628 | void Sema::warnOnReservedIdentifier(const NamedDecl *D) { |
5629 | // Avoid warning twice on the same identifier, and don't warn on redeclaration |
5630 | // of system decl. |
5631 | if (D->getPreviousDecl() || D->isImplicit()) |
5632 | return; |
5633 | ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); |
5634 | if (Status != ReservedIdentifierStatus::NotReserved && |
5635 | !Context.getSourceManager().isInSystemHeader(D->getLocation())) |
5636 | Diag(D->getLocation(), diag::warn_reserved_extern_symbol) |
5637 | << D << static_cast<int>(Status); |
5638 | } |
5639 | |
5640 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { |
5641 | D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); |
5642 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); |
5643 | |
5644 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && |
5645 | Dcl && Dcl->getDeclContext()->isFileContext()) |
5646 | Dcl->setTopLevelDeclInObjCContainer(); |
5647 | |
5648 | return Dcl; |
5649 | } |
5650 | |
5651 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: |
5652 | /// If T is the name of a class, then each of the following shall have a |
5653 | /// name different from T: |
5654 | /// - every static data member of class T; |
5655 | /// - every member function of class T |
5656 | /// - every member of class T that is itself a type; |
5657 | /// \returns true if the declaration name violates these rules. |
5658 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, |
5659 | DeclarationNameInfo NameInfo) { |
5660 | DeclarationName Name = NameInfo.getName(); |
5661 | |
5662 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); |
5663 | while (Record && Record->isAnonymousStructOrUnion()) |
5664 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); |
5665 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { |
5666 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; |
5667 | return true; |
5668 | } |
5669 | |
5670 | return false; |
5671 | } |
5672 | |
5673 | /// Diagnose a declaration whose declarator-id has the given |
5674 | /// nested-name-specifier. |
5675 | /// |
5676 | /// \param SS The nested-name-specifier of the declarator-id. |
5677 | /// |
5678 | /// \param DC The declaration context to which the nested-name-specifier |
5679 | /// resolves. |
5680 | /// |
5681 | /// \param Name The name of the entity being declared. |
5682 | /// |
5683 | /// \param Loc The location of the name of the entity being declared. |
5684 | /// |
5685 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus |
5686 | /// we're declaring an explicit / partial specialization / instantiation. |
5687 | /// |
5688 | /// \returns true if we cannot safely recover from this error, false otherwise. |
5689 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, |
5690 | DeclarationName Name, |
5691 | SourceLocation Loc, bool IsTemplateId) { |
5692 | DeclContext *Cur = CurContext; |
5693 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) |
5694 | Cur = Cur->getParent(); |
5695 | |
5696 | // If the user provided a superfluous scope specifier that refers back to the |
5697 | // class in which the entity is already declared, diagnose and ignore it. |
5698 | // |
5699 | // class X { |
5700 | // void X::f(); |
5701 | // }; |
5702 | // |
5703 | // Note, it was once ill-formed to give redundant qualification in all |
5704 | // contexts, but that rule was removed by DR482. |
5705 | if (Cur->Equals(DC)) { |
5706 | if (Cur->isRecord()) { |
5707 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification |
5708 | : diag::err_member_extra_qualification) |
5709 | << Name << FixItHint::CreateRemoval(SS.getRange()); |
5710 | SS.clear(); |
5711 | } else { |
5712 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; |
5713 | } |
5714 | return false; |
5715 | } |
5716 | |
5717 | // Check whether the qualifying scope encloses the scope of the original |
5718 | // declaration. For a template-id, we perform the checks in |
5719 | // CheckTemplateSpecializationScope. |
5720 | if (!Cur->Encloses(DC) && !IsTemplateId) { |
5721 | if (Cur->isRecord()) |
5722 | Diag(Loc, diag::err_member_qualification) |
5723 | << Name << SS.getRange(); |
5724 | else if (isa<TranslationUnitDecl>(DC)) |
5725 | Diag(Loc, diag::err_invalid_declarator_global_scope) |
5726 | << Name << SS.getRange(); |
5727 | else if (isa<FunctionDecl>(Cur)) |
5728 | Diag(Loc, diag::err_invalid_declarator_in_function) |
5729 | << Name << SS.getRange(); |
5730 | else if (isa<BlockDecl>(Cur)) |
5731 | Diag(Loc, diag::err_invalid_declarator_in_block) |
5732 | << Name << SS.getRange(); |
5733 | else |
5734 | Diag(Loc, diag::err_invalid_declarator_scope) |
5735 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); |
5736 | |
5737 | return true; |
5738 | } |
5739 | |
5740 | if (Cur->isRecord()) { |
5741 | // Cannot qualify members within a class. |
5742 | Diag(Loc, diag::err_member_qualification) |
5743 | << Name << SS.getRange(); |
5744 | SS.clear(); |
5745 | |
5746 | // C++ constructors and destructors with incorrect scopes can break |
5747 | // our AST invariants by having the wrong underlying types. If |
5748 | // that's the case, then drop this declaration entirely. |
5749 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || |
5750 | Name.getNameKind() == DeclarationName::CXXDestructorName) && |
5751 | !Context.hasSameType(Name.getCXXNameType(), |
5752 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) |
5753 | return true; |
5754 | |
5755 | return false; |
5756 | } |
5757 | |
5758 | // C++11 [dcl.meaning]p1: |
5759 | // [...] "The nested-name-specifier of the qualified declarator-id shall |
5760 | // not begin with a decltype-specifer" |
5761 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); |
5762 | while (SpecLoc.getPrefix()) |
5763 | SpecLoc = SpecLoc.getPrefix(); |
5764 | if (dyn_cast_or_null<DecltypeType>( |
5765 | SpecLoc.getNestedNameSpecifier()->getAsType())) |
5766 | Diag(Loc, diag::err_decltype_in_declarator) |
5767 | << SpecLoc.getTypeLoc().getSourceRange(); |
5768 | |
5769 | return false; |
5770 | } |
5771 | |
5772 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, |
5773 | MultiTemplateParamsArg TemplateParamLists) { |
5774 | // TODO: consider using NameInfo for diagnostic. |
5775 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
5776 | DeclarationName Name = NameInfo.getName(); |
5777 | |
5778 | // All of these full declarators require an identifier. If it doesn't have |
5779 | // one, the ParsedFreeStandingDeclSpec action should be used. |
5780 | if (D.isDecompositionDeclarator()) { |
5781 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); |
5782 | } else if (!Name) { |
5783 | if (!D.isInvalidType()) // Reject this if we think it is valid. |
5784 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) |
5785 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); |
5786 | return nullptr; |
5787 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) |
5788 | return nullptr; |
5789 | |
5790 | // The scope passed in may not be a decl scope. Zip up the scope tree until |
5791 | // we find one that is. |
5792 | while ((S->getFlags() & Scope::DeclScope) == 0 || |
5793 | (S->getFlags() & Scope::TemplateParamScope) != 0) |
5794 | S = S->getParent(); |
5795 | |
5796 | DeclContext *DC = CurContext; |
5797 | if (D.getCXXScopeSpec().isInvalid()) |
5798 | D.setInvalidType(); |
5799 | else if (D.getCXXScopeSpec().isSet()) { |
5800 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), |
5801 | UPPC_DeclarationQualifier)) |
5802 | return nullptr; |
5803 | |
5804 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); |
5805 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); |
5806 | if (!DC || isa<EnumDecl>(DC)) { |
5807 | // If we could not compute the declaration context, it's because the |
5808 | // declaration context is dependent but does not refer to a class, |
5809 | // class template, or class template partial specialization. Complain |
5810 | // and return early, to avoid the coming semantic disaster. |
5811 | Diag(D.getIdentifierLoc(), |
5812 | diag::err_template_qualified_declarator_no_match) |
5813 | << D.getCXXScopeSpec().getScopeRep() |
5814 | << D.getCXXScopeSpec().getRange(); |
5815 | return nullptr; |
5816 | } |
5817 | bool IsDependentContext = DC->isDependentContext(); |
5818 | |
5819 | if (!IsDependentContext && |
5820 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) |
5821 | return nullptr; |
5822 | |
5823 | // If a class is incomplete, do not parse entities inside it. |
5824 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { |
5825 | Diag(D.getIdentifierLoc(), |
5826 | diag::err_member_def_undefined_record) |
5827 | << Name << DC << D.getCXXScopeSpec().getRange(); |
5828 | return nullptr; |
5829 | } |
5830 | if (!D.getDeclSpec().isFriendSpecified()) { |
5831 | if (diagnoseQualifiedDeclaration( |
5832 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), |
5833 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { |
5834 | if (DC->isRecord()) |
5835 | return nullptr; |
5836 | |
5837 | D.setInvalidType(); |
5838 | } |
5839 | } |
5840 | |
5841 | // Check whether we need to rebuild the type of the given |
5842 | // declaration in the current instantiation. |
5843 | if (EnteringContext && IsDependentContext && |
5844 | TemplateParamLists.size() != 0) { |
5845 | ContextRAII SavedContext(*this, DC); |
5846 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) |
5847 | D.setInvalidType(); |
5848 | } |
5849 | } |
5850 | |
5851 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
5852 | QualType R = TInfo->getType(); |
5853 | |
5854 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, |
5855 | UPPC_DeclarationType)) |
5856 | D.setInvalidType(); |
5857 | |
5858 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
5859 | forRedeclarationInCurContext()); |
5860 | |
5861 | // See if this is a redefinition of a variable in the same scope. |
5862 | if (!D.getCXXScopeSpec().isSet()) { |
5863 | bool IsLinkageLookup = false; |
5864 | bool CreateBuiltins = false; |
5865 | |
5866 | // If the declaration we're planning to build will be a function |
5867 | // or object with linkage, then look for another declaration with |
5868 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). |
5869 | // |
5870 | // If the declaration we're planning to build will be declared with |
5871 | // external linkage in the translation unit, create any builtin with |
5872 | // the same name. |
5873 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
5874 | /* Do nothing*/; |
5875 | else if (CurContext->isFunctionOrMethod() && |
5876 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || |
5877 | R->isFunctionType())) { |
5878 | IsLinkageLookup = true; |
5879 | CreateBuiltins = |
5880 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); |
5881 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && |
5882 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) |
5883 | CreateBuiltins = true; |
5884 | |
5885 | if (IsLinkageLookup) { |
5886 | Previous.clear(LookupRedeclarationWithLinkage); |
5887 | Previous.setRedeclarationKind(ForExternalRedeclaration); |
5888 | } |
5889 | |
5890 | LookupName(Previous, S, CreateBuiltins); |
5891 | } else { // Something like "int foo::x;" |
5892 | LookupQualifiedName(Previous, DC); |
5893 | |
5894 | // C++ [dcl.meaning]p1: |
5895 | // When the declarator-id is qualified, the declaration shall refer to a |
5896 | // previously declared member of the class or namespace to which the |
5897 | // qualifier refers (or, in the case of a namespace, of an element of the |
5898 | // inline namespace set of that namespace (7.3.1)) or to a specialization |
5899 | // thereof; [...] |
5900 | // |
5901 | // Note that we already checked the context above, and that we do not have |
5902 | // enough information to make sure that Previous contains the declaration |
5903 | // we want to match. For example, given: |
5904 | // |
5905 | // class X { |
5906 | // void f(); |
5907 | // void f(float); |
5908 | // }; |
5909 | // |
5910 | // void X::f(int) { } // ill-formed |
5911 | // |
5912 | // In this case, Previous will point to the overload set |
5913 | // containing the two f's declared in X, but neither of them |
5914 | // matches. |
5915 | |
5916 | // C++ [dcl.meaning]p1: |
5917 | // [...] the member shall not merely have been introduced by a |
5918 | // using-declaration in the scope of the class or namespace nominated by |
5919 | // the nested-name-specifier of the declarator-id. |
5920 | RemoveUsingDecls(Previous); |
5921 | } |
5922 | |
5923 | if (Previous.isSingleResult() && |
5924 | Previous.getFoundDecl()->isTemplateParameter()) { |
5925 | // Maybe we will complain about the shadowed template parameter. |
5926 | if (!D.isInvalidType()) |
5927 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), |
5928 | Previous.getFoundDecl()); |
5929 | |
5930 | // Just pretend that we didn't see the previous declaration. |
5931 | Previous.clear(); |
5932 | } |
5933 | |
5934 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) |
5935 | // Forget that the previous declaration is the injected-class-name. |
5936 | Previous.clear(); |
5937 | |
5938 | // In C++, the previous declaration we find might be a tag type |
5939 | // (class or enum). In this case, the new declaration will hide the |
5940 | // tag type. Note that this applies to functions, function templates, and |
5941 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. |
5942 | if (Previous.isSingleTagDecl() && |
5943 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && |
5944 | (TemplateParamLists.size() == 0 || R->isFunctionType())) |
5945 | Previous.clear(); |
5946 | |
5947 | // Check that there are no default arguments other than in the parameters |
5948 | // of a function declaration (C++ only). |
5949 | if (getLangOpts().CPlusPlus) |
5950 | CheckExtraCXXDefaultArguments(D); |
5951 | |
5952 | NamedDecl *New; |
5953 | |
5954 | bool AddToScope = true; |
5955 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { |
5956 | if (TemplateParamLists.size()) { |
5957 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); |
5958 | return nullptr; |
5959 | } |
5960 | |
5961 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); |
5962 | } else if (R->isFunctionType()) { |
5963 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, |
5964 | TemplateParamLists, |
5965 | AddToScope); |
5966 | } else { |
5967 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, |
5968 | AddToScope); |
5969 | } |
5970 | |
5971 | if (!New) |
5972 | return nullptr; |
5973 | |
5974 | // If this has an identifier and is not a function template specialization, |
5975 | // add it to the scope stack. |
5976 | if (New->getDeclName() && AddToScope) |
5977 | PushOnScopeChains(New, S); |
5978 | |
5979 | if (isInOpenMPDeclareTargetContext()) |
5980 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); |
5981 | |
5982 | return New; |
5983 | } |
5984 | |
5985 | /// Helper method to turn variable array types into constant array |
5986 | /// types in certain situations which would otherwise be errors (for |
5987 | /// GCC compatibility). |
5988 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, |
5989 | ASTContext &Context, |
5990 | bool &SizeIsNegative, |
5991 | llvm::APSInt &Oversized) { |
5992 | // This method tries to turn a variable array into a constant |
5993 | // array even when the size isn't an ICE. This is necessary |
5994 | // for compatibility with code that depends on gcc's buggy |
5995 | // constant expression folding, like struct {char x[(int)(char*)2];} |
5996 | SizeIsNegative = false; |
5997 | Oversized = 0; |
5998 | |
5999 | if (T->isDependentType()) |
6000 | return QualType(); |
6001 | |
6002 | QualifierCollector Qs; |
6003 | const Type *Ty = Qs.strip(T); |
6004 | |
6005 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { |
6006 | QualType Pointee = PTy->getPointeeType(); |
6007 | QualType FixedType = |
6008 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, |
6009 | Oversized); |
6010 | if (FixedType.isNull()) return FixedType; |
6011 | FixedType = Context.getPointerType(FixedType); |
6012 | return Qs.apply(Context, FixedType); |
6013 | } |
6014 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { |
6015 | QualType Inner = PTy->getInnerType(); |
6016 | QualType FixedType = |
6017 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, |
6018 | Oversized); |
6019 | if (FixedType.isNull()) return FixedType; |
6020 | FixedType = Context.getParenType(FixedType); |
6021 | return Qs.apply(Context, FixedType); |
6022 | } |
6023 | |
6024 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); |
6025 | if (!VLATy) |
6026 | return QualType(); |
6027 | |
6028 | QualType ElemTy = VLATy->getElementType(); |
6029 | if (ElemTy->isVariablyModifiedType()) { |
6030 | ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, |
6031 | SizeIsNegative, Oversized); |
6032 | if (ElemTy.isNull()) |
6033 | return QualType(); |
6034 | } |
6035 | |
6036 | Expr::EvalResult Result; |
6037 | if (!VLATy->getSizeExpr() || |
6038 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) |
6039 | return QualType(); |
6040 | |
6041 | llvm::APSInt Res = Result.Val.getInt(); |
6042 | |
6043 | // Check whether the array size is negative. |
6044 | if (Res.isSigned() && Res.isNegative()) { |
6045 | SizeIsNegative = true; |
6046 | return QualType(); |
6047 | } |
6048 | |
6049 | // Check whether the array is too large to be addressed. |
6050 | unsigned ActiveSizeBits = |
6051 | (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && |
6052 | !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) |
6053 | ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) |
6054 | : Res.getActiveBits(); |
6055 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { |
6056 | Oversized = Res; |
6057 | return QualType(); |
6058 | } |
6059 | |
6060 | QualType FoldedArrayType = Context.getConstantArrayType( |
6061 | ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); |
6062 | return Qs.apply(Context, FoldedArrayType); |
6063 | } |
6064 | |
6065 | static void |
6066 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { |
6067 | SrcTL = SrcTL.getUnqualifiedLoc(); |
6068 | DstTL = DstTL.getUnqualifiedLoc(); |
6069 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { |
6070 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); |
6071 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), |
6072 | DstPTL.getPointeeLoc()); |
6073 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); |
6074 | return; |
6075 | } |
6076 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { |
6077 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); |
6078 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), |
6079 | DstPTL.getInnerLoc()); |
6080 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); |
6081 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); |
6082 | return; |
6083 | } |
6084 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); |
6085 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); |
6086 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); |
6087 | TypeLoc DstElemTL = DstATL.getElementLoc(); |
6088 | if (VariableArrayTypeLoc SrcElemATL = |
6089 | SrcElemTL.getAs<VariableArrayTypeLoc>()) { |
6090 | ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); |
6091 | FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); |
6092 | } else { |
6093 | DstElemTL.initializeFullCopy(SrcElemTL); |
6094 | } |
6095 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); |
6096 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); |
6097 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); |
6098 | } |
6099 | |
6100 | /// Helper method to turn variable array types into constant array |
6101 | /// types in certain situations which would otherwise be errors (for |
6102 | /// GCC compatibility). |
6103 | static TypeSourceInfo* |
6104 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, |
6105 | ASTContext &Context, |
6106 |