Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 3197, column 5
Value stored to 'NewType' is never read

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