Bug Summary

File:build-llvm/tools/clang/include/clang/AST/Attrs.inc
Warning:line 1187, column 9
Null pointer passed as an argument to a 'nonnull' parameter

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp

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