Bug Summary

File:build-llvm/tools/clang/include/clang/AST/Attrs.inc
Warning:line 1095, column 5
Called C++ object pointer is null

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-eagerly-assume -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/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-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/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-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp

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")(static_cast <bool> (IIDecl && "Didn't find decl"
) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 462, __extension__ __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-7~svn338205/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")(static_cast <bool> (getLangOpts().MSVCCompat &&
"shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail
("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 555, __extension__ __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-7~svn338205/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() &&(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 759, __extension__ __PRETTY_FUNCTION__))
759 "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 759, __extension__ __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 &&(static_cast <bool> (getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1211, __extension__ __PRETTY_FUNCTION__))
1211 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1211, __extension__ __PRETTY_FUNCTION__))
;
1212 CurContext = DC;
1213 S->setEntity(DC);
1214}
1215
1216void Sema::PopDeclContext() {
1217 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1217, __extension__ __PRETTY_FUNCTION__))
;
1218
1219 CurContext = getContainingDC(CurContext);
1220 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1220, __extension__ __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")(static_cast <bool> (CurContext && "skipping definition of undefined tag"
) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1230, __extension__ __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")(static_cast <bool> (!S->getEntity() && "scope already has entity"
) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1261, __extension__ __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")(static_cast <bool> (Ancestor->getEntity() == CurContext
&& "ancestor context mismatch") ? void (0) : __assert_fail
("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1266, __extension__ __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!")(static_cast <bool> (S->getEntity() == CurContext &&
"Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1274, __extension__ __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() &&(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1296, __extension__ __PRETTY_FUNCTION__))
1296 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1296, __extension__ __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!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1313, __extension__ __PRETTY_FUNCTION__))
;
1314 CurContext = CurContext->getLexicalParent();
1315 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1315, __extension__ __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)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1556, __extension__ __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(D->getLocEnd(),
1739 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1740 if (AfterColon.isInvalid())
1741 return;
1742 Hint = FixItHint::CreateRemoval(CharSourceRange::
1743 getCharRange(D->getLocStart(), AfterColon));
1744 }
1745}
1746
1747void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1748 if (D->getTypeForDecl()->isDependentType())
1749 return;
1750
1751 for (auto *TmpD : D->decls()) {
1752 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1753 DiagnoseUnusedDecl(T);
1754 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1755 DiagnoseUnusedNestedTypedefs(R);
1756 }
1757}
1758
1759/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1760/// unless they are marked attr(unused).
1761void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1762 if (!ShouldDiagnoseUnusedDecl(D))
1763 return;
1764
1765 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1766 // typedefs can be referenced later on, so the diagnostics are emitted
1767 // at end-of-translation-unit.
1768 UnusedLocalTypedefNameCandidates.insert(TD);
1769 return;
1770 }
1771
1772 FixItHint Hint;
1773 GenerateFixForUnusedDecl(D, Context, Hint);
1774
1775 unsigned DiagID;
1776 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1777 DiagID = diag::warn_unused_exception_param;
1778 else if (isa<LabelDecl>(D))
1779 DiagID = diag::warn_unused_label;
1780 else
1781 DiagID = diag::warn_unused_variable;
1782
1783 Diag(D->getLocation(), DiagID) << D << Hint;
1784}
1785
1786static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1787 // Verify that we have no forward references left. If so, there was a goto
1788 // or address of a label taken, but no definition of it. Label fwd
1789 // definitions are indicated with a null substmt which is also not a resolved
1790 // MS inline assembly label name.
1791 bool Diagnose = false;
1792 if (L->isMSAsmLabel())
1793 Diagnose = !L->isResolvedMSAsmLabel();
1794 else
1795 Diagnose = L->getStmt() == nullptr;
1796 if (Diagnose)
1797 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1798}
1799
1800void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1801 S->mergeNRVOIntoParent();
1802
1803 if (S->decl_empty()) return;
1804 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1805, __extension__ __PRETTY_FUNCTION__))
1805 "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1805, __extension__ __PRETTY_FUNCTION__))
;
1806
1807 for (auto *TmpD : S->decls()) {
1808 assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??"
) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1808, __extension__ __PRETTY_FUNCTION__))
;
1809
1810 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) &&
"Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1810, __extension__ __PRETTY_FUNCTION__))
;
1811 NamedDecl *D = cast<NamedDecl>(TmpD);
1812
1813 // Diagnose unused variables in this scope.
1814 if (!S->hasUnrecoverableErrorOccurred()) {
1815 DiagnoseUnusedDecl(D);
1816 if (const auto *RD = dyn_cast<RecordDecl>(D))
1817 DiagnoseUnusedNestedTypedefs(RD);
1818 }
1819
1820 if (!D->getDeclName()) continue;
1821
1822 // If this was a forward reference to a label, verify it was defined.
1823 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1824 CheckPoppedLabel(LD, *this);
1825
1826 // Remove this name from our lexical scope, and warn on it if we haven't
1827 // already.
1828 IdResolver.RemoveDecl(D);
1829 auto ShadowI = ShadowingDecls.find(D);
1830 if (ShadowI != ShadowingDecls.end()) {
1831 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1832 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1833 << D << FD << FD->getParent();
1834 Diag(FD->getLocation(), diag::note_previous_declaration);
1835 }
1836 ShadowingDecls.erase(ShadowI);
1837 }
1838 }
1839}
1840
1841/// Look for an Objective-C class in the translation unit.
1842///
1843/// \param Id The name of the Objective-C class we're looking for. If
1844/// typo-correction fixes this name, the Id will be updated
1845/// to the fixed name.
1846///
1847/// \param IdLoc The location of the name in the translation unit.
1848///
1849/// \param DoTypoCorrection If true, this routine will attempt typo correction
1850/// if there is no class with the given name.
1851///
1852/// \returns The declaration of the named Objective-C class, or NULL if the
1853/// class could not be found.
1854ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1855 SourceLocation IdLoc,
1856 bool DoTypoCorrection) {
1857 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1858 // creation from this context.
1859 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1860
1861 if (!IDecl && DoTypoCorrection) {
1862 // Perform typo correction at the given location, but only if we
1863 // find an Objective-C class name.
1864 if (TypoCorrection C = CorrectTypo(
1865 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1866 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1867 CTK_ErrorRecovery)) {
1868 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1869 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1870 Id = IDecl->getIdentifier();
1871 }
1872 }
1873 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1874 // This routine must always return a class definition, if any.
1875 if (Def && Def->getDefinition())
1876 Def = Def->getDefinition();
1877 return Def;
1878}
1879
1880/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1881/// from S, where a non-field would be declared. This routine copes
1882/// with the difference between C and C++ scoping rules in structs and
1883/// unions. For example, the following code is well-formed in C but
1884/// ill-formed in C++:
1885/// @code
1886/// struct S6 {
1887/// enum { BAR } e;
1888/// };
1889///
1890/// void test_S6() {
1891/// struct S6 a;
1892/// a.e = BAR;
1893/// }
1894/// @endcode
1895/// For the declaration of BAR, this routine will return a different
1896/// scope. The scope S will be the scope of the unnamed enumeration
1897/// within S6. In C++, this routine will return the scope associated
1898/// with S6, because the enumeration's scope is a transparent
1899/// context but structures can contain non-field names. In C, this
1900/// routine will return the translation unit scope, since the
1901/// enumeration's scope is a transparent context and structures cannot
1902/// contain non-field names.
1903Scope *Sema::getNonFieldDeclScope(Scope *S) {
1904 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1905 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1906 (S->isClassScope() && !getLangOpts().CPlusPlus))
1907 S = S->getParent();
1908 return S;
1909}
1910
1911/// Looks up the declaration of "struct objc_super" and
1912/// saves it for later use in building builtin declaration of
1913/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1914/// pre-existing declaration exists no action takes place.
1915static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1916 IdentifierInfo *II) {
1917 if (!II->isStr("objc_msgSendSuper"))
1918 return;
1919 ASTContext &Context = ThisSema.Context;
1920
1921 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1922 SourceLocation(), Sema::LookupTagName);
1923 ThisSema.LookupName(Result, S);
1924 if (Result.getResultKind() == LookupResult::Found)
1925 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1926 Context.setObjCSuperType(Context.getTagDeclType(TD));
1927}
1928
1929static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1930 switch (Error) {
1931 case ASTContext::GE_None:
1932 return "";
1933 case ASTContext::GE_Missing_stdio:
1934 return "stdio.h";
1935 case ASTContext::GE_Missing_setjmp:
1936 return "setjmp.h";
1937 case ASTContext::GE_Missing_ucontext:
1938 return "ucontext.h";
1939 }
1940 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 1940)
;
1941}
1942
1943/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1944/// file scope. lazily create a decl for it. ForRedeclaration is true
1945/// if we're creating this built-in in anticipation of redeclaring the
1946/// built-in.
1947NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1948 Scope *S, bool ForRedeclaration,
1949 SourceLocation Loc) {
1950 LookupPredefedObjCSuperType(*this, S, II);
1951
1952 ASTContext::GetBuiltinTypeError Error;
1953 QualType R = Context.GetBuiltinType(ID, Error);
1954 if (Error) {
1955 if (ForRedeclaration)
1956 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1957 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1958 return nullptr;
1959 }
1960
1961 if (!ForRedeclaration &&
1962 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1963 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1964 Diag(Loc, diag::ext_implicit_lib_function_decl)
1965 << Context.BuiltinInfo.getName(ID) << R;
1966 if (Context.BuiltinInfo.getHeaderName(ID) &&
1967 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1968 Diag(Loc, diag::note_include_header_or_declare)
1969 << Context.BuiltinInfo.getHeaderName(ID)
1970 << Context.BuiltinInfo.getName(ID);
1971 }
1972
1973 if (R.isNull())
1974 return nullptr;
1975
1976 DeclContext *Parent = Context.getTranslationUnitDecl();
1977 if (getLangOpts().CPlusPlus) {
1978 LinkageSpecDecl *CLinkageDecl =
1979 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1980 LinkageSpecDecl::lang_c, false);
1981 CLinkageDecl->setImplicit();
1982 Parent->addDecl(CLinkageDecl);
1983 Parent = CLinkageDecl;
1984 }
1985
1986 FunctionDecl *New = FunctionDecl::Create(Context,
1987 Parent,
1988 Loc, Loc, II, R, /*TInfo=*/nullptr,
1989 SC_Extern,
1990 false,
1991 R->isFunctionProtoType());
1992 New->setImplicit();
1993
1994 // Create Decl objects for each parameter, adding them to the
1995 // FunctionDecl.
1996 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1997 SmallVector<ParmVarDecl*, 16> Params;
1998 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1999 ParmVarDecl *parm =
2000 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2001 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2002 SC_None, nullptr);
2003 parm->setScopeInfo(0, i);
2004 Params.push_back(parm);
2005 }
2006 New->setParams(Params);
2007 }
2008
2009 AddKnownFunctionAttributes(New);
2010 RegisterLocallyScopedExternCDecl(New, S);
2011
2012 // TUScope is the translation-unit scope to insert this function into.
2013 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2014 // relate Scopes to DeclContexts, and probably eliminate CurContext
2015 // entirely, but we're not there yet.
2016 DeclContext *SavedContext = CurContext;
2017 CurContext = Parent;
2018 PushOnScopeChains(New, TUScope);
2019 CurContext = SavedContext;
2020 return New;
2021}
2022
2023/// Typedef declarations don't have linkage, but they still denote the same
2024/// entity if their types are the same.
2025/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2026/// isSameEntity.
2027static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2028 TypedefNameDecl *Decl,
2029 LookupResult &Previous) {
2030 // This is only interesting when modules are enabled.
2031 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2032 return;
2033
2034 // Empty sets are uninteresting.
2035 if (Previous.empty())
2036 return;
2037
2038 LookupResult::Filter Filter = Previous.makeFilter();
2039 while (Filter.hasNext()) {
2040 NamedDecl *Old = Filter.next();
2041
2042 // Non-hidden declarations are never ignored.
2043 if (S.isVisible(Old))
2044 continue;
2045
2046 // Declarations of the same entity are not ignored, even if they have
2047 // different linkages.
2048 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2049 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2050 Decl->getUnderlyingType()))
2051 continue;
2052
2053 // If both declarations give a tag declaration a typedef name for linkage
2054 // purposes, then they declare the same entity.
2055 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2056 Decl->getAnonDeclWithTypedefName())
2057 continue;
2058 }
2059
2060 Filter.erase();
2061 }
2062
2063 Filter.done();
2064}
2065
2066bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2067 QualType OldType;
2068 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2069 OldType = OldTypedef->getUnderlyingType();
2070 else
2071 OldType = Context.getTypeDeclType(Old);
2072 QualType NewType = New->getUnderlyingType();
2073
2074 if (NewType->isVariablyModifiedType()) {
2075 // Must not redefine a typedef with a variably-modified type.
2076 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2077 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2078 << Kind << NewType;
2079 if (Old->getLocation().isValid())
2080 notePreviousDefinition(Old, New->getLocation());
2081 New->setInvalidDecl();
2082 return true;
2083 }
2084
2085 if (OldType != NewType &&
2086 !OldType->isDependentType() &&
2087 !NewType->isDependentType() &&
2088 !Context.hasSameType(OldType, NewType)) {
2089 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2090 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2091 << Kind << NewType << OldType;
2092 if (Old->getLocation().isValid())
2093 notePreviousDefinition(Old, New->getLocation());
2094 New->setInvalidDecl();
2095 return true;
2096 }
2097 return false;
2098}
2099
2100/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2101/// same name and scope as a previous declaration 'Old'. Figure out
2102/// how to resolve this situation, merging decls or emitting
2103/// diagnostics as appropriate. If there was an error, set New to be invalid.
2104///
2105void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2106 LookupResult &OldDecls) {
2107 // If the new decl is known invalid already, don't bother doing any
2108 // merging checks.
2109 if (New->isInvalidDecl()) return;
2110
2111 // Allow multiple definitions for ObjC built-in typedefs.
2112 // FIXME: Verify the underlying types are equivalent!
2113 if (getLangOpts().ObjC1) {
2114 const IdentifierInfo *TypeID = New->getIdentifier();
2115 switch (TypeID->getLength()) {
2116 default: break;
2117 case 2:
2118 {
2119 if (!TypeID->isStr("id"))
2120 break;
2121 QualType T = New->getUnderlyingType();
2122 if (!T->isPointerType())
2123 break;
2124 if (!T->isVoidPointerType()) {
2125 QualType PT = T->getAs<PointerType>()->getPointeeType();
2126 if (!PT->isStructureType())
2127 break;
2128 }
2129 Context.setObjCIdRedefinitionType(T);
2130 // Install the built-in type for 'id', ignoring the current definition.
2131 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2132 return;
2133 }
2134 case 5:
2135 if (!TypeID->isStr("Class"))
2136 break;
2137 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2138 // Install the built-in type for 'Class', ignoring the current definition.
2139 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2140 return;
2141 case 3:
2142 if (!TypeID->isStr("SEL"))
2143 break;
2144 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2145 // Install the built-in type for 'SEL', ignoring the current definition.
2146 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2147 return;
2148 }
2149 // Fall through - the typedef name was not a builtin type.
2150 }
2151
2152 // Verify the old decl was also a type.
2153 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2154 if (!Old) {
2155 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2156 << New->getDeclName();
2157
2158 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2159 if (OldD->getLocation().isValid())
2160 notePreviousDefinition(OldD, New->getLocation());
2161
2162 return New->setInvalidDecl();
2163 }
2164
2165 // If the old declaration is invalid, just give up here.
2166 if (Old->isInvalidDecl())
2167 return New->setInvalidDecl();
2168
2169 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2170 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2171 auto *NewTag = New->getAnonDeclWithTypedefName();
2172 NamedDecl *Hidden = nullptr;
2173 if (OldTag && NewTag &&
2174 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2175 !hasVisibleDefinition(OldTag, &Hidden)) {
2176 // There is a definition of this tag, but it is not visible. Use it
2177 // instead of our tag.
2178 New->setTypeForDecl(OldTD->getTypeForDecl());
2179 if (OldTD->isModed())
2180 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2181 OldTD->getUnderlyingType());
2182 else
2183 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2184
2185 // Make the old tag definition visible.
2186 makeMergedDefinitionVisible(Hidden);
2187
2188 // If this was an unscoped enumeration, yank all of its enumerators
2189 // out of the scope.
2190 if (isa<EnumDecl>(NewTag)) {
2191 Scope *EnumScope = getNonFieldDeclScope(S);
2192 for (auto *D : NewTag->decls()) {
2193 auto *ED = cast<EnumConstantDecl>(D);
2194 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 2194, __extension__ __PRETTY_FUNCTION__))
;
2195 EnumScope->RemoveDecl(ED);
2196 IdResolver.RemoveDecl(ED);
2197 ED->getLexicalDeclContext()->removeDecl(ED);
2198 }
2199 }
2200 }
2201 }
2202
2203 // If the typedef types are not identical, reject them in all languages and
2204 // with any extensions enabled.
2205 if (isIncompatibleTypedef(Old, New))
2206 return;
2207
2208 // The types match. Link up the redeclaration chain and merge attributes if
2209 // the old declaration was a typedef.
2210 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2211 New->setPreviousDecl(Typedef);
2212 mergeDeclAttributes(New, Old);
2213 }
2214
2215 if (getLangOpts().MicrosoftExt)
2216 return;
2217
2218 if (getLangOpts().CPlusPlus) {
2219 // C++ [dcl.typedef]p2:
2220 // In a given non-class scope, a typedef specifier can be used to
2221 // redefine the name of any type declared in that scope to refer
2222 // to the type to which it already refers.
2223 if (!isa<CXXRecordDecl>(CurContext))
2224 return;
2225
2226 // C++0x [dcl.typedef]p4:
2227 // In a given class scope, a typedef specifier can be used to redefine
2228 // any class-name declared in that scope that is not also a typedef-name
2229 // to refer to the type to which it already refers.
2230 //
2231 // This wording came in via DR424, which was a correction to the
2232 // wording in DR56, which accidentally banned code like:
2233 //
2234 // struct S {
2235 // typedef struct A { } A;
2236 // };
2237 //
2238 // in the C++03 standard. We implement the C++0x semantics, which
2239 // allow the above but disallow
2240 //
2241 // struct S {
2242 // typedef int I;
2243 // typedef int I;
2244 // };
2245 //
2246 // since that was the intent of DR56.
2247 if (!isa<TypedefNameDecl>(Old))
2248 return;
2249
2250 Diag(New->getLocation(), diag::err_redefinition)
2251 << New->getDeclName();
2252 notePreviousDefinition(Old, New->getLocation());
2253 return New->setInvalidDecl();
2254 }
2255
2256 // Modules always permit redefinition of typedefs, as does C11.
2257 if (getLangOpts().Modules || getLangOpts().C11)
2258 return;
2259
2260 // If we have a redefinition of a typedef in C, emit a warning. This warning
2261 // is normally mapped to an error, but can be controlled with
2262 // -Wtypedef-redefinition. If either the original or the redefinition is
2263 // in a system header, don't emit this for compatibility with GCC.
2264 if (getDiagnostics().getSuppressSystemWarnings() &&
2265 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2266 (Old->isImplicit() ||
2267 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2268 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2269 return;
2270
2271 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2272 << New->getDeclName();
2273 notePreviousDefinition(Old, New->getLocation());
2274}
2275
2276/// DeclhasAttr - returns true if decl Declaration already has the target
2277/// attribute.
2278static bool DeclHasAttr(const Decl *D, const Attr *A) {
2279 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2280 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2281 for (const auto *i : D->attrs())
2282 if (i->getKind() == A->getKind()) {
2283 if (Ann) {
2284 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2285 return true;
2286 continue;
2287 }
2288 // FIXME: Don't hardcode this check
2289 if (OA && isa<OwnershipAttr>(i))
2290 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2291 return true;
2292 }
2293
2294 return false;
2295}
2296
2297static bool isAttributeTargetADefinition(Decl *D) {
2298 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2299 return VD->isThisDeclarationADefinition();
2300 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2301 return TD->isCompleteDefinition() || TD->isBeingDefined();
2302 return true;
2303}
2304
2305/// Merge alignment attributes from \p Old to \p New, taking into account the
2306/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2307///
2308/// \return \c true if any attributes were added to \p New.
2309static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2310 // Look for alignas attributes on Old, and pick out whichever attribute
2311 // specifies the strictest alignment requirement.
2312 AlignedAttr *OldAlignasAttr = nullptr;
2313 AlignedAttr *OldStrictestAlignAttr = nullptr;
2314 unsigned OldAlign = 0;
2315 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2316 // FIXME: We have no way of representing inherited dependent alignments
2317 // in a case like:
2318 // template<int A, int B> struct alignas(A) X;
2319 // template<int A, int B> struct alignas(B) X {};
2320 // For now, we just ignore any alignas attributes which are not on the
2321 // definition in such a case.
2322 if (I->isAlignmentDependent())
2323 return false;
2324
2325 if (I->isAlignas())
2326 OldAlignasAttr = I;
2327
2328 unsigned Align = I->getAlignment(S.Context);
2329 if (Align > OldAlign) {
2330 OldAlign = Align;
2331 OldStrictestAlignAttr = I;
2332 }
2333 }
2334
2335 // Look for alignas attributes on New.
2336 AlignedAttr *NewAlignasAttr = nullptr;
2337 unsigned NewAlign = 0;
2338 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2339 if (I->isAlignmentDependent())
2340 return false;
2341
2342 if (I->isAlignas())
2343 NewAlignasAttr = I;
2344
2345 unsigned Align = I->getAlignment(S.Context);
2346 if (Align > NewAlign)
2347 NewAlign = Align;
2348 }
2349
2350 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2351 // Both declarations have 'alignas' attributes. We require them to match.
2352 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2353 // fall short. (If two declarations both have alignas, they must both match
2354 // every definition, and so must match each other if there is a definition.)
2355
2356 // If either declaration only contains 'alignas(0)' specifiers, then it
2357 // specifies the natural alignment for the type.
2358 if (OldAlign == 0 || NewAlign == 0) {
2359 QualType Ty;
2360 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2361 Ty = VD->getType();
2362 else
2363 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2364
2365 if (OldAlign == 0)
2366 OldAlign = S.Context.getTypeAlign(Ty);
2367 if (NewAlign == 0)
2368 NewAlign = S.Context.getTypeAlign(Ty);
2369 }
2370
2371 if (OldAlign != NewAlign) {
2372 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2373 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2374 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2375 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2376 }
2377 }
2378
2379 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2380 // C++11 [dcl.align]p6:
2381 // if any declaration of an entity has an alignment-specifier,
2382 // every defining declaration of that entity shall specify an
2383 // equivalent alignment.
2384 // C11 6.7.5/7:
2385 // If the definition of an object does not have an alignment
2386 // specifier, any other declaration of that object shall also
2387 // have no alignment specifier.
2388 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2389 << OldAlignasAttr;
2390 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2391 << OldAlignasAttr;
2392 }
2393
2394 bool AnyAdded = false;
2395
2396 // Ensure we have an attribute representing the strictest alignment.
2397 if (OldAlign > NewAlign) {
2398 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2399 Clone->setInherited(true);
2400 New->addAttr(Clone);
2401 AnyAdded = true;
2402 }
2403
2404 // Ensure we have an alignas attribute if the old declaration had one.
2405 if (OldAlignasAttr && !NewAlignasAttr &&
2406 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2407 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2408 Clone->setInherited(true);
2409 New->addAttr(Clone);
2410 AnyAdded = true;
2411 }
2412
2413 return AnyAdded;
2414}
2415
2416static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2417 const InheritableAttr *Attr,
2418 Sema::AvailabilityMergeKind AMK) {
2419 // This function copies an attribute Attr from a previous declaration to the
2420 // new declaration D if the new declaration doesn't itself have that attribute
2421 // yet or if that attribute allows duplicates.
2422 // If you're adding a new attribute that requires logic different from
2423 // "use explicit attribute on decl if present, else use attribute from
2424 // previous decl", for example if the attribute needs to be consistent
2425 // between redeclarations, you need to call a custom merge function here.
2426 InheritableAttr *NewAttr = nullptr;
2427 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2428 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2429 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2430 AA->isImplicit(), AA->getIntroduced(),
2431 AA->getDeprecated(),
2432 AA->getObsoleted(), AA->getUnavailable(),
2433 AA->getMessage(), AA->getStrict(),
2434 AA->getReplacement(), AMK,
2435 AttrSpellingListIndex);
2436 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2437 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2438 AttrSpellingListIndex);
2439 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2440 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441 AttrSpellingListIndex);
2442 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2443 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2444 AttrSpellingListIndex);
2445 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2446 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2447 AttrSpellingListIndex);
2448 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2449 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2450 FA->getFormatIdx(), FA->getFirstArg(),
2451 AttrSpellingListIndex);
2452 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2453 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2454 AttrSpellingListIndex);
2455 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2456 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2457 AttrSpellingListIndex);
2458 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460 AttrSpellingListIndex,
2461 IA->getSemanticSpelling());
2462 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464 &S.Context.Idents.get(AA->getSpelling()),
2465 AttrSpellingListIndex);
2466 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468 isa<CUDAGlobalAttr>(Attr))) {
2469 // CUDA target attributes are part of function signature for
2470 // overloading purposes and must not be merged.
2471 return false;
2472 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477 NewAttr = S.mergeInternalLinkageAttr(
2478 D, InternalLinkageA->getRange(),
2479 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480 AttrSpellingListIndex);
2481 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483 &S.Context.Idents.get(CommonA->getSpelling()),
2484 AttrSpellingListIndex);
2485 else if (isa<AlignedAttr>(Attr))
2486 // AlignedAttrs are handled separately, because we need to handle all
2487 // such attributes on a declaration at the same time.
2488 NewAttr = nullptr;
2489 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490 (AMK == Sema::AMK_Override ||
2491 AMK == Sema::AMK_ProtocolImplementation))
2492 NewAttr = nullptr;
2493 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2495 UA->getGuid());
2496 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2498
2499 if (NewAttr) {
2500 NewAttr->setInherited(true);
2501 D->addAttr(NewAttr);
2502 if (isa<MSInheritanceAttr>(NewAttr))
2503 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2504 return true;
2505 }
2506
2507 return false;
2508}
2509
2510static const NamedDecl *getDefinition(const Decl *D) {
2511 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512 return TD->getDefinition();
2513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514 const VarDecl *Def = VD->getDefinition();
2515 if (Def)
2516 return Def;
2517 return VD->getActingDefinition();
2518 }
2519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520 return FD->getDefinition();
2521 return nullptr;
2522}
2523
2524static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525 for (const auto *Attribute : D->attrs())
2526 if (Attribute->getKind() == Kind)
2527 return true;
2528 return false;
2529}
2530
2531/// checkNewAttributesAfterDef - If we already have a definition, check that
2532/// there are no new attributes in this declaration.
2533static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534 if (!New->hasAttrs())
2535 return;
2536
2537 const NamedDecl *Def = getDefinition(Old);
2538 if (!Def || Def == New)
2539 return;
2540
2541 AttrVec &NewAttributes = New->getAttrs();
2542 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543 const Attr *NewAttribute = NewAttributes[I];
2544
2545 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547 Sema::SkipBodyInfo SkipBody;
2548 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2549
2550 // If we're skipping this definition, drop the "alias" attribute.
2551 if (SkipBody.ShouldSkip) {
2552 NewAttributes.erase(NewAttributes.begin() + I);
2553 --E;
2554 continue;
2555 }
2556 } else {
2557 VarDecl *VD = cast<VarDecl>(New);
2558 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559 VarDecl::TentativeDefinition
2560 ? diag::err_alias_after_tentative
2561 : diag::err_redefinition;
2562 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563 if (Diag == diag::err_redefinition)
2564 S.notePreviousDefinition(Def, VD->getLocation());
2565 else
2566 S.Diag(Def->getLocation(), diag::note_previous_definition);
2567 VD->setInvalidDecl();
2568 }
2569 ++I;
2570 continue;
2571 }
2572
2573 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574 // Tentative definitions are only interesting for the alias check above.
2575 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2576 ++I;
2577 continue;
2578 }
2579 }
2580
2581 if (hasAttribute(Def, NewAttribute->getKind())) {
2582 ++I;
2583 continue; // regular attr merging will take care of validating this.
2584 }
2585
2586 if (isa<C11NoReturnAttr>(NewAttribute)) {
2587 // C's _Noreturn is allowed to be added to a function after it is defined.
2588 ++I;
2589 continue;
2590 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591 if (AA->isAlignas()) {
2592 // C++11 [dcl.align]p6:
2593 // if any declaration of an entity has an alignment-specifier,
2594 // every defining declaration of that entity shall specify an
2595 // equivalent alignment.
2596 // C11 6.7.5/7:
2597 // If the definition of an object does not have an alignment
2598 // specifier, any other declaration of that object shall also
2599 // have no alignment specifier.
2600 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2601 << AA;
2602 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2603 << AA;
2604 NewAttributes.erase(NewAttributes.begin() + I);
2605 --E;
2606 continue;
2607 }
2608 }
2609
2610 S.Diag(NewAttribute->getLocation(),
2611 diag::warn_attribute_precede_definition);
2612 S.Diag(Def->getLocation(), diag::note_previous_definition);
2613 NewAttributes.erase(NewAttributes.begin() + I);
2614 --E;
2615 }
2616}
2617
2618/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620 AvailabilityMergeKind AMK) {
2621 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622 UsedAttr *NewAttr = OldAttr->clone(Context);
2623 NewAttr->setInherited(true);
2624 New->addAttr(NewAttr);
2625 }
2626
2627 if (!Old->hasAttrs() && !New->hasAttrs())
2628 return;
2629
2630 // Attributes declared post-definition are currently ignored.
2631 checkNewAttributesAfterDef(*this, New, Old);
2632
2633 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635 if (OldA->getLabel() != NewA->getLabel()) {
2636 // This redeclaration changes __asm__ label.
2637 Diag(New->getLocation(), diag::err_different_asm_label);
2638 Diag(OldA->getLocation(), diag::note_previous_declaration);
2639 }
2640 } else if (Old->isUsed()) {
2641 // This redeclaration adds an __asm__ label to a declaration that has
2642 // already been ODR-used.
2643 Diag(New->getLocation(), diag::err_late_asm_label_name)
2644 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2645 }
2646 }
2647
2648 // Re-declaration cannot add abi_tag's.
2649 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653 NewTag) == OldAbiTagAttr->tags_end()) {
2654 Diag(NewAbiTagAttr->getLocation(),
2655 diag::err_new_abi_tag_on_redeclaration)
2656 << NewTag;
2657 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2658 }
2659 }
2660 } else {
2661 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662 Diag(Old->getLocation(), diag::note_previous_declaration);
2663 }
2664 }
2665
2666 // This redeclaration adds a section attribute.
2667 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668 if (auto *VD = dyn_cast<VarDecl>(New)) {
2669 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671 Diag(Old->getLocation(), diag::note_previous_declaration);
2672 }
2673 }
2674 }
2675
2676 // Redeclaration adds code-seg attribute.
2677 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2678 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2679 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2680 Diag(New->getLocation(), diag::warn_mismatched_section)
2681 << 0 /*codeseg*/;
2682 Diag(Old->getLocation(), diag::note_previous_declaration);
2683 }
2684
2685 if (!Old->hasAttrs())
2686 return;
2687
2688 bool foundAny = New->hasAttrs();
2689
2690 // Ensure that any moving of objects within the allocated map is done before
2691 // we process them.
2692 if (!foundAny) New->setAttrs(AttrVec());
2693
2694 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2695 // Ignore deprecated/unavailable/availability attributes if requested.
2696 AvailabilityMergeKind LocalAMK = AMK_None;
2697 if (isa<DeprecatedAttr>(I) ||
2698 isa<UnavailableAttr>(I) ||
2699 isa<AvailabilityAttr>(I)) {
2700 switch (AMK) {
2701 case AMK_None:
2702 continue;
2703
2704 case AMK_Redeclaration:
2705 case AMK_Override:
2706 case AMK_ProtocolImplementation:
2707 LocalAMK = AMK;
2708 break;
2709 }
2710 }
2711
2712 // Already handled.
2713 if (isa<UsedAttr>(I))
2714 continue;
2715
2716 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2717 foundAny = true;
2718 }
2719
2720 if (mergeAlignedAttrs(*this, New, Old))
2721 foundAny = true;
2722
2723 if (!foundAny) New->dropAttrs();
2724}
2725
2726/// mergeParamDeclAttributes - Copy attributes from the old parameter
2727/// to the new one.
2728static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2729 const ParmVarDecl *oldDecl,
2730 Sema &S) {
2731 // C++11 [dcl.attr.depend]p2:
2732 // The first declaration of a function shall specify the
2733 // carries_dependency attribute for its declarator-id if any declaration
2734 // of the function specifies the carries_dependency attribute.
2735 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2736 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2737 S.Diag(CDA->getLocation(),
2738 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2739 // Find the first declaration of the parameter.
2740 // FIXME: Should we build redeclaration chains for function parameters?
2741 const FunctionDecl *FirstFD =
2742 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2743 const ParmVarDecl *FirstVD =
2744 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2745 S.Diag(FirstVD->getLocation(),
2746 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2747 }
2748
2749 if (!oldDecl->hasAttrs())
2750 return;
2751
2752 bool foundAny = newDecl->hasAttrs();
2753
2754 // Ensure that any moving of objects within the allocated map is
2755 // done before we process them.
2756 if (!foundAny) newDecl->setAttrs(AttrVec());
2757
2758 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2759 if (!DeclHasAttr(newDecl, I)) {
2760 InheritableAttr *newAttr =
2761 cast<InheritableParamAttr>(I->clone(S.Context));
2762 newAttr->setInherited(true);
2763 newDecl->addAttr(newAttr);
2764 foundAny = true;
2765 }
2766 }
2767
2768 if (!foundAny) newDecl->dropAttrs();
2769}
2770
2771static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2772 const ParmVarDecl *OldParam,
2773 Sema &S) {
2774 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2775 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2776 if (*Oldnullability != *Newnullability) {
2777 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2778 << DiagNullabilityKind(
2779 *Newnullability,
2780 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2781 != 0))
2782 << DiagNullabilityKind(
2783 *Oldnullability,
2784 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2785 != 0));
2786 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2787 }
2788 } else {
2789 QualType NewT = NewParam->getType();
2790 NewT = S.Context.getAttributedType(
2791 AttributedType::getNullabilityAttrKind(*Oldnullability),
2792 NewT, NewT);
2793 NewParam->setType(NewT);
2794 }
2795 }
2796}
2797
2798namespace {
2799
2800/// Used in MergeFunctionDecl to keep track of function parameters in
2801/// C.
2802struct GNUCompatibleParamWarning {
2803 ParmVarDecl *OldParm;
2804 ParmVarDecl *NewParm;
2805 QualType PromotedType;
2806};
2807
2808} // end anonymous namespace
2809
2810/// getSpecialMember - get the special member enum for a method.
2811Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2812 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2813 if (Ctor->isDefaultConstructor())
2814 return Sema::CXXDefaultConstructor;
2815
2816 if (Ctor->isCopyConstructor())
2817 return Sema::CXXCopyConstructor;
2818
2819 if (Ctor->isMoveConstructor())
2820 return Sema::CXXMoveConstructor;
2821 } else if (isa<CXXDestructorDecl>(MD)) {
2822 return Sema::CXXDestructor;
2823 } else if (MD->isCopyAssignmentOperator()) {
2824 return Sema::CXXCopyAssignment;
2825 } else if (MD->isMoveAssignmentOperator()) {
2826 return Sema::CXXMoveAssignment;
2827 }
2828
2829 return Sema::CXXInvalid;
2830}
2831
2832// Determine whether the previous declaration was a definition, implicit
2833// declaration, or a declaration.
2834template <typename T>
2835static std::pair<diag::kind, SourceLocation>
2836getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2837 diag::kind PrevDiag;
2838 SourceLocation OldLocation = Old->getLocation();
2839 if (Old->isThisDeclarationADefinition())
2840 PrevDiag = diag::note_previous_definition;
2841 else if (Old->isImplicit()) {
2842 PrevDiag = diag::note_previous_implicit_declaration;
2843 if (OldLocation.isInvalid())
2844 OldLocation = New->getLocation();
2845 } else
2846 PrevDiag = diag::note_previous_declaration;
2847 return std::make_pair(PrevDiag, OldLocation);
2848}
2849
2850/// canRedefineFunction - checks if a function can be redefined. Currently,
2851/// only extern inline functions can be redefined, and even then only in
2852/// GNU89 mode.
2853static bool canRedefineFunction(const FunctionDecl *FD,
2854 const LangOptions& LangOpts) {
2855 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2856 !LangOpts.CPlusPlus &&
2857 FD->isInlineSpecified() &&
2858 FD->getStorageClass() == SC_Extern);
2859}
2860
2861const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2862 const AttributedType *AT = T->getAs<AttributedType>();
2863 while (AT && !AT->isCallingConv())
2864 AT = AT->getModifiedType()->getAs<AttributedType>();
2865 return AT;
2866}
2867
2868template <typename T>
2869static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2870 const DeclContext *DC = Old->getDeclContext();
2871 if (DC->isRecord())
2872 return false;
2873
2874 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2875 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2876 return true;
2877 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2878 return true;
2879 return false;
2880}
2881
2882template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2883static bool isExternC(VarTemplateDecl *) { return false; }
2884
2885/// Check whether a redeclaration of an entity introduced by a
2886/// using-declaration is valid, given that we know it's not an overload
2887/// (nor a hidden tag declaration).
2888template<typename ExpectedDecl>
2889static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2890 ExpectedDecl *New) {
2891 // C++11 [basic.scope.declarative]p4:
2892 // Given a set of declarations in a single declarative region, each of
2893 // which specifies the same unqualified name,
2894 // -- they shall all refer to the same entity, or all refer to functions
2895 // and function templates; or
2896 // -- exactly one declaration shall declare a class name or enumeration
2897 // name that is not a typedef name and the other declarations shall all
2898 // refer to the same variable or enumerator, or all refer to functions
2899 // and function templates; in this case the class name or enumeration
2900 // name is hidden (3.3.10).
2901
2902 // C++11 [namespace.udecl]p14:
2903 // If a function declaration in namespace scope or block scope has the
2904 // same name and the same parameter-type-list as a function introduced
2905 // by a using-declaration, and the declarations do not declare the same
2906 // function, the program is ill-formed.
2907
2908 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2909 if (Old &&
2910 !Old->getDeclContext()->getRedeclContext()->Equals(
2911 New->getDeclContext()->getRedeclContext()) &&
2912 !(isExternC(Old) && isExternC(New)))
2913 Old = nullptr;
2914
2915 if (!Old) {
2916 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2917 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2918 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2919 return true;
2920 }
2921 return false;
2922}
2923
2924static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2925 const FunctionDecl *B) {
2926 assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams
()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 2926, __extension__ __PRETTY_FUNCTION__))
;
2927
2928 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2929 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2930 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2931 if (AttrA == AttrB)
2932 return true;
2933 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2934 };
2935
2936 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2937}
2938
2939/// If necessary, adjust the semantic declaration context for a qualified
2940/// declaration to name the correct inline namespace within the qualifier.
2941static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2942 DeclaratorDecl *OldD) {
2943 // The only case where we need to update the DeclContext is when
2944 // redeclaration lookup for a qualified name finds a declaration
2945 // in an inline namespace within the context named by the qualifier:
2946 //
2947 // inline namespace N { int f(); }
2948 // int ::f(); // Sema DC needs adjusting from :: to N::.
2949 //
2950 // For unqualified declarations, the semantic context *can* change
2951 // along the redeclaration chain (for local extern declarations,
2952 // extern "C" declarations, and friend declarations in particular).
2953 if (!NewD->getQualifier())
2954 return;
2955
2956 // NewD is probably already in the right context.
2957 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2958 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2959 if (NamedDC->Equals(SemaDC))
2960 return;
2961
2962 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 2964, __extension__ __PRETTY_FUNCTION__))
2963 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 2964, __extension__ __PRETTY_FUNCTION__))
2964 "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 2964, __extension__ __PRETTY_FUNCTION__))
;
2965
2966 auto *LexDC = NewD->getLexicalDeclContext();
2967 auto FixSemaDC = [=](NamedDecl *D) {
2968 if (!D)
2969 return;
2970 D->setDeclContext(SemaDC);
2971 D->setLexicalDeclContext(LexDC);
2972 };
2973
2974 FixSemaDC(NewD);
2975 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2976 FixSemaDC(FD->getDescribedFunctionTemplate());
2977 else if (auto *VD = dyn_cast<VarDecl>(NewD))
2978 FixSemaDC(VD->getDescribedVarTemplate());
2979}
2980
2981/// MergeFunctionDecl - We just parsed a function 'New' from
2982/// declarator D which has the same name and scope as a previous
2983/// declaration 'Old'. Figure out how to resolve this situation,
2984/// merging decls or emitting diagnostics as appropriate.
2985///
2986/// In C++, New and Old must be declarations that are not
2987/// overloaded. Use IsOverload to determine whether New and Old are
2988/// overloaded, and to select the Old declaration that New should be
2989/// merged with.
2990///
2991/// Returns true if there was an error, false otherwise.
2992bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2993 Scope *S, bool MergeTypeWithOld) {
2994 // Verify the old decl was also a function.
2995 FunctionDecl *Old = OldD->getAsFunction();
2996 if (!Old) {
2997 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2998 if (New->getFriendObjectKind()) {
2999 Diag(New->getLocation(), diag::err_using_decl_friend);
3000 Diag(Shadow->getTargetDecl()->getLocation(),
3001 diag::note_using_decl_target);
3002 Diag(Shadow->getUsingDecl()->getLocation(),
3003 diag::note_using_decl) << 0;
3004 return true;
3005 }
3006
3007 // Check whether the two declarations might declare the same function.
3008 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3009 return true;
3010 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3011 } else {
3012 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3013 << New->getDeclName();
3014 notePreviousDefinition(OldD, New->getLocation());
3015 return true;
3016 }
3017 }
3018
3019 // If the old declaration is invalid, just give up here.
3020 if (Old->isInvalidDecl())
3021 return true;
3022
3023 // Disallow redeclaration of some builtins.
3024 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3025 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3026 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3027 << Old << Old->getType();
3028 return true;
3029 }
3030
3031 diag::kind PrevDiag;
3032 SourceLocation OldLocation;
3033 std::tie(PrevDiag, OldLocation) =
3034 getNoteDiagForInvalidRedeclaration(Old, New);
3035
3036 // Don't complain about this if we're in GNU89 mode and the old function
3037 // is an extern inline function.
3038 // Don't complain about specializations. They are not supposed to have
3039 // storage classes.
3040 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3041 New->getStorageClass() == SC_Static &&
3042 Old->hasExternalFormalLinkage() &&
3043 !New->getTemplateSpecializationInfo() &&
3044 !canRedefineFunction(Old, getLangOpts())) {
3045 if (getLangOpts().MicrosoftExt) {
3046 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3047 Diag(OldLocation, PrevDiag);
3048 } else {
3049 Diag(New->getLocation(), diag::err_static_non_static) << New;
3050 Diag(OldLocation, PrevDiag);
3051 return true;
3052 }
3053 }
3054
3055 if (New->hasAttr<InternalLinkageAttr>() &&
3056 !Old->hasAttr<InternalLinkageAttr>()) {
3057 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3058 << New->getDeclName();
3059 notePreviousDefinition(Old, New->getLocation());
3060 New->dropAttr<InternalLinkageAttr>();
3061 }
3062
3063 if (CheckRedeclarationModuleOwnership(New, Old))
3064 return true;
3065
3066 if (!getLangOpts().CPlusPlus) {
3067 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3068 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3069 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3070 << New << OldOvl;
3071
3072 // Try our best to find a decl that actually has the overloadable
3073 // attribute for the note. In most cases (e.g. programs with only one
3074 // broken declaration/definition), this won't matter.
3075 //
3076 // FIXME: We could do this if we juggled some extra state in
3077 // OverloadableAttr, rather than just removing it.
3078 const Decl *DiagOld = Old;
3079 if (OldOvl) {
3080 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3081 const auto *A = D->getAttr<OverloadableAttr>();
3082 return A && !A->isImplicit();
3083 });
3084 // If we've implicitly added *all* of the overloadable attrs to this
3085 // chain, emitting a "previous redecl" note is pointless.
3086 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3087 }
3088
3089 if (DiagOld)
3090 Diag(DiagOld->getLocation(),
3091 diag::note_attribute_overloadable_prev_overload)
3092 << OldOvl;
3093
3094 if (OldOvl)
3095 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3096 else
3097 New->dropAttr<OverloadableAttr>();
3098 }
3099 }
3100
3101 // If a function is first declared with a calling convention, but is later
3102 // declared or defined without one, all following decls assume the calling
3103 // convention of the first.
3104 //
3105 // It's OK if a function is first declared without a calling convention,
3106 // but is later declared or defined with the default calling convention.
3107 //
3108 // To test if either decl has an explicit calling convention, we look for
3109 // AttributedType sugar nodes on the type as written. If they are missing or
3110 // were canonicalized away, we assume the calling convention was implicit.
3111 //
3112 // Note also that we DO NOT return at this point, because we still have
3113 // other tests to run.
3114 QualType OldQType = Context.getCanonicalType(Old->getType());
3115 QualType NewQType = Context.getCanonicalType(New->getType());
3116 const FunctionType *OldType = cast<FunctionType>(OldQType);
3117 const FunctionType *NewType = cast<FunctionType>(NewQType);
3118 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3119 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3120 bool RequiresAdjustment = false;
3121
3122 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3123 FunctionDecl *First = Old->getFirstDecl();
3124 const FunctionType *FT =
3125 First->getType().getCanonicalType()->castAs<FunctionType>();
3126 FunctionType::ExtInfo FI = FT->getExtInfo();
3127 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3128 if (!NewCCExplicit) {
3129 // Inherit the CC from the previous declaration if it was specified
3130 // there but not here.
3131 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3132 RequiresAdjustment = true;
3133 } else {
3134 // Calling conventions aren't compatible, so complain.
3135 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3136 Diag(New->getLocation(), diag::err_cconv_change)
3137 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3138 << !FirstCCExplicit
3139 << (!FirstCCExplicit ? "" :
3140 FunctionType::getNameForCallConv(FI.getCC()));
3141
3142 // Put the note on the first decl, since it is the one that matters.
3143 Diag(First->getLocation(), diag::note_previous_declaration);
3144 return true;
3145 }
3146 }
3147
3148 // FIXME: diagnose the other way around?
3149 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3150 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3151 RequiresAdjustment = true;
3152 }
3153
3154 // Merge regparm attribute.
3155 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3156 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3157 if (NewTypeInfo.getHasRegParm()) {
3158 Diag(New->getLocation(), diag::err_regparm_mismatch)
3159 << NewType->getRegParmType()
3160 << OldType->getRegParmType();
3161 Diag(OldLocation, diag::note_previous_declaration);
3162 return true;
3163 }
3164
3165 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3166 RequiresAdjustment = true;
3167 }
3168
3169 // Merge ns_returns_retained attribute.
3170 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3171 if (NewTypeInfo.getProducesResult()) {
3172 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3173 << "'ns_returns_retained'";
3174 Diag(OldLocation, diag::note_previous_declaration);
3175 return true;
3176 }
3177
3178 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3179 RequiresAdjustment = true;
3180 }
3181
3182 if (OldTypeInfo.getNoCallerSavedRegs() !=
3183 NewTypeInfo.getNoCallerSavedRegs()) {
3184 if (NewTypeInfo.getNoCallerSavedRegs()) {
3185 AnyX86NoCallerSavedRegistersAttr *Attr =
3186 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3187 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3188 Diag(OldLocation, diag::note_previous_declaration);
3189 return true;
3190 }
3191
3192 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3193 RequiresAdjustment = true;
3194 }
3195
3196 if (RequiresAdjustment) {
3197 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3198 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3199 New->setType(QualType(AdjustedType, 0));
3200 NewQType = Context.getCanonicalType(New->getType());
3201 NewType = cast<FunctionType>(NewQType);
3202 }
3203
3204 // If this redeclaration makes the function inline, we may need to add it to
3205 // UndefinedButUsed.
3206 if (!Old->isInlined() && New->isInlined() &&
3207 !New->hasAttr<GNUInlineAttr>() &&
3208 !getLangOpts().GNUInline &&
3209 Old->isUsed(false) &&
3210 !Old->isDefined() && !New->isThisDeclarationADefinition())
3211 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3212 SourceLocation()));
3213
3214 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3215 // about it.
3216 if (New->hasAttr<GNUInlineAttr>() &&
3217 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3218 UndefinedButUsed.erase(Old->getCanonicalDecl());
3219 }
3220
3221 // If pass_object_size params don't match up perfectly, this isn't a valid
3222 // redeclaration.
3223 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3224 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3225 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3226 << New->getDeclName();
3227 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3228 return true;
3229 }
3230
3231 if (getLangOpts().CPlusPlus) {
3232 // C++1z [over.load]p2
3233 // Certain function declarations cannot be overloaded:
3234 // -- Function declarations that differ only in the return type,
3235 // the exception specification, or both cannot be overloaded.
3236
3237 // Check the exception specifications match. This may recompute the type of
3238 // both Old and New if it resolved exception specifications, so grab the
3239 // types again after this. Because this updates the type, we do this before
3240 // any of the other checks below, which may update the "de facto" NewQType
3241 // but do not necessarily update the type of New.
3242 if (CheckEquivalentExceptionSpec(Old, New))
3243 return true;
3244 OldQType = Context.getCanonicalType(Old->getType());
3245 NewQType = Context.getCanonicalType(New->getType());
3246
3247 // Go back to the type source info to compare the declared return types,
3248 // per C++1y [dcl.type.auto]p13:
3249 // Redeclarations or specializations of a function or function template
3250 // with a declared return type that uses a placeholder type shall also
3251 // use that placeholder, not a deduced type.
3252 QualType OldDeclaredReturnType =
3253 (Old->getTypeSourceInfo()
3254 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3255 : OldType)->getReturnType();
3256 QualType NewDeclaredReturnType =
3257 (New->getTypeSourceInfo()
3258 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3259 : NewType)->getReturnType();
3260 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3261 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3262 New->isLocalExternDecl())) {
3263 QualType ResQT;
3264 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3265 OldDeclaredReturnType->isObjCObjectPointerType())
3266 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3267 if (ResQT.isNull()) {
3268 if (New->isCXXClassMember() && New->isOutOfLine())
3269 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3270 << New << New->getReturnTypeSourceRange();
3271 else
3272 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3273 << New->getReturnTypeSourceRange();
3274 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3275 << Old->getReturnTypeSourceRange();
3276 return true;
3277 }
3278 else
3279 NewQType = ResQT;
3280 }
3281
3282 QualType OldReturnType = OldType->getReturnType();
3283 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3284 if (OldReturnType != NewReturnType) {
3285 // If this function has a deduced return type and has already been
3286 // defined, copy the deduced value from the old declaration.
3287 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3288 if (OldAT && OldAT->isDeduced()) {
3289 New->setType(
3290 SubstAutoType(New->getType(),
3291 OldAT->isDependentType() ? Context.DependentTy
3292 : OldAT->getDeducedType()));
3293 NewQType = Context.getCanonicalType(
3294 SubstAutoType(NewQType,
3295 OldAT->isDependentType() ? Context.DependentTy
3296 : OldAT->getDeducedType()));
3297 }
3298 }
3299
3300 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3301 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3302 if (OldMethod && NewMethod) {
3303 // Preserve triviality.
3304 NewMethod->setTrivial(OldMethod->isTrivial());
3305
3306 // MSVC allows explicit template specialization at class scope:
3307 // 2 CXXMethodDecls referring to the same function will be injected.
3308 // We don't want a redeclaration error.
3309 bool IsClassScopeExplicitSpecialization =
3310 OldMethod->isFunctionTemplateSpecialization() &&
3311 NewMethod->isFunctionTemplateSpecialization();
3312 bool isFriend = NewMethod->getFriendObjectKind();
3313
3314 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3315 !IsClassScopeExplicitSpecialization) {
3316 // -- Member function declarations with the same name and the
3317 // same parameter types cannot be overloaded if any of them
3318 // is a static member function declaration.
3319 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3320 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3321 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3322 return true;
3323 }
3324
3325 // C++ [class.mem]p1:
3326 // [...] A member shall not be declared twice in the
3327 // member-specification, except that a nested class or member
3328 // class template can be declared and then later defined.
3329 if (!inTemplateInstantiation()) {
3330 unsigned NewDiag;
3331 if (isa<CXXConstructorDecl>(OldMethod))
3332 NewDiag = diag::err_constructor_redeclared;
3333 else if (isa<CXXDestructorDecl>(NewMethod))
3334 NewDiag = diag::err_destructor_redeclared;
3335 else if (isa<CXXConversionDecl>(NewMethod))
3336 NewDiag = diag::err_conv_function_redeclared;
3337 else
3338 NewDiag = diag::err_member_redeclared;
3339
3340 Diag(New->getLocation(), NewDiag);
3341 } else {
3342 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3343 << New << New->getType();
3344 }
3345 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3346 return true;
3347
3348 // Complain if this is an explicit declaration of a special
3349 // member that was initially declared implicitly.
3350 //
3351 // As an exception, it's okay to befriend such methods in order
3352 // to permit the implicit constructor/destructor/operator calls.
3353 } else if (OldMethod->isImplicit()) {
3354 if (isFriend) {
3355 NewMethod->setImplicit();
3356 } else {
3357 Diag(NewMethod->getLocation(),
3358 diag::err_definition_of_implicitly_declared_member)
3359 << New << getSpecialMember(OldMethod);
3360 return true;
3361 }
3362 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3363 Diag(NewMethod->getLocation(),
3364 diag::err_definition_of_explicitly_defaulted_member)
3365 << getSpecialMember(OldMethod);
3366 return true;
3367 }
3368 }
3369
3370 // C++11 [dcl.attr.noreturn]p1:
3371 // The first declaration of a function shall specify the noreturn
3372 // attribute if any declaration of that function specifies the noreturn
3373 // attribute.
3374 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3375 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3376 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3377 Diag(Old->getFirstDecl()->getLocation(),
3378 diag::note_noreturn_missing_first_decl);
3379 }
3380
3381 // C++11 [dcl.attr.depend]p2:
3382 // The first declaration of a function shall specify the
3383 // carries_dependency attribute for its declarator-id if any declaration
3384 // of the function specifies the carries_dependency attribute.
3385 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3386 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3387 Diag(CDA->getLocation(),
3388 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3389 Diag(Old->getFirstDecl()->getLocation(),
3390 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3391 }
3392
3393 // (C++98 8.3.5p3):
3394 // All declarations for a function shall agree exactly in both the
3395 // return type and the parameter-type-list.
3396 // We also want to respect all the extended bits except noreturn.
3397
3398 // noreturn should now match unless the old type info didn't have it.
3399 QualType OldQTypeForComparison = OldQType;
3400 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3401 auto *OldType = OldQType->castAs<FunctionProtoType>();
3402 const FunctionType *OldTypeForComparison
3403 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3404 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3405 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 3405, __extension__ __PRETTY_FUNCTION__))
;
3406 }
3407
3408 if (haveIncompatibleLanguageLinkages(Old, New)) {
3409 // As a special case, retain the language linkage from previous
3410 // declarations of a friend function as an extension.
3411 //
3412 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3413 // and is useful because there's otherwise no way to specify language
3414 // linkage within class scope.
3415 //
3416 // Check cautiously as the friend object kind isn't yet complete.
3417 if (New->getFriendObjectKind() != Decl::FOK_None) {
3418 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3419 Diag(OldLocation, PrevDiag);
3420 } else {
3421 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3422 Diag(OldLocation, PrevDiag);
3423 return true;
3424 }
3425 }
3426
3427 if (OldQTypeForComparison == NewQType)
3428 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3429
3430 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3431 New->isLocalExternDecl()) {
3432 // It's OK if we couldn't merge types for a local function declaraton
3433 // if either the old or new type is dependent. We'll merge the types
3434 // when we instantiate the function.
3435 return false;
3436 }
3437
3438 // Fall through for conflicting redeclarations and redefinitions.
3439 }
3440
3441 // C: Function types need to be compatible, not identical. This handles
3442 // duplicate function decls like "void f(int); void f(enum X);" properly.
3443 if (!getLangOpts().CPlusPlus &&
3444 Context.typesAreCompatible(OldQType, NewQType)) {
3445 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3446 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3447 const FunctionProtoType *OldProto = nullptr;
3448 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3449 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3450 // The old declaration provided a function prototype, but the
3451 // new declaration does not. Merge in the prototype.
3452 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() &&
"Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 3452, __extension__ __PRETTY_FUNCTION__))
;
3453 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3454 NewQType =
3455 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3456 OldProto->getExtProtoInfo());
3457 New->setType(NewQType);
3458 New->setHasInheritedPrototype();
3459
3460 // Synthesize parameters with the same types.
3461 SmallVector<ParmVarDecl*, 16> Params;
3462 for (const auto &ParamType : OldProto->param_types()) {
3463 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3464 SourceLocation(), nullptr,
3465 ParamType, /*TInfo=*/nullptr,
3466 SC_None, nullptr);
3467 Param->setScopeInfo(0, Params.size());
3468 Param->setImplicit();
3469 Params.push_back(Param);
3470 }
3471
3472 New->setParams(Params);
3473 }
3474
3475 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3476 }
3477
3478 // GNU C permits a K&R definition to follow a prototype declaration
3479 // if the declared types of the parameters in the K&R definition
3480 // match the types in the prototype declaration, even when the
3481 // promoted types of the parameters from the K&R definition differ
3482 // from the types in the prototype. GCC then keeps the types from
3483 // the prototype.
3484 //
3485 // If a variadic prototype is followed by a non-variadic K&R definition,
3486 // the K&R definition becomes variadic. This is sort of an edge case, but
3487 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3488 // C99 6.9.1p8.
3489 if (!getLangOpts().CPlusPlus &&
3490 Old->hasPrototype() && !New->hasPrototype() &&
3491 New->getType()->getAs<FunctionProtoType>() &&
3492 Old->getNumParams() == New->getNumParams()) {
3493 SmallVector<QualType, 16> ArgTypes;
3494 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3495 const FunctionProtoType *OldProto
3496 = Old->getType()->getAs<FunctionProtoType>();
3497 const FunctionProtoType *NewProto
3498 = New->getType()->getAs<FunctionProtoType>();
3499
3500 // Determine whether this is the GNU C extension.
3501 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3502 NewProto->getReturnType());
3503 bool LooseCompatible = !MergedReturn.isNull();
3504 for (unsigned Idx = 0, End = Old->getNumParams();
3505 LooseCompatible && Idx != End; ++Idx) {
3506 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3507 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3508 if (Context.typesAreCompatible(OldParm->getType(),
3509 NewProto->getParamType(Idx))) {
3510 ArgTypes.push_back(NewParm->getType());
3511 } else if (Context.typesAreCompatible(OldParm->getType(),
3512 NewParm->getType(),
3513 /*CompareUnqualified=*/true)) {
3514 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3515 NewProto->getParamType(Idx) };
3516 Warnings.push_back(Warn);
3517 ArgTypes.push_back(NewParm->getType());
3518 } else
3519 LooseCompatible = false;
3520 }
3521
3522 if (LooseCompatible) {
3523 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3524 Diag(Warnings[Warn].NewParm->getLocation(),
3525 diag::ext_param_promoted_not_compatible_with_prototype)
3526 << Warnings[Warn].PromotedType
3527 << Warnings[Warn].OldParm->getType();
3528 if (Warnings[Warn].OldParm->getLocation().isValid())
3529 Diag(Warnings[Warn].OldParm->getLocation(),
3530 diag::note_previous_declaration);
3531 }
3532
3533 if (MergeTypeWithOld)
3534 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3535 OldProto->getExtProtoInfo()));
3536 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3537 }
3538
3539 // Fall through to diagnose conflicting types.
3540 }
3541
3542 // A function that has already been declared has been redeclared or
3543 // defined with a different type; show an appropriate diagnostic.
3544
3545 // If the previous declaration was an implicitly-generated builtin
3546 // declaration, then at the very least we should use a specialized note.
3547 unsigned BuiltinID;
3548 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3549 // If it's actually a library-defined builtin function like 'malloc'
3550 // or 'printf', just warn about the incompatible redeclaration.
3551 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3552 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3553 Diag(OldLocation, diag::note_previous_builtin_declaration)
3554 << Old << Old->getType();
3555
3556 // If this is a global redeclaration, just forget hereafter
3557 // about the "builtin-ness" of the function.
3558 //
3559 // Doing this for local extern declarations is problematic. If
3560 // the builtin declaration remains visible, a second invalid
3561 // local declaration will produce a hard error; if it doesn't
3562 // remain visible, a single bogus local redeclaration (which is
3563 // actually only a warning) could break all the downstream code.
3564 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3565 New->getIdentifier()->revertBuiltin();
3566
3567 return false;
3568 }
3569
3570 PrevDiag = diag::note_previous_builtin_declaration;
3571 }
3572
3573 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3574 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3575 return true;
3576}
3577
3578/// Completes the merge of two function declarations that are
3579/// known to be compatible.
3580///
3581/// This routine handles the merging of attributes and other
3582/// properties of function declarations from the old declaration to
3583/// the new declaration, once we know that New is in fact a
3584/// redeclaration of Old.
3585///
3586/// \returns false
3587bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3588 Scope *S, bool MergeTypeWithOld) {
3589 // Merge the attributes
3590 mergeDeclAttributes(New, Old);
3591
3592 // Merge "pure" flag.
3593 if (Old->isPure())
3594 New->setPure();
3595
3596 // Merge "used" flag.
3597 if (Old->getMostRecentDecl()->isUsed(false))
3598 New->setIsUsed();
3599
3600 // Merge attributes from the parameters. These can mismatch with K&R
3601 // declarations.
3602 if (New->getNumParams() == Old->getNumParams())
3603 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3604 ParmVarDecl *NewParam = New->getParamDecl(i);
3605 ParmVarDecl *OldParam = Old->getParamDecl(i);
3606 mergeParamDeclAttributes(NewParam, OldParam, *this);
3607 mergeParamDeclTypes(NewParam, OldParam, *this);
3608 }
3609
3610 if (getLangOpts().CPlusPlus)
3611 return MergeCXXFunctionDecl(New, Old, S);
3612
3613 // Merge the function types so the we get the composite types for the return
3614 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3615 // was visible.
3616 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3617 if (!Merged.isNull() && MergeTypeWithOld)
3618 New->setType(Merged);
3619
3620 return false;
3621}
3622
3623void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3624 ObjCMethodDecl *oldMethod) {
3625 // Merge the attributes, including deprecated/unavailable
3626 AvailabilityMergeKind MergeKind =
3627 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3628 ? AMK_ProtocolImplementation
3629 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3630 : AMK_Override;
3631
3632 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3633
3634 // Merge attributes from the parameters.
3635 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3636 oe = oldMethod->param_end();
3637 for (ObjCMethodDecl::param_iterator
3638 ni = newMethod->param_begin(), ne = newMethod->param_end();
3639 ni != ne && oi != oe; ++ni, ++oi)
3640 mergeParamDeclAttributes(*ni, *oi, *this);
3641
3642 CheckObjCMethodOverride(newMethod, oldMethod);
3643}
3644
3645static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3646 assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType
(), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 3646, __extension__ __PRETTY_FUNCTION__))
;
3647
3648 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3649 ? diag::err_redefinition_different_type
3650 : diag::err_redeclaration_different_type)
3651 << New->getDeclName() << New->getType() << Old->getType();
3652
3653 diag::kind PrevDiag;
3654 SourceLocation OldLocation;
3655 std::tie(PrevDiag, OldLocation)
3656 = getNoteDiagForInvalidRedeclaration(Old, New);
3657 S.Diag(OldLocation, PrevDiag);
3658 New->setInvalidDecl();
3659}
3660
3661/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3662/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3663/// emitting diagnostics as appropriate.
3664///
3665/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3666/// to here in AddInitializerToDecl. We can't check them before the initializer
3667/// is attached.
3668void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3669 bool MergeTypeWithOld) {
3670 if (New->isInvalidDecl() || Old->isInvalidDecl())
3671 return;
3672
3673 QualType MergedT;
3674 if (getLangOpts().CPlusPlus) {
3675 if (New->getType()->isUndeducedType()) {
3676 // We don't know what the new type is until the initializer is attached.
3677 return;
3678 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3679 // These could still be something that needs exception specs checked.
3680 return MergeVarDeclExceptionSpecs(New, Old);
3681 }
3682 // C++ [basic.link]p10:
3683 // [...] the types specified by all declarations referring to a given
3684 // object or function shall be identical, except that declarations for an
3685 // array object can specify array types that differ by the presence or
3686 // absence of a major array bound (8.3.4).
3687 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3688 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3689 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3690
3691 // We are merging a variable declaration New into Old. If it has an array
3692 // bound, and that bound differs from Old's bound, we should diagnose the
3693 // mismatch.
3694 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3695 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3696 PrevVD = PrevVD->getPreviousDecl()) {
3697 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3698 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3699 continue;
3700
3701 if (!Context.hasSameType(NewArray, PrevVDTy))
3702 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3703 }
3704 }
3705
3706 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3707 if (Context.hasSameType(OldArray->getElementType(),
3708 NewArray->getElementType()))
3709 MergedT = New->getType();
3710 }
3711 // FIXME: Check visibility. New is hidden but has a complete type. If New
3712 // has no array bound, it should not inherit one from Old, if Old is not
3713 // visible.
3714 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3715 if (Context.hasSameType(OldArray->getElementType(),
3716 NewArray->getElementType()))
3717 MergedT = Old->getType();
3718 }
3719 }
3720 else if (New->getType()->isObjCObjectPointerType() &&
3721 Old->getType()->isObjCObjectPointerType()) {
3722 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3723 Old->getType());
3724 }
3725 } else {
3726 // C 6.2.7p2:
3727 // All declarations that refer to the same object or function shall have
3728 // compatible type.
3729 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3730 }
3731 if (MergedT.isNull()) {
3732 // It's OK if we couldn't merge types if either type is dependent, for a
3733 // block-scope variable. In other cases (static data members of class
3734 // templates, variable templates, ...), we require the types to be
3735 // equivalent.
3736 // FIXME: The C++ standard doesn't say anything about this.
3737 if ((New->getType()->isDependentType() ||
3738 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3739 // If the old type was dependent, we can't merge with it, so the new type
3740 // becomes dependent for now. We'll reproduce the original type when we
3741 // instantiate the TypeSourceInfo for the variable.
3742 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3743 New->setType(Context.DependentTy);
3744 return;
3745 }
3746 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3747 }
3748
3749 // Don't actually update the type on the new declaration if the old
3750 // declaration was an extern declaration in a different scope.
3751 if (MergeTypeWithOld)
3752 New->setType(MergedT);
3753}
3754
3755static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3756 LookupResult &Previous) {
3757 // C11 6.2.7p4:
3758 // For an identifier with internal or external linkage declared
3759 // in a scope in which a prior declaration of that identifier is
3760 // visible, if the prior declaration specifies internal or
3761 // external linkage, the type of the identifier at the later
3762 // declaration becomes the composite type.
3763 //
3764 // If the variable isn't visible, we do not merge with its type.
3765 if (Previous.isShadowed())
3766 return false;
3767
3768 if (S.getLangOpts().CPlusPlus) {
3769 // C++11 [dcl.array]p3:
3770 // If there is a preceding declaration of the entity in the same
3771 // scope in which the bound was specified, an omitted array bound
3772 // is taken to be the same as in that earlier declaration.
3773 return NewVD->isPreviousDeclInSameBlockScope() ||
3774 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3775 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3776 } else {
3777 // If the old declaration was function-local, don't merge with its
3778 // type unless we're in the same function.
3779 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3780 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3781 }
3782}
3783
3784/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3785/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3786/// situation, merging decls or emitting diagnostics as appropriate.
3787///
3788/// Tentative definition rules (C99 6.9.2p2) are checked by
3789/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3790/// definitions here, since the initializer hasn't been attached.
3791///
3792void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3793 // If the new decl is already invalid, don't do any other checking.
3794 if (New->isInvalidDecl())
3795 return;
3796
3797 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3798 return;
3799
3800 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3801
3802 // Verify the old decl was also a variable or variable template.
3803 VarDecl *Old = nullptr;
3804 VarTemplateDecl *OldTemplate = nullptr;
3805 if (Previous.isSingleResult()) {
3806 if (NewTemplate) {
3807 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3808 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3809
3810 if (auto *Shadow =
3811 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3812 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3813 return New->setInvalidDecl();
3814 } else {
3815 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3816
3817 if (auto *Shadow =
3818 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3819 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3820 return New->setInvalidDecl();
3821 }
3822 }
3823 if (!Old) {
3824 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3825 << New->getDeclName();
3826 notePreviousDefinition(Previous.getRepresentativeDecl(),
3827 New->getLocation());
3828 return New->setInvalidDecl();
3829 }
3830
3831 // Ensure the template parameters are compatible.
3832 if (NewTemplate &&
3833 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3834 OldTemplate->getTemplateParameters(),
3835 /*Complain=*/true, TPL_TemplateMatch))
3836 return New->setInvalidDecl();
3837
3838 // C++ [class.mem]p1:
3839 // A member shall not be declared twice in the member-specification [...]
3840 //
3841 // Here, we need only consider static data members.
3842 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3843 Diag(New->getLocation(), diag::err_duplicate_member)
3844 << New->getIdentifier();
3845 Diag(Old->getLocation(), diag::note_previous_declaration);
3846 New->setInvalidDecl();
3847 }
3848
3849 mergeDeclAttributes(New, Old);
3850 // Warn if an already-declared variable is made a weak_import in a subsequent
3851 // declaration
3852 if (New->hasAttr<WeakImportAttr>() &&
3853 Old->getStorageClass() == SC_None &&
3854 !Old->hasAttr<WeakImportAttr>()) {
3855 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3856 notePreviousDefinition(Old, New->getLocation());
3857 // Remove weak_import attribute on new declaration.
3858 New->dropAttr<WeakImportAttr>();
3859 }
3860
3861 if (New->hasAttr<InternalLinkageAttr>() &&
3862 !Old->hasAttr<InternalLinkageAttr>()) {
3863 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3864 << New->getDeclName();
3865 notePreviousDefinition(Old, New->getLocation());
3866 New->dropAttr<InternalLinkageAttr>();
3867 }
3868
3869 // Merge the types.
3870 VarDecl *MostRecent = Old->getMostRecentDecl();
3871 if (MostRecent != Old) {
3872 MergeVarDeclTypes(New, MostRecent,
3873 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3874 if (New->isInvalidDecl())
3875 return;
3876 }
3877
3878 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3879 if (New->isInvalidDecl())
3880 return;
3881
3882 diag::kind PrevDiag;
3883 SourceLocation OldLocation;
3884 std::tie(PrevDiag, OldLocation) =
3885 getNoteDiagForInvalidRedeclaration(Old, New);
3886
3887 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3888 if (New->getStorageClass() == SC_Static &&
3889 !New->isStaticDataMember() &&
3890 Old->hasExternalFormalLinkage()) {
3891 if (getLangOpts().MicrosoftExt) {
3892 Diag(New->getLocation(), diag::ext_static_non_static)
3893 << New->getDeclName();
3894 Diag(OldLocation, PrevDiag);
3895 } else {
3896 Diag(New->getLocation(), diag::err_static_non_static)
3897 << New->getDeclName();
3898 Diag(OldLocation, PrevDiag);
3899 return New->setInvalidDecl();
3900 }
3901 }
3902 // C99 6.2.2p4:
3903 // For an identifier declared with the storage-class specifier
3904 // extern in a scope in which a prior declaration of that
3905 // identifier is visible,23) if the prior declaration specifies
3906 // internal or external linkage, the linkage of the identifier at
3907 // the later declaration is the same as the linkage specified at
3908 // the prior declaration. If no prior declaration is visible, or
3909 // if the prior declaration specifies no linkage, then the
3910 // identifier has external linkage.
3911 if (New->hasExternalStorage() && Old->hasLinkage())
3912 /* Okay */;
3913 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3914 !New->isStaticDataMember() &&
3915 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3916 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3917 Diag(OldLocation, PrevDiag);
3918 return New->setInvalidDecl();
3919 }
3920
3921 // Check if extern is followed by non-extern and vice-versa.
3922 if (New->hasExternalStorage() &&
3923 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3924 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3925 Diag(OldLocation, PrevDiag);
3926 return New->setInvalidDecl();
3927 }
3928 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3929 !New->hasExternalStorage()) {
3930 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3931 Diag(OldLocation, PrevDiag);
3932 return New->setInvalidDecl();
3933 }
3934
3935 if (CheckRedeclarationModuleOwnership(New, Old))
3936 return;
3937
3938 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3939
3940 // FIXME: The test for external storage here seems wrong? We still
3941 // need to check for mismatches.
3942 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3943 // Don't complain about out-of-line definitions of static members.
3944 !(Old->getLexicalDeclContext()->isRecord() &&
3945 !New->getLexicalDeclContext()->isRecord())) {
3946 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3947 Diag(OldLocation, PrevDiag);
3948 return New->setInvalidDecl();
3949 }
3950
3951 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3952 if (VarDecl *Def = Old->getDefinition()) {
3953 // C++1z [dcl.fcn.spec]p4:
3954 // If the definition of a variable appears in a translation unit before
3955 // its first declaration as inline, the program is ill-formed.
3956 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3957 Diag(Def->getLocation(), diag::note_previous_definition);
3958 }
3959 }
3960
3961 // If this redeclaration makes the variable inline, we may need to add it to
3962 // UndefinedButUsed.
3963 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3964 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3965 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3966 SourceLocation()));
3967
3968 if (New->getTLSKind() != Old->getTLSKind()) {
3969 if (!Old->getTLSKind()) {
3970 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3971 Diag(OldLocation, PrevDiag);
3972 } else if (!New->getTLSKind()) {
3973 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3974 Diag(OldLocation, PrevDiag);
3975 } else {
3976 // Do not allow redeclaration to change the variable between requiring
3977 // static and dynamic initialization.
3978 // FIXME: GCC allows this, but uses the TLS keyword on the first
3979 // declaration to determine the kind. Do we need to be compatible here?
3980 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3981 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3982 Diag(OldLocation, PrevDiag);
3983 }
3984 }
3985
3986 // C++ doesn't have tentative definitions, so go right ahead and check here.
3987 if (getLangOpts().CPlusPlus &&
3988 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3989 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3990 Old->getCanonicalDecl()->isConstexpr()) {
3991 // This definition won't be a definition any more once it's been merged.
3992 Diag(New->getLocation(),
3993 diag::warn_deprecated_redundant_constexpr_static_def);
3994 } else if (VarDecl *Def = Old->getDefinition()) {
3995 if (checkVarDeclRedefinition(Def, New))
3996 return;
3997 }
3998 }
3999
4000 if (haveIncompatibleLanguageLinkages(Old, New)) {
4001 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4002 Diag(OldLocation, PrevDiag);
4003 New->setInvalidDecl();
4004 return;
4005 }
4006
4007 // Merge "used" flag.
4008 if (Old->getMostRecentDecl()->isUsed(false))
4009 New->setIsUsed();
4010
4011 // Keep a chain of previous declarations.
4012 New->setPreviousDecl(Old);
4013 if (NewTemplate)
4014 NewTemplate->setPreviousDecl(OldTemplate);
4015 adjustDeclContextForDeclaratorDecl(New, Old);
4016
4017 // Inherit access appropriately.
4018 New->setAccess(Old->getAccess());
4019 if (NewTemplate)
4020 NewTemplate->setAccess(New->getAccess());
4021
4022 if (Old->isInline())
4023 New->setImplicitlyInline();
4024}
4025
4026void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4027 SourceManager &SrcMgr = getSourceManager();
4028 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4029 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4030 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4031 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4032 auto &HSI = PP.getHeaderSearchInfo();
4033 StringRef HdrFilename =
4034 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4035
4036 auto noteFromModuleOrInclude = [&](Module *Mod,
4037 SourceLocation IncLoc) -> bool {
4038 // Redefinition errors with modules are common with non modular mapped
4039 // headers, example: a non-modular header H in module A that also gets
4040 // included directly in a TU. Pointing twice to the same header/definition
4041 // is confusing, try to get better diagnostics when modules is on.
4042 if (IncLoc.isValid()) {
4043 if (Mod) {
4044 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4045 << HdrFilename.str() << Mod->getFullModuleName();
4046 if (!Mod->DefinitionLoc.isInvalid())
4047 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4048 << Mod->getFullModuleName();
4049 } else {
4050 Diag(IncLoc, diag::note_redefinition_include_same_file)
4051 << HdrFilename.str();
4052 }
4053 return true;
4054 }
4055
4056 return false;
4057 };
4058
4059 // Is it the same file and same offset? Provide more information on why
4060 // this leads to a redefinition error.
4061 bool EmittedDiag = false;
4062 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4063 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4064 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4065 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4066 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4067
4068 // If the header has no guards, emit a note suggesting one.
4069 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4070 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4071
4072 if (EmittedDiag)
4073 return;
4074 }
4075
4076 // Redefinition coming from different files or couldn't do better above.
4077 if (Old->getLocation().isValid())
4078 Diag(Old->getLocation(), diag::note_previous_definition);
4079}
4080
4081/// We've just determined that \p Old and \p New both appear to be definitions
4082/// of the same variable. Either diagnose or fix the problem.
4083bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4084 if (!hasVisibleDefinition(Old) &&
4085 (New->getFormalLinkage() == InternalLinkage ||
4086 New->isInline() ||
4087 New->getDescribedVarTemplate() ||
4088 New->getNumTemplateParameterLists() ||
4089 New->getDeclContext()->isDependentContext())) {
4090 // The previous definition is hidden, and multiple definitions are
4091 // permitted (in separate TUs). Demote this to a declaration.
4092 New->demoteThisDefinitionToDeclaration();
4093
4094 // Make the canonical definition visible.
4095 if (auto *OldTD = Old->getDescribedVarTemplate())
4096 makeMergedDefinitionVisible(OldTD);
4097 makeMergedDefinitionVisible(Old);
4098 return false;
4099 } else {
4100 Diag(New->getLocation(), diag::err_redefinition) << New;
4101 notePreviousDefinition(Old, New->getLocation());
4102 New->setInvalidDecl();
4103 return true;
4104 }
4105}
4106
4107/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4108/// no declarator (e.g. "struct foo;") is parsed.
4109Decl *
4110Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4111 RecordDecl *&AnonRecord) {
4112 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4113 AnonRecord);
4114}
4115
4116// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4117// disambiguate entities defined in different scopes.
4118// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4119// compatibility.
4120// We will pick our mangling number depending on which version of MSVC is being
4121// targeted.
4122static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4123 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4124 ? S->getMSCurManglingNumber()
4125 : S->getMSLastManglingNumber();
4126}
4127
4128void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4129 if (!Context.getLangOpts().CPlusPlus)
4130 return;
4131
4132 if (isa<CXXRecordDecl>(Tag->getParent())) {
4133 // If this tag is the direct child of a class, number it if
4134 // it is anonymous.
4135 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4136 return;
4137 MangleNumberingContext &MCtx =
4138 Context.getManglingNumberContext(Tag->getParent());
4139 Context.setManglingNumber(
4140 Tag, MCtx.getManglingNumber(
4141 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4142 return;
4143 }
4144
4145 // If this tag isn't a direct child of a class, number it if it is local.
4146 Decl *ManglingContextDecl;
4147 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4148 Tag->getDeclContext(), ManglingContextDecl)) {
4149 Context.setManglingNumber(
4150 Tag, MCtx->getManglingNumber(
4151 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4152 }
4153}
4154
4155void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4156 TypedefNameDecl *NewTD) {
4157 if (TagFromDeclSpec->isInvalidDecl())
4158 return;
4159
4160 // Do nothing if the tag already has a name for linkage purposes.
4161 if (TagFromDeclSpec->hasNameForLinkage())
4162 return;
4163
4164 // A well-formed anonymous tag must always be a TUK_Definition.
4165 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4165, __extension__ __PRETTY_FUNCTION__))
;
4166
4167 // The type must match the tag exactly; no qualifiers allowed.
4168 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4169 Context.getTagDeclType(TagFromDeclSpec))) {
4170 if (getLangOpts().CPlusPlus)
4171 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4172 return;
4173 }
4174
4175 // If we've already computed linkage for the anonymous tag, then
4176 // adding a typedef name for the anonymous decl can change that
4177 // linkage, which might be a serious problem. Diagnose this as
4178 // unsupported and ignore the typedef name. TODO: we should
4179 // pursue this as a language defect and establish a formal rule
4180 // for how to handle it.
4181 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4182 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4183
4184 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4185 tagLoc = getLocForEndOfToken(tagLoc);
4186
4187 llvm::SmallString<40> textToInsert;
4188 textToInsert += ' ';
4189 textToInsert += NewTD->getIdentifier()->getName();
4190 Diag(tagLoc, diag::note_typedef_changes_linkage)
4191 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4192 return;
4193 }
4194
4195 // Otherwise, set this is the anon-decl typedef for the tag.
4196 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4197}
4198
4199static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4200 switch (T) {
4201 case DeclSpec::TST_class:
4202 return 0;
4203 case DeclSpec::TST_struct:
4204 return 1;
4205 case DeclSpec::TST_interface:
4206 return 2;
4207 case DeclSpec::TST_union:
4208 return 3;
4209 case DeclSpec::TST_enum:
4210 return 4;
4211 default:
4212 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4212)
;
4213 }
4214}
4215
4216/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4217/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4218/// parameters to cope with template friend declarations.
4219Decl *
4220Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4221 MultiTemplateParamsArg TemplateParams,
4222 bool IsExplicitInstantiation,
4223 RecordDecl *&AnonRecord) {
4224 Decl *TagD = nullptr;
4225 TagDecl *Tag = nullptr;
4226 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4227 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4228 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4229 DS.getTypeSpecType() == DeclSpec::TST_union ||
4230 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4231 TagD = DS.getRepAsDecl();
4232
4233 if (!TagD) // We probably had an error
4234 return nullptr;
4235
4236 // Note that the above type specs guarantee that the
4237 // type rep is a Decl, whereas in many of the others
4238 // it's a Type.
4239 if (isa<TagDecl>(TagD))
4240 Tag = cast<TagDecl>(TagD);
4241 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4242 Tag = CTD->getTemplatedDecl();
4243 }
4244
4245 if (Tag) {
4246 handleTagNumbering(Tag, S);
4247 Tag->setFreeStanding();
4248 if (Tag->isInvalidDecl())
4249 return Tag;
4250 }
4251
4252 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4253 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4254 // or incomplete types shall not be restrict-qualified."
4255 if (TypeQuals & DeclSpec::TQ_restrict)
4256 Diag(DS.getRestrictSpecLoc(),
4257 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4258 << DS.getSourceRange();
4259 }
4260
4261 if (DS.isInlineSpecified())
4262 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4263 << getLangOpts().CPlusPlus17;
4264
4265 if (DS.isConstexprSpecified()) {
4266 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4267 // and definitions of functions and variables.
4268 if (Tag)
4269 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4270 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4271 else
4272 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4273 // Don't emit warnings after this error.
4274 return TagD;
4275 }
4276
4277 DiagnoseFunctionSpecifiers(DS);
4278
4279 if (DS.isFriendSpecified()) {
4280 // If we're dealing with a decl but not a TagDecl, assume that
4281 // whatever routines created it handled the friendship aspect.
4282 if (TagD && !Tag)
4283 return nullptr;
4284 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4285 }
4286
4287 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4288 bool IsExplicitSpecialization =
4289 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4290 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4291 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4292 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4293 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4294 // nested-name-specifier unless it is an explicit instantiation
4295 // or an explicit specialization.
4296 //
4297 // FIXME: We allow class template partial specializations here too, per the
4298 // obvious intent of DR1819.
4299 //
4300 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4301 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4302 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4303 return nullptr;
4304 }
4305
4306 // Track whether this decl-specifier declares anything.
4307 bool DeclaresAnything = true;
4308
4309 // Handle anonymous struct definitions.
4310 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4311 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4312 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4313 if (getLangOpts().CPlusPlus ||
4314 Record->getDeclContext()->isRecord()) {
4315 // If CurContext is a DeclContext that can contain statements,
4316 // RecursiveASTVisitor won't visit the decls that
4317 // BuildAnonymousStructOrUnion() will put into CurContext.
4318 // Also store them here so that they can be part of the
4319 // DeclStmt that gets created in this case.
4320 // FIXME: Also return the IndirectFieldDecls created by
4321 // BuildAnonymousStructOr union, for the same reason?
4322 if (CurContext->isFunctionOrMethod())
4323 AnonRecord = Record;
4324 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4325 Context.getPrintingPolicy());
4326 }
4327
4328 DeclaresAnything = false;
4329 }
4330 }
4331
4332 // C11 6.7.2.1p2:
4333 // A struct-declaration that does not declare an anonymous structure or
4334 // anonymous union shall contain a struct-declarator-list.
4335 //
4336 // This rule also existed in C89 and C99; the grammar for struct-declaration
4337 // did not permit a struct-declaration without a struct-declarator-list.
4338 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4339 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4340 // Check for Microsoft C extension: anonymous struct/union member.
4341 // Handle 2 kinds of anonymous struct/union:
4342 // struct STRUCT;
4343 // union UNION;
4344 // and
4345 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4346 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4347 if ((Tag && Tag->getDeclName()) ||
4348 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4349 RecordDecl *Record = nullptr;
4350 if (Tag)
4351 Record = dyn_cast<RecordDecl>(Tag);
4352 else if (const RecordType *RT =
4353 DS.getRepAsType().get()->getAsStructureType())
4354 Record = RT->getDecl();
4355 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4356 Record = UT->getDecl();
4357
4358 if (Record && getLangOpts().MicrosoftExt) {
4359 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4360 << Record->isUnion() << DS.getSourceRange();
4361 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4362 }
4363
4364 DeclaresAnything = false;
4365 }
4366 }
4367
4368 // Skip all the checks below if we have a type error.
4369 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4370 (TagD && TagD->isInvalidDecl()))
4371 return TagD;
4372
4373 if (getLangOpts().CPlusPlus &&
4374 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4375 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4376 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4377 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4378 DeclaresAnything = false;
4379
4380 if (!DS.isMissingDeclaratorOk()) {
4381 // Customize diagnostic for a typedef missing a name.
4382 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4383 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4384 << DS.getSourceRange();
4385 else
4386 DeclaresAnything = false;
4387 }
4388
4389 if (DS.isModulePrivateSpecified() &&
4390 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4391 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4392 << Tag->getTagKind()
4393 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4394
4395 ActOnDocumentableDecl(TagD);
4396
4397 // C 6.7/2:
4398 // A declaration [...] shall declare at least a declarator [...], a tag,
4399 // or the members of an enumeration.
4400 // C++ [dcl.dcl]p3:
4401 // [If there are no declarators], and except for the declaration of an
4402 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4403 // names into the program, or shall redeclare a name introduced by a
4404 // previous declaration.
4405 if (!DeclaresAnything) {
4406 // In C, we allow this as a (popular) extension / bug. Don't bother
4407 // producing further diagnostics for redundant qualifiers after this.
4408 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4409 return TagD;
4410 }
4411
4412 // C++ [dcl.stc]p1:
4413 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4414 // init-declarator-list of the declaration shall not be empty.
4415 // C++ [dcl.fct.spec]p1:
4416 // If a cv-qualifier appears in a decl-specifier-seq, the
4417 // init-declarator-list of the declaration shall not be empty.
4418 //
4419 // Spurious qualifiers here appear to be valid in C.
4420 unsigned DiagID = diag::warn_standalone_specifier;
4421 if (getLangOpts().CPlusPlus)
4422 DiagID = diag::ext_standalone_specifier;
4423
4424 // Note that a linkage-specification sets a storage class, but
4425 // 'extern "C" struct foo;' is actually valid and not theoretically
4426 // useless.
4427 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4428 if (SCS == DeclSpec::SCS_mutable)
4429 // Since mutable is not a viable storage class specifier in C, there is
4430 // no reason to treat it as an extension. Instead, diagnose as an error.
4431 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4432 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4433 Diag(DS.getStorageClassSpecLoc(), DiagID)
4434 << DeclSpec::getSpecifierName(SCS);
4435 }
4436
4437 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4438 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4439 << DeclSpec::getSpecifierName(TSCS);
4440 if (DS.getTypeQualifiers()) {
4441 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4442 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4443 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4444 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4445 // Restrict is covered above.
4446 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4447 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4448 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4449 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4450 }
4451
4452 // Warn about ignored type attributes, for example:
4453 // __attribute__((aligned)) struct A;
4454 // Attributes should be placed after tag to apply to type declaration.
4455 if (!DS.getAttributes().empty()) {
4456 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4457 if (TypeSpecType == DeclSpec::TST_class ||
4458 TypeSpecType == DeclSpec::TST_struct ||
4459 TypeSpecType == DeclSpec::TST_interface ||
4460 TypeSpecType == DeclSpec::TST_union ||
4461 TypeSpecType == DeclSpec::TST_enum) {
4462 for (const ParsedAttr &AL : DS.getAttributes())
4463 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4464 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4465 }
4466 }
4467
4468 return TagD;
4469}
4470
4471/// We are trying to inject an anonymous member into the given scope;
4472/// check if there's an existing declaration that can't be overloaded.
4473///
4474/// \return true if this is a forbidden redeclaration
4475static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4476 Scope *S,
4477 DeclContext *Owner,
4478 DeclarationName Name,
4479 SourceLocation NameLoc,
4480 bool IsUnion) {
4481 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4482 Sema::ForVisibleRedeclaration);
4483 if (!SemaRef.LookupName(R, S)) return false;
4484
4485 // Pick a representative declaration.
4486 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4487 assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl"
) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4487, __extension__ __PRETTY_FUNCTION__))
;
4488
4489 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4490 return false;
4491
4492 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4493 << IsUnion << Name;
4494 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4495
4496 return true;
4497}
4498
4499/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4500/// anonymous struct or union AnonRecord into the owning context Owner
4501/// and scope S. This routine will be invoked just after we realize
4502/// that an unnamed union or struct is actually an anonymous union or
4503/// struct, e.g.,
4504///
4505/// @code
4506/// union {
4507/// int i;
4508/// float f;
4509/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4510/// // f into the surrounding scope.x
4511/// @endcode
4512///
4513/// This routine is recursive, injecting the names of nested anonymous
4514/// structs/unions into the owning context and scope as well.
4515static bool
4516InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4517 RecordDecl *AnonRecord, AccessSpecifier AS,
4518 SmallVectorImpl<NamedDecl *> &Chaining) {
4519 bool Invalid = false;
4520
4521 // Look every FieldDecl and IndirectFieldDecl with a name.
4522 for (auto *D : AnonRecord->decls()) {
4523 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4524 cast<NamedDecl>(D)->getDeclName()) {
4525 ValueDecl *VD = cast<ValueDecl>(D);
4526 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4527 VD->getLocation(),
4528 AnonRecord->isUnion())) {
4529 // C++ [class.union]p2:
4530 // The names of the members of an anonymous union shall be
4531 // distinct from the names of any other entity in the
4532 // scope in which the anonymous union is declared.
4533 Invalid = true;
4534 } else {
4535 // C++ [class.union]p2:
4536 // For the purpose of name lookup, after the anonymous union
4537 // definition, the members of the anonymous union are
4538 // considered to have been defined in the scope in which the
4539 // anonymous union is declared.
4540 unsigned OldChainingSize = Chaining.size();
4541 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4542 Chaining.append(IF->chain_begin(), IF->chain_end());
4543 else
4544 Chaining.push_back(VD);
4545
4546 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4546, __extension__ __PRETTY_FUNCTION__))
;
4547 NamedDecl **NamedChain =
4548 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4549 for (unsigned i = 0; i < Chaining.size(); i++)
4550 NamedChain[i] = Chaining[i];
4551
4552 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4553 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4554 VD->getType(), {NamedChain, Chaining.size()});
4555
4556 for (const auto *Attr : VD->attrs())
4557 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4558
4559 IndirectField->setAccess(AS);
4560 IndirectField->setImplicit();
4561 SemaRef.PushOnScopeChains(IndirectField, S);
4562
4563 // That includes picking up the appropriate access specifier.
4564 if (AS != AS_none) IndirectField->setAccess(AS);
4565
4566 Chaining.resize(OldChainingSize);
4567 }
4568 }
4569 }
4570
4571 return Invalid;
4572}
4573
4574/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4575/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4576/// illegal input values are mapped to SC_None.
4577static StorageClass
4578StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4579 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4580 assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4581, __extension__ __PRETTY_FUNCTION__))
4581 "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4581, __extension__ __PRETTY_FUNCTION__))
;
4582 switch (StorageClassSpec) {
4583 case DeclSpec::SCS_unspecified: return SC_None;
4584 case DeclSpec::SCS_extern:
4585 if (DS.isExternInLinkageSpec())
4586 return SC_None;
4587 return SC_Extern;
4588 case DeclSpec::SCS_static: return SC_Static;
4589 case DeclSpec::SCS_auto: return SC_Auto;
4590 case DeclSpec::SCS_register: return SC_Register;
4591 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4592 // Illegal SCSs map to None: error reporting is up to the caller.
4593 case DeclSpec::SCS_mutable: // Fall through.
4594 case DeclSpec::SCS_typedef: return SC_None;
4595 }
4596 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4596)
;
4597}
4598
4599static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4600 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4600, __extension__ __PRETTY_FUNCTION__))
;
4601
4602 for (const auto *I : Record->decls()) {
4603 const auto *FD = dyn_cast<FieldDecl>(I);
4604 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4605 FD = IFD->getAnonField();
4606 if (FD && FD->hasInClassInitializer())
4607 return FD->getLocation();
4608 }
4609
4610 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4610)
;
4611}
4612
4613static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4614 SourceLocation DefaultInitLoc) {
4615 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4616 return;
4617
4618 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4619 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4620}
4621
4622static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4623 CXXRecordDecl *AnonUnion) {
4624 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4625 return;
4626
4627 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4628}
4629
4630/// BuildAnonymousStructOrUnion - Handle the declaration of an
4631/// anonymous structure or union. Anonymous unions are a C++ feature
4632/// (C++ [class.union]) and a C11 feature; anonymous structures
4633/// are a C11 feature and GNU C++ extension.
4634Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4635 AccessSpecifier AS,
4636 RecordDecl *Record,
4637 const PrintingPolicy &Policy) {
4638 DeclContext *Owner = Record->getDeclContext();
4639
4640 // Diagnose whether this anonymous struct/union is an extension.
4641 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4642 Diag(Record->getLocation(), diag::ext_anonymous_union);
4643 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4644 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4645 else if (!Record->isUnion() && !getLangOpts().C11)
4646 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4647
4648 // C and C++ require different kinds of checks for anonymous
4649 // structs/unions.
4650 bool Invalid = false;
4651 if (getLangOpts().CPlusPlus) {
4652 const char *PrevSpec = nullptr;
4653 unsigned DiagID;
4654 if (Record->isUnion()) {
4655 // C++ [class.union]p6:
4656 // C++17 [class.union.anon]p2:
4657 // Anonymous unions declared in a named namespace or in the
4658 // global namespace shall be declared static.
4659 DeclContext *OwnerScope = Owner->getRedeclContext();
4660 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4661 (OwnerScope->isTranslationUnit() ||
4662 (OwnerScope->isNamespace() &&
4663 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4664 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4665 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4666
4667 // Recover by adding 'static'.
4668 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4669 PrevSpec, DiagID, Policy);
4670 }
4671 // C++ [class.union]p6:
4672 // A storage class is not allowed in a declaration of an
4673 // anonymous union in a class scope.
4674 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4675 isa<RecordDecl>(Owner)) {
4676 Diag(DS.getStorageClassSpecLoc(),
4677 diag::err_anonymous_union_with_storage_spec)
4678 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4679
4680 // Recover by removing the storage specifier.
4681 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4682 SourceLocation(),
4683 PrevSpec, DiagID, Context.getPrintingPolicy());
4684 }
4685 }
4686
4687 // Ignore const/volatile/restrict qualifiers.
4688 if (DS.getTypeQualifiers()) {
4689 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4690 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4691 << Record->isUnion() << "const"
4692 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4693 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4694 Diag(DS.getVolatileSpecLoc(),
4695 diag::ext_anonymous_struct_union_qualified)
4696 << Record->isUnion() << "volatile"
4697 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4698 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4699 Diag(DS.getRestrictSpecLoc(),
4700 diag::ext_anonymous_struct_union_qualified)
4701 << Record->isUnion() << "restrict"
4702 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4703 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4704 Diag(DS.getAtomicSpecLoc(),
4705 diag::ext_anonymous_struct_union_qualified)
4706 << Record->isUnion() << "_Atomic"
4707 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4708 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4709 Diag(DS.getUnalignedSpecLoc(),
4710 diag::ext_anonymous_struct_union_qualified)
4711 << Record->isUnion() << "__unaligned"
4712 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4713
4714 DS.ClearTypeQualifiers();
4715 }
4716
4717 // C++ [class.union]p2:
4718 // The member-specification of an anonymous union shall only
4719 // define non-static data members. [Note: nested types and
4720 // functions cannot be declared within an anonymous union. ]
4721 for (auto *Mem : Record->decls()) {
4722 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4723 // C++ [class.union]p3:
4724 // An anonymous union shall not have private or protected
4725 // members (clause 11).
4726 assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void
(0) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4726, __extension__ __PRETTY_FUNCTION__))
;
4727 if (FD->getAccess() != AS_public) {
4728 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4729 << Record->isUnion() << (FD->getAccess() == AS_protected);
4730 Invalid = true;
4731 }
4732
4733 // C++ [class.union]p1
4734 // An object of a class with a non-trivial constructor, a non-trivial
4735 // copy constructor, a non-trivial destructor, or a non-trivial copy
4736 // assignment operator cannot be a member of a union, nor can an
4737 // array of such objects.
4738 if (CheckNontrivialField(FD))
4739 Invalid = true;
4740 } else if (Mem->isImplicit()) {
4741 // Any implicit members are fine.
4742 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4743 // This is a type that showed up in an
4744 // elaborated-type-specifier inside the anonymous struct or
4745 // union, but which actually declares a type outside of the
4746 // anonymous struct or union. It's okay.
4747 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4748 if (!MemRecord->isAnonymousStructOrUnion() &&
4749 MemRecord->getDeclName()) {
4750 // Visual C++ allows type definition in anonymous struct or union.
4751 if (getLangOpts().MicrosoftExt)
4752 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4753 << Record->isUnion();
4754 else {
4755 // This is a nested type declaration.
4756 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4757 << Record->isUnion();
4758 Invalid = true;
4759 }
4760 } else {
4761 // This is an anonymous type definition within another anonymous type.
4762 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4763 // not part of standard C++.
4764 Diag(MemRecord->getLocation(),
4765 diag::ext_anonymous_record_with_anonymous_type)
4766 << Record->isUnion();
4767 }
4768 } else if (isa<AccessSpecDecl>(Mem)) {
4769 // Any access specifier is fine.
4770 } else if (isa<StaticAssertDecl>(Mem)) {
4771 // In C++1z, static_assert declarations are also fine.
4772 } else {
4773 // We have something that isn't a non-static data
4774 // member. Complain about it.
4775 unsigned DK = diag::err_anonymous_record_bad_member;
4776 if (isa<TypeDecl>(Mem))
4777 DK = diag::err_anonymous_record_with_type;
4778 else if (isa<FunctionDecl>(Mem))
4779 DK = diag::err_anonymous_record_with_function;
4780 else if (isa<VarDecl>(Mem))
4781 DK = diag::err_anonymous_record_with_static;
4782
4783 // Visual C++ allows type definition in anonymous struct or union.
4784 if (getLangOpts().MicrosoftExt &&
4785 DK == diag::err_anonymous_record_with_type)
4786 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4787 << Record->isUnion();
4788 else {
4789 Diag(Mem->getLocation(), DK) << Record->isUnion();
4790 Invalid = true;
4791 }
4792 }
4793 }
4794
4795 // C++11 [class.union]p8 (DR1460):
4796 // At most one variant member of a union may have a
4797 // brace-or-equal-initializer.
4798 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4799 Owner->isRecord())
4800 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4801 cast<CXXRecordDecl>(Record));
4802 }
4803
4804 if (!Record->isUnion() && !Owner->isRecord()) {
4805 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4806 << getLangOpts().CPlusPlus;
4807 Invalid = true;
4808 }
4809
4810 // Mock up a declarator.
4811 Declarator Dc(DS, DeclaratorContext::MemberContext);
4812 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4813 assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4813, __extension__ __PRETTY_FUNCTION__))
;
4814
4815 // Create a declaration for this anonymous struct/union.
4816 NamedDecl *Anon = nullptr;
4817 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4818 Anon = FieldDecl::Create(Context, OwningClass,
4819 DS.getLocStart(),
4820 Record->getLocation(),
4821 /*IdentifierInfo=*/nullptr,
4822 Context.getTypeDeclType(Record),
4823 TInfo,
4824 /*BitWidth=*/nullptr, /*Mutable=*/false,
4825 /*InitStyle=*/ICIS_NoInit);
4826 Anon->setAccess(AS);
4827 if (getLangOpts().CPlusPlus)
4828 FieldCollector->Add(cast<FieldDecl>(Anon));
4829 } else {
4830 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4831 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4832 if (SCSpec == DeclSpec::SCS_mutable) {
4833 // mutable can only appear on non-static class members, so it's always
4834 // an error here
4835 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4836 Invalid = true;
4837 SC = SC_None;
4838 }
4839
4840 Anon = VarDecl::Create(Context, Owner,
4841 DS.getLocStart(),
4842 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4843 Context.getTypeDeclType(Record),
4844 TInfo, SC);
4845
4846 // Default-initialize the implicit variable. This initialization will be
4847 // trivial in almost all cases, except if a union member has an in-class
4848 // initializer:
4849 // union { int n = 0; };
4850 ActOnUninitializedDecl(Anon);
4851 }
4852 Anon->setImplicit();
4853
4854 // Mark this as an anonymous struct/union type.
4855 Record->setAnonymousStructOrUnion(true);
4856
4857 // Add the anonymous struct/union object to the current
4858 // context. We'll be referencing this object when we refer to one of
4859 // its members.
4860 Owner->addDecl(Anon);
4861
4862 // Inject the members of the anonymous struct/union into the owning
4863 // context and into the identifier resolver chain for name lookup
4864 // purposes.
4865 SmallVector<NamedDecl*, 2> Chain;
4866 Chain.push_back(Anon);
4867
4868 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4869 Invalid = true;
4870
4871 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4872 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4873 Decl *ManglingContextDecl;
4874 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4875 NewVD->getDeclContext(), ManglingContextDecl)) {
4876 Context.setManglingNumber(
4877 NewVD, MCtx->getManglingNumber(
4878 NewVD, getMSManglingNumber(getLangOpts(), S)));
4879 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4880 }
4881 }
4882 }
4883
4884 if (Invalid)
4885 Anon->setInvalidDecl();
4886
4887 return Anon;
4888}
4889
4890/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4891/// Microsoft C anonymous structure.
4892/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4893/// Example:
4894///
4895/// struct A { int a; };
4896/// struct B { struct A; int b; };
4897///
4898/// void foo() {
4899/// B var;
4900/// var.a = 3;
4901/// }
4902///
4903Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4904 RecordDecl *Record) {
4905 assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!"
) ? void (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4905, __extension__ __PRETTY_FUNCTION__))
;
4906
4907 // Mock up a declarator.
4908 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4909 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4910 assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 4910, __extension__ __PRETTY_FUNCTION__))
;
4911
4912 auto *ParentDecl = cast<RecordDecl>(CurContext);
4913 QualType RecTy = Context.getTypeDeclType(Record);
4914
4915 // Create a declaration for this anonymous struct.
4916 NamedDecl *Anon = FieldDecl::Create(Context,
4917 ParentDecl,
4918 DS.getLocStart(),
4919 DS.getLocStart(),
4920 /*IdentifierInfo=*/nullptr,
4921 RecTy,
4922 TInfo,
4923 /*BitWidth=*/nullptr, /*Mutable=*/false,
4924 /*InitStyle=*/ICIS_NoInit);
4925 Anon->setImplicit();
4926
4927 // Add the anonymous struct object to the current context.
4928 CurContext->addDecl(Anon);
4929
4930 // Inject the members of the anonymous struct into the current
4931 // context and into the identifier resolver chain for name lookup
4932 // purposes.
4933 SmallVector<NamedDecl*, 2> Chain;
4934 Chain.push_back(Anon);
4935
4936 RecordDecl *RecordDef = Record->getDefinition();
4937 if (RequireCompleteType(Anon->getLocation(), RecTy,
4938 diag::err_field_incomplete) ||
4939 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4940 AS_none, Chain)) {
4941 Anon->setInvalidDecl();
4942 ParentDecl->setInvalidDecl();
4943 }
4944
4945 return Anon;
4946}
4947
4948/// GetNameForDeclarator - Determine the full declaration name for the
4949/// given Declarator.
4950DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4951 return GetNameFromUnqualifiedId(D.getName());
4952}
4953
4954/// Retrieves the declaration name from a parsed unqualified-id.
4955DeclarationNameInfo
4956Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4957 DeclarationNameInfo NameInfo;
4958 NameInfo.setLoc(Name.StartLocation);
4959
4960 switch (Name.getKind()) {
4961
4962 case UnqualifiedIdKind::IK_ImplicitSelfParam:
4963 case UnqualifiedIdKind::IK_Identifier:
4964 NameInfo.setName(Name.Identifier);
4965 NameInfo.setLoc(Name.StartLocation);
4966 return NameInfo;
4967
4968 case UnqualifiedIdKind::IK_DeductionGuideName: {
4969 // C++ [temp.deduct.guide]p3:
4970 // The simple-template-id shall name a class template specialization.
4971 // The template-name shall be the same identifier as the template-name
4972 // of the simple-template-id.
4973 // These together intend to imply that the template-name shall name a
4974 // class template.
4975 // FIXME: template<typename T> struct X {};
4976 // template<typename T> using Y = X<T>;
4977 // Y(int) -> Y<int>;
4978 // satisfies these rules but does not name a class template.
4979 TemplateName TN = Name.TemplateName.get().get();
4980 auto *Template = TN.getAsTemplateDecl();
4981 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4982 Diag(Name.StartLocation,
4983 diag::err_deduction_guide_name_not_class_template)
4984 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4985 if (Template)
4986 Diag(Template->getLocation(), diag::note_template_decl_here);
4987 return DeclarationNameInfo();
4988 }
4989
4990 NameInfo.setName(
4991 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4992 NameInfo.setLoc(Name.StartLocation);
4993 return NameInfo;
4994 }
4995
4996 case UnqualifiedIdKind::IK_OperatorFunctionId:
4997 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4998 Name.OperatorFunctionId.Operator));
4999 NameInfo.setLoc(Name.StartLocation);
5000 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5001 = Name.OperatorFunctionId.SymbolLocations[0];
5002 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5003 = Name.EndLocation.getRawEncoding();
5004 return NameInfo;
5005
5006 case UnqualifiedIdKind::IK_LiteralOperatorId:
5007 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5008 Name.Identifier));
5009 NameInfo.setLoc(Name.StartLocation);
5010 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5011 return NameInfo;
5012
5013 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5014 TypeSourceInfo *TInfo;
5015 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5016 if (Ty.isNull())
5017 return DeclarationNameInfo();
5018 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5019 Context.getCanonicalType(Ty)));
5020 NameInfo.setLoc(Name.StartLocation);
5021 NameInfo.setNamedTypeInfo(TInfo);
5022 return NameInfo;
5023 }
5024
5025 case UnqualifiedIdKind::IK_ConstructorName: {
5026 TypeSourceInfo *TInfo;
5027 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5028 if (Ty.isNull())
5029 return DeclarationNameInfo();
5030 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5031 Context.getCanonicalType(Ty)));
5032 NameInfo.setLoc(Name.StartLocation);
5033 NameInfo.setNamedTypeInfo(TInfo);
5034 return NameInfo;
5035 }
5036
5037 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5038 // In well-formed code, we can only have a constructor
5039 // template-id that refers to the current context, so go there
5040 // to find the actual type being constructed.
5041 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5042 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5043 return DeclarationNameInfo();
5044
5045 // Determine the type of the class being constructed.
5046 QualType CurClassType = Context.getTypeDeclType(CurClass);
5047
5048 // FIXME: Check two things: that the template-id names the same type as
5049 // CurClassType, and that the template-id does not occur when the name
5050 // was qualified.
5051
5052 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5053 Context.getCanonicalType(CurClassType)));
5054 NameInfo.setLoc(Name.StartLocation);
5055 // FIXME: should we retrieve TypeSourceInfo?
5056 NameInfo.setNamedTypeInfo(nullptr);
5057 return NameInfo;
5058 }
5059
5060 case UnqualifiedIdKind::IK_DestructorName: {
5061 TypeSourceInfo *TInfo;
5062 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5063 if (Ty.isNull())
5064 return DeclarationNameInfo();
5065 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5066 Context.getCanonicalType(Ty)));
5067 NameInfo.setLoc(Name.StartLocation);
5068 NameInfo.setNamedTypeInfo(TInfo);
5069 return NameInfo;
5070 }
5071
5072 case UnqualifiedIdKind::IK_TemplateId: {
5073 TemplateName TName = Name.TemplateId->Template.get();
5074 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5075 return Context.getNameForTemplate(TName, TNameLoc);
5076 }
5077
5078 } // switch (Name.getKind())
5079
5080 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 5080)
;
5081}
5082
5083static QualType getCoreType(QualType Ty) {
5084 do {
5085 if (Ty->isPointerType() || Ty->isReferenceType())
5086 Ty = Ty->getPointeeType();
5087 else if (Ty->isArrayType())
5088 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5089 else
5090 return Ty.withoutLocalFastQualifiers();
5091 } while (true);
5092}
5093
5094/// hasSimilarParameters - Determine whether the C++ functions Declaration
5095/// and Definition have "nearly" matching parameters. This heuristic is
5096/// used to improve diagnostics in the case where an out-of-line function
5097/// definition doesn't match any declaration within the class or namespace.
5098/// Also sets Params to the list of indices to the parameters that differ
5099/// between the declaration and the definition. If hasSimilarParameters
5100/// returns true and Params is empty, then all of the parameters match.
5101static bool hasSimilarParameters(ASTContext &Context,
5102 FunctionDecl *Declaration,
5103 FunctionDecl *Definition,
5104 SmallVectorImpl<unsigned> &Params) {
5105 Params.clear();
5106 if (Declaration->param_size() != Definition->param_size())
5107 return false;
5108 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5109 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5110 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5111
5112 // The parameter types are identical
5113 if (Context.hasSameType(DefParamTy, DeclParamTy))
5114 continue;
5115
5116 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5117 QualType DefParamBaseTy = getCoreType(DefParamTy);
5118 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5119 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5120
5121 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5122 (DeclTyName && DeclTyName == DefTyName))
5123 Params.push_back(Idx);
5124 else // The two parameters aren't even close
5125 return false;
5126 }
5127
5128 return true;
5129}
5130
5131/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5132/// declarator needs to be rebuilt in the current instantiation.
5133/// Any bits of declarator which appear before the name are valid for
5134/// consideration here. That's specifically the type in the decl spec
5135/// and the base type in any member-pointer chunks.
5136static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5137 DeclarationName Name) {
5138 // The types we specifically need to rebuild are:
5139 // - typenames, typeofs, and decltypes
5140 // - types which will become injected class names
5141 // Of course, we also need to rebuild any type referencing such a
5142 // type. It's safest to just say "dependent", but we call out a
5143 // few cases here.
5144
5145 DeclSpec &DS = D.getMutableDeclSpec();
5146 switch (DS.getTypeSpecType()) {
5147 case DeclSpec::TST_typename:
5148 case DeclSpec::TST_typeofType:
5149 case DeclSpec::TST_underlyingType:
5150 case DeclSpec::TST_atomic: {
5151 // Grab the type from the parser.
5152 TypeSourceInfo *TSI = nullptr;
5153 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5154 if (T.isNull() || !T->isDependentType()) break;
5155
5156 // Make sure there's a type source info. This isn't really much
5157 // of a waste; most dependent types should have type source info
5158 // attached already.
5159 if (!TSI)
5160 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5161
5162 // Rebuild the type in the current instantiation.
5163 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5164 if (!TSI) return true;
5165
5166 // Store the new type back in the decl spec.
5167 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5168 DS.UpdateTypeRep(LocType);
5169 break;
5170 }
5171
5172 case DeclSpec::TST_decltype:
5173 case DeclSpec::TST_typeofExpr: {
5174 Expr *E = DS.getRepAsExpr();
5175 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5176 if (Result.isInvalid()) return true;
5177 DS.UpdateExprRep(Result.get());
5178 break;
5179 }
5180
5181 default:
5182 // Nothing to do for these decl specs.
5183 break;
5184 }
5185
5186 // It doesn't matter what order we do this in.
5187 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5188 DeclaratorChunk &Chunk = D.getTypeObject(I);
5189
5190 // The only type information in the declarator which can come
5191 // before the declaration name is the base type of a member
5192 // pointer.
5193 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5194 continue;
5195
5196 // Rebuild the scope specifier in-place.
5197 CXXScopeSpec &SS = Chunk.Mem.Scope();
5198 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5199 return true;
5200 }
5201
5202 return false;
5203}
5204
5205Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5206 D.setFunctionDefinitionKind(FDK_Declaration);
5207 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5208
5209 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5210 Dcl && Dcl->getDeclContext()->isFileContext())
5211 Dcl->setTopLevelDeclInObjCContainer();
5212
5213 if (getLangOpts().OpenCL)
5214 setCurrentOpenCLExtensionForDecl(Dcl);
5215
5216 return Dcl;
5217}
5218
5219/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5220/// If T is the name of a class, then each of the following shall have a
5221/// name different from T:
5222/// - every static data member of class T;
5223/// - every member function of class T
5224/// - every member of class T that is itself a type;
5225/// \returns true if the declaration name violates these rules.
5226bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5227 DeclarationNameInfo NameInfo) {
5228 DeclarationName Name = NameInfo.getName();
5229
5230 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5231 while (Record && Record->isAnonymousStructOrUnion())
5232 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5233 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5234 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5235 return true;
5236 }
5237
5238 return false;
5239}
5240
5241/// Diagnose a declaration whose declarator-id has the given
5242/// nested-name-specifier.
5243///
5244/// \param SS The nested-name-specifier of the declarator-id.
5245///
5246/// \param DC The declaration context to which the nested-name-specifier
5247/// resolves.
5248///
5249/// \param Name The name of the entity being declared.
5250///
5251/// \param Loc The location of the name of the entity being declared.
5252///
5253/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5254/// we're declaring an explicit / partial specialization / instantiation.
5255///
5256/// \returns true if we cannot safely recover from this error, false otherwise.
5257bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5258 DeclarationName Name,
5259 SourceLocation Loc, bool IsTemplateId) {
5260 DeclContext *Cur = CurContext;
5261 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5262 Cur = Cur->getParent();
5263
5264 // If the user provided a superfluous scope specifier that refers back to the
5265 // class in which the entity is already declared, diagnose and ignore it.
5266 //
5267 // class X {
5268 // void X::f();
5269 // };
5270 //
5271 // Note, it was once ill-formed to give redundant qualification in all
5272 // contexts, but that rule was removed by DR482.
5273 if (Cur->Equals(DC)) {
5274 if (Cur->isRecord()) {
5275 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5276 : diag::err_member_extra_qualification)
5277 << Name << FixItHint::CreateRemoval(SS.getRange());
5278 SS.clear();
5279 } else {
5280 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5281 }
5282 return false;
5283 }
5284
5285 // Check whether the qualifying scope encloses the scope of the original
5286 // declaration. For a template-id, we perform the checks in
5287 // CheckTemplateSpecializationScope.
5288 if (!Cur->Encloses(DC) && !IsTemplateId) {
5289 if (Cur->isRecord())
5290 Diag(Loc, diag::err_member_qualification)
5291 << Name << SS.getRange();
5292 else if (isa<TranslationUnitDecl>(DC))
5293 Diag(Loc, diag::err_invalid_declarator_global_scope)
5294 << Name << SS.getRange();
5295 else if (isa<FunctionDecl>(Cur))
5296 Diag(Loc, diag::err_invalid_declarator_in_function)
5297 << Name << SS.getRange();
5298 else if (isa<BlockDecl>(Cur))
5299 Diag(Loc, diag::err_invalid_declarator_in_block)
5300 << Name << SS.getRange();
5301 else
5302 Diag(Loc, diag::err_invalid_declarator_scope)
5303 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5304
5305 return true;
5306 }
5307
5308 if (Cur->isRecord()) {
5309 // Cannot qualify members within a class.
5310 Diag(Loc, diag::err_member_qualification)
5311 << Name << SS.getRange();
5312 SS.clear();
5313
5314 // C++ constructors and destructors with incorrect scopes can break
5315 // our AST invariants by having the wrong underlying types. If
5316 // that's the case, then drop this declaration entirely.
5317 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5318 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5319 !Context.hasSameType(Name.getCXXNameType(),
5320 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5321 return true;
5322
5323 return false;
5324 }
5325
5326 // C++11 [dcl.meaning]p1:
5327 // [...] "The nested-name-specifier of the qualified declarator-id shall
5328 // not begin with a decltype-specifer"
5329 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5330 while (SpecLoc.getPrefix())
5331 SpecLoc = SpecLoc.getPrefix();
5332 if (dyn_cast_or_null<DecltypeType>(
5333 SpecLoc.getNestedNameSpecifier()->getAsType()))
5334 Diag(Loc, diag::err_decltype_in_declarator)
5335 << SpecLoc.getTypeLoc().getSourceRange();
5336
5337 return false;
5338}
5339
5340NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5341 MultiTemplateParamsArg TemplateParamLists) {
5342 // TODO: consider using NameInfo for diagnostic.
5343 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5344 DeclarationName Name = NameInfo.getName();
5345
5346 // All of these full declarators require an identifier. If it doesn't have
5347 // one, the ParsedFreeStandingDeclSpec action should be used.
5348 if (D.isDecompositionDeclarator()) {
5349 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5350 } else if (!Name) {
5351 if (!D.isInvalidType()) // Reject this if we think it is valid.
5352 Diag(D.getDeclSpec().getLocStart(),
5353 diag::err_declarator_need_ident)
5354 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5355 return nullptr;
5356 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5357 return nullptr;
5358
5359 // The scope passed in may not be a decl scope. Zip up the scope tree until
5360 // we find one that is.
5361 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5362 (S->getFlags() & Scope::TemplateParamScope) != 0)
5363 S = S->getParent();
5364
5365 DeclContext *DC = CurContext;
5366 if (D.getCXXScopeSpec().isInvalid())
5367 D.setInvalidType();
5368 else if (D.getCXXScopeSpec().isSet()) {
5369 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5370 UPPC_DeclarationQualifier))
5371 return nullptr;
5372
5373 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5374 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5375 if (!DC || isa<EnumDecl>(DC)) {
5376 // If we could not compute the declaration context, it's because the
5377 // declaration context is dependent but does not refer to a class,
5378 // class template, or class template partial specialization. Complain
5379 // and return early, to avoid the coming semantic disaster.
5380 Diag(D.getIdentifierLoc(),
5381 diag::err_template_qualified_declarator_no_match)
5382 << D.getCXXScopeSpec().getScopeRep()
5383 << D.getCXXScopeSpec().getRange();
5384 return nullptr;
5385 }
5386 bool IsDependentContext = DC->isDependentContext();
5387
5388 if (!IsDependentContext &&
5389 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5390 return nullptr;
5391
5392 // If a class is incomplete, do not parse entities inside it.
5393 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5394 Diag(D.getIdentifierLoc(),
5395 diag::err_member_def_undefined_record)
5396 << Name << DC << D.getCXXScopeSpec().getRange();
5397 return nullptr;
5398 }
5399 if (!D.getDeclSpec().isFriendSpecified()) {
5400 if (diagnoseQualifiedDeclaration(
5401 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5402 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5403 if (DC->isRecord())
5404 return nullptr;
5405
5406 D.setInvalidType();
5407 }
5408 }
5409
5410 // Check whether we need to rebuild the type of the given
5411 // declaration in the current instantiation.
5412 if (EnteringContext && IsDependentContext &&
5413 TemplateParamLists.size() != 0) {
5414 ContextRAII SavedContext(*this, DC);
5415 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5416 D.setInvalidType();
5417 }
5418 }
5419
5420 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5421 QualType R = TInfo->getType();
5422
5423 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5424 UPPC_DeclarationType))
5425 D.setInvalidType();
5426
5427 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5428 forRedeclarationInCurContext());
5429
5430 // See if this is a redefinition of a variable in the same scope.
5431 if (!D.getCXXScopeSpec().isSet()) {
5432 bool IsLinkageLookup = false;
5433 bool CreateBuiltins = false;
5434
5435 // If the declaration we're planning to build will be a function
5436 // or object with linkage, then look for another declaration with
5437 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5438 //
5439 // If the declaration we're planning to build will be declared with
5440 // external linkage in the translation unit, create any builtin with
5441 // the same name.
5442 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5443 /* Do nothing*/;
5444 else if (CurContext->isFunctionOrMethod() &&
5445 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5446 R->isFunctionType())) {
5447 IsLinkageLookup = true;
5448 CreateBuiltins =
5449 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5450 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5451 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5452 CreateBuiltins = true;
5453
5454 if (IsLinkageLookup) {
5455 Previous.clear(LookupRedeclarationWithLinkage);
5456 Previous.setRedeclarationKind(ForExternalRedeclaration);
5457 }
5458
5459 LookupName(Previous, S, CreateBuiltins);
5460 } else { // Something like "int foo::x;"
5461 LookupQualifiedName(Previous, DC);
5462
5463 // C++ [dcl.meaning]p1:
5464 // When the declarator-id is qualified, the declaration shall refer to a
5465 // previously declared member of the class or namespace to which the
5466 // qualifier refers (or, in the case of a namespace, of an element of the
5467 // inline namespace set of that namespace (7.3.1)) or to a specialization
5468 // thereof; [...]
5469 //
5470 // Note that we already checked the context above, and that we do not have
5471 // enough information to make sure that Previous contains the declaration
5472 // we want to match. For example, given:
5473 //
5474 // class X {
5475 // void f();
5476 // void f(float);
5477 // };
5478 //
5479 // void X::f(int) { } // ill-formed
5480 //
5481 // In this case, Previous will point to the overload set
5482 // containing the two f's declared in X, but neither of them
5483 // matches.
5484
5485 // C++ [dcl.meaning]p1:
5486 // [...] the member shall not merely have been introduced by a
5487 // using-declaration in the scope of the class or namespace nominated by
5488 // the nested-name-specifier of the declarator-id.
5489 RemoveUsingDecls(Previous);
5490 }
5491
5492 if (Previous.isSingleResult() &&
5493 Previous.getFoundDecl()->isTemplateParameter()) {
5494 // Maybe we will complain about the shadowed template parameter.
5495 if (!D.isInvalidType())
5496 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5497 Previous.getFoundDecl());
5498
5499 // Just pretend that we didn't see the previous declaration.
5500 Previous.clear();
5501 }
5502
5503 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5504 // Forget that the previous declaration is the injected-class-name.
5505 Previous.clear();
5506
5507 // In C++, the previous declaration we find might be a tag type
5508 // (class or enum). In this case, the new declaration will hide the
5509 // tag type. Note that this applies to functions, function templates, and
5510 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5511 if (Previous.isSingleTagDecl() &&
5512 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5513 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5514 Previous.clear();
5515
5516 // Check that there are no default arguments other than in the parameters
5517 // of a function declaration (C++ only).
5518 if (getLangOpts().CPlusPlus)
5519 CheckExtraCXXDefaultArguments(D);
5520
5521 NamedDecl *New;
5522
5523 bool AddToScope = true;
5524 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5525 if (TemplateParamLists.size()) {
5526 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5527 return nullptr;
5528 }
5529
5530 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5531 } else if (R->isFunctionType()) {
5532 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5533 TemplateParamLists,
5534 AddToScope);
5535 } else {
5536 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5537 AddToScope);
5538 }
5539
5540 if (!New)
5541 return nullptr;
5542
5543 // If this has an identifier and is not a function template specialization,
5544 // add it to the scope stack.
5545 if (New->getDeclName() && AddToScope) {
5546 // Only make a locally-scoped extern declaration visible if it is the first
5547 // declaration of this entity. Qualified lookup for such an entity should
5548 // only find this declaration if there is no visible declaration of it.
5549 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5550 PushOnScopeChains(New, S, AddToContext);
5551 if (!AddToContext)
5552 CurContext->addHiddenDecl(New);
5553 }
5554
5555 if (isInOpenMPDeclareTargetContext())
5556 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5557
5558 return New;
5559}
5560
5561/// Helper method to turn variable array types into constant array
5562/// types in certain situations which would otherwise be errors (for
5563/// GCC compatibility).
5564static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5565 ASTContext &Context,
5566 bool &SizeIsNegative,
5567 llvm::APSInt &Oversized) {
5568 // This method tries to turn a variable array into a constant
5569 // array even when the size isn't an ICE. This is necessary
5570 // for compatibility with code that depends on gcc's buggy
5571 // constant expression folding, like struct {char x[(int)(char*)2];}
5572 SizeIsNegative = false;
5573 Oversized = 0;
5574
5575 if (T->isDependentType())
5576 return QualType();
5577
5578 QualifierCollector Qs;
5579 const Type *Ty = Qs.strip(T);
5580
5581 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5582 QualType Pointee = PTy->getPointeeType();
5583 QualType FixedType =
5584 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5585 Oversized);
5586 if (FixedType.isNull()) return FixedType;
5587 FixedType = Context.getPointerType(FixedType);
5588 return Qs.apply(Context, FixedType);
5589 }
5590 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5591 QualType Inner = PTy->getInnerType();
5592 QualType FixedType =
5593 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5594 Oversized);
5595 if (FixedType.isNull()) return FixedType;
5596 FixedType = Context.getParenType(FixedType);
5597 return Qs.apply(Context, FixedType);
5598 }
5599
5600 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5601 if (!VLATy)
5602 return QualType();
5603 // FIXME: We should probably handle this case
5604 if (VLATy->getElementType()->isVariablyModifiedType())
5605 return QualType();
5606
5607 llvm::APSInt Res;
5608 if (!VLATy->getSizeExpr() ||
5609 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5610 return QualType();
5611
5612 // Check whether the array size is negative.
5613 if (Res.isSigned() && Res.isNegative()) {
5614 SizeIsNegative = true;
5615 return QualType();
5616 }
5617
5618 // Check whether the array is too large to be addressed.
5619 unsigned ActiveSizeBits
5620 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5621 Res);
5622 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5623 Oversized = Res;
5624 return QualType();
5625 }
5626
5627 return Context.getConstantArrayType(VLATy->getElementType(),
5628 Res, ArrayType::Normal, 0);
5629}
5630
5631static void
5632FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5633 SrcTL = SrcTL.getUnqualifiedLoc();
5634 DstTL = DstTL.getUnqualifiedLoc();
5635 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5636 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5637 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5638 DstPTL.getPointeeLoc());
5639 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5640 return;
5641 }
5642 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5643 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5644 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5645 DstPTL.getInnerLoc());
5646 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5647 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5648 return;
5649 }
5650 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5651 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5652 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5653 TypeLoc DstElemTL = DstATL.getElementLoc();
5654 DstElemTL.initializeFullCopy(SrcElemTL);
5655 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5656 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5657 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5658}
5659
5660/// Helper method to turn variable array types into constant array
5661/// types in certain situations which would otherwise be errors (for
5662/// GCC compatibility).
5663static TypeSourceInfo*
5664TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5665 ASTContext &Context,
5666 bool &SizeIsNegative,
5667 llvm::APSInt &Oversized) {
5668 QualType FixedTy
5669 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5670 SizeIsNegative, Oversized);
5671 if (FixedTy.isNull())
5672 return nullptr;
5673 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5674 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5675 FixedTInfo->getTypeLoc());
5676 return FixedTInfo;
5677}
5678
5679/// Register the given locally-scoped extern "C" declaration so
5680/// that it can be found later for redeclarations. We include any extern "C"
5681/// declaration that is not visible in the translation unit here, not just
5682/// function-scope declarations.
5683void
5684Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5685 if (!getLangOpts().CPlusPlus &&
5686 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5687 // Don't need to track declarations in the TU in C.
5688 return;
5689
5690 // Note that we have a locally-scoped external with this name.
5691 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5692}
5693
5694NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5695 // FIXME: We can have multiple results via __attribute__((overloadable)).
5696 auto Result = Context.getExternCContextDecl()->lookup(Name);
5697 return Result.empty() ? nullptr : *Result.begin();
5698}
5699
5700/// Diagnose function specifiers on a declaration of an identifier that
5701/// does not identify a function.
5702void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5703 // FIXME: We should probably indicate the identifier in question to avoid
5704 // confusion for constructs like "virtual int a(), b;"
5705 if (DS.isVirtualSpecified())
5706 Diag(DS.getVirtualSpecLoc(),
5707 diag::err_virtual_non_function);
5708
5709 if (DS.isExplicitSpecified())
5710 Diag(DS.getExplicitSpecLoc(),
5711 diag::err_explicit_non_function);
5712
5713 if (DS.isNoreturnSpecified())
5714 Diag(DS.getNoreturnSpecLoc(),
5715 diag::err_noreturn_non_function);
5716}
5717
5718NamedDecl*
5719Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5720 TypeSourceInfo *TInfo, LookupResult &Previous) {
5721 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5722 if (D.getCXXScopeSpec().isSet()) {
5723 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5724 << D.getCXXScopeSpec().getRange();
5725 D.setInvalidType();
5726 // Pretend we didn't see the scope specifier.
5727 DC = CurContext;
5728 Previous.clear();
5729 }
5730
5731 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5732
5733 if (D.getDeclSpec().isInlineSpecified())
5734 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5735 << getLangOpts().CPlusPlus17;
5736 if (D.getDeclSpec().isConstexprSpecified())
5737 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5738 << 1;
5739
5740 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5741 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5742 Diag(D.getName().StartLocation,
5743 diag::err_deduction_guide_invalid_specifier)
5744 << "typedef";
5745 else
5746 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5747 << D.getName().getSourceRange();
5748 return nullptr;
5749 }
5750
5751 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5752 if (!NewTD) return nullptr;
5753
5754 // Handle attributes prior to checking for duplicates in MergeVarDecl
5755 ProcessDeclAttributes(S, NewTD, D);
5756
5757 CheckTypedefForVariablyModifiedType(S, NewTD);
5758
5759 bool Redeclaration = D.isRedeclaration();
5760 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5761 D.setRedeclaration(Redeclaration);
5762 return ND;
5763}
5764
5765void
5766Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5767 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5768 // then it shall have block scope.
5769 // Note that variably modified types must be fixed before merging the decl so
5770 // that redeclarations will match.
5771 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5772 QualType T = TInfo->getType();
5773 if (T->isVariablyModifiedType()) {
5774 setFunctionHasBranchProtectedScope();
5775
5776 if (S->getFnParent() == nullptr) {
5777 bool SizeIsNegative;
5778 llvm::APSInt Oversized;
5779 TypeSourceInfo *FixedTInfo =
5780 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5781 SizeIsNegative,
5782 Oversized);
5783 if (FixedTInfo) {
5784 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5785 NewTD->setTypeSourceInfo(FixedTInfo);
5786 } else {
5787 if (SizeIsNegative)
5788 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5789 else if (T->isVariableArrayType())
5790 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5791 else if (Oversized.getBoolValue())
5792 Diag(NewTD->getLocation(), diag::err_array_too_large)
5793 << Oversized.toString(10);
5794 else
5795 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5796 NewTD->setInvalidDecl();
5797 }
5798 }
5799 }
5800}
5801
5802/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5803/// declares a typedef-name, either using the 'typedef' type specifier or via
5804/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5805NamedDecl*
5806Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5807 LookupResult &Previous, bool &Redeclaration) {
5808
5809 // Find the shadowed declaration before filtering for scope.
5810 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5811
5812 // Merge the decl with the existing one if appropriate. If the decl is
5813 // in an outer scope, it isn't the same thing.
5814 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5815 /*AllowInlineNamespace*/false);
5816 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5817 if (!Previous.empty()) {
5818 Redeclaration = true;
5819 MergeTypedefNameDecl(S, NewTD, Previous);
5820 }
5821
5822 if (ShadowedDecl && !Redeclaration)
5823 CheckShadow(NewTD, ShadowedDecl, Previous);
5824
5825 // If this is the C FILE type, notify the AST context.
5826 if (IdentifierInfo *II = NewTD->getIdentifier())
5827 if (!NewTD->isInvalidDecl() &&
5828 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5829 if (II->isStr("FILE"))
5830 Context.setFILEDecl(NewTD);
5831 else if (II->isStr("jmp_buf"))
5832 Context.setjmp_bufDecl(NewTD);
5833 else if (II->isStr("sigjmp_buf"))
5834 Context.setsigjmp_bufDecl(NewTD);
5835 else if (II->isStr("ucontext_t"))
5836 Context.setucontext_tDecl(NewTD);
5837 }
5838
5839 return NewTD;
5840}
5841
5842/// Determines whether the given declaration is an out-of-scope
5843/// previous declaration.
5844///
5845/// This routine should be invoked when name lookup has found a
5846/// previous declaration (PrevDecl) that is not in the scope where a
5847/// new declaration by the same name is being introduced. If the new
5848/// declaration occurs in a local scope, previous declarations with
5849/// linkage may still be considered previous declarations (C99
5850/// 6.2.2p4-5, C++ [basic.link]p6).
5851///
5852/// \param PrevDecl the previous declaration found by name
5853/// lookup
5854///
5855/// \param DC the context in which the new declaration is being
5856/// declared.
5857///
5858/// \returns true if PrevDecl is an out-of-scope previous declaration
5859/// for a new delcaration with the same name.
5860static bool
5861isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5862 ASTContext &Context) {
5863 if (!PrevDecl)
5864 return false;
5865
5866 if (!PrevDecl->hasLinkage())
5867 return false;
5868
5869 if (Context.getLangOpts().CPlusPlus) {
5870 // C++ [basic.link]p6:
5871 // If there is a visible declaration of an entity with linkage
5872 // having the same name and type, ignoring entities declared
5873 // outside the innermost enclosing namespace scope, the block
5874 // scope declaration declares that same entity and receives the
5875 // linkage of the previous declaration.
5876 DeclContext *OuterContext = DC->getRedeclContext();
5877 if (!OuterContext->isFunctionOrMethod())
5878 // This rule only applies to block-scope declarations.
5879 return false;
5880
5881 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5882 if (PrevOuterContext->isRecord())
5883 // We found a member function: ignore it.
5884 return false;
5885
5886 // Find the innermost enclosing namespace for the new and
5887 // previous declarations.
5888 OuterContext = OuterContext->getEnclosingNamespaceContext();
5889 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5890
5891 // The previous declaration is in a different namespace, so it
5892 // isn't the same function.
5893 if (!OuterContext->Equals(PrevOuterContext))
5894 return false;
5895 }
5896
5897 return true;
5898}
5899
5900static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5901 CXXScopeSpec &SS = D.getCXXScopeSpec();
5902 if (!SS.isSet()) return;
5903 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5904}
5905
5906bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5907 QualType type = decl->getType();
5908 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5909 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5910 // Various kinds of declaration aren't allowed to be __autoreleasing.
5911 unsigned kind = -1U;
5912 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5913 if (var->hasAttr<BlocksAttr>())
5914 kind = 0; // __block
5915 else if (!var->hasLocalStorage())
5916 kind = 1; // global
5917 } else if (isa<ObjCIvarDecl>(decl)) {
5918 kind = 3; // ivar
5919 } else if (isa<FieldDecl>(decl)) {
5920 kind = 2; // field
5921 }
5922
5923 if (kind != -1U) {
5924 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5925 << kind;
5926 }
5927 } else if (lifetime == Qualifiers::OCL_None) {
5928 // Try to infer lifetime.
5929 if (!type->isObjCLifetimeType())
5930 return false;
5931
5932 lifetime = type->getObjCARCImplicitLifetime();
5933 type = Context.getLifetimeQualifiedType(type, lifetime);
5934 decl->setType(type);
5935 }
5936
5937 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5938 // Thread-local variables cannot have lifetime.
5939 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5940 var->getTLSKind()) {
5941 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5942 << var->getType();
5943 return true;
5944 }
5945 }
5946
5947 return false;
5948}
5949
5950static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5951 // Ensure that an auto decl is deduced otherwise the checks below might cache
5952 // the wrong linkage.
5953 assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(&
ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 5953, __extension__ __PRETTY_FUNCTION__))
;
5954
5955 // 'weak' only applies to declarations with external linkage.
5956 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5957 if (!ND.isExternallyVisible()) {
5958 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5959 ND.dropAttr<WeakAttr>();
5960 }
5961 }
5962 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5963 if (ND.isExternallyVisible()) {
5964 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5965 ND.dropAttr<WeakRefAttr>();
5966 ND.dropAttr<AliasAttr>();
5967 }
5968 }
5969
5970 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5971 if (VD->hasInit()) {
5972 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5973 assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 5974, __extension__ __PRETTY_FUNCTION__))
5974 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp"
, 5974, __extension__ __PRETTY_FUNCTION__))
;
5975 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5976 VD->dropAttr<AliasAttr>();
5977 }
5978 }
5979 }
5980
5981 // 'selectany' only applies to externally visible variable declarations.
5982 // It does not apply to functions.
5983 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5984 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5985 S.Diag(Attr->getLocation(),
5986 diag::err_attribute_selectany_non_extern_data);
5987 ND.dropAttr<SelectAnyAttr>();
5988 }
5989 }
5990
5991 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5992 // dll attributes require external linkage. Static locals may have external
5993 // linkage but still cannot be explicitly imported or exported.
5994 auto *VD = dyn_cast<VarDecl>(&ND);
5995 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5996 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5997 << &ND << Attr;
5998 ND.setInvalidDecl();
5999 }
6000 }
6001
6002 // Virtual functions cannot be marked as 'notail'.
6003 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6004 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6005 if (MD->isVirtual()) {
6006 S.Diag(ND.getLocation(),
6007 diag::err_invalid_attribute_on_virtual_function)
6008 << Attr;
6009 ND.dropAttr<NotTailCalledAttr>();
6010 }
6011}
6012
6013static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6014 NamedDecl *NewDecl,
6015 bool IsSpecialization,
6016 bool IsDefinition) {
6017 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6018 return;
6019
6020 bool IsTemplate = false;
6021 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6022 OldDecl = OldTD->getTemplatedDecl();
6023 IsTemplate = true;
6024 if (!IsSpecialization)
6025 IsDefinition = false;
6026 }
6027 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6028 NewDecl = NewTD->getTemplatedDecl();
6029 IsTemplate = true;
6030 }
6031
6032 if (!OldDecl || !NewDecl)
6033 return;
6034
6035 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6036 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6037 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6038 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6039
6040 // dllimport and dllexport are inheritable attributes so we have to exclude
6041 // inherited attribute instances.
6042 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6043 (NewExportAttr && !NewExportAttr->isInherited());
6044
6045 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6046 // the only exception being explicit specializations.
6047 // Implicitly generated declarations are also excluded for now because there
6048 // is no other way to switch these to use dllimport or dllexport.
6049 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6050
6051 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6052 // Allow with a warning for free functions and global variables.
6053 bool JustWarn = false;
6054 if (!OldDecl->isCXXClassMember()) {
6055 auto *VD = dyn_cast<VarDecl>(OldDecl);
6056 if (VD && !VD->getDescribedVarTemplate())
6057 JustWarn = true;
6058 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6059 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6060 JustWarn = true;
6061 }
6062
6063 // We cannot change a declaration that's been used because IR has already
6064 // been emitted. Dllimported functions will still work though (modulo
6065 // address equality) as they can use the thunk.
6066 if (OldDecl->isUsed())
6067 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6068 JustWarn = false;