Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 11112, column 16
Called C++ object pointer is uninitialized

Annotated Source Code

[?] Use j/k keys for keyboard navigation

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/// \brief 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 default:
152 break;
153 }
154
155 return false;
156}
157
158namespace {
159enum class UnqualifiedTypeNameLookupResult {
160 NotFound,
161 FoundNonType,
162 FoundType
163};
164} // end anonymous namespace
165
166/// \brief Tries to perform unqualified lookup of the type decls in bases for
167/// dependent class.
168/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169/// type decl, \a FoundType if only type decls are found.
170static UnqualifiedTypeNameLookupResult
171lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172 SourceLocation NameLoc,
173 const CXXRecordDecl *RD) {
174 if (!RD->hasDefinition())
175 return UnqualifiedTypeNameLookupResult::NotFound;
176 // Look for type decls in base classes.
177 UnqualifiedTypeNameLookupResult FoundTypeDecl =
178 UnqualifiedTypeNameLookupResult::NotFound;
179 for (const auto &Base : RD->bases()) {
180 const CXXRecordDecl *BaseRD = nullptr;
181 if (auto *BaseTT = Base.getType()->getAs<TagType>())
182 BaseRD = BaseTT->getAsCXXRecordDecl();
183 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184 // Look for type decls in dependent base classes that have known primary
185 // templates.
186 if (!TST || !TST->isDependentType())
187 continue;
188 auto *TD = TST->getTemplateName().getAsTemplateDecl();
189 if (!TD)
190 continue;
191 if (auto *BasePrimaryTemplate =
192 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194 BaseRD = BasePrimaryTemplate;
195 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196 if (const ClassTemplatePartialSpecializationDecl *PS =
197 CTD->findPartialSpecialization(Base.getType()))
198 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199 BaseRD = PS;
200 }
201 }
202 }
203 if (BaseRD) {
204 for (NamedDecl *ND : BaseRD->lookup(&II)) {
205 if (!isa<TypeDecl>(ND))
206 return UnqualifiedTypeNameLookupResult::FoundNonType;
207 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208 }
209 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211 case UnqualifiedTypeNameLookupResult::FoundNonType:
212 return UnqualifiedTypeNameLookupResult::FoundNonType;
213 case UnqualifiedTypeNameLookupResult::FoundType:
214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215 break;
216 case UnqualifiedTypeNameLookupResult::NotFound:
217 break;
218 }
219 }
220 }
221 }
222
223 return FoundTypeDecl;
224}
225
226static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227 const IdentifierInfo &II,
228 SourceLocation NameLoc) {
229 // Lookup in the parent class template context, if any.
230 const CXXRecordDecl *RD = nullptr;
231 UnqualifiedTypeNameLookupResult FoundTypeDecl =
232 UnqualifiedTypeNameLookupResult::NotFound;
233 for (DeclContext *DC = S.CurContext;
234 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235 DC = DC->getParent()) {
236 // Look for type decls in dependent base classes that have known primary
237 // templates.
238 RD = dyn_cast<CXXRecordDecl>(DC);
239 if (RD && RD->getDescribedClassTemplate())
240 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241 }
242 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243 return nullptr;
244
245 // We found some types in dependent base classes. Recover as if the user
246 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
247 // lookup during template instantiation.
248 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249
250 ASTContext &Context = S.Context;
251 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252 cast<Type>(Context.getRecordType(RD)));
253 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254
255 CXXScopeSpec SS;
256 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257
258 TypeLocBuilder Builder;
259 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260 DepTL.setNameLoc(NameLoc);
261 DepTL.setElaboratedKeywordLoc(SourceLocation());
262 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264}
265
266/// \brief If the identifier refers to a type name within this scope,
267/// return the declaration of that type.
268///
269/// This routine performs ordinary name lookup of the identifier II
270/// within the given scope, with optional C++ scope specifier SS, to
271/// determine whether the name refers to a type. If so, returns an
272/// opaque pointer (actually a QualType) corresponding to that
273/// type. Otherwise, returns NULL.
274ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275 Scope *S, CXXScopeSpec *SS,
276 bool isClassName, bool HasTrailingDot,
277 ParsedType ObjectTypePtr,
278 bool IsCtorOrDtorName,
279 bool WantNontrivialTypeSourceInfo,
280 bool IsClassTemplateDeductionContext,
281 IdentifierInfo **CorrectedII) {
282 // FIXME: Consider allowing this outside C++1z mode as an extension.
283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
285 !isClassName && !HasTrailingDot;
286
287 // Determine where we will perform name lookup.
288 DeclContext *LookupCtx = nullptr;
289 if (ObjectTypePtr) {
290 QualType ObjectType = ObjectTypePtr.get();
291 if (ObjectType->isRecordType())
292 LookupCtx = computeDeclContext(ObjectType);
293 } else if (SS && SS->isNotEmpty()) {
294 LookupCtx = computeDeclContext(*SS, false);
295
296 if (!LookupCtx) {
297 if (isDependentScopeSpecifier(*SS)) {
298 // C++ [temp.res]p3:
299 // A qualified-id that refers to a type and in which the
300 // nested-name-specifier depends on a template-parameter (14.6.2)
301 // shall be prefixed by the keyword typename to indicate that the
302 // qualified-id denotes a type, forming an
303 // elaborated-type-specifier (7.1.5.3).
304 //
305 // We therefore do not perform any name lookup if the result would
306 // refer to a member of an unknown specialization.
307 if (!isClassName && !IsCtorOrDtorName)
308 return nullptr;
309
310 // We know from the grammar that this name refers to a type,
311 // so build a dependent node to describe the type.
312 if (WantNontrivialTypeSourceInfo)
313 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314
315 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317 II, NameLoc);
318 return ParsedType::make(T);
319 }
320
321 return nullptr;
322 }
323
324 if (!LookupCtx->isDependentContext() &&
325 RequireCompleteDeclContext(*SS, LookupCtx))
326 return nullptr;
327 }
328
329 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330 // lookup for class-names.
331 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332 LookupOrdinaryName;
333 LookupResult Result(*this, &II, NameLoc, Kind);
334 if (LookupCtx) {
335 // Perform "qualified" name lookup into the declaration context we
336 // computed, which is either the type of the base of a member access
337 // expression or the declaration context associated with a prior
338 // nested-name-specifier.
339 LookupQualifiedName(Result, LookupCtx);
340
341 if (ObjectTypePtr && Result.empty()) {
342 // C++ [basic.lookup.classref]p3:
343 // If the unqualified-id is ~type-name, the type-name is looked up
344 // in the context of the entire postfix-expression. If the type T of
345 // the object expression is of a class type C, the type-name is also
346 // looked up in the scope of class C. At least one of the lookups shall
347 // find a name that refers to (possibly cv-qualified) T.
348 LookupName(Result, S);
349 }
350 } else {
351 // Perform unqualified name lookup.
352 LookupName(Result, S);
353
354 // For unqualified lookup in a class template in MSVC mode, look into
355 // dependent base classes where the primary class template is known.
356 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357 if (ParsedType TypeInBase =
358 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359 return TypeInBase;
360 }
361 }
362
363 NamedDecl *IIDecl = nullptr;
364 switch (Result.getResultKind()) {
365 case LookupResult::NotFound:
366 case LookupResult::NotFoundInCurrentInstantiation:
367 if (CorrectedII) {
368 TypoCorrection Correction =
369 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370 llvm::make_unique<TypeNameValidatorCCC>(
371 true, isClassName, AllowDeducedTemplate),
372 CTK_ErrorRecovery);
373 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374 TemplateTy Template;
375 bool MemberOfUnknownSpecialization;
376 UnqualifiedId TemplateName;
377 TemplateName.setIdentifier(NewII, NameLoc);
378 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379 CXXScopeSpec NewSS, *NewSSPtr = SS;
380 if (SS && NNS) {
381 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382 NewSSPtr = &NewSS;
383 }
384 if (Correction && (NNS || NewII != &II) &&
385 // Ignore a correction to a template type as the to-be-corrected
386 // identifier is not a template (typo correction for template names
387 // is handled elsewhere).
388 !(getLangOpts().CPlusPlus && NewSSPtr &&
389 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390 Template, MemberOfUnknownSpecialization))) {
391 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392 isClassName, HasTrailingDot, ObjectTypePtr,
393 IsCtorOrDtorName,
394 WantNontrivialTypeSourceInfo,
395 IsClassTemplateDeductionContext);
396 if (Ty) {
397 diagnoseTypo(Correction,
398 PDiag(diag::err_unknown_type_or_class_name_suggest)
399 << Result.getLookupName() << isClassName);
400 if (SS && NNS)
401 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402 *CorrectedII = NewII;
403 return Ty;
404 }
405 }
406 }
407 // If typo correction failed or was not performed, fall through
408 LLVM_FALLTHROUGH[[clang::fallthrough]];
409 case LookupResult::FoundOverloaded:
410 case LookupResult::FoundUnresolvedValue:
411 Result.suppressDiagnostics();
412 return nullptr;
413
414 case LookupResult::Ambiguous:
415 // Recover from type-hiding ambiguities by hiding the type. We'll
416 // do the lookup again when looking for an object, and we can
417 // diagnose the error then. If we don't do this, then the error
418 // about hiding the type will be immediately followed by an error
419 // that only makes sense if the identifier was treated like a type.
420 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421 Result.suppressDiagnostics();
422 return nullptr;
423 }
424
425 // Look to see if we have a type anywhere in the list of results.
426 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427 Res != ResEnd; ++Res) {
428 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430 if (!IIDecl ||
431 (*Res)->getLocation().getRawEncoding() <
432 IIDecl->getLocation().getRawEncoding())
433 IIDecl = *Res;
434 }
435 }
436
437 if (!IIDecl) {
438 // None of the entities we found is a type, so there is no way
439 // to even assume that the result is a type. In this case, don't
440 // complain about the ambiguity. The parser will either try to
441 // perform this lookup again (e.g., as an object name), which
442 // will produce the ambiguity, or will complain that it expected
443 // a type name.
444 Result.suppressDiagnostics();
445 return nullptr;
446 }
447
448 // We found a type within the ambiguous lookup; diagnose the
449 // ambiguity and then return that type. This might be the right
450 // answer, or it might not be, but it suppresses any attempt to
451 // perform the name lookup again.
452 break;
453
454 case LookupResult::Found:
455 IIDecl = Result.getFoundDecl();
456 break;
457 }
458
459 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 459, __extension__ __PRETTY_FUNCTION__))
;
460
461 QualType T;
462 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463 // C++ [class.qual]p2: A lookup that would find the injected-class-name
464 // instead names the constructors of the class, except when naming a class.
465 // This is ill-formed when we're not actually forming a ctor or dtor name.
466 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469 FoundRD->isInjectedClassName() &&
470 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472 << &II << /*Type*/1;
473
474 DiagnoseUseOfDecl(IIDecl, NameLoc);
475
476 T = Context.getTypeDeclType(TD);
477 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480 if (!HasTrailingDot)
481 T = Context.getObjCInterfaceType(IDecl);
482 } else if (AllowDeducedTemplate) {
483 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485 QualType(), false);
486 }
487
488 if (T.isNull()) {
489 // If it's not plausibly a type, suppress diagnostics.
490 Result.suppressDiagnostics();
491 return nullptr;
492 }
493
494 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495 // constructor or destructor name (in such a case, the scope specifier
496 // will be attached to the enclosing Expr or Decl node).
497 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498 !isa<ObjCInterfaceDecl>(IIDecl)) {
499 if (WantNontrivialTypeSourceInfo) {
500 // Construct a type with type-source information.
501 TypeLocBuilder Builder;
502 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503
504 T = getElaboratedType(ETK_None, *SS, T);
505 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506 ElabTL.setElaboratedKeywordLoc(SourceLocation());
507 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509 } else {
510 T = getElaboratedType(ETK_None, *SS, T);
511 }
512 }
513
514 return ParsedType::make(T);
515}
516
517// Builds a fake NNS for the given decl context.
518static NestedNameSpecifier *
519synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520 for (;; DC = DC->getLookupParent()) {
521 DC = DC->getPrimaryContext();
522 auto *ND = dyn_cast<NamespaceDecl>(DC);
523 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524 return NestedNameSpecifier::Create(Context, nullptr, ND);
525 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527 RD->getTypeForDecl());
528 else if (isa<TranslationUnitDecl>(DC))
529 return NestedNameSpecifier::GlobalSpecifier(Context);
530 }
531 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 531)
;
532}
533
534/// Find the parent class with dependent bases of the innermost enclosing method
535/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536/// up allowing unqualified dependent type names at class-level, which MSVC
537/// correctly rejects.
538static const CXXRecordDecl *
539findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541 DC = DC->getPrimaryContext();
542 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543 if (MD->getParent()->hasAnyDependentBases())
544 return MD->getParent();
545 }
546 return nullptr;
547}
548
549ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550 SourceLocation NameLoc,
551 bool IsTemplateTypeArg) {
552 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 552, __extension__ __PRETTY_FUNCTION__))
;
553
554 NestedNameSpecifier *NNS = nullptr;
555 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556 // If we weren't able to parse a default template argument, delay lookup
557 // until instantiation time by making a non-dependent DependentTypeName. We
558 // pretend we saw a NestedNameSpecifier referring to the current scope, and
559 // lookup is retried.
560 // FIXME: This hurts our diagnostic quality, since we get errors like "no
561 // type named 'Foo' in 'current_namespace'" when the user didn't write any
562 // name specifiers.
563 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565 } else if (const CXXRecordDecl *RD =
566 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567 // Build a DependentNameType that will perform lookup into RD at
568 // instantiation time.
569 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570 RD->getTypeForDecl());
571
572 // Diagnose that this identifier was undeclared, and retry the lookup during
573 // template instantiation.
574 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575 << RD;
576 } else {
577 // This is not a situation that we should recover from.
578 return ParsedType();
579 }
580
581 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582
583 // Build type location information. We synthesized the qualifier, so we have
584 // to build a fake NestedNameSpecifierLoc.
585 NestedNameSpecifierLocBuilder NNSLocBuilder;
586 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588
589 TypeLocBuilder Builder;
590 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591 DepTL.setNameLoc(NameLoc);
592 DepTL.setElaboratedKeywordLoc(SourceLocation());
593 DepTL.setQualifierLoc(QualifierLoc);
594 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595}
596
597/// isTagName() - This method is called *for error recovery purposes only*
598/// to determine if the specified name is a valid tag name ("struct foo"). If
599/// so, this returns the TST for the tag corresponding to it (TST_enum,
600/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
601/// cases in C where the user forgot to specify the tag.
602DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603 // Do a tag name lookup in this scope.
604 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605 LookupName(R, S, false);
606 R.suppressDiagnostics();
607 if (R.getResultKind() == LookupResult::Found)
608 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609 switch (TD->getTagKind()) {
610 case TTK_Struct: return DeclSpec::TST_struct;
611 case TTK_Interface: return DeclSpec::TST_interface;
612 case TTK_Union: return DeclSpec::TST_union;
613 case TTK_Class: return DeclSpec::TST_class;
614 case TTK_Enum: return DeclSpec::TST_enum;
615 }
616 }
617
618 return DeclSpec::TST_unspecified;
619}
620
621/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622/// if a CXXScopeSpec's type is equal to the type of one of the base classes
623/// then downgrade the missing typename error to a warning.
624/// This is needed for MSVC compatibility; Example:
625/// @code
626/// template<class T> class A {
627/// public:
628/// typedef int TYPE;
629/// };
630/// template<class T> class B : public A<T> {
631/// public:
632/// A<T>::TYPE a; // no typename required because A<T> is a base class.
633/// };
634/// @endcode
635bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636 if (CurContext->isRecord()) {
637 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638 return true;
639
640 const Type *Ty = SS->getScopeRep()->getAsType();
641
642 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643 for (const auto &Base : RD->bases())
644 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645 return true;
646 return S->isFunctionPrototypeScope();
647 }
648 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649}
650
651void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652 SourceLocation IILoc,
653 Scope *S,
654 CXXScopeSpec *SS,
655 ParsedType &SuggestedType,
656 bool IsTemplateName) {
657 // Don't report typename errors for editor placeholders.
658 if (II->isEditorPlaceholder())
659 return;
660 // We don't have anything to suggest (yet).
661 SuggestedType = nullptr;
662
663 // There may have been a typo in the name of the type. Look up typo
664 // results, in case we have something that we can suggest.
665 if (TypoCorrection Corrected =
666 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667 llvm::make_unique<TypeNameValidatorCCC>(
668 false, false, IsTemplateName, !IsTemplateName),
669 CTK_ErrorRecovery)) {
670 // FIXME: Support error recovery for the template-name case.
671 bool CanRecover = !IsTemplateName;
672 if (Corrected.isKeyword()) {
673 // We corrected to a keyword.
674 diagnoseTypo(Corrected,
675 PDiag(IsTemplateName ? diag::err_no_template_suggest
676 : diag::err_unknown_typename_suggest)
677 << II);
678 II = Corrected.getCorrectionAsIdentifierInfo();
679 } else {
680 // We found a similarly-named type or interface; suggest that.
681 if (!SS || !SS->isSet()) {
682 diagnoseTypo(Corrected,
683 PDiag(IsTemplateName ? diag::err_no_template_suggest
684 : diag::err_unknown_typename_suggest)
685 << II, CanRecover);
686 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689 II->getName().equals(CorrectedStr);
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName
692 ? diag::err_no_member_template_suggest
693 : diag::err_unknown_nested_typename_suggest)
694 << II << DC << DroppedSpecifier << SS->getRange(),
695 CanRecover);
696 } else {
697 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 697)
;
698 }
699
700 if (!CanRecover)
701 return;
702
703 CXXScopeSpec tmpSS;
704 if (Corrected.getCorrectionSpecifier())
705 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706 SourceRange(IILoc));
707 // FIXME: Support class template argument deduction here.
708 SuggestedType =
709 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711 /*IsCtorOrDtorName=*/false,
712 /*NonTrivialTypeSourceInfo=*/true);
713 }
714 return;
715 }
716
717 if (getLangOpts().CPlusPlus && !IsTemplateName) {
718 // See if II is a class template that the user forgot to pass arguments to.
719 UnqualifiedId Name;
720 Name.setIdentifier(II, IILoc);
721 CXXScopeSpec EmptySS;
722 TemplateTy TemplateResult;
723 bool MemberOfUnknownSpecialization;
724 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725 Name, nullptr, true, TemplateResult,
726 MemberOfUnknownSpecialization) == TNK_Type_template) {
727 TemplateName TplName = TemplateResult.get();
728 Diag(IILoc, diag::err_template_missing_args)
729 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732 << TplDecl->getTemplateParameters()->getSourceRange();
733 }
734 return;
735 }
736 }
737
738 // FIXME: Should we move the logic that tries to recover from a missing tag
739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740
741 if (!SS || (!SS->isSet() && !SS->isInvalid()))
742 Diag(IILoc, IsTemplateName ? diag::err_no_template
743 : diag::err_unknown_typename)
744 << II;
745 else if (DeclContext *DC = computeDeclContext(*SS, false))
746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747 : diag::err_typename_nested_not_found)
748 << II << DC << SS->getRange();
749 else if (isDependentScopeSpecifier(*SS)) {
750 unsigned DiagID = diag::err_typename_missing;
751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752 DiagID = diag::ext_typename_missing;
753
754 Diag(SS->getRange().getBegin(), DiagID)
755 << SS->getScopeRep() << II->getName()
756 << SourceRange(SS->getRange().getBegin(), IILoc)
757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758 SuggestedType = ActOnTypenameType(S, SourceLocation(),
759 *SS, *II, IILoc).get();
760 } else {
761 assert(SS && SS->isInvalid() &&(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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 762, __extension__ __PRETTY_FUNCTION__))
762 "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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 762, __extension__ __PRETTY_FUNCTION__))
;
763 }
764}
765
766/// \brief Determine whether the given result set contains either a type name
767/// or
768static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770 NextToken.is(tok::less);
771
772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774 return true;
775
776 if (CheckTemplate && isa<TemplateDecl>(*I))
777 return true;
778 }
779
780 return false;
781}
782
783static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784 Scope *S, CXXScopeSpec &SS,
785 IdentifierInfo *&Name,
786 SourceLocation NameLoc) {
787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788 SemaRef.LookupParsedName(R, S, &SS);
789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790 StringRef FixItTagName;
791 switch (Tag->getTagKind()) {
792 case TTK_Class:
793 FixItTagName = "class ";
794 break;
795
796 case TTK_Enum:
797 FixItTagName = "enum ";
798 break;
799
800 case TTK_Struct:
801 FixItTagName = "struct ";
802 break;
803
804 case TTK_Interface:
805 FixItTagName = "__interface ";
806 break;
807
808 case TTK_Union:
809 FixItTagName = "union ";
810 break;
811 }
812
813 StringRef TagName = FixItTagName.drop_back();
814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817
818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819 I != IEnd; ++I)
820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821 << Name << TagName;
822
823 // Replace lookup results with just the tag decl.
824 Result.clear(Sema::LookupTagName);
825 SemaRef.LookupParsedName(Result, S, &SS);
826 return true;
827 }
828
829 return false;
830}
831
832/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834 QualType T, SourceLocation NameLoc) {
835 ASTContext &Context = S.Context;
836
837 TypeLocBuilder Builder;
838 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839
840 T = S.getElaboratedType(ETK_None, SS, T);
841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842 ElabTL.setElaboratedKeywordLoc(SourceLocation());
843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845}
846
847Sema::NameClassification
848Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849 SourceLocation NameLoc, const Token &NextToken,
850 bool IsAddressOfOperand,
851 std::unique_ptr<CorrectionCandidateCallback> CCC) {
852 DeclarationNameInfo NameInfo(Name, NameLoc);
853 ObjCMethodDecl *CurMethod = getCurMethodDecl();
854
855 if (NextToken.is(tok::coloncolon)) {
856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859 isCurrentClassName(*Name, S, &SS)) {
860 // Per [class.qual]p2, this names the constructors of SS, not the
861 // injected-class-name. We don't have a classification for that.
862 // There's not much point caching this result, since the parser
863 // will reject it later.
864 return NameClassification::Unknown();
865 }
866
867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868 LookupParsedName(Result, S, &SS, !CurMethod);
869
870 // For unqualified lookup in a class template in MSVC mode, look into
871 // dependent base classes where the primary class template is known.
872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873 if (ParsedType TypeInBase =
874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875 return TypeInBase;
876 }
877
878 // Perform lookup for Objective-C instance variables (including automatically
879 // synthesized instance variables), if we're in an Objective-C method.
880 // FIXME: This lookup really, really needs to be folded in to the normal
881 // unqualified lookup mechanism.
882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884 if (E.get() || E.isInvalid())
885 return E;
886 }
887
888 bool SecondTry = false;
889 bool IsFilteredTemplateName = false;
890
891Corrected:
892 switch (Result.getResultKind()) {
893 case LookupResult::NotFound:
894 // If an unqualified-id is followed by a '(', then we have a function
895 // call.
896 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897 // In C++, this is an ADL-only call.
898 // FIXME: Reference?
899 if (getLangOpts().CPlusPlus)
900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901
902 // C90 6.3.2.2:
903 // If the expression that precedes the parenthesized argument list in a
904 // function call consists solely of an identifier, and if no
905 // declaration is visible for this identifier, the identifier is
906 // implicitly declared exactly as if, in the innermost block containing
907 // the function call, the declaration
908 //
909 // extern int identifier ();
910 //
911 // appeared.
912 //
913 // We also allow this in C99 as an extension.
914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915 Result.addDecl(D);
916 Result.resolveKind();
917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918 }
919 }
920
921 // In C, we first see whether there is a tag type by the same name, in
922 // which case it's likely that the user just forgot to write "enum",
923 // "struct", or "union".
924 if (!getLangOpts().CPlusPlus && !SecondTry &&
925 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926 break;
927 }
928
929 // Perform typo correction to determine if there is another name that is
930 // close to this name.
931 if (!SecondTry && CCC) {
932 SecondTry = true;
933 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934 Result.getLookupKind(), S,
935 &SS, std::move(CCC),
936 CTK_ErrorRecovery)) {
937 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938 unsigned QualifiedDiag = diag::err_no_member_suggest;
939
940 NamedDecl *FirstDecl = Corrected.getFoundDecl();
941 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944 UnqualifiedDiag = diag::err_no_template_suggest;
945 QualifiedDiag = diag::err_no_member_template_suggest;
946 } else if (UnderlyingFirstDecl &&
947 (isa<TypeDecl>(UnderlyingFirstDecl) ||
948 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950 UnqualifiedDiag = diag::err_unknown_typename_suggest;
951 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952 }
953
954 if (SS.isEmpty()) {
955 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956 } else {// FIXME: is this even reachable? Test it.
957 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959 Name->getName().equals(CorrectedStr);
960 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961 << Name << computeDeclContext(SS, false)
962 << DroppedSpecifier << SS.getRange());
963 }
964
965 // Update the name, so that the caller has the new name.
966 Name = Corrected.getCorrectionAsIdentifierInfo();
967
968 // Typo correction corrected to a keyword.
969 if (Corrected.isKeyword())
970 return Name;
971
972 // Also update the LookupResult...
973 // FIXME: This should probably go away at some point
974 Result.clear();
975 Result.setLookupName(Corrected.getCorrection());
976 if (FirstDecl)
977 Result.addDecl(FirstDecl);
978
979 // If we found an Objective-C instance variable, let
980 // LookupInObjCMethod build the appropriate expression to
981 // reference the ivar.
982 // FIXME: This is a gross hack.
983 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984 Result.clear();
985 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986 return E;
987 }
988
989 goto Corrected;
990 }
991 }
992
993 // We failed to correct; just fall through and let the parser deal with it.
994 Result.suppressDiagnostics();
995 return NameClassification::Unknown();
996
997 case LookupResult::NotFoundInCurrentInstantiation: {
998 // We performed name lookup into the current instantiation, and there were
999 // dependent bases, so we treat this result the same way as any other
1000 // dependent nested-name-specifier.
1001
1002 // C++ [temp.res]p2:
1003 // A name used in a template declaration or definition and that is
1004 // dependent on a template-parameter is assumed not to name a type
1005 // unless the applicable name lookup finds a type name or the name is
1006 // qualified by the keyword typename.
1007 //
1008 // FIXME: If the next token is '<', we might want to ask the parser to
1009 // perform some heroics to see if we actually have a
1010 // template-argument-list, which would indicate a missing 'template'
1011 // keyword here.
1012 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013 NameInfo, IsAddressOfOperand,
1014 /*TemplateArgs=*/nullptr);
1015 }
1016
1017 case LookupResult::Found:
1018 case LookupResult::FoundOverloaded:
1019 case LookupResult::FoundUnresolvedValue:
1020 break;
1021
1022 case LookupResult::Ambiguous:
1023 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024 hasAnyAcceptableTemplateNames(Result)) {
1025 // C++ [temp.local]p3:
1026 // A lookup that finds an injected-class-name (10.2) can result in an
1027 // ambiguity in certain cases (for example, if it is found in more than
1028 // one base class). If all of the injected-class-names that are found
1029 // refer to specializations of the same class template, and if the name
1030 // is followed by a template-argument-list, the reference refers to the
1031 // class template itself and not a specialization thereof, and is not
1032 // ambiguous.
1033 //
1034 // This filtering can make an ambiguous result into an unambiguous one,
1035 // so try again after filtering out template names.
1036 FilterAcceptableTemplateNames(Result);
1037 if (!Result.isAmbiguous()) {
1038 IsFilteredTemplateName = true;
1039 break;
1040 }
1041 }
1042
1043 // Diagnose the ambiguity and return an error.
1044 return NameClassification::Error();
1045 }
1046
1047 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049 // C++ [temp.names]p3:
1050 // After name lookup (3.4) finds that a name is a template-name or that
1051 // an operator-function-id or a literal- operator-id refers to a set of
1052 // overloaded functions any member of which is a function template if
1053 // this is followed by a <, the < is always taken as the delimiter of a
1054 // template-argument-list and never as the less-than operator.
1055 if (!IsFilteredTemplateName)
1056 FilterAcceptableTemplateNames(Result);
1057
1058 if (!Result.empty()) {
1059 bool IsFunctionTemplate;
1060 bool IsVarTemplate;
1061 TemplateName Template;
1062 if (Result.end() - Result.begin() > 1) {
1063 IsFunctionTemplate = true;
1064 Template = Context.getOverloadedTemplateName(Result.begin(),
1065 Result.end());
1066 } else {
1067 TemplateDecl *TD
1068 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070 IsVarTemplate = isa<VarTemplateDecl>(TD);
1071
1072 if (SS.isSet() && !SS.isInvalid())
1073 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074 /*TemplateKeyword=*/false,
1075 TD);
1076 else
1077 Template = TemplateName(TD);
1078 }
1079
1080 if (IsFunctionTemplate) {
1081 // Function templates always go through overload resolution, at which
1082 // point we'll perform the various checks (e.g., accessibility) we need
1083 // to based on which function we selected.
1084 Result.suppressDiagnostics();
1085
1086 return NameClassification::FunctionTemplate(Template);
1087 }
1088
1089 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090 : NameClassification::TypeTemplate(Template);
1091 }
1092 }
1093
1094 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096 DiagnoseUseOfDecl(Type, NameLoc);
1097 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098 QualType T = Context.getTypeDeclType(Type);
1099 if (SS.isNotEmpty())
1100 return buildNestedType(*this, SS, T, NameLoc);
1101 return ParsedType::make(T);
1102 }
1103
1104 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105 if (!Class) {
1106 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107 if (ObjCCompatibleAliasDecl *Alias =
1108 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109 Class = Alias->getClassInterface();
1110 }
1111
1112 if (Class) {
1113 DiagnoseUseOfDecl(Class, NameLoc);
1114
1115 if (NextToken.is(tok::period)) {
1116 // Interface. <something> is parsed as a property reference expression.
1117 // Just return "unknown" as a fall-through for now.
1118 Result.suppressDiagnostics();
1119 return NameClassification::Unknown();
1120 }
1121
1122 QualType T = Context.getObjCInterfaceType(Class);
1123 return ParsedType::make(T);
1124 }
1125
1126 // We can have a type template here if we're classifying a template argument.
1127 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128 !isa<VarTemplateDecl>(FirstDecl))
1129 return NameClassification::TypeTemplate(
1130 TemplateName(cast<TemplateDecl>(FirstDecl)));
1131
1132 // Check for a tag type hidden by a non-type decl in a few cases where it
1133 // seems likely a type is wanted instead of the non-type that was found.
1134 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135 if ((NextToken.is(tok::identifier) ||
1136 (NextIsOp &&
1137 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140 DiagnoseUseOfDecl(Type, NameLoc);
1141 QualType T = Context.getTypeDeclType(Type);
1142 if (SS.isNotEmpty())
1143 return buildNestedType(*this, SS, T, NameLoc);
1144 return ParsedType::make(T);
1145 }
1146
1147 if (FirstDecl->isCXXClassMember())
1148 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149 nullptr, S);
1150
1151 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152 return BuildDeclarationNameExpr(SS, Result, ADL);
1153}
1154
1155Sema::TemplateNameKindForDiagnostics
1156Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157 auto *TD = Name.getAsTemplateDecl();
1158 if (!TD)
1159 return TemplateNameKindForDiagnostics::DependentTemplate;
1160 if (isa<ClassTemplateDecl>(TD))
1161 return TemplateNameKindForDiagnostics::ClassTemplate;
1162 if (isa<FunctionTemplateDecl>(TD))
1163 return TemplateNameKindForDiagnostics::FunctionTemplate;
1164 if (isa<VarTemplateDecl>(TD))
1165 return TemplateNameKindForDiagnostics::VarTemplate;
1166 if (isa<TypeAliasTemplateDecl>(TD))
1167 return TemplateNameKindForDiagnostics::AliasTemplate;
1168 if (isa<TemplateTemplateParmDecl>(TD))
1169 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170 return TemplateNameKindForDiagnostics::DependentTemplate;
1171}
1172
1173// Determines the context to return to after temporarily entering a
1174// context. This depends in an unnecessarily complicated way on the
1175// exact ordering of callbacks from the parser.
1176DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177
1178 // Functions defined inline within classes aren't parsed until we've
1179 // finished parsing the top-level class, so the top-level class is
1180 // the context we'll need to return to.
1181 // A Lambda call operator whose parent is a class must not be treated
1182 // as an inline member function. A Lambda can be used legally
1183 // either as an in-class member initializer or a default argument. These
1184 // are parsed once the class has been marked complete and so the containing
1185 // context would be the nested class (when the lambda is defined in one);
1186 // If the class is not complete, then the lambda is being used in an
1187 // ill-formed fashion (such as to specify the width of a bit-field, or
1188 // in an array-bound) - in which case we still want to return the
1189 // lexically containing DC (which could be a nested class).
1190 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191 DC = DC->getLexicalParent();
1192
1193 // A function not defined within a class will always return to its
1194 // lexical context.
1195 if (!isa<CXXRecordDecl>(DC))
1196 return DC;
1197
1198 // A C++ inline method/friend is parsed *after* the topmost class
1199 // it was declared in is fully parsed ("complete"); the topmost
1200 // class is the context we need to return to.
1201 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202 DC = RD;
1203
1204 // Return the declaration context of the topmost class the inline method is
1205 // declared in.
1206 return DC;
1207 }
1208
1209 return DC->getLexicalParent();
1210}
1211
1212void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1214, __extension__ __PRETTY_FUNCTION__))
1214 "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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1214, __extension__ __PRETTY_FUNCTION__))
;
1215 CurContext = DC;
1216 S->setEntity(DC);
1217}
1218
1219void Sema::PopDeclContext() {
1220 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1220, __extension__ __PRETTY_FUNCTION__))
;
1221
1222 CurContext = getContainingDC(CurContext);
1223 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1223, __extension__ __PRETTY_FUNCTION__))
;
1224}
1225
1226Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227 Decl *D) {
1228 // Unlike PushDeclContext, the context to which we return is not necessarily
1229 // the containing DC of TD, because the new context will be some pre-existing
1230 // TagDecl definition instead of a fresh one.
1231 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232 CurContext = cast<TagDecl>(D)->getDefinition();
1233 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1233, __extension__ __PRETTY_FUNCTION__))
;
1234 // Start lookups from the parent of the current context; we don't want to look
1235 // into the pre-existing complete definition.
1236 S->setEntity(CurContext->getLookupParent());
1237 return Result;
1238}
1239
1240void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241 CurContext = static_cast<decltype(CurContext)>(Context);
1242}
1243
1244/// EnterDeclaratorContext - Used when we must lookup names in the context
1245/// of a declarator's nested name specifier.
1246///
1247void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248 // C++0x [basic.lookup.unqual]p13:
1249 // A name used in the definition of a static data member of class
1250 // X (after the qualified-id of the static member) is looked up as
1251 // if the name was used in a member function of X.
1252 // C++0x [basic.lookup.unqual]p14:
1253 // If a variable member of a namespace is defined outside of the
1254 // scope of its namespace then any name used in the definition of
1255 // the variable member (after the declarator-id) is looked up as
1256 // if the definition of the variable member occurred in its
1257 // namespace.
1258 // Both of these imply that we should push a scope whose context
1259 // is the semantic context of the declaration. We can't use
1260 // PushDeclContext here because that context is not necessarily
1261 // lexically contained in the current context. Fortunately,
1262 // the containing scope should have the appropriate information.
1263
1264 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1264, __extension__ __PRETTY_FUNCTION__))
;
1265
1266#ifndef NDEBUG
1267 Scope *Ancestor = S->getParent();
1268 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1269, __extension__ __PRETTY_FUNCTION__))
;
1270#endif
1271
1272 CurContext = DC;
1273 S->setEntity(DC);
1274}
1275
1276void Sema::ExitDeclaratorContext(Scope *S) {
1277 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1277, __extension__ __PRETTY_FUNCTION__))
;
1278
1279 // Switch back to the lexical context. The safety of this is
1280 // enforced by an assert in EnterDeclaratorContext.
1281 Scope *Ancestor = S->getParent();
1282 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283 CurContext = Ancestor->getEntity();
1284
1285 // We don't need to do anything with the scope, which is going to
1286 // disappear.
1287}
1288
1289void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290 // We assume that the caller has already called
1291 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292 FunctionDecl *FD = D->getAsFunction();
1293 if (!FD)
1294 return;
1295
1296 // Same implementation as PushDeclContext, but enters the context
1297 // from the lexical parent, rather than the top-level class.
1298 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1299, __extension__ __PRETTY_FUNCTION__))
1299 "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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1299, __extension__ __PRETTY_FUNCTION__))
;
1300 CurContext = FD;
1301 S->setEntity(CurContext);
1302
1303 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304 ParmVarDecl *Param = FD->getParamDecl(P);
1305 // If the parameter has an identifier, then add it to the scope
1306 if (Param->getIdentifier()) {
1307 S->AddDecl(Param);
1308 IdResolver.AddDecl(Param);
1309 }
1310 }
1311}
1312
1313void Sema::ActOnExitFunctionContext() {
1314 // Same implementation as PopDeclContext, but returns to the lexical parent,
1315 // rather than the top-level class.
1316 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1316, __extension__ __PRETTY_FUNCTION__))
;
1317 CurContext = CurContext->getLexicalParent();
1318 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1318, __extension__ __PRETTY_FUNCTION__))
;
1319}
1320
1321/// \brief Determine whether we allow overloading of the function
1322/// PrevDecl with another declaration.
1323///
1324/// This routine determines whether overloading is possible, not
1325/// whether some new function is actually an overload. It will return
1326/// true in C++ (where we can always provide overloads) or, as an
1327/// extension, in C when the previous function is already an
1328/// overloaded function declaration or has the "overloadable"
1329/// attribute.
1330static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331 ASTContext &Context,
1332 const FunctionDecl *New) {
1333 if (Context.getLangOpts().CPlusPlus)
1334 return true;
1335
1336 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337 return true;
1338
1339 return Previous.getResultKind() == LookupResult::Found &&
1340 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341 New->hasAttr<OverloadableAttr>());
1342}
1343
1344/// Add this decl to the scope shadowed decl chains.
1345void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346 // Move up the scope chain until we find the nearest enclosing
1347 // non-transparent context. The declaration will be introduced into this
1348 // scope.
1349 while (S->getEntity() && S->getEntity()->isTransparentContext())
1350 S = S->getParent();
1351
1352 // Add scoped declarations into their context, so that they can be
1353 // found later. Declarations without a context won't be inserted
1354 // into any context.
1355 if (AddToContext)
1356 CurContext->addDecl(D);
1357
1358 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359 // are function-local declarations.
1360 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361 !D->getDeclContext()->getRedeclContext()->Equals(
1362 D->getLexicalDeclContext()->getRedeclContext()) &&
1363 !D->getLexicalDeclContext()->isFunctionOrMethod())
1364 return;
1365
1366 // Template instantiations should also not be pushed into scope.
1367 if (isa<FunctionDecl>(D) &&
1368 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369 return;
1370
1371 // If this replaces anything in the current scope,
1372 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373 IEnd = IdResolver.end();
1374 for (; I != IEnd; ++I) {
1375 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376 S->RemoveDecl(*I);
1377 IdResolver.RemoveDecl(*I);
1378
1379 // Should only need to replace one decl.
1380 break;
1381 }
1382 }
1383
1384 S->AddDecl(D);
1385
1386 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387 // Implicitly-generated labels may end up getting generated in an order that
1388 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389 // the label at the appropriate place in the identifier chain.
1390 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392 if (IDC == CurContext) {
1393 if (!S->isDeclScope(*I))
1394 continue;
1395 } else if (IDC->Encloses(CurContext))
1396 break;
1397 }
1398
1399 IdResolver.InsertDeclAfter(I, D);
1400 } else {
1401 IdResolver.AddDecl(D);
1402 }
1403}
1404
1405void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407 TUScope->AddDecl(D);
1408}
1409
1410bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411 bool AllowInlineNamespace) {
1412 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413}
1414
1415Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416 DeclContext *TargetDC = DC->getPrimaryContext();
1417 do {
1418 if (DeclContext *ScopeDC = S->getEntity())
1419 if (ScopeDC->getPrimaryContext() == TargetDC)
1420 return S;
1421 } while ((S = S->getParent()));
1422
1423 return nullptr;
1424}
1425
1426static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427 DeclContext*,
1428 ASTContext&);
1429
1430/// Filters out lookup results that don't fall within the given scope
1431/// as determined by isDeclInScope.
1432void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433 bool ConsiderLinkage,
1434 bool AllowInlineNamespace) {
1435 LookupResult::Filter F = R.makeFilter();
1436 while (F.hasNext()) {
1437 NamedDecl *D = F.next();
1438
1439 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440 continue;
1441
1442 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443 continue;
1444
1445 F.erase();
1446 }
1447
1448 F.done();
1449}
1450
1451/// We've determined that \p New is a redeclaration of \p Old. Check that they
1452/// have compatible owning modules.
1453bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454 // FIXME: The Modules TS is not clear about how friend declarations are
1455 // to be treated. It's not meaningful to have different owning modules for
1456 // linkage in redeclarations of the same entity, so for now allow the
1457 // redeclaration and change the owning modules to match.
1458 if (New->getFriendObjectKind() &&
1459 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460 New->setLocalOwningModule(Old->getOwningModule());
1461 makeMergedDefinitionVisible(New);
1462 return false;
1463 }
1464
1465 Module *NewM = New->getOwningModule();
1466 Module *OldM = Old->getOwningModule();
1467 if (NewM == OldM)
1468 return false;
1469
1470 // FIXME: Check proclaimed-ownership-declarations here too.
1471 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473 if (NewIsModuleInterface || OldIsModuleInterface) {
1474 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475 // if a declaration of D [...] appears in the purview of a module, all
1476 // other such declarations shall appear in the purview of the same module
1477 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478 << New
1479 << NewIsModuleInterface
1480 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481 << OldIsModuleInterface
1482 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483 Diag(Old->getLocation(), diag::note_previous_declaration);
1484 New->setInvalidDecl();
1485 return true;
1486 }
1487
1488 return false;
1489}
1490
1491static bool isUsingDecl(NamedDecl *D) {
1492 return isa<UsingShadowDecl>(D) ||
1493 isa<UnresolvedUsingTypenameDecl>(D) ||
1494 isa<UnresolvedUsingValueDecl>(D);
1495}
1496
1497/// Removes using shadow declarations from the lookup results.
1498static void RemoveUsingDecls(LookupResult &R) {
1499 LookupResult::Filter F = R.makeFilter();
1500 while (F.hasNext())
1501 if (isUsingDecl(F.next()))
1502 F.erase();
1503
1504 F.done();
1505}
1506
1507/// \brief Check for this common pattern:
1508/// @code
1509/// class S {
1510/// S(const S&); // DO NOT IMPLEMENT
1511/// void operator=(const S&); // DO NOT IMPLEMENT
1512/// };
1513/// @endcode
1514static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515 // FIXME: Should check for private access too but access is set after we get
1516 // the decl here.
1517 if (D->doesThisDeclarationHaveABody())
1518 return false;
1519
1520 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521 return CD->isCopyConstructor();
1522 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1523 return Method->isCopyAssignmentOperator();
1524 return false;
1525}
1526
1527// We need this to handle
1528//
1529// typedef struct {
1530// void *foo() { return 0; }
1531// } A;
1532//
1533// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1534// for example. If 'A', foo will have external linkage. If we have '*A',
1535// foo will have no linkage. Since we can't know until we get to the end
1536// of the typedef, this function finds out if D might have non-external linkage.
1537// Callers should verify at the end of the TU if it D has external linkage or
1538// not.
1539bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1540 const DeclContext *DC = D->getDeclContext();
1541 while (!DC->isTranslationUnit()) {
1542 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1543 if (!RD->hasNameForLinkage())
1544 return true;
1545 }
1546 DC = DC->getParent();
1547 }
1548
1549 return !D->isExternallyVisible();
1550}
1551
1552// FIXME: This needs to be refactored; some other isInMainFile users want
1553// these semantics.
1554static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1555 if (S.TUKind != TU_Complete)
1556 return false;
1557 return S.SourceMgr.isInMainFile(Loc);
1558}
1559
1560bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1561 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1561, __extension__ __PRETTY_FUNCTION__))
;
1562
1563 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1564 return false;
1565
1566 // Ignore all entities declared within templates, and out-of-line definitions
1567 // of members of class templates.
1568 if (D->getDeclContext()->isDependentContext() ||
1569 D->getLexicalDeclContext()->isDependentContext())
1570 return false;
1571
1572 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1573 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1574 return false;
1575 // A non-out-of-line declaration of a member specialization was implicitly
1576 // instantiated; it's the out-of-line declaration that we're interested in.
1577 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1578 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1579 return false;
1580
1581 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1582 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1583 return false;
1584 } else {
1585 // 'static inline' functions are defined in headers; don't warn.
1586 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1587 return false;
1588 }
1589
1590 if (FD->doesThisDeclarationHaveABody() &&
1591 Context.DeclMustBeEmitted(FD))
1592 return false;
1593 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594 // Constants and utility variables are defined in headers with internal
1595 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1596 // like "inline".)
1597 if (!isMainFileLoc(*this, VD->getLocation()))
1598 return false;
1599
1600 if (Context.DeclMustBeEmitted(VD))
1601 return false;
1602
1603 if (VD->isStaticDataMember() &&
1604 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1605 return false;
1606 if (VD->isStaticDataMember() &&
1607 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1608 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1609 return false;
1610
1611 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1612 return false;
1613 } else {
1614 return false;
1615 }
1616
1617 // Only warn for unused decls internal to the translation unit.
1618 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1619 // for inline functions defined in the main source file, for instance.
1620 return mightHaveNonExternalLinkage(D);
1621}
1622
1623void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1624 if (!D)
1625 return;
1626
1627 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1628 const FunctionDecl *First = FD->getFirstDecl();
1629 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630 return; // First should already be in the vector.
1631 }
1632
1633 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1634 const VarDecl *First = VD->getFirstDecl();
1635 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1636 return; // First should already be in the vector.
1637 }
1638
1639 if (ShouldWarnIfUnusedFileScopedDecl(D))
1640 UnusedFileScopedDecls.push_back(D);
1641}
1642
1643static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1644 if (D->isInvalidDecl())
1645 return false;
1646
1647 bool Referenced = false;
1648 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1649 // For a decomposition declaration, warn if none of the bindings are
1650 // referenced, instead of if the variable itself is referenced (which
1651 // it is, by the bindings' expressions).
1652 for (auto *BD : DD->bindings()) {
1653 if (BD->isReferenced()) {
1654 Referenced = true;
1655 break;
1656 }
1657 }
1658 } else if (!D->getDeclName()) {
1659 return false;
1660 } else if (D->isReferenced() || D->isUsed()) {
1661 Referenced = true;
1662 }
1663
1664 if (Referenced || D->hasAttr<UnusedAttr>() ||
1665 D->hasAttr<ObjCPreciseLifetimeAttr>())
1666 return false;
1667
1668 if (isa<LabelDecl>(D))
1669 return true;
1670
1671 // Except for labels, we only care about unused decls that are local to
1672 // functions.
1673 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1674 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1675 // For dependent types, the diagnostic is deferred.
1676 WithinFunction =
1677 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1678 if (!WithinFunction)
1679 return false;
1680
1681 if (isa<TypedefNameDecl>(D))
1682 return true;
1683
1684 // White-list anything that isn't a local variable.
1685 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1686 return false;
1687
1688 // Types of valid local variables should be complete, so this should succeed.
1689 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1690
1691 // White-list anything with an __attribute__((unused)) type.
1692 const auto *Ty = VD->getType().getTypePtr();
1693
1694 // Only look at the outermost level of typedef.
1695 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1696 if (TT->getDecl()->hasAttr<UnusedAttr>())
1697 return false;
1698 }
1699
1700 // If we failed to complete the type for some reason, or if the type is
1701 // dependent, don't diagnose the variable.
1702 if (Ty->isIncompleteType() || Ty->isDependentType())
1703 return false;
1704
1705 // Look at the element type to ensure that the warning behaviour is
1706 // consistent for both scalars and arrays.
1707 Ty = Ty->getBaseElementTypeUnsafe();
1708
1709 if (const TagType *TT = Ty->getAs<TagType>()) {
1710 const TagDecl *Tag = TT->getDecl();
1711 if (Tag->hasAttr<UnusedAttr>())
1712 return false;
1713
1714 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1715 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1716 return false;
1717
1718 if (const Expr *Init = VD->getInit()) {
1719 if (const ExprWithCleanups *Cleanups =
1720 dyn_cast<ExprWithCleanups>(Init))
1721 Init = Cleanups->getSubExpr();
1722 const CXXConstructExpr *Construct =
1723 dyn_cast<CXXConstructExpr>(Init);
1724 if (Construct && !Construct->isElidable()) {
1725 CXXConstructorDecl *CD = Construct->getConstructor();
1726 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1727 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1728 return false;
1729 }
1730 }
1731 }
1732 }
1733
1734 // TODO: __attribute__((unused)) templates?
1735 }
1736
1737 return true;
1738}
1739
1740static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1741 FixItHint &Hint) {
1742 if (isa<LabelDecl>(D)) {
1743 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1744 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1745 if (AfterColon.isInvalid())
1746 return;
1747 Hint = FixItHint::CreateRemoval(CharSourceRange::
1748 getCharRange(D->getLocStart(), AfterColon));
1749 }
1750}
1751
1752void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1753 if (D->getTypeForDecl()->isDependentType())
1754 return;
1755
1756 for (auto *TmpD : D->decls()) {
1757 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1758 DiagnoseUnusedDecl(T);
1759 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1760 DiagnoseUnusedNestedTypedefs(R);
1761 }
1762}
1763
1764/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1765/// unless they are marked attr(unused).
1766void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1767 if (!ShouldDiagnoseUnusedDecl(D))
1768 return;
1769
1770 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1771 // typedefs can be referenced later on, so the diagnostics are emitted
1772 // at end-of-translation-unit.
1773 UnusedLocalTypedefNameCandidates.insert(TD);
1774 return;
1775 }
1776
1777 FixItHint Hint;
1778 GenerateFixForUnusedDecl(D, Context, Hint);
1779
1780 unsigned DiagID;
1781 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1782 DiagID = diag::warn_unused_exception_param;
1783 else if (isa<LabelDecl>(D))
1784 DiagID = diag::warn_unused_label;
1785 else
1786 DiagID = diag::warn_unused_variable;
1787
1788 Diag(D->getLocation(), DiagID) << D << Hint;
1789}
1790
1791static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1792 // Verify that we have no forward references left. If so, there was a goto
1793 // or address of a label taken, but no definition of it. Label fwd
1794 // definitions are indicated with a null substmt which is also not a resolved
1795 // MS inline assembly label name.
1796 bool Diagnose = false;
1797 if (L->isMSAsmLabel())
1798 Diagnose = !L->isResolvedMSAsmLabel();
1799 else
1800 Diagnose = L->getStmt() == nullptr;
1801 if (Diagnose)
1802 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1803}
1804
1805void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1806 S->mergeNRVOIntoParent();
1807
1808 if (S->decl_empty()) return;
1809 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1810, __extension__ __PRETTY_FUNCTION__))
1810 "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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1810, __extension__ __PRETTY_FUNCTION__))
;
1811
1812 for (auto *TmpD : S->decls()) {
1813 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1813, __extension__ __PRETTY_FUNCTION__))
;
1814
1815 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1815, __extension__ __PRETTY_FUNCTION__))
;
1816 NamedDecl *D = cast<NamedDecl>(TmpD);
1817
1818 // Diagnose unused variables in this scope.
1819 if (!S->hasUnrecoverableErrorOccurred()) {
1820 DiagnoseUnusedDecl(D);
1821 if (const auto *RD = dyn_cast<RecordDecl>(D))
1822 DiagnoseUnusedNestedTypedefs(RD);
1823 }
1824
1825 if (!D->getDeclName()) continue;
1826
1827 // If this was a forward reference to a label, verify it was defined.
1828 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1829 CheckPoppedLabel(LD, *this);
1830
1831 // Remove this name from our lexical scope, and warn on it if we haven't
1832 // already.
1833 IdResolver.RemoveDecl(D);
1834 auto ShadowI = ShadowingDecls.find(D);
1835 if (ShadowI != ShadowingDecls.end()) {
1836 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1837 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1838 << D << FD << FD->getParent();
1839 Diag(FD->getLocation(), diag::note_previous_declaration);
1840 }
1841 ShadowingDecls.erase(ShadowI);
1842 }
1843 }
1844}
1845
1846/// \brief Look for an Objective-C class in the translation unit.
1847///
1848/// \param Id The name of the Objective-C class we're looking for. If
1849/// typo-correction fixes this name, the Id will be updated
1850/// to the fixed name.
1851///
1852/// \param IdLoc The location of the name in the translation unit.
1853///
1854/// \param DoTypoCorrection If true, this routine will attempt typo correction
1855/// if there is no class with the given name.
1856///
1857/// \returns The declaration of the named Objective-C class, or NULL if the
1858/// class could not be found.
1859ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1860 SourceLocation IdLoc,
1861 bool DoTypoCorrection) {
1862 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1863 // creation from this context.
1864 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1865
1866 if (!IDecl && DoTypoCorrection) {
1867 // Perform typo correction at the given location, but only if we
1868 // find an Objective-C class name.
1869 if (TypoCorrection C = CorrectTypo(
1870 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1871 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1872 CTK_ErrorRecovery)) {
1873 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1874 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1875 Id = IDecl->getIdentifier();
1876 }
1877 }
1878 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1879 // This routine must always return a class definition, if any.
1880 if (Def && Def->getDefinition())
1881 Def = Def->getDefinition();
1882 return Def;
1883}
1884
1885/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1886/// from S, where a non-field would be declared. This routine copes
1887/// with the difference between C and C++ scoping rules in structs and
1888/// unions. For example, the following code is well-formed in C but
1889/// ill-formed in C++:
1890/// @code
1891/// struct S6 {
1892/// enum { BAR } e;
1893/// };
1894///
1895/// void test_S6() {
1896/// struct S6 a;
1897/// a.e = BAR;
1898/// }
1899/// @endcode
1900/// For the declaration of BAR, this routine will return a different
1901/// scope. The scope S will be the scope of the unnamed enumeration
1902/// within S6. In C++, this routine will return the scope associated
1903/// with S6, because the enumeration's scope is a transparent
1904/// context but structures can contain non-field names. In C, this
1905/// routine will return the translation unit scope, since the
1906/// enumeration's scope is a transparent context and structures cannot
1907/// contain non-field names.
1908Scope *Sema::getNonFieldDeclScope(Scope *S) {
1909 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1910 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1911 (S->isClassScope() && !getLangOpts().CPlusPlus))
1912 S = S->getParent();
1913 return S;
1914}
1915
1916/// \brief Looks up the declaration of "struct objc_super" and
1917/// saves it for later use in building builtin declaration of
1918/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1919/// pre-existing declaration exists no action takes place.
1920static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1921 IdentifierInfo *II) {
1922 if (!II->isStr("objc_msgSendSuper"))
1923 return;
1924 ASTContext &Context = ThisSema.Context;
1925
1926 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1927 SourceLocation(), Sema::LookupTagName);
1928 ThisSema.LookupName(Result, S);
1929 if (Result.getResultKind() == LookupResult::Found)
1930 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1931 Context.setObjCSuperType(Context.getTagDeclType(TD));
1932}
1933
1934static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1935 switch (Error) {
1936 case ASTContext::GE_None:
1937 return "";
1938 case ASTContext::GE_Missing_stdio:
1939 return "stdio.h";
1940 case ASTContext::GE_Missing_setjmp:
1941 return "setjmp.h";
1942 case ASTContext::GE_Missing_ucontext:
1943 return "ucontext.h";
1944 }
1945 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 1945)
;
1946}
1947
1948/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1949/// file scope. lazily create a decl for it. ForRedeclaration is true
1950/// if we're creating this built-in in anticipation of redeclaring the
1951/// built-in.
1952NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1953 Scope *S, bool ForRedeclaration,
1954 SourceLocation Loc) {
1955 LookupPredefedObjCSuperType(*this, S, II);
1956
1957 ASTContext::GetBuiltinTypeError Error;
1958 QualType R = Context.GetBuiltinType(ID, Error);
1959 if (Error) {
1960 if (ForRedeclaration)
1961 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1962 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1963 return nullptr;
1964 }
1965
1966 if (!ForRedeclaration &&
1967 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1968 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1969 Diag(Loc, diag::ext_implicit_lib_function_decl)
1970 << Context.BuiltinInfo.getName(ID) << R;
1971 if (Context.BuiltinInfo.getHeaderName(ID) &&
1972 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1973 Diag(Loc, diag::note_include_header_or_declare)
1974 << Context.BuiltinInfo.getHeaderName(ID)
1975 << Context.BuiltinInfo.getName(ID);
1976 }
1977
1978 if (R.isNull())
1979 return nullptr;
1980
1981 DeclContext *Parent = Context.getTranslationUnitDecl();
1982 if (getLangOpts().CPlusPlus) {
1983 LinkageSpecDecl *CLinkageDecl =
1984 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1985 LinkageSpecDecl::lang_c, false);
1986 CLinkageDecl->setImplicit();
1987 Parent->addDecl(CLinkageDecl);
1988 Parent = CLinkageDecl;
1989 }
1990
1991 FunctionDecl *New = FunctionDecl::Create(Context,
1992 Parent,
1993 Loc, Loc, II, R, /*TInfo=*/nullptr,
1994 SC_Extern,
1995 false,
1996 R->isFunctionProtoType());
1997 New->setImplicit();
1998
1999 // Create Decl objects for each parameter, adding them to the
2000 // FunctionDecl.
2001 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2002 SmallVector<ParmVarDecl*, 16> Params;
2003 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2004 ParmVarDecl *parm =
2005 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2006 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2007 SC_None, nullptr);
2008 parm->setScopeInfo(0, i);
2009 Params.push_back(parm);
2010 }
2011 New->setParams(Params);
2012 }
2013
2014 AddKnownFunctionAttributes(New);
2015 RegisterLocallyScopedExternCDecl(New, S);
2016
2017 // TUScope is the translation-unit scope to insert this function into.
2018 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2019 // relate Scopes to DeclContexts, and probably eliminate CurContext
2020 // entirely, but we're not there yet.
2021 DeclContext *SavedContext = CurContext;
2022 CurContext = Parent;
2023 PushOnScopeChains(New, TUScope);
2024 CurContext = SavedContext;
2025 return New;
2026}
2027
2028/// Typedef declarations don't have linkage, but they still denote the same
2029/// entity if their types are the same.
2030/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2031/// isSameEntity.
2032static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2033 TypedefNameDecl *Decl,
2034 LookupResult &Previous) {
2035 // This is only interesting when modules are enabled.
2036 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2037 return;
2038
2039 // Empty sets are uninteresting.
2040 if (Previous.empty())
2041 return;
2042
2043 LookupResult::Filter Filter = Previous.makeFilter();
2044 while (Filter.hasNext()) {
2045 NamedDecl *Old = Filter.next();
2046
2047 // Non-hidden declarations are never ignored.
2048 if (S.isVisible(Old))
2049 continue;
2050
2051 // Declarations of the same entity are not ignored, even if they have
2052 // different linkages.
2053 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2054 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2055 Decl->getUnderlyingType()))
2056 continue;
2057
2058 // If both declarations give a tag declaration a typedef name for linkage
2059 // purposes, then they declare the same entity.
2060 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2061 Decl->getAnonDeclWithTypedefName())
2062 continue;
2063 }
2064
2065 Filter.erase();
2066 }
2067
2068 Filter.done();
2069}
2070
2071bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2072 QualType OldType;
2073 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2074 OldType = OldTypedef->getUnderlyingType();
2075 else
2076 OldType = Context.getTypeDeclType(Old);
2077 QualType NewType = New->getUnderlyingType();
2078
2079 if (NewType->isVariablyModifiedType()) {
2080 // Must not redefine a typedef with a variably-modified type.
2081 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2082 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2083 << Kind << NewType;
2084 if (Old->getLocation().isValid())
2085 notePreviousDefinition(Old, New->getLocation());
2086 New->setInvalidDecl();
2087 return true;
2088 }
2089
2090 if (OldType != NewType &&
2091 !OldType->isDependentType() &&
2092 !NewType->isDependentType() &&
2093 !Context.hasSameType(OldType, NewType)) {
2094 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2095 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2096 << Kind << NewType << OldType;
2097 if (Old->getLocation().isValid())
2098 notePreviousDefinition(Old, New->getLocation());
2099 New->setInvalidDecl();
2100 return true;
2101 }
2102 return false;
2103}
2104
2105/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2106/// same name and scope as a previous declaration 'Old'. Figure out
2107/// how to resolve this situation, merging decls or emitting
2108/// diagnostics as appropriate. If there was an error, set New to be invalid.
2109///
2110void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2111 LookupResult &OldDecls) {
2112 // If the new decl is known invalid already, don't bother doing any
2113 // merging checks.
2114 if (New->isInvalidDecl()) return;
2115
2116 // Allow multiple definitions for ObjC built-in typedefs.
2117 // FIXME: Verify the underlying types are equivalent!
2118 if (getLangOpts().ObjC1) {
2119 const IdentifierInfo *TypeID = New->getIdentifier();
2120 switch (TypeID->getLength()) {
2121 default: break;
2122 case 2:
2123 {
2124 if (!TypeID->isStr("id"))
2125 break;
2126 QualType T = New->getUnderlyingType();
2127 if (!T->isPointerType())
2128 break;
2129 if (!T->isVoidPointerType()) {
2130 QualType PT = T->getAs<PointerType>()->getPointeeType();
2131 if (!PT->isStructureType())
2132 break;
2133 }
2134 Context.setObjCIdRedefinitionType(T);
2135 // Install the built-in type for 'id', ignoring the current definition.
2136 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2137 return;
2138 }
2139 case 5:
2140 if (!TypeID->isStr("Class"))
2141 break;
2142 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2143 // Install the built-in type for 'Class', ignoring the current definition.
2144 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2145 return;
2146 case 3:
2147 if (!TypeID->isStr("SEL"))
2148 break;
2149 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2150 // Install the built-in type for 'SEL', ignoring the current definition.
2151 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2152 return;
2153 }
2154 // Fall through - the typedef name was not a builtin type.
2155 }
2156
2157 // Verify the old decl was also a type.
2158 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2159 if (!Old) {
2160 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2161 << New->getDeclName();
2162
2163 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2164 if (OldD->getLocation().isValid())
2165 notePreviousDefinition(OldD, New->getLocation());
2166
2167 return New->setInvalidDecl();
2168 }
2169
2170 // If the old declaration is invalid, just give up here.
2171 if (Old->isInvalidDecl())
2172 return New->setInvalidDecl();
2173
2174 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2175 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2176 auto *NewTag = New->getAnonDeclWithTypedefName();
2177 NamedDecl *Hidden = nullptr;
2178 if (OldTag && NewTag &&
2179 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2180 !hasVisibleDefinition(OldTag, &Hidden)) {
2181 // There is a definition of this tag, but it is not visible. Use it
2182 // instead of our tag.
2183 New->setTypeForDecl(OldTD->getTypeForDecl());
2184 if (OldTD->isModed())
2185 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2186 OldTD->getUnderlyingType());
2187 else
2188 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2189
2190 // Make the old tag definition visible.
2191 makeMergedDefinitionVisible(Hidden);
2192
2193 // If this was an unscoped enumeration, yank all of its enumerators
2194 // out of the scope.
2195 if (isa<EnumDecl>(NewTag)) {
2196 Scope *EnumScope = getNonFieldDeclScope(S);
2197 for (auto *D : NewTag->decls()) {
2198 auto *ED = cast<EnumConstantDecl>(D);
2199 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 2199, __extension__ __PRETTY_FUNCTION__))
;
2200 EnumScope->RemoveDecl(ED);
2201 IdResolver.RemoveDecl(ED);
2202 ED->getLexicalDeclContext()->removeDecl(ED);
2203 }
2204 }
2205 }
2206 }
2207
2208 // If the typedef types are not identical, reject them in all languages and
2209 // with any extensions enabled.
2210 if (isIncompatibleTypedef(Old, New))
2211 return;
2212
2213 // The types match. Link up the redeclaration chain and merge attributes if
2214 // the old declaration was a typedef.
2215 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2216 New->setPreviousDecl(Typedef);
2217 mergeDeclAttributes(New, Old);
2218 }
2219
2220 if (getLangOpts().MicrosoftExt)
2221 return;
2222
2223 if (getLangOpts().CPlusPlus) {
2224 // C++ [dcl.typedef]p2:
2225 // In a given non-class scope, a typedef specifier can be used to
2226 // redefine the name of any type declared in that scope to refer
2227 // to the type to which it already refers.
2228 if (!isa<CXXRecordDecl>(CurContext))
2229 return;
2230
2231 // C++0x [dcl.typedef]p4:
2232 // In a given class scope, a typedef specifier can be used to redefine
2233 // any class-name declared in that scope that is not also a typedef-name
2234 // to refer to the type to which it already refers.
2235 //
2236 // This wording came in via DR424, which was a correction to the
2237 // wording in DR56, which accidentally banned code like:
2238 //
2239 // struct S {
2240 // typedef struct A { } A;
2241 // };
2242 //
2243 // in the C++03 standard. We implement the C++0x semantics, which
2244 // allow the above but disallow
2245 //
2246 // struct S {
2247 // typedef int I;
2248 // typedef int I;
2249 // };
2250 //
2251 // since that was the intent of DR56.
2252 if (!isa<TypedefNameDecl>(Old))
2253 return;
2254
2255 Diag(New->getLocation(), diag::err_redefinition)
2256 << New->getDeclName();
2257 notePreviousDefinition(Old, New->getLocation());
2258 return New->setInvalidDecl();
2259 }
2260
2261 // Modules always permit redefinition of typedefs, as does C11.
2262 if (getLangOpts().Modules || getLangOpts().C11)
2263 return;
2264
2265 // If we have a redefinition of a typedef in C, emit a warning. This warning
2266 // is normally mapped to an error, but can be controlled with
2267 // -Wtypedef-redefinition. If either the original or the redefinition is
2268 // in a system header, don't emit this for compatibility with GCC.
2269 if (getDiagnostics().getSuppressSystemWarnings() &&
2270 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2271 (Old->isImplicit() ||
2272 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2273 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2274 return;
2275
2276 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2277 << New->getDeclName();
2278 notePreviousDefinition(Old, New->getLocation());
2279}
2280
2281/// DeclhasAttr - returns true if decl Declaration already has the target
2282/// attribute.
2283static bool DeclHasAttr(const Decl *D, const Attr *A) {
2284 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2285 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2286 for (const auto *i : D->attrs())
2287 if (i->getKind() == A->getKind()) {
2288 if (Ann) {
2289 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2290 return true;
2291 continue;
2292 }
2293 // FIXME: Don't hardcode this check
2294 if (OA && isa<OwnershipAttr>(i))
2295 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2296 return true;
2297 }
2298
2299 return false;
2300}
2301
2302static bool isAttributeTargetADefinition(Decl *D) {
2303 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2304 return VD->isThisDeclarationADefinition();
2305 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2306 return TD->isCompleteDefinition() || TD->isBeingDefined();
2307 return true;
2308}
2309
2310/// Merge alignment attributes from \p Old to \p New, taking into account the
2311/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2312///
2313/// \return \c true if any attributes were added to \p New.
2314static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2315 // Look for alignas attributes on Old, and pick out whichever attribute
2316 // specifies the strictest alignment requirement.
2317 AlignedAttr *OldAlignasAttr = nullptr;
2318 AlignedAttr *OldStrictestAlignAttr = nullptr;
2319 unsigned OldAlign = 0;
2320 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2321 // FIXME: We have no way of representing inherited dependent alignments
2322 // in a case like:
2323 // template<int A, int B> struct alignas(A) X;
2324 // template<int A, int B> struct alignas(B) X {};
2325 // For now, we just ignore any alignas attributes which are not on the
2326 // definition in such a case.
2327 if (I->isAlignmentDependent())
2328 return false;
2329
2330 if (I->isAlignas())
2331 OldAlignasAttr = I;
2332
2333 unsigned Align = I->getAlignment(S.Context);
2334 if (Align > OldAlign) {
2335 OldAlign = Align;
2336 OldStrictestAlignAttr = I;
2337 }
2338 }
2339
2340 // Look for alignas attributes on New.
2341 AlignedAttr *NewAlignasAttr = nullptr;
2342 unsigned NewAlign = 0;
2343 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2344 if (I->isAlignmentDependent())
2345 return false;
2346
2347 if (I->isAlignas())
2348 NewAlignasAttr = I;
2349
2350 unsigned Align = I->getAlignment(S.Context);
2351 if (Align > NewAlign)
2352 NewAlign = Align;
2353 }
2354
2355 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2356 // Both declarations have 'alignas' attributes. We require them to match.
2357 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2358 // fall short. (If two declarations both have alignas, they must both match
2359 // every definition, and so must match each other if there is a definition.)
2360
2361 // If either declaration only contains 'alignas(0)' specifiers, then it
2362 // specifies the natural alignment for the type.
2363 if (OldAlign == 0 || NewAlign == 0) {
2364 QualType Ty;
2365 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2366 Ty = VD->getType();
2367 else
2368 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2369
2370 if (OldAlign == 0)
2371 OldAlign = S.Context.getTypeAlign(Ty);
2372 if (NewAlign == 0)
2373 NewAlign = S.Context.getTypeAlign(Ty);
2374 }
2375
2376 if (OldAlign != NewAlign) {
2377 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2378 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2379 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2380 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2381 }
2382 }
2383
2384 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2385 // C++11 [dcl.align]p6:
2386 // if any declaration of an entity has an alignment-specifier,
2387 // every defining declaration of that entity shall specify an
2388 // equivalent alignment.
2389 // C11 6.7.5/7:
2390 // If the definition of an object does not have an alignment
2391 // specifier, any other declaration of that object shall also
2392 // have no alignment specifier.
2393 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2394 << OldAlignasAttr;
2395 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2396 << OldAlignasAttr;
2397 }
2398
2399 bool AnyAdded = false;
2400
2401 // Ensure we have an attribute representing the strictest alignment.
2402 if (OldAlign > NewAlign) {
2403 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2404 Clone->setInherited(true);
2405 New->addAttr(Clone);
2406 AnyAdded = true;
2407 }
2408
2409 // Ensure we have an alignas attribute if the old declaration had one.
2410 if (OldAlignasAttr && !NewAlignasAttr &&
2411 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2412 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2413 Clone->setInherited(true);
2414 New->addAttr(Clone);
2415 AnyAdded = true;
2416 }
2417
2418 return AnyAdded;
2419}
2420
2421static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2422 const InheritableAttr *Attr,
2423 Sema::AvailabilityMergeKind AMK) {
2424 // This function copies an attribute Attr from a previous declaration to the
2425 // new declaration D if the new declaration doesn't itself have that attribute
2426 // yet or if that attribute allows duplicates.
2427 // If you're adding a new attribute that requires logic different from
2428 // "use explicit attribute on decl if present, else use attribute from
2429 // previous decl", for example if the attribute needs to be consistent
2430 // between redeclarations, you need to call a custom merge function here.
2431 InheritableAttr *NewAttr = nullptr;
2432 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2433 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2434 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2435 AA->isImplicit(), AA->getIntroduced(),
2436 AA->getDeprecated(),
2437 AA->getObsoleted(), AA->getUnavailable(),
2438 AA->getMessage(), AA->getStrict(),
2439 AA->getReplacement(), AMK,
2440 AttrSpellingListIndex);
2441 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2442 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2443 AttrSpellingListIndex);
2444 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2445 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2446 AttrSpellingListIndex);
2447 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2448 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2449 AttrSpellingListIndex);
2450 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2451 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2452 AttrSpellingListIndex);
2453 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2454 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2455 FA->getFormatIdx(), FA->getFirstArg(),
2456 AttrSpellingListIndex);
2457 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2458 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2459 AttrSpellingListIndex);
2460 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2461 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2462 AttrSpellingListIndex,
2463 IA->getSemanticSpelling());
2464 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2465 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2466 &S.Context.Idents.get(AA->getSpelling()),
2467 AttrSpellingListIndex);
2468 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2469 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2470 isa<CUDAGlobalAttr>(Attr))) {
2471 // CUDA target attributes are part of function signature for
2472 // overloading purposes and must not be merged.
2473 return false;
2474 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2475 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2476 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2477 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2478 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2479 NewAttr = S.mergeInternalLinkageAttr(
2480 D, InternalLinkageA->getRange(),
2481 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2482 AttrSpellingListIndex);
2483 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2484 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2485 &S.Context.Idents.get(CommonA->getSpelling()),
2486 AttrSpellingListIndex);
2487 else if (isa<AlignedAttr>(Attr))
2488 // AlignedAttrs are handled separately, because we need to handle all
2489 // such attributes on a declaration at the same time.
2490 NewAttr = nullptr;
2491 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2492 (AMK == Sema::AMK_Override ||
2493 AMK == Sema::AMK_ProtocolImplementation))
2494 NewAttr = nullptr;
2495 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2496 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2497 UA->getGuid());
2498 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2499 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2500
2501 if (NewAttr) {
2502 NewAttr->setInherited(true);
2503 D->addAttr(NewAttr);
2504 if (isa<MSInheritanceAttr>(NewAttr))
2505 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2506 return true;
2507 }
2508
2509 return false;
2510}
2511
2512static const NamedDecl *getDefinition(const Decl *D) {
2513 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2514 return TD->getDefinition();
2515 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2516 const VarDecl *Def = VD->getDefinition();
2517 if (Def)
2518 return Def;
2519 return VD->getActingDefinition();
2520 }
2521 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2522 return FD->getDefinition();
2523 return nullptr;
2524}
2525
2526static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2527 for (const auto *Attribute : D->attrs())
2528 if (Attribute->getKind() == Kind)
2529 return true;
2530 return false;
2531}
2532
2533/// checkNewAttributesAfterDef - If we already have a definition, check that
2534/// there are no new attributes in this declaration.
2535static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2536 if (!New->hasAttrs())
2537 return;
2538
2539 const NamedDecl *Def = getDefinition(Old);
2540 if (!Def || Def == New)
2541 return;
2542
2543 AttrVec &NewAttributes = New->getAttrs();
2544 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2545 const Attr *NewAttribute = NewAttributes[I];
2546
2547 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2549 Sema::SkipBodyInfo SkipBody;
2550 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2551
2552 // If we're skipping this definition, drop the "alias" attribute.
2553 if (SkipBody.ShouldSkip) {
2554 NewAttributes.erase(NewAttributes.begin() + I);
2555 --E;
2556 continue;
2557 }
2558 } else {
2559 VarDecl *VD = cast<VarDecl>(New);
2560 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2561 VarDecl::TentativeDefinition
2562 ? diag::err_alias_after_tentative
2563 : diag::err_redefinition;
2564 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2565 if (Diag == diag::err_redefinition)
2566 S.notePreviousDefinition(Def, VD->getLocation());
2567 else
2568 S.Diag(Def->getLocation(), diag::note_previous_definition);
2569 VD->setInvalidDecl();
2570 }
2571 ++I;
2572 continue;
2573 }
2574
2575 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2576 // Tentative definitions are only interesting for the alias check above.
2577 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2578 ++I;
2579 continue;
2580 }
2581 }
2582
2583 if (hasAttribute(Def, NewAttribute->getKind())) {
2584 ++I;
2585 continue; // regular attr merging will take care of validating this.
2586 }
2587
2588 if (isa<C11NoReturnAttr>(NewAttribute)) {
2589 // C's _Noreturn is allowed to be added to a function after it is defined.
2590 ++I;
2591 continue;
2592 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2593 if (AA->isAlignas()) {
2594 // C++11 [dcl.align]p6:
2595 // if any declaration of an entity has an alignment-specifier,
2596 // every defining declaration of that entity shall specify an
2597 // equivalent alignment.
2598 // C11 6.7.5/7:
2599 // If the definition of an object does not have an alignment
2600 // specifier, any other declaration of that object shall also
2601 // have no alignment specifier.
2602 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2603 << AA;
2604 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2605 << AA;
2606 NewAttributes.erase(NewAttributes.begin() + I);
2607 --E;
2608 continue;
2609 }
2610 }
2611
2612 S.Diag(NewAttribute->getLocation(),
2613 diag::warn_attribute_precede_definition);
2614 S.Diag(Def->getLocation(), diag::note_previous_definition);
2615 NewAttributes.erase(NewAttributes.begin() + I);
2616 --E;
2617 }
2618}
2619
2620/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2621void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2622 AvailabilityMergeKind AMK) {
2623 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2624 UsedAttr *NewAttr = OldAttr->clone(Context);
2625 NewAttr->setInherited(true);
2626 New->addAttr(NewAttr);
2627 }
2628
2629 if (!Old->hasAttrs() && !New->hasAttrs())
2630 return;
2631
2632 // Attributes declared post-definition are currently ignored.
2633 checkNewAttributesAfterDef(*this, New, Old);
2634
2635 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2636 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2637 if (OldA->getLabel() != NewA->getLabel()) {
2638 // This redeclaration changes __asm__ label.
2639 Diag(New->getLocation(), diag::err_different_asm_label);
2640 Diag(OldA->getLocation(), diag::note_previous_declaration);
2641 }
2642 } else if (Old->isUsed()) {
2643 // This redeclaration adds an __asm__ label to a declaration that has
2644 // already been ODR-used.
2645 Diag(New->getLocation(), diag::err_late_asm_label_name)
2646 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2647 }
2648 }
2649
2650 // Re-declaration cannot add abi_tag's.
2651 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2652 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2653 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2654 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2655 NewTag) == OldAbiTagAttr->tags_end()) {
2656 Diag(NewAbiTagAttr->getLocation(),
2657 diag::err_new_abi_tag_on_redeclaration)
2658 << NewTag;
2659 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2660 }
2661 }
2662 } else {
2663 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2664 Diag(Old->getLocation(), diag::note_previous_declaration);
2665 }
2666 }
2667
2668 // This redeclaration adds a section attribute.
2669 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2670 if (auto *VD = dyn_cast<VarDecl>(New)) {
2671 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2672 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2673 Diag(Old->getLocation(), diag::note_previous_declaration);
2674 }
2675 }
2676 }
2677
2678 if (!Old->hasAttrs())
2679 return;
2680
2681 bool foundAny = New->hasAttrs();
2682
2683 // Ensure that any moving of objects within the allocated map is done before
2684 // we process them.
2685 if (!foundAny) New->setAttrs(AttrVec());
2686
2687 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2688 // Ignore deprecated/unavailable/availability attributes if requested.
2689 AvailabilityMergeKind LocalAMK = AMK_None;
2690 if (isa<DeprecatedAttr>(I) ||
2691 isa<UnavailableAttr>(I) ||
2692 isa<AvailabilityAttr>(I)) {
2693 switch (AMK) {
2694 case AMK_None:
2695 continue;
2696
2697 case AMK_Redeclaration:
2698 case AMK_Override:
2699 case AMK_ProtocolImplementation:
2700 LocalAMK = AMK;
2701 break;
2702 }
2703 }
2704
2705 // Already handled.
2706 if (isa<UsedAttr>(I))
2707 continue;
2708
2709 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2710 foundAny = true;
2711 }
2712
2713 if (mergeAlignedAttrs(*this, New, Old))
2714 foundAny = true;
2715
2716 if (!foundAny) New->dropAttrs();
2717}
2718
2719/// mergeParamDeclAttributes - Copy attributes from the old parameter
2720/// to the new one.
2721static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2722 const ParmVarDecl *oldDecl,
2723 Sema &S) {
2724 // C++11 [dcl.attr.depend]p2:
2725 // The first declaration of a function shall specify the
2726 // carries_dependency attribute for its declarator-id if any declaration
2727 // of the function specifies the carries_dependency attribute.
2728 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2729 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2730 S.Diag(CDA->getLocation(),
2731 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2732 // Find the first declaration of the parameter.
2733 // FIXME: Should we build redeclaration chains for function parameters?
2734 const FunctionDecl *FirstFD =
2735 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2736 const ParmVarDecl *FirstVD =
2737 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2738 S.Diag(FirstVD->getLocation(),
2739 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2740 }
2741
2742 if (!oldDecl->hasAttrs())
2743 return;
2744
2745 bool foundAny = newDecl->hasAttrs();
2746
2747 // Ensure that any moving of objects within the allocated map is
2748 // done before we process them.
2749 if (!foundAny) newDecl->setAttrs(AttrVec());
2750
2751 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2752 if (!DeclHasAttr(newDecl, I)) {
2753 InheritableAttr *newAttr =
2754 cast<InheritableParamAttr>(I->clone(S.Context));
2755 newAttr->setInherited(true);
2756 newDecl->addAttr(newAttr);
2757 foundAny = true;
2758 }
2759 }
2760
2761 if (!foundAny) newDecl->dropAttrs();
2762}
2763
2764static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2765 const ParmVarDecl *OldParam,
2766 Sema &S) {
2767 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2768 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2769 if (*Oldnullability != *Newnullability) {
2770 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2771 << DiagNullabilityKind(
2772 *Newnullability,
2773 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2774 != 0))
2775 << DiagNullabilityKind(
2776 *Oldnullability,
2777 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2778 != 0));
2779 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2780 }
2781 } else {
2782 QualType NewT = NewParam->getType();
2783 NewT = S.Context.getAttributedType(
2784 AttributedType::getNullabilityAttrKind(*Oldnullability),
2785 NewT, NewT);
2786 NewParam->setType(NewT);
2787 }
2788 }
2789}
2790
2791namespace {
2792
2793/// Used in MergeFunctionDecl to keep track of function parameters in
2794/// C.
2795struct GNUCompatibleParamWarning {
2796 ParmVarDecl *OldParm;
2797 ParmVarDecl *NewParm;
2798 QualType PromotedType;
2799};
2800
2801} // end anonymous namespace
2802
2803/// getSpecialMember - get the special member enum for a method.
2804Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2805 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2806 if (Ctor->isDefaultConstructor())
2807 return Sema::CXXDefaultConstructor;
2808
2809 if (Ctor->isCopyConstructor())
2810 return Sema::CXXCopyConstructor;
2811
2812 if (Ctor->isMoveConstructor())
2813 return Sema::CXXMoveConstructor;
2814 } else if (isa<CXXDestructorDecl>(MD)) {
2815 return Sema::CXXDestructor;
2816 } else if (MD->isCopyAssignmentOperator()) {
2817 return Sema::CXXCopyAssignment;
2818 } else if (MD->isMoveAssignmentOperator()) {
2819 return Sema::CXXMoveAssignment;
2820 }
2821
2822 return Sema::CXXInvalid;
2823}
2824
2825// Determine whether the previous declaration was a definition, implicit
2826// declaration, or a declaration.
2827template <typename T>
2828static std::pair<diag::kind, SourceLocation>
2829getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2830 diag::kind PrevDiag;
2831 SourceLocation OldLocation = Old->getLocation();
2832 if (Old->isThisDeclarationADefinition())
2833 PrevDiag = diag::note_previous_definition;
2834 else if (Old->isImplicit()) {
2835 PrevDiag = diag::note_previous_implicit_declaration;
2836 if (OldLocation.isInvalid())
2837 OldLocation = New->getLocation();
2838 } else
2839 PrevDiag = diag::note_previous_declaration;
2840 return std::make_pair(PrevDiag, OldLocation);
2841}
2842
2843/// canRedefineFunction - checks if a function can be redefined. Currently,
2844/// only extern inline functions can be redefined, and even then only in
2845/// GNU89 mode.
2846static bool canRedefineFunction(const FunctionDecl *FD,
2847 const LangOptions& LangOpts) {
2848 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2849 !LangOpts.CPlusPlus &&
2850 FD->isInlineSpecified() &&
2851 FD->getStorageClass() == SC_Extern);
2852}
2853
2854const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2855 const AttributedType *AT = T->getAs<AttributedType>();
2856 while (AT && !AT->isCallingConv())
2857 AT = AT->getModifiedType()->getAs<AttributedType>();
2858 return AT;
2859}
2860
2861template <typename T>
2862static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2863 const DeclContext *DC = Old->getDeclContext();
2864 if (DC->isRecord())
2865 return false;
2866
2867 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2868 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2869 return true;
2870 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2871 return true;
2872 return false;
2873}
2874
2875template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2876static bool isExternC(VarTemplateDecl *) { return false; }
2877
2878/// \brief Check whether a redeclaration of an entity introduced by a
2879/// using-declaration is valid, given that we know it's not an overload
2880/// (nor a hidden tag declaration).
2881template<typename ExpectedDecl>
2882static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2883 ExpectedDecl *New) {
2884 // C++11 [basic.scope.declarative]p4:
2885 // Given a set of declarations in a single declarative region, each of
2886 // which specifies the same unqualified name,
2887 // -- they shall all refer to the same entity, or all refer to functions
2888 // and function templates; or
2889 // -- exactly one declaration shall declare a class name or enumeration
2890 // name that is not a typedef name and the other declarations shall all
2891 // refer to the same variable or enumerator, or all refer to functions
2892 // and function templates; in this case the class name or enumeration
2893 // name is hidden (3.3.10).
2894
2895 // C++11 [namespace.udecl]p14:
2896 // If a function declaration in namespace scope or block scope has the
2897 // same name and the same parameter-type-list as a function introduced
2898 // by a using-declaration, and the declarations do not declare the same
2899 // function, the program is ill-formed.
2900
2901 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2902 if (Old &&
2903 !Old->getDeclContext()->getRedeclContext()->Equals(
2904 New->getDeclContext()->getRedeclContext()) &&
2905 !(isExternC(Old) && isExternC(New)))
2906 Old = nullptr;
2907
2908 if (!Old) {
2909 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2910 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2911 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2912 return true;
2913 }
2914 return false;
2915}
2916
2917static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2918 const FunctionDecl *B) {
2919 assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams
()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 2919, __extension__ __PRETTY_FUNCTION__))
;
2920
2921 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2922 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2923 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2924 if (AttrA == AttrB)
2925 return true;
2926 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2927 };
2928
2929 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2930}
2931
2932/// MergeFunctionDecl - We just parsed a function 'New' from
2933/// declarator D which has the same name and scope as a previous
2934/// declaration 'Old'. Figure out how to resolve this situation,
2935/// merging decls or emitting diagnostics as appropriate.
2936///
2937/// In C++, New and Old must be declarations that are not
2938/// overloaded. Use IsOverload to determine whether New and Old are
2939/// overloaded, and to select the Old declaration that New should be
2940/// merged with.
2941///
2942/// Returns true if there was an error, false otherwise.
2943bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2944 Scope *S, bool MergeTypeWithOld) {
2945 // Verify the old decl was also a function.
2946 FunctionDecl *Old = OldD->getAsFunction();
2947 if (!Old) {
2948 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2949 if (New->getFriendObjectKind()) {
2950 Diag(New->getLocation(), diag::err_using_decl_friend);
2951 Diag(Shadow->getTargetDecl()->getLocation(),
2952 diag::note_using_decl_target);
2953 Diag(Shadow->getUsingDecl()->getLocation(),
2954 diag::note_using_decl) << 0;
2955 return true;
2956 }
2957
2958 // Check whether the two declarations might declare the same function.
2959 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2960 return true;
2961 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2962 } else {
2963 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2964 << New->getDeclName();
2965 notePreviousDefinition(OldD, New->getLocation());
2966 return true;
2967 }
2968 }
2969
2970 // If the old declaration is invalid, just give up here.
2971 if (Old->isInvalidDecl())
2972 return true;
2973
2974 diag::kind PrevDiag;
2975 SourceLocation OldLocation;
2976 std::tie(PrevDiag, OldLocation) =
2977 getNoteDiagForInvalidRedeclaration(Old, New);
2978
2979 // Don't complain about this if we're in GNU89 mode and the old function
2980 // is an extern inline function.
2981 // Don't complain about specializations. They are not supposed to have
2982 // storage classes.
2983 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2984 New->getStorageClass() == SC_Static &&
2985 Old->hasExternalFormalLinkage() &&
2986 !New->getTemplateSpecializationInfo() &&
2987 !canRedefineFunction(Old, getLangOpts())) {
2988 if (getLangOpts().MicrosoftExt) {
2989 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2990 Diag(OldLocation, PrevDiag);
2991 } else {
2992 Diag(New->getLocation(), diag::err_static_non_static) << New;
2993 Diag(OldLocation, PrevDiag);
2994 return true;
2995 }
2996 }
2997
2998 if (New->hasAttr<InternalLinkageAttr>() &&
2999 !Old->hasAttr<InternalLinkageAttr>()) {
3000 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3001 << New->getDeclName();
3002 notePreviousDefinition(Old, New->getLocation());
3003 New->dropAttr<InternalLinkageAttr>();
3004 }
3005
3006 if (CheckRedeclarationModuleOwnership(New, Old))
3007 return true;
3008
3009 if (!getLangOpts().CPlusPlus) {
3010 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3011 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3012 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3013 << New << OldOvl;
3014
3015 // Try our best to find a decl that actually has the overloadable
3016 // attribute for the note. In most cases (e.g. programs with only one
3017 // broken declaration/definition), this won't matter.
3018 //
3019 // FIXME: We could do this if we juggled some extra state in
3020 // OverloadableAttr, rather than just removing it.
3021 const Decl *DiagOld = Old;
3022 if (OldOvl) {
3023 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3024 const auto *A = D->getAttr<OverloadableAttr>();
3025 return A && !A->isImplicit();
3026 });
3027 // If we've implicitly added *all* of the overloadable attrs to this
3028 // chain, emitting a "previous redecl" note is pointless.
3029 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3030 }
3031
3032 if (DiagOld)
3033 Diag(DiagOld->getLocation(),
3034 diag::note_attribute_overloadable_prev_overload)
3035 << OldOvl;
3036
3037 if (OldOvl)
3038 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3039 else
3040 New->dropAttr<OverloadableAttr>();
3041 }
3042 }
3043
3044 // If a function is first declared with a calling convention, but is later
3045 // declared or defined without one, all following decls assume the calling
3046 // convention of the first.
3047 //
3048 // It's OK if a function is first declared without a calling convention,
3049 // but is later declared or defined with the default calling convention.
3050 //
3051 // To test if either decl has an explicit calling convention, we look for
3052 // AttributedType sugar nodes on the type as written. If they are missing or
3053 // were canonicalized away, we assume the calling convention was implicit.
3054 //
3055 // Note also that we DO NOT return at this point, because we still have
3056 // other tests to run.
3057 QualType OldQType = Context.getCanonicalType(Old->getType());
3058 QualType NewQType = Context.getCanonicalType(New->getType());
3059 const FunctionType *OldType = cast<FunctionType>(OldQType);
3060 const FunctionType *NewType = cast<FunctionType>(NewQType);
3061 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3062 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3063 bool RequiresAdjustment = false;
3064
3065 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3066 FunctionDecl *First = Old->getFirstDecl();
3067 const FunctionType *FT =
3068 First->getType().getCanonicalType()->castAs<FunctionType>();
3069 FunctionType::ExtInfo FI = FT->getExtInfo();
3070 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3071 if (!NewCCExplicit) {
3072 // Inherit the CC from the previous declaration if it was specified
3073 // there but not here.
3074 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3075 RequiresAdjustment = true;
3076 } else {
3077 // Calling conventions aren't compatible, so complain.
3078 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3079 Diag(New->getLocation(), diag::err_cconv_change)
3080 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3081 << !FirstCCExplicit
3082 << (!FirstCCExplicit ? "" :
3083 FunctionType::getNameForCallConv(FI.getCC()));
3084
3085 // Put the note on the first decl, since it is the one that matters.
3086 Diag(First->getLocation(), diag::note_previous_declaration);
3087 return true;
3088 }
3089 }
3090
3091 // FIXME: diagnose the other way around?
3092 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3093 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3094 RequiresAdjustment = true;
3095 }
3096
3097 // Merge regparm attribute.
3098 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3099 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3100 if (NewTypeInfo.getHasRegParm()) {
3101 Diag(New->getLocation(), diag::err_regparm_mismatch)
3102 << NewType->getRegParmType()
3103 << OldType->getRegParmType();
3104 Diag(OldLocation, diag::note_previous_declaration);
3105 return true;
3106 }
3107
3108 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3109 RequiresAdjustment = true;
3110 }
3111
3112 // Merge ns_returns_retained attribute.
3113 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3114 if (NewTypeInfo.getProducesResult()) {
3115 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3116 << "'ns_returns_retained'";
3117 Diag(OldLocation, diag::note_previous_declaration);
3118 return true;
3119 }
3120
3121 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3122 RequiresAdjustment = true;
3123 }
3124
3125 if (OldTypeInfo.getNoCallerSavedRegs() !=
3126 NewTypeInfo.getNoCallerSavedRegs()) {
3127 if (NewTypeInfo.getNoCallerSavedRegs()) {
3128 AnyX86NoCallerSavedRegistersAttr *Attr =
3129 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3130 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3131 Diag(OldLocation, diag::note_previous_declaration);
3132 return true;
3133 }
3134
3135 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3136 RequiresAdjustment = true;
3137 }
3138
3139 if (RequiresAdjustment) {
3140 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3141 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3142 New->setType(QualType(AdjustedType, 0));
3143 NewQType = Context.getCanonicalType(New->getType());
3144 NewType = cast<FunctionType>(NewQType);
3145 }
3146
3147 // If this redeclaration makes the function inline, we may need to add it to
3148 // UndefinedButUsed.
3149 if (!Old->isInlined() && New->isInlined() &&
3150 !New->hasAttr<GNUInlineAttr>() &&
3151 !getLangOpts().GNUInline &&
3152 Old->isUsed(false) &&
3153 !Old->isDefined() && !New->isThisDeclarationADefinition())
3154 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3155 SourceLocation()));
3156
3157 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3158 // about it.
3159 if (New->hasAttr<GNUInlineAttr>() &&
3160 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3161 UndefinedButUsed.erase(Old->getCanonicalDecl());
3162 }
3163
3164 // If pass_object_size params don't match up perfectly, this isn't a valid
3165 // redeclaration.
3166 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3167 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3168 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3169 << New->getDeclName();
3170 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3171 return true;
3172 }
3173
3174 if (getLangOpts().CPlusPlus) {
3175 // C++1z [over.load]p2
3176 // Certain function declarations cannot be overloaded:
3177 // -- Function declarations that differ only in the return type,
3178 // the exception specification, or both cannot be overloaded.
3179
3180 // Check the exception specifications match. This may recompute the type of
3181 // both Old and New if it resolved exception specifications, so grab the
3182 // types again after this. Because this updates the type, we do this before
3183 // any of the other checks below, which may update the "de facto" NewQType
3184 // but do not necessarily update the type of New.
3185 if (CheckEquivalentExceptionSpec(Old, New))
3186 return true;
3187 OldQType = Context.getCanonicalType(Old->getType());
3188 NewQType = Context.getCanonicalType(New->getType());
3189
3190 // Go back to the type source info to compare the declared return types,
3191 // per C++1y [dcl.type.auto]p13:
3192 // Redeclarations or specializations of a function or function template
3193 // with a declared return type that uses a placeholder type shall also
3194 // use that placeholder, not a deduced type.
3195 QualType OldDeclaredReturnType =
3196 (Old->getTypeSourceInfo()
3197 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3198 : OldType)->getReturnType();
3199 QualType NewDeclaredReturnType =
3200 (New->getTypeSourceInfo()
3201 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3202 : NewType)->getReturnType();
3203 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3204 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3205 New->isLocalExternDecl())) {
3206 QualType ResQT;
3207 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3208 OldDeclaredReturnType->isObjCObjectPointerType())
3209 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3210 if (ResQT.isNull()) {
3211 if (New->isCXXClassMember() && New->isOutOfLine())
3212 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3213 << New << New->getReturnTypeSourceRange();
3214 else
3215 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3216 << New->getReturnTypeSourceRange();
3217 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3218 << Old->getReturnTypeSourceRange();
3219 return true;
3220 }
3221 else
3222 NewQType = ResQT;
3223 }
3224
3225 QualType OldReturnType = OldType->getReturnType();
3226 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3227 if (OldReturnType != NewReturnType) {
3228 // If this function has a deduced return type and has already been
3229 // defined, copy the deduced value from the old declaration.
3230 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3231 if (OldAT && OldAT->isDeduced()) {
3232 New->setType(
3233 SubstAutoType(New->getType(),
3234 OldAT->isDependentType() ? Context.DependentTy
3235 : OldAT->getDeducedType()));
3236 NewQType = Context.getCanonicalType(
3237 SubstAutoType(NewQType,
3238 OldAT->isDependentType() ? Context.DependentTy
3239 : OldAT->getDeducedType()));
3240 }
3241 }
3242
3243 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3244 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3245 if (OldMethod && NewMethod) {
3246 // Preserve triviality.
3247 NewMethod->setTrivial(OldMethod->isTrivial());
3248
3249 // MSVC allows explicit template specialization at class scope:
3250 // 2 CXXMethodDecls referring to the same function will be injected.
3251 // We don't want a redeclaration error.
3252 bool IsClassScopeExplicitSpecialization =
3253 OldMethod->isFunctionTemplateSpecialization() &&
3254 NewMethod->isFunctionTemplateSpecialization();
3255 bool isFriend = NewMethod->getFriendObjectKind();
3256
3257 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3258 !IsClassScopeExplicitSpecialization) {
3259 // -- Member function declarations with the same name and the
3260 // same parameter types cannot be overloaded if any of them
3261 // is a static member function declaration.
3262 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3263 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3264 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3265 return true;
3266 }
3267
3268 // C++ [class.mem]p1:
3269 // [...] A member shall not be declared twice in the
3270 // member-specification, except that a nested class or member
3271 // class template can be declared and then later defined.
3272 if (!inTemplateInstantiation()) {
3273 unsigned NewDiag;
3274 if (isa<CXXConstructorDecl>(OldMethod))
3275 NewDiag = diag::err_constructor_redeclared;
3276 else if (isa<CXXDestructorDecl>(NewMethod))
3277 NewDiag = diag::err_destructor_redeclared;
3278 else if (isa<CXXConversionDecl>(NewMethod))
3279 NewDiag = diag::err_conv_function_redeclared;
3280 else
3281 NewDiag = diag::err_member_redeclared;
3282
3283 Diag(New->getLocation(), NewDiag);
3284 } else {
3285 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3286 << New << New->getType();
3287 }
3288 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3289 return true;
3290
3291 // Complain if this is an explicit declaration of a special
3292 // member that was initially declared implicitly.
3293 //
3294 // As an exception, it's okay to befriend such methods in order
3295 // to permit the implicit constructor/destructor/operator calls.
3296 } else if (OldMethod->isImplicit()) {
3297 if (isFriend) {
3298 NewMethod->setImplicit();
3299 } else {
3300 Diag(NewMethod->getLocation(),
3301 diag::err_definition_of_implicitly_declared_member)
3302 << New << getSpecialMember(OldMethod);
3303 return true;
3304 }
3305 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3306 Diag(NewMethod->getLocation(),
3307 diag::err_definition_of_explicitly_defaulted_member)
3308 << getSpecialMember(OldMethod);
3309 return true;
3310 }
3311 }
3312
3313 // C++11 [dcl.attr.noreturn]p1:
3314 // The first declaration of a function shall specify the noreturn
3315 // attribute if any declaration of that function specifies the noreturn
3316 // attribute.
3317 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3318 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3319 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3320 Diag(Old->getFirstDecl()->getLocation(),
3321 diag::note_noreturn_missing_first_decl);
3322 }
3323
3324 // C++11 [dcl.attr.depend]p2:
3325 // The first declaration of a function shall specify the
3326 // carries_dependency attribute for its declarator-id if any declaration
3327 // of the function specifies the carries_dependency attribute.
3328 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3329 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3330 Diag(CDA->getLocation(),
3331 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3332 Diag(Old->getFirstDecl()->getLocation(),
3333 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3334 }
3335
3336 // (C++98 8.3.5p3):
3337 // All declarations for a function shall agree exactly in both the
3338 // return type and the parameter-type-list.
3339 // We also want to respect all the extended bits except noreturn.
3340
3341 // noreturn should now match unless the old type info didn't have it.
3342 QualType OldQTypeForComparison = OldQType;
3343 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3344 auto *OldType = OldQType->castAs<FunctionProtoType>();
3345 const FunctionType *OldTypeForComparison
3346 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3347 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3348 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 3348, __extension__ __PRETTY_FUNCTION__))
;
3349 }
3350
3351 if (haveIncompatibleLanguageLinkages(Old, New)) {
3352 // As a special case, retain the language linkage from previous
3353 // declarations of a friend function as an extension.
3354 //
3355 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3356 // and is useful because there's otherwise no way to specify language
3357 // linkage within class scope.
3358 //
3359 // Check cautiously as the friend object kind isn't yet complete.
3360 if (New->getFriendObjectKind() != Decl::FOK_None) {
3361 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3362 Diag(OldLocation, PrevDiag);
3363 } else {
3364 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3365 Diag(OldLocation, PrevDiag);
3366 return true;
3367 }
3368 }
3369
3370 if (OldQTypeForComparison == NewQType)
3371 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3372
3373 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3374 New->isLocalExternDecl()) {
3375 // It's OK if we couldn't merge types for a local function declaraton
3376 // if either the old or new type is dependent. We'll merge the types
3377 // when we instantiate the function.
3378 return false;
3379 }
3380
3381 // Fall through for conflicting redeclarations and redefinitions.
3382 }
3383
3384 // C: Function types need to be compatible, not identical. This handles
3385 // duplicate function decls like "void f(int); void f(enum X);" properly.
3386 if (!getLangOpts().CPlusPlus &&
3387 Context.typesAreCompatible(OldQType, NewQType)) {
3388 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3389 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3390 const FunctionProtoType *OldProto = nullptr;
3391 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3392 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3393 // The old declaration provided a function prototype, but the
3394 // new declaration does not. Merge in the prototype.
3395 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 3395, __extension__ __PRETTY_FUNCTION__))
;
3396 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3397 NewQType =
3398 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3399 OldProto->getExtProtoInfo());
3400 New->setType(NewQType);
3401 New->setHasInheritedPrototype();
3402
3403 // Synthesize parameters with the same types.
3404 SmallVector<ParmVarDecl*, 16> Params;
3405 for (const auto &ParamType : OldProto->param_types()) {
3406 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3407 SourceLocation(), nullptr,
3408 ParamType, /*TInfo=*/nullptr,
3409 SC_None, nullptr);
3410 Param->setScopeInfo(0, Params.size());
3411 Param->setImplicit();
3412 Params.push_back(Param);
3413 }
3414
3415 New->setParams(Params);
3416 }
3417
3418 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3419 }
3420
3421 // GNU C permits a K&R definition to follow a prototype declaration
3422 // if the declared types of the parameters in the K&R definition
3423 // match the types in the prototype declaration, even when the
3424 // promoted types of the parameters from the K&R definition differ
3425 // from the types in the prototype. GCC then keeps the types from
3426 // the prototype.
3427 //
3428 // If a variadic prototype is followed by a non-variadic K&R definition,
3429 // the K&R definition becomes variadic. This is sort of an edge case, but
3430 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3431 // C99 6.9.1p8.
3432 if (!getLangOpts().CPlusPlus &&
3433 Old->hasPrototype() && !New->hasPrototype() &&
3434 New->getType()->getAs<FunctionProtoType>() &&
3435 Old->getNumParams() == New->getNumParams()) {
3436 SmallVector<QualType, 16> ArgTypes;
3437 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3438 const FunctionProtoType *OldProto
3439 = Old->getType()->getAs<FunctionProtoType>();
3440 const FunctionProtoType *NewProto
3441 = New->getType()->getAs<FunctionProtoType>();
3442
3443 // Determine whether this is the GNU C extension.
3444 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3445 NewProto->getReturnType());
3446 bool LooseCompatible = !MergedReturn.isNull();
3447 for (unsigned Idx = 0, End = Old->getNumParams();
3448 LooseCompatible && Idx != End; ++Idx) {
3449 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3450 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3451 if (Context.typesAreCompatible(OldParm->getType(),
3452 NewProto->getParamType(Idx))) {
3453 ArgTypes.push_back(NewParm->getType());
3454 } else if (Context.typesAreCompatible(OldParm->getType(),
3455 NewParm->getType(),
3456 /*CompareUnqualified=*/true)) {
3457 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3458 NewProto->getParamType(Idx) };
3459 Warnings.push_back(Warn);
3460 ArgTypes.push_back(NewParm->getType());
3461 } else
3462 LooseCompatible = false;
3463 }
3464
3465 if (LooseCompatible) {
3466 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3467 Diag(Warnings[Warn].NewParm->getLocation(),
3468 diag::ext_param_promoted_not_compatible_with_prototype)
3469 << Warnings[Warn].PromotedType
3470 << Warnings[Warn].OldParm->getType();
3471 if (Warnings[Warn].OldParm->getLocation().isValid())
3472 Diag(Warnings[Warn].OldParm->getLocation(),
3473 diag::note_previous_declaration);
3474 }
3475
3476 if (MergeTypeWithOld)
3477 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3478 OldProto->getExtProtoInfo()));
3479 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3480 }
3481
3482 // Fall through to diagnose conflicting types.
3483 }
3484
3485 // A function that has already been declared has been redeclared or
3486 // defined with a different type; show an appropriate diagnostic.
3487
3488 // If the previous declaration was an implicitly-generated builtin
3489 // declaration, then at the very least we should use a specialized note.
3490 unsigned BuiltinID;
3491 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3492 // If it's actually a library-defined builtin function like 'malloc'
3493 // or 'printf', just warn about the incompatible redeclaration.
3494 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3495 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3496 Diag(OldLocation, diag::note_previous_builtin_declaration)
3497 << Old << Old->getType();
3498
3499 // If this is a global redeclaration, just forget hereafter
3500 // about the "builtin-ness" of the function.
3501 //
3502 // Doing this for local extern declarations is problematic. If
3503 // the builtin declaration remains visible, a second invalid
3504 // local declaration will produce a hard error; if it doesn't
3505 // remain visible, a single bogus local redeclaration (which is
3506 // actually only a warning) could break all the downstream code.
3507 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3508 New->getIdentifier()->revertBuiltin();
3509
3510 return false;
3511 }
3512
3513 PrevDiag = diag::note_previous_builtin_declaration;
3514 }
3515
3516 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3517 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3518 return true;
3519}
3520
3521/// \brief Completes the merge of two function declarations that are
3522/// known to be compatible.
3523///
3524/// This routine handles the merging of attributes and other
3525/// properties of function declarations from the old declaration to
3526/// the new declaration, once we know that New is in fact a
3527/// redeclaration of Old.
3528///
3529/// \returns false
3530bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3531 Scope *S, bool MergeTypeWithOld) {
3532 // Merge the attributes
3533 mergeDeclAttributes(New, Old);
3534
3535 // Merge "pure" flag.
3536 if (Old->isPure())
3537 New->setPure();
3538
3539 // Merge "used" flag.
3540 if (Old->getMostRecentDecl()->isUsed(false))
3541 New->setIsUsed();
3542
3543 // Merge attributes from the parameters. These can mismatch with K&R
3544 // declarations.
3545 if (New->getNumParams() == Old->getNumParams())
3546 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3547 ParmVarDecl *NewParam = New->getParamDecl(i);
3548 ParmVarDecl *OldParam = Old->getParamDecl(i);
3549 mergeParamDeclAttributes(NewParam, OldParam, *this);
3550 mergeParamDeclTypes(NewParam, OldParam, *this);
3551 }
3552
3553 if (getLangOpts().CPlusPlus)
3554 return MergeCXXFunctionDecl(New, Old, S);
3555
3556 // Merge the function types so the we get the composite types for the return
3557 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3558 // was visible.
3559 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3560 if (!Merged.isNull() && MergeTypeWithOld)
3561 New->setType(Merged);
3562
3563 return false;
3564}
3565
3566void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3567 ObjCMethodDecl *oldMethod) {
3568 // Merge the attributes, including deprecated/unavailable
3569 AvailabilityMergeKind MergeKind =
3570 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3571 ? AMK_ProtocolImplementation
3572 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3573 : AMK_Override;
3574
3575 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3576
3577 // Merge attributes from the parameters.
3578 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3579 oe = oldMethod->param_end();
3580 for (ObjCMethodDecl::param_iterator
3581 ni = newMethod->param_begin(), ne = newMethod->param_end();
3582 ni != ne && oi != oe; ++ni, ++oi)
3583 mergeParamDeclAttributes(*ni, *oi, *this);
3584}
3585
3586static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3587 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 3587, __extension__ __PRETTY_FUNCTION__))
;
3588
3589 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3590 ? diag::err_redefinition_different_type
3591 : diag::err_redeclaration_different_type)
3592 << New->getDeclName() << New->getType() << Old->getType();
3593
3594 diag::kind PrevDiag;
3595 SourceLocation OldLocation;
3596 std::tie(PrevDiag, OldLocation)
3597 = getNoteDiagForInvalidRedeclaration(Old, New);
3598 S.Diag(OldLocation, PrevDiag);
3599 New->setInvalidDecl();
3600}
3601
3602/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3603/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3604/// emitting diagnostics as appropriate.
3605///
3606/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3607/// to here in AddInitializerToDecl. We can't check them before the initializer
3608/// is attached.
3609void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3610 bool MergeTypeWithOld) {
3611 if (New->isInvalidDecl() || Old->isInvalidDecl())
3612 return;
3613
3614 QualType MergedT;
3615 if (getLangOpts().CPlusPlus) {
3616 if (New->getType()->isUndeducedType()) {
3617 // We don't know what the new type is until the initializer is attached.
3618 return;
3619 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3620 // These could still be something that needs exception specs checked.
3621 return MergeVarDeclExceptionSpecs(New, Old);
3622 }
3623 // C++ [basic.link]p10:
3624 // [...] the types specified by all declarations referring to a given
3625 // object or function shall be identical, except that declarations for an
3626 // array object can specify array types that differ by the presence or
3627 // absence of a major array bound (8.3.4).
3628 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3629 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3630 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3631
3632 // We are merging a variable declaration New into Old. If it has an array
3633 // bound, and that bound differs from Old's bound, we should diagnose the
3634 // mismatch.
3635 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3636 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3637 PrevVD = PrevVD->getPreviousDecl()) {
3638 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3639 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3640 continue;
3641
3642 if (!Context.hasSameType(NewArray, PrevVDTy))
3643 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3644 }
3645 }
3646
3647 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3648 if (Context.hasSameType(OldArray->getElementType(),
3649 NewArray->getElementType()))
3650 MergedT = New->getType();
3651 }
3652 // FIXME: Check visibility. New is hidden but has a complete type. If New
3653 // has no array bound, it should not inherit one from Old, if Old is not
3654 // visible.
3655 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3656 if (Context.hasSameType(OldArray->getElementType(),
3657 NewArray->getElementType()))
3658 MergedT = Old->getType();
3659 }
3660 }
3661 else if (New->getType()->isObjCObjectPointerType() &&
3662 Old->getType()->isObjCObjectPointerType()) {
3663 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3664 Old->getType());
3665 }
3666 } else {
3667 // C 6.2.7p2:
3668 // All declarations that refer to the same object or function shall have
3669 // compatible type.
3670 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3671 }
3672 if (MergedT.isNull()) {
3673 // It's OK if we couldn't merge types if either type is dependent, for a
3674 // block-scope variable. In other cases (static data members of class
3675 // templates, variable templates, ...), we require the types to be
3676 // equivalent.
3677 // FIXME: The C++ standard doesn't say anything about this.
3678 if ((New->getType()->isDependentType() ||
3679 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3680 // If the old type was dependent, we can't merge with it, so the new type
3681 // becomes dependent for now. We'll reproduce the original type when we
3682 // instantiate the TypeSourceInfo for the variable.
3683 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3684 New->setType(Context.DependentTy);
3685 return;
3686 }
3687 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3688 }
3689
3690 // Don't actually update the type on the new declaration if the old
3691 // declaration was an extern declaration in a different scope.
3692 if (MergeTypeWithOld)
3693 New->setType(MergedT);
3694}
3695
3696static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3697 LookupResult &Previous) {
3698 // C11 6.2.7p4:
3699 // For an identifier with internal or external linkage declared
3700 // in a scope in which a prior declaration of that identifier is
3701 // visible, if the prior declaration specifies internal or
3702 // external linkage, the type of the identifier at the later
3703 // declaration becomes the composite type.
3704 //
3705 // If the variable isn't visible, we do not merge with its type.
3706 if (Previous.isShadowed())
3707 return false;
3708
3709 if (S.getLangOpts().CPlusPlus) {
3710 // C++11 [dcl.array]p3:
3711 // If there is a preceding declaration of the entity in the same
3712 // scope in which the bound was specified, an omitted array bound
3713 // is taken to be the same as in that earlier declaration.
3714 return NewVD->isPreviousDeclInSameBlockScope() ||
3715 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3716 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3717 } else {
3718 // If the old declaration was function-local, don't merge with its
3719 // type unless we're in the same function.
3720 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3721 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3722 }
3723}
3724
3725/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3726/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3727/// situation, merging decls or emitting diagnostics as appropriate.
3728///
3729/// Tentative definition rules (C99 6.9.2p2) are checked by
3730/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3731/// definitions here, since the initializer hasn't been attached.
3732///
3733void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3734 // If the new decl is already invalid, don't do any other checking.
3735 if (New->isInvalidDecl())
3736 return;
3737
3738 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3739 return;
3740
3741 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3742
3743 // Verify the old decl was also a variable or variable template.
3744 VarDecl *Old = nullptr;
3745 VarTemplateDecl *OldTemplate = nullptr;
3746 if (Previous.isSingleResult()) {
3747 if (NewTemplate) {
3748 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3749 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3750
3751 if (auto *Shadow =
3752 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3753 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3754 return New->setInvalidDecl();
3755 } else {
3756 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3757
3758 if (auto *Shadow =
3759 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3760 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3761 return New->setInvalidDecl();
3762 }
3763 }
3764 if (!Old) {
3765 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3766 << New->getDeclName();
3767 notePreviousDefinition(Previous.getRepresentativeDecl(),
3768 New->getLocation());
3769 return New->setInvalidDecl();
3770 }
3771
3772 // Ensure the template parameters are compatible.
3773 if (NewTemplate &&
3774 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3775 OldTemplate->getTemplateParameters(),
3776 /*Complain=*/true, TPL_TemplateMatch))
3777 return New->setInvalidDecl();
3778
3779 // C++ [class.mem]p1:
3780 // A member shall not be declared twice in the member-specification [...]
3781 //
3782 // Here, we need only consider static data members.
3783 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3784 Diag(New->getLocation(), diag::err_duplicate_member)
3785 << New->getIdentifier();
3786 Diag(Old->getLocation(), diag::note_previous_declaration);
3787 New->setInvalidDecl();
3788 }
3789
3790 mergeDeclAttributes(New, Old);
3791 // Warn if an already-declared variable is made a weak_import in a subsequent
3792 // declaration
3793 if (New->hasAttr<WeakImportAttr>() &&
3794 Old->getStorageClass() == SC_None &&
3795 !Old->hasAttr<WeakImportAttr>()) {
3796 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3797 notePreviousDefinition(Old, New->getLocation());
3798 // Remove weak_import attribute on new declaration.
3799 New->dropAttr<WeakImportAttr>();
3800 }
3801
3802 if (New->hasAttr<InternalLinkageAttr>() &&
3803 !Old->hasAttr<InternalLinkageAttr>()) {
3804 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3805 << New->getDeclName();
3806 notePreviousDefinition(Old, New->getLocation());
3807 New->dropAttr<InternalLinkageAttr>();
3808 }
3809
3810 // Merge the types.
3811 VarDecl *MostRecent = Old->getMostRecentDecl();
3812 if (MostRecent != Old) {
3813 MergeVarDeclTypes(New, MostRecent,
3814 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3815 if (New->isInvalidDecl())
3816 return;
3817 }
3818
3819 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3820 if (New->isInvalidDecl())
3821 return;
3822
3823 diag::kind PrevDiag;
3824 SourceLocation OldLocation;
3825 std::tie(PrevDiag, OldLocation) =
3826 getNoteDiagForInvalidRedeclaration(Old, New);
3827
3828 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3829 if (New->getStorageClass() == SC_Static &&
3830 !New->isStaticDataMember() &&
3831 Old->hasExternalFormalLinkage()) {
3832 if (getLangOpts().MicrosoftExt) {
3833 Diag(New->getLocation(), diag::ext_static_non_static)
3834 << New->getDeclName();
3835 Diag(OldLocation, PrevDiag);
3836 } else {
3837 Diag(New->getLocation(), diag::err_static_non_static)
3838 << New->getDeclName();
3839 Diag(OldLocation, PrevDiag);
3840 return New->setInvalidDecl();
3841 }
3842 }
3843 // C99 6.2.2p4:
3844 // For an identifier declared with the storage-class specifier
3845 // extern in a scope in which a prior declaration of that
3846 // identifier is visible,23) if the prior declaration specifies
3847 // internal or external linkage, the linkage of the identifier at
3848 // the later declaration is the same as the linkage specified at
3849 // the prior declaration. If no prior declaration is visible, or
3850 // if the prior declaration specifies no linkage, then the
3851 // identifier has external linkage.
3852 if (New->hasExternalStorage() && Old->hasLinkage())
3853 /* Okay */;
3854 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3855 !New->isStaticDataMember() &&
3856 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3857 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3858 Diag(OldLocation, PrevDiag);
3859 return New->setInvalidDecl();
3860 }
3861
3862 // Check if extern is followed by non-extern and vice-versa.
3863 if (New->hasExternalStorage() &&
3864 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3865 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3866 Diag(OldLocation, PrevDiag);
3867 return New->setInvalidDecl();
3868 }
3869 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3870 !New->hasExternalStorage()) {
3871 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3872 Diag(OldLocation, PrevDiag);
3873 return New->setInvalidDecl();
3874 }
3875
3876 if (CheckRedeclarationModuleOwnership(New, Old))
3877 return;
3878
3879 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3880
3881 // FIXME: The test for external storage here seems wrong? We still
3882 // need to check for mismatches.
3883 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3884 // Don't complain about out-of-line definitions of static members.
3885 !(Old->getLexicalDeclContext()->isRecord() &&
3886 !New->getLexicalDeclContext()->isRecord())) {
3887 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3888 Diag(OldLocation, PrevDiag);
3889 return New->setInvalidDecl();
3890 }
3891
3892 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3893 if (VarDecl *Def = Old->getDefinition()) {
3894 // C++1z [dcl.fcn.spec]p4:
3895 // If the definition of a variable appears in a translation unit before
3896 // its first declaration as inline, the program is ill-formed.
3897 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3898 Diag(Def->getLocation(), diag::note_previous_definition);
3899 }
3900 }
3901
3902 // If this redeclaration makes the variable inline, we may need to add it to
3903 // UndefinedButUsed.
3904 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3905 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3906 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3907 SourceLocation()));
3908
3909 if (New->getTLSKind() != Old->getTLSKind()) {
3910 if (!Old->getTLSKind()) {
3911 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3912 Diag(OldLocation, PrevDiag);
3913 } else if (!New->getTLSKind()) {
3914 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3915 Diag(OldLocation, PrevDiag);
3916 } else {
3917 // Do not allow redeclaration to change the variable between requiring
3918 // static and dynamic initialization.
3919 // FIXME: GCC allows this, but uses the TLS keyword on the first
3920 // declaration to determine the kind. Do we need to be compatible here?
3921 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3922 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3923 Diag(OldLocation, PrevDiag);
3924 }
3925 }
3926
3927 // C++ doesn't have tentative definitions, so go right ahead and check here.
3928 if (getLangOpts().CPlusPlus &&
3929 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3930 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3931 Old->getCanonicalDecl()->isConstexpr()) {
3932 // This definition won't be a definition any more once it's been merged.
3933 Diag(New->getLocation(),
3934 diag::warn_deprecated_redundant_constexpr_static_def);
3935 } else if (VarDecl *Def = Old->getDefinition()) {
3936 if (checkVarDeclRedefinition(Def, New))
3937 return;
3938 }
3939 }
3940
3941 if (haveIncompatibleLanguageLinkages(Old, New)) {
3942 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3943 Diag(OldLocation, PrevDiag);
3944 New->setInvalidDecl();
3945 return;
3946 }
3947
3948 // Merge "used" flag.
3949 if (Old->getMostRecentDecl()->isUsed(false))
3950 New->setIsUsed();
3951
3952 // Keep a chain of previous declarations.
3953 New->setPreviousDecl(Old);
3954 if (NewTemplate)
3955 NewTemplate->setPreviousDecl(OldTemplate);
3956
3957 // Inherit access appropriately.
3958 New->setAccess(Old->getAccess());
3959 if (NewTemplate)
3960 NewTemplate->setAccess(New->getAccess());
3961
3962 if (Old->isInline())
3963 New->setImplicitlyInline();
3964}
3965
3966void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3967 SourceManager &SrcMgr = getSourceManager();
3968 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3969 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3970 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3971 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3972 auto &HSI = PP.getHeaderSearchInfo();
3973 StringRef HdrFilename =
3974 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3975
3976 auto noteFromModuleOrInclude = [&](Module *Mod,
3977 SourceLocation IncLoc) -> bool {
3978 // Redefinition errors with modules are common with non modular mapped
3979 // headers, example: a non-modular header H in module A that also gets
3980 // included directly in a TU. Pointing twice to the same header/definition
3981 // is confusing, try to get better diagnostics when modules is on.
3982 if (IncLoc.isValid()) {
3983 if (Mod) {
3984 Diag(IncLoc, diag::note_redefinition_modules_same_file)
3985 << HdrFilename.str() << Mod->getFullModuleName();
3986 if (!Mod->DefinitionLoc.isInvalid())
3987 Diag(Mod->DefinitionLoc, diag::note_defined_here)
3988 << Mod->getFullModuleName();
3989 } else {
3990 Diag(IncLoc, diag::note_redefinition_include_same_file)
3991 << HdrFilename.str();
3992 }
3993 return true;
3994 }
3995
3996 return false;
3997 };
3998
3999 // Is it the same file and same offset? Provide more information on why
4000 // this leads to a redefinition error.
4001 bool EmittedDiag = false;
4002 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4003 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4004 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4005 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4006 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4007
4008 // If the header has no guards, emit a note suggesting one.
4009 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4010 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4011
4012 if (EmittedDiag)
4013 return;
4014 }
4015
4016 // Redefinition coming from different files or couldn't do better above.
4017 Diag(Old->getLocation(), diag::note_previous_definition);
4018}
4019
4020/// We've just determined that \p Old and \p New both appear to be definitions
4021/// of the same variable. Either diagnose or fix the problem.
4022bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4023 if (!hasVisibleDefinition(Old) &&
4024 (New->getFormalLinkage() == InternalLinkage ||
4025 New->isInline() ||
4026 New->getDescribedVarTemplate() ||
4027 New->getNumTemplateParameterLists() ||
4028 New->getDeclContext()->isDependentContext())) {
4029 // The previous definition is hidden, and multiple definitions are
4030 // permitted (in separate TUs). Demote this to a declaration.
4031 New->demoteThisDefinitionToDeclaration();
4032
4033 // Make the canonical definition visible.
4034 if (auto *OldTD = Old->getDescribedVarTemplate())
4035 makeMergedDefinitionVisible(OldTD);
4036 makeMergedDefinitionVisible(Old);
4037 return false;
4038 } else {
4039 Diag(New->getLocation(), diag::err_redefinition) << New;
4040 notePreviousDefinition(Old, New->getLocation());
4041 New->setInvalidDecl();
4042 return true;
4043 }
4044}
4045
4046/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4047/// no declarator (e.g. "struct foo;") is parsed.
4048Decl *
4049Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4050 RecordDecl *&AnonRecord) {
4051 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4052 AnonRecord);
4053}
4054
4055// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4056// disambiguate entities defined in different scopes.
4057// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4058// compatibility.
4059// We will pick our mangling number depending on which version of MSVC is being
4060// targeted.
4061static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4062 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4063 ? S->getMSCurManglingNumber()
4064 : S->getMSLastManglingNumber();
4065}
4066
4067void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4068 if (!Context.getLangOpts().CPlusPlus)
4069 return;
4070
4071 if (isa<CXXRecordDecl>(Tag->getParent())) {
4072 // If this tag is the direct child of a class, number it if
4073 // it is anonymous.
4074 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4075 return;
4076 MangleNumberingContext &MCtx =
4077 Context.getManglingNumberContext(Tag->getParent());
4078 Context.setManglingNumber(
4079 Tag, MCtx.getManglingNumber(
4080 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4081 return;
4082 }
4083
4084 // If this tag isn't a direct child of a class, number it if it is local.
4085 Decl *ManglingContextDecl;
4086 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4087 Tag->getDeclContext(), ManglingContextDecl)) {
4088 Context.setManglingNumber(
4089 Tag, MCtx->getManglingNumber(
4090 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4091 }
4092}
4093
4094void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4095 TypedefNameDecl *NewTD) {
4096 if (TagFromDeclSpec->isInvalidDecl())
4097 return;
4098
4099 // Do nothing if the tag already has a name for linkage purposes.
4100 if (TagFromDeclSpec->hasNameForLinkage())
4101 return;
4102
4103 // A well-formed anonymous tag must always be a TUK_Definition.
4104 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4104, __extension__ __PRETTY_FUNCTION__))
;
4105
4106 // The type must match the tag exactly; no qualifiers allowed.
4107 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4108 Context.getTagDeclType(TagFromDeclSpec))) {
4109 if (getLangOpts().CPlusPlus)
4110 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4111 return;
4112 }
4113
4114 // If we've already computed linkage for the anonymous tag, then
4115 // adding a typedef name for the anonymous decl can change that
4116 // linkage, which might be a serious problem. Diagnose this as
4117 // unsupported and ignore the typedef name. TODO: we should
4118 // pursue this as a language defect and establish a formal rule
4119 // for how to handle it.
4120 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4121 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4122
4123 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4124 tagLoc = getLocForEndOfToken(tagLoc);
4125
4126 llvm::SmallString<40> textToInsert;
4127 textToInsert += ' ';
4128 textToInsert += NewTD->getIdentifier()->getName();
4129 Diag(tagLoc, diag::note_typedef_changes_linkage)
4130 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4131 return;
4132 }
4133
4134 // Otherwise, set this is the anon-decl typedef for the tag.
4135 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4136}
4137
4138static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4139 switch (T) {
4140 case DeclSpec::TST_class:
4141 return 0;
4142 case DeclSpec::TST_struct:
4143 return 1;
4144 case DeclSpec::TST_interface:
4145 return 2;
4146 case DeclSpec::TST_union:
4147 return 3;
4148 case DeclSpec::TST_enum:
4149 return 4;
4150 default:
4151 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4151)
;
4152 }
4153}
4154
4155/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4156/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4157/// parameters to cope with template friend declarations.
4158Decl *
4159Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4160 MultiTemplateParamsArg TemplateParams,
4161 bool IsExplicitInstantiation,
4162 RecordDecl *&AnonRecord) {
4163 Decl *TagD = nullptr;
4164 TagDecl *Tag = nullptr;
4165 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4166 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4167 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4168 DS.getTypeSpecType() == DeclSpec::TST_union ||
4169 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4170 TagD = DS.getRepAsDecl();
4171
4172 if (!TagD) // We probably had an error
4173 return nullptr;
4174
4175 // Note that the above type specs guarantee that the
4176 // type rep is a Decl, whereas in many of the others
4177 // it's a Type.
4178 if (isa<TagDecl>(TagD))
4179 Tag = cast<TagDecl>(TagD);
4180 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4181 Tag = CTD->getTemplatedDecl();
4182 }
4183
4184 if (Tag) {
4185 handleTagNumbering(Tag, S);
4186 Tag->setFreeStanding();
4187 if (Tag->isInvalidDecl())
4188 return Tag;
4189 }
4190
4191 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4192 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4193 // or incomplete types shall not be restrict-qualified."
4194 if (TypeQuals & DeclSpec::TQ_restrict)
4195 Diag(DS.getRestrictSpecLoc(),
4196 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4197 << DS.getSourceRange();
4198 }
4199
4200 if (DS.isInlineSpecified())
4201 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4202 << getLangOpts().CPlusPlus17;
4203
4204 if (DS.isConstexprSpecified()) {
4205 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4206 // and definitions of functions and variables.
4207 if (Tag)
4208 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4209 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4210 else
4211 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4212 // Don't emit warnings after this error.
4213 return TagD;
4214 }
4215
4216 DiagnoseFunctionSpecifiers(DS);
4217
4218 if (DS.isFriendSpecified()) {
4219 // If we're dealing with a decl but not a TagDecl, assume that
4220 // whatever routines created it handled the friendship aspect.
4221 if (TagD && !Tag)
4222 return nullptr;
4223 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4224 }
4225
4226 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4227 bool IsExplicitSpecialization =
4228 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4229 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4230 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4231 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4232 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4233 // nested-name-specifier unless it is an explicit instantiation
4234 // or an explicit specialization.
4235 //
4236 // FIXME: We allow class template partial specializations here too, per the
4237 // obvious intent of DR1819.
4238 //
4239 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4240 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4241 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4242 return nullptr;
4243 }
4244
4245 // Track whether this decl-specifier declares anything.
4246 bool DeclaresAnything = true;
4247
4248 // Handle anonymous struct definitions.
4249 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4250 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4251 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4252 if (getLangOpts().CPlusPlus ||
4253 Record->getDeclContext()->isRecord()) {
4254 // If CurContext is a DeclContext that can contain statements,
4255 // RecursiveASTVisitor won't visit the decls that
4256 // BuildAnonymousStructOrUnion() will put into CurContext.
4257 // Also store them here so that they can be part of the
4258 // DeclStmt that gets created in this case.
4259 // FIXME: Also return the IndirectFieldDecls created by
4260 // BuildAnonymousStructOr union, for the same reason?
4261 if (CurContext->isFunctionOrMethod())
4262 AnonRecord = Record;
4263 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4264 Context.getPrintingPolicy());
4265 }
4266
4267 DeclaresAnything = false;
4268 }
4269 }
4270
4271 // C11 6.7.2.1p2:
4272 // A struct-declaration that does not declare an anonymous structure or
4273 // anonymous union shall contain a struct-declarator-list.
4274 //
4275 // This rule also existed in C89 and C99; the grammar for struct-declaration
4276 // did not permit a struct-declaration without a struct-declarator-list.
4277 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4278 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4279 // Check for Microsoft C extension: anonymous struct/union member.
4280 // Handle 2 kinds of anonymous struct/union:
4281 // struct STRUCT;
4282 // union UNION;
4283 // and
4284 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4285 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4286 if ((Tag && Tag->getDeclName()) ||
4287 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4288 RecordDecl *Record = nullptr;
4289 if (Tag)
4290 Record = dyn_cast<RecordDecl>(Tag);
4291 else if (const RecordType *RT =
4292 DS.getRepAsType().get()->getAsStructureType())
4293 Record = RT->getDecl();
4294 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4295 Record = UT->getDecl();
4296
4297 if (Record && getLangOpts().MicrosoftExt) {
4298 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4299 << Record->isUnion() << DS.getSourceRange();
4300 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4301 }
4302
4303 DeclaresAnything = false;
4304 }
4305 }
4306
4307 // Skip all the checks below if we have a type error.
4308 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4309 (TagD && TagD->isInvalidDecl()))
4310 return TagD;
4311
4312 if (getLangOpts().CPlusPlus &&
4313 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4314 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4315 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4316 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4317 DeclaresAnything = false;
4318
4319 if (!DS.isMissingDeclaratorOk()) {
4320 // Customize diagnostic for a typedef missing a name.
4321 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4322 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4323 << DS.getSourceRange();
4324 else
4325 DeclaresAnything = false;
4326 }
4327
4328 if (DS.isModulePrivateSpecified() &&
4329 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4330 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4331 << Tag->getTagKind()
4332 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4333
4334 ActOnDocumentableDecl(TagD);
4335
4336 // C 6.7/2:
4337 // A declaration [...] shall declare at least a declarator [...], a tag,
4338 // or the members of an enumeration.
4339 // C++ [dcl.dcl]p3:
4340 // [If there are no declarators], and except for the declaration of an
4341 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4342 // names into the program, or shall redeclare a name introduced by a
4343 // previous declaration.
4344 if (!DeclaresAnything) {
4345 // In C, we allow this as a (popular) extension / bug. Don't bother
4346 // producing further diagnostics for redundant qualifiers after this.
4347 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4348 return TagD;
4349 }
4350
4351 // C++ [dcl.stc]p1:
4352 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4353 // init-declarator-list of the declaration shall not be empty.
4354 // C++ [dcl.fct.spec]p1:
4355 // If a cv-qualifier appears in a decl-specifier-seq, the
4356 // init-declarator-list of the declaration shall not be empty.
4357 //
4358 // Spurious qualifiers here appear to be valid in C.
4359 unsigned DiagID = diag::warn_standalone_specifier;
4360 if (getLangOpts().CPlusPlus)
4361 DiagID = diag::ext_standalone_specifier;
4362
4363 // Note that a linkage-specification sets a storage class, but
4364 // 'extern "C" struct foo;' is actually valid and not theoretically
4365 // useless.
4366 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4367 if (SCS == DeclSpec::SCS_mutable)
4368 // Since mutable is not a viable storage class specifier in C, there is
4369 // no reason to treat it as an extension. Instead, diagnose as an error.
4370 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4371 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4372 Diag(DS.getStorageClassSpecLoc(), DiagID)
4373 << DeclSpec::getSpecifierName(SCS);
4374 }
4375
4376 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4377 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4378 << DeclSpec::getSpecifierName(TSCS);
4379 if (DS.getTypeQualifiers()) {
4380 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4381 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4382 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4383 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4384 // Restrict is covered above.
4385 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4386 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4387 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4388 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4389 }
4390
4391 // Warn about ignored type attributes, for example:
4392 // __attribute__((aligned)) struct A;
4393 // Attributes should be placed after tag to apply to type declaration.
4394 if (!DS.getAttributes().empty()) {
4395 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4396 if (TypeSpecType == DeclSpec::TST_class ||
4397 TypeSpecType == DeclSpec::TST_struct ||
4398 TypeSpecType == DeclSpec::TST_interface ||
4399 TypeSpecType == DeclSpec::TST_union ||
4400 TypeSpecType == DeclSpec::TST_enum) {
4401 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4402 attrs = attrs->getNext())
4403 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4404 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4405 }
4406 }
4407
4408 return TagD;
4409}
4410
4411/// We are trying to inject an anonymous member into the given scope;
4412/// check if there's an existing declaration that can't be overloaded.
4413///
4414/// \return true if this is a forbidden redeclaration
4415static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4416 Scope *S,
4417 DeclContext *Owner,
4418 DeclarationName Name,
4419 SourceLocation NameLoc,
4420 bool IsUnion) {
4421 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4422 Sema::ForVisibleRedeclaration);
4423 if (!SemaRef.LookupName(R, S)) return false;
4424
4425 // Pick a representative declaration.
4426 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4427 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4427, __extension__ __PRETTY_FUNCTION__))
;
4428
4429 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4430 return false;
4431
4432 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4433 << IsUnion << Name;
4434 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4435
4436 return true;
4437}
4438
4439/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4440/// anonymous struct or union AnonRecord into the owning context Owner
4441/// and scope S. This routine will be invoked just after we realize
4442/// that an unnamed union or struct is actually an anonymous union or
4443/// struct, e.g.,
4444///
4445/// @code
4446/// union {
4447/// int i;
4448/// float f;
4449/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4450/// // f into the surrounding scope.x
4451/// @endcode
4452///
4453/// This routine is recursive, injecting the names of nested anonymous
4454/// structs/unions into the owning context and scope as well.
4455static bool
4456InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4457 RecordDecl *AnonRecord, AccessSpecifier AS,
4458 SmallVectorImpl<NamedDecl *> &Chaining) {
4459 bool Invalid = false;
4460
4461 // Look every FieldDecl and IndirectFieldDecl with a name.
4462 for (auto *D : AnonRecord->decls()) {
4463 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4464 cast<NamedDecl>(D)->getDeclName()) {
4465 ValueDecl *VD = cast<ValueDecl>(D);
4466 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4467 VD->getLocation(),
4468 AnonRecord->isUnion())) {
4469 // C++ [class.union]p2:
4470 // The names of the members of an anonymous union shall be
4471 // distinct from the names of any other entity in the
4472 // scope in which the anonymous union is declared.
4473 Invalid = true;
4474 } else {
4475 // C++ [class.union]p2:
4476 // For the purpose of name lookup, after the anonymous union
4477 // definition, the members of the anonymous union are
4478 // considered to have been defined in the scope in which the
4479 // anonymous union is declared.
4480 unsigned OldChainingSize = Chaining.size();
4481 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4482 Chaining.append(IF->chain_begin(), IF->chain_end());
4483 else
4484 Chaining.push_back(VD);
4485
4486 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4486, __extension__ __PRETTY_FUNCTION__))
;
4487 NamedDecl **NamedChain =
4488 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4489 for (unsigned i = 0; i < Chaining.size(); i++)
4490 NamedChain[i] = Chaining[i];
4491
4492 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4493 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4494 VD->getType(), {NamedChain, Chaining.size()});
4495
4496 for (const auto *Attr : VD->attrs())
4497 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4498
4499 IndirectField->setAccess(AS);
4500 IndirectField->setImplicit();
4501 SemaRef.PushOnScopeChains(IndirectField, S);
4502
4503 // That includes picking up the appropriate access specifier.
4504 if (AS != AS_none) IndirectField->setAccess(AS);
4505
4506 Chaining.resize(OldChainingSize);
4507 }
4508 }
4509 }
4510
4511 return Invalid;
4512}
4513
4514/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4515/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4516/// illegal input values are mapped to SC_None.
4517static StorageClass
4518StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4519 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4520 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4521, __extension__ __PRETTY_FUNCTION__))
4521 "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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4521, __extension__ __PRETTY_FUNCTION__))
;
4522 switch (StorageClassSpec) {
4523 case DeclSpec::SCS_unspecified: return SC_None;
4524 case DeclSpec::SCS_extern:
4525 if (DS.isExternInLinkageSpec())
4526 return SC_None;
4527 return SC_Extern;
4528 case DeclSpec::SCS_static: return SC_Static;
4529 case DeclSpec::SCS_auto: return SC_Auto;
4530 case DeclSpec::SCS_register: return SC_Register;
4531 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4532 // Illegal SCSs map to None: error reporting is up to the caller.
4533 case DeclSpec::SCS_mutable: // Fall through.
4534 case DeclSpec::SCS_typedef: return SC_None;
4535 }
4536 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4536)
;
4537}
4538
4539static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4540 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4540, __extension__ __PRETTY_FUNCTION__))
;
4541
4542 for (const auto *I : Record->decls()) {
4543 const auto *FD = dyn_cast<FieldDecl>(I);
4544 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4545 FD = IFD->getAnonField();
4546 if (FD && FD->hasInClassInitializer())
4547 return FD->getLocation();
4548 }
4549
4550 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4550)
;
4551}
4552
4553static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4554 SourceLocation DefaultInitLoc) {
4555 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4556 return;
4557
4558 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4559 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4560}
4561
4562static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4563 CXXRecordDecl *AnonUnion) {
4564 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4565 return;
4566
4567 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4568}
4569
4570/// BuildAnonymousStructOrUnion - Handle the declaration of an
4571/// anonymous structure or union. Anonymous unions are a C++ feature
4572/// (C++ [class.union]) and a C11 feature; anonymous structures
4573/// are a C11 feature and GNU C++ extension.
4574Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4575 AccessSpecifier AS,
4576 RecordDecl *Record,
4577 const PrintingPolicy &Policy) {
4578 DeclContext *Owner = Record->getDeclContext();
4579
4580 // Diagnose whether this anonymous struct/union is an extension.
4581 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4582 Diag(Record->getLocation(), diag::ext_anonymous_union);
4583 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4584 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4585 else if (!Record->isUnion() && !getLangOpts().C11)
4586 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4587
4588 // C and C++ require different kinds of checks for anonymous
4589 // structs/unions.
4590 bool Invalid = false;
4591 if (getLangOpts().CPlusPlus) {
4592 const char *PrevSpec = nullptr;
4593 unsigned DiagID;
4594 if (Record->isUnion()) {
4595 // C++ [class.union]p6:
4596 // Anonymous unions declared in a named namespace or in the
4597 // global namespace shall be declared static.
4598 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4599 (isa<TranslationUnitDecl>(Owner) ||
4600 (isa<NamespaceDecl>(Owner) &&
4601 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4602 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4603 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4604
4605 // Recover by adding 'static'.
4606 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4607 PrevSpec, DiagID, Policy);
4608 }
4609 // C++ [class.union]p6:
4610 // A storage class is not allowed in a declaration of an
4611 // anonymous union in a class scope.
4612 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4613 isa<RecordDecl>(Owner)) {
4614 Diag(DS.getStorageClassSpecLoc(),
4615 diag::err_anonymous_union_with_storage_spec)
4616 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4617
4618 // Recover by removing the storage specifier.
4619 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4620 SourceLocation(),
4621 PrevSpec, DiagID, Context.getPrintingPolicy());
4622 }
4623 }
4624
4625 // Ignore const/volatile/restrict qualifiers.
4626 if (DS.getTypeQualifiers()) {
4627 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4628 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4629 << Record->isUnion() << "const"
4630 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4631 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4632 Diag(DS.getVolatileSpecLoc(),
4633 diag::ext_anonymous_struct_union_qualified)
4634 << Record->isUnion() << "volatile"
4635 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4636 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4637 Diag(DS.getRestrictSpecLoc(),
4638 diag::ext_anonymous_struct_union_qualified)
4639 << Record->isUnion() << "restrict"
4640 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4641 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4642 Diag(DS.getAtomicSpecLoc(),
4643 diag::ext_anonymous_struct_union_qualified)
4644 << Record->isUnion() << "_Atomic"
4645 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4646 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4647 Diag(DS.getUnalignedSpecLoc(),
4648 diag::ext_anonymous_struct_union_qualified)
4649 << Record->isUnion() << "__unaligned"
4650 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4651
4652 DS.ClearTypeQualifiers();
4653 }
4654
4655 // C++ [class.union]p2:
4656 // The member-specification of an anonymous union shall only
4657 // define non-static data members. [Note: nested types and
4658 // functions cannot be declared within an anonymous union. ]
4659 for (auto *Mem : Record->decls()) {
4660 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4661 // C++ [class.union]p3:
4662 // An anonymous union shall not have private or protected
4663 // members (clause 11).
4664 assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void
(0) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4664, __extension__ __PRETTY_FUNCTION__))
;
4665 if (FD->getAccess() != AS_public) {
4666 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4667 << Record->isUnion() << (FD->getAccess() == AS_protected);
4668 Invalid = true;
4669 }
4670
4671 // C++ [class.union]p1
4672 // An object of a class with a non-trivial constructor, a non-trivial
4673 // copy constructor, a non-trivial destructor, or a non-trivial copy
4674 // assignment operator cannot be a member of a union, nor can an
4675 // array of such objects.
4676 if (CheckNontrivialField(FD))
4677 Invalid = true;
4678 } else if (Mem->isImplicit()) {
4679 // Any implicit members are fine.
4680 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4681 // This is a type that showed up in an
4682 // elaborated-type-specifier inside the anonymous struct or
4683 // union, but which actually declares a type outside of the
4684 // anonymous struct or union. It's okay.
4685 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4686 if (!MemRecord->isAnonymousStructOrUnion() &&
4687 MemRecord->getDeclName()) {
4688 // Visual C++ allows type definition in anonymous struct or union.
4689 if (getLangOpts().MicrosoftExt)
4690 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4691 << Record->isUnion();
4692 else {
4693 // This is a nested type declaration.
4694 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4695 << Record->isUnion();
4696 Invalid = true;
4697 }
4698 } else {
4699 // This is an anonymous type definition within another anonymous type.
4700 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4701 // not part of standard C++.
4702 Diag(MemRecord->getLocation(),
4703 diag::ext_anonymous_record_with_anonymous_type)
4704 << Record->isUnion();
4705 }
4706 } else if (isa<AccessSpecDecl>(Mem)) {
4707 // Any access specifier is fine.
4708 } else if (isa<StaticAssertDecl>(Mem)) {
4709 // In C++1z, static_assert declarations are also fine.
4710 } else {
4711 // We have something that isn't a non-static data
4712 // member. Complain about it.
4713 unsigned DK = diag::err_anonymous_record_bad_member;
4714 if (isa<TypeDecl>(Mem))
4715 DK = diag::err_anonymous_record_with_type;
4716 else if (isa<FunctionDecl>(Mem))
4717 DK = diag::err_anonymous_record_with_function;
4718 else if (isa<VarDecl>(Mem))
4719 DK = diag::err_anonymous_record_with_static;
4720
4721 // Visual C++ allows type definition in anonymous struct or union.
4722 if (getLangOpts().MicrosoftExt &&
4723 DK == diag::err_anonymous_record_with_type)
4724 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4725 << Record->isUnion();
4726 else {
4727 Diag(Mem->getLocation(), DK) << Record->isUnion();
4728 Invalid = true;
4729 }
4730 }
4731 }
4732
4733 // C++11 [class.union]p8 (DR1460):
4734 // At most one variant member of a union may have a
4735 // brace-or-equal-initializer.
4736 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4737 Owner->isRecord())
4738 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4739 cast<CXXRecordDecl>(Record));
4740 }
4741
4742 if (!Record->isUnion() && !Owner->isRecord()) {
4743 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4744 << getLangOpts().CPlusPlus;
4745 Invalid = true;
4746 }
4747
4748 // Mock up a declarator.
4749 Declarator Dc(DS, DeclaratorContext::MemberContext);
4750 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4751 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4751, __extension__ __PRETTY_FUNCTION__))
;
4752
4753 // Create a declaration for this anonymous struct/union.
4754 NamedDecl *Anon = nullptr;
4755 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4756 Anon = FieldDecl::Create(Context, OwningClass,
4757 DS.getLocStart(),
4758 Record->getLocation(),
4759 /*IdentifierInfo=*/nullptr,
4760 Context.getTypeDeclType(Record),
4761 TInfo,
4762 /*BitWidth=*/nullptr, /*Mutable=*/false,
4763 /*InitStyle=*/ICIS_NoInit);
4764 Anon->setAccess(AS);
4765 if (getLangOpts().CPlusPlus)
4766 FieldCollector->Add(cast<FieldDecl>(Anon));
4767 } else {
4768 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4769 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4770 if (SCSpec == DeclSpec::SCS_mutable) {
4771 // mutable can only appear on non-static class members, so it's always
4772 // an error here
4773 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4774 Invalid = true;
4775 SC = SC_None;
4776 }
4777
4778 Anon = VarDecl::Create(Context, Owner,
4779 DS.getLocStart(),
4780 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4781 Context.getTypeDeclType(Record),
4782 TInfo, SC);
4783
4784 // Default-initialize the implicit variable. This initialization will be
4785 // trivial in almost all cases, except if a union member has an in-class
4786 // initializer:
4787 // union { int n = 0; };
4788 ActOnUninitializedDecl(Anon);
4789 }
4790 Anon->setImplicit();
4791
4792 // Mark this as an anonymous struct/union type.
4793 Record->setAnonymousStructOrUnion(true);
4794
4795 // Add the anonymous struct/union object to the current
4796 // context. We'll be referencing this object when we refer to one of
4797 // its members.
4798 Owner->addDecl(Anon);
4799
4800 // Inject the members of the anonymous struct/union into the owning
4801 // context and into the identifier resolver chain for name lookup
4802 // purposes.
4803 SmallVector<NamedDecl*, 2> Chain;
4804 Chain.push_back(Anon);
4805
4806 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4807 Invalid = true;
4808
4809 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4810 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4811 Decl *ManglingContextDecl;
4812 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4813 NewVD->getDeclContext(), ManglingContextDecl)) {
4814 Context.setManglingNumber(
4815 NewVD, MCtx->getManglingNumber(
4816 NewVD, getMSManglingNumber(getLangOpts(), S)));
4817 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4818 }
4819 }
4820 }
4821
4822 if (Invalid)
4823 Anon->setInvalidDecl();
4824
4825 return Anon;
4826}
4827
4828/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4829/// Microsoft C anonymous structure.
4830/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4831/// Example:
4832///
4833/// struct A { int a; };
4834/// struct B { struct A; int b; };
4835///
4836/// void foo() {
4837/// B var;
4838/// var.a = 3;
4839/// }
4840///
4841Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4842 RecordDecl *Record) {
4843 assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!"
) ? void (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4843, __extension__ __PRETTY_FUNCTION__))
;
4844
4845 // Mock up a declarator.
4846 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4847 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4848 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 4848, __extension__ __PRETTY_FUNCTION__))
;
4849
4850 auto *ParentDecl = cast<RecordDecl>(CurContext);
4851 QualType RecTy = Context.getTypeDeclType(Record);
4852
4853 // Create a declaration for this anonymous struct.
4854 NamedDecl *Anon = FieldDecl::Create(Context,
4855 ParentDecl,
4856 DS.getLocStart(),
4857 DS.getLocStart(),
4858 /*IdentifierInfo=*/nullptr,
4859 RecTy,
4860 TInfo,
4861 /*BitWidth=*/nullptr, /*Mutable=*/false,
4862 /*InitStyle=*/ICIS_NoInit);
4863 Anon->setImplicit();
4864
4865 // Add the anonymous struct object to the current context.
4866 CurContext->addDecl(Anon);
4867
4868 // Inject the members of the anonymous struct into the current
4869 // context and into the identifier resolver chain for name lookup
4870 // purposes.
4871 SmallVector<NamedDecl*, 2> Chain;
4872 Chain.push_back(Anon);
4873
4874 RecordDecl *RecordDef = Record->getDefinition();
4875 if (RequireCompleteType(Anon->getLocation(), RecTy,
4876 diag::err_field_incomplete) ||
4877 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4878 AS_none, Chain)) {
4879 Anon->setInvalidDecl();
4880 ParentDecl->setInvalidDecl();
4881 }
4882
4883 return Anon;
4884}
4885
4886/// GetNameForDeclarator - Determine the full declaration name for the
4887/// given Declarator.
4888DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4889 return GetNameFromUnqualifiedId(D.getName());
4890}
4891
4892/// \brief Retrieves the declaration name from a parsed unqualified-id.
4893DeclarationNameInfo
4894Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4895 DeclarationNameInfo NameInfo;
4896 NameInfo.setLoc(Name.StartLocation);
4897
4898 switch (Name.getKind()) {
4899
4900 case UnqualifiedIdKind::IK_ImplicitSelfParam:
4901 case UnqualifiedIdKind::IK_Identifier:
4902 NameInfo.setName(Name.Identifier);
4903 NameInfo.setLoc(Name.StartLocation);
4904 return NameInfo;
4905
4906 case UnqualifiedIdKind::IK_DeductionGuideName: {
4907 // C++ [temp.deduct.guide]p3:
4908 // The simple-template-id shall name a class template specialization.
4909 // The template-name shall be the same identifier as the template-name
4910 // of the simple-template-id.
4911 // These together intend to imply that the template-name shall name a
4912 // class template.
4913 // FIXME: template<typename T> struct X {};
4914 // template<typename T> using Y = X<T>;
4915 // Y(int) -> Y<int>;
4916 // satisfies these rules but does not name a class template.
4917 TemplateName TN = Name.TemplateName.get().get();
4918 auto *Template = TN.getAsTemplateDecl();
4919 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4920 Diag(Name.StartLocation,
4921 diag::err_deduction_guide_name_not_class_template)
4922 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4923 if (Template)
4924 Diag(Template->getLocation(), diag::note_template_decl_here);
4925 return DeclarationNameInfo();
4926 }
4927
4928 NameInfo.setName(
4929 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4930 NameInfo.setLoc(Name.StartLocation);
4931 return NameInfo;
4932 }
4933
4934 case UnqualifiedIdKind::IK_OperatorFunctionId:
4935 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4936 Name.OperatorFunctionId.Operator));
4937 NameInfo.setLoc(Name.StartLocation);
4938 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4939 = Name.OperatorFunctionId.SymbolLocations[0];
4940 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4941 = Name.EndLocation.getRawEncoding();
4942 return NameInfo;
4943
4944 case UnqualifiedIdKind::IK_LiteralOperatorId:
4945 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4946 Name.Identifier));
4947 NameInfo.setLoc(Name.StartLocation);
4948 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4949 return NameInfo;
4950
4951 case UnqualifiedIdKind::IK_ConversionFunctionId: {
4952 TypeSourceInfo *TInfo;
4953 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4954 if (Ty.isNull())
4955 return DeclarationNameInfo();
4956 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4957 Context.getCanonicalType(Ty)));
4958 NameInfo.setLoc(Name.StartLocation);
4959 NameInfo.setNamedTypeInfo(TInfo);
4960 return NameInfo;
4961 }
4962
4963 case UnqualifiedIdKind::IK_ConstructorName: {
4964 TypeSourceInfo *TInfo;
4965 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4966 if (Ty.isNull())
4967 return DeclarationNameInfo();
4968 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4969 Context.getCanonicalType(Ty)));
4970 NameInfo.setLoc(Name.StartLocation);
4971 NameInfo.setNamedTypeInfo(TInfo);
4972 return NameInfo;
4973 }
4974
4975 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
4976 // In well-formed code, we can only have a constructor
4977 // template-id that refers to the current context, so go there
4978 // to find the actual type being constructed.
4979 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4980 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4981 return DeclarationNameInfo();
4982
4983 // Determine the type of the class being constructed.
4984 QualType CurClassType = Context.getTypeDeclType(CurClass);
4985
4986 // FIXME: Check two things: that the template-id names the same type as
4987 // CurClassType, and that the template-id does not occur when the name
4988 // was qualified.
4989
4990 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4991 Context.getCanonicalType(CurClassType)));
4992 NameInfo.setLoc(Name.StartLocation);
4993 // FIXME: should we retrieve TypeSourceInfo?
4994 NameInfo.setNamedTypeInfo(nullptr);
4995 return NameInfo;
4996 }
4997
4998 case UnqualifiedIdKind::IK_DestructorName: {
4999 TypeSourceInfo *TInfo;
5000 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5001 if (Ty.isNull())
5002 return DeclarationNameInfo();
5003 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5004 Context.getCanonicalType(Ty)));
5005 NameInfo.setLoc(Name.StartLocation);
5006 NameInfo.setNamedTypeInfo(TInfo);
5007 return NameInfo;
5008 }
5009
5010 case UnqualifiedIdKind::IK_TemplateId: {
5011 TemplateName TName = Name.TemplateId->Template.get();
5012 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5013 return Context.getNameForTemplate(TName, TNameLoc);
5014 }
5015
5016 } // switch (Name.getKind())
5017
5018 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 5018)
;
5019}
5020
5021static QualType getCoreType(QualType Ty) {
5022 do {
5023 if (Ty->isPointerType() || Ty->isReferenceType())
5024 Ty = Ty->getPointeeType();
5025 else if (Ty->isArrayType())
5026 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5027 else
5028 return Ty.withoutLocalFastQualifiers();
5029 } while (true);
5030}
5031
5032/// hasSimilarParameters - Determine whether the C++ functions Declaration
5033/// and Definition have "nearly" matching parameters. This heuristic is
5034/// used to improve diagnostics in the case where an out-of-line function
5035/// definition doesn't match any declaration within the class or namespace.
5036/// Also sets Params to the list of indices to the parameters that differ
5037/// between the declaration and the definition. If hasSimilarParameters
5038/// returns true and Params is empty, then all of the parameters match.
5039static bool hasSimilarParameters(ASTContext &Context,
5040 FunctionDecl *Declaration,
5041 FunctionDecl *Definition,
5042 SmallVectorImpl<unsigned> &Params) {
5043 Params.clear();
5044 if (Declaration->param_size() != Definition->param_size())
5045 return false;
5046 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5047 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5048 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5049
5050 // The parameter types are identical
5051 if (Context.hasSameType(DefParamTy, DeclParamTy))
5052 continue;
5053
5054 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5055 QualType DefParamBaseTy = getCoreType(DefParamTy);
5056 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5057 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5058
5059 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5060 (DeclTyName && DeclTyName == DefTyName))
5061 Params.push_back(Idx);
5062 else // The two parameters aren't even close
5063 return false;
5064 }
5065
5066 return true;
5067}
5068
5069/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5070/// declarator needs to be rebuilt in the current instantiation.
5071/// Any bits of declarator which appear before the name are valid for
5072/// consideration here. That's specifically the type in the decl spec
5073/// and the base type in any member-pointer chunks.
5074static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5075 DeclarationName Name) {
5076 // The types we specifically need to rebuild are:
5077 // - typenames, typeofs, and decltypes
5078 // - types which will become injected class names
5079 // Of course, we also need to rebuild any type referencing such a
5080 // type. It's safest to just say "dependent", but we call out a
5081 // few cases here.
5082
5083 DeclSpec &DS = D.getMutableDeclSpec();
5084 switch (DS.getTypeSpecType()) {
5085 case DeclSpec::TST_typename:
5086 case DeclSpec::TST_typeofType:
5087 case DeclSpec::TST_underlyingType:
5088 case DeclSpec::TST_atomic: {
5089 // Grab the type from the parser.
5090 TypeSourceInfo *TSI = nullptr;
5091 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5092 if (T.isNull() || !T->isDependentType()) break;
5093
5094 // Make sure there's a type source info. This isn't really much
5095 // of a waste; most dependent types should have type source info
5096 // attached already.
5097 if (!TSI)
5098 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5099
5100 // Rebuild the type in the current instantiation.
5101 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5102 if (!TSI) return true;
5103
5104 // Store the new type back in the decl spec.
5105 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5106 DS.UpdateTypeRep(LocType);
5107 break;
5108 }
5109
5110 case DeclSpec::TST_decltype:
5111 case DeclSpec::TST_typeofExpr: {
5112 Expr *E = DS.getRepAsExpr();
5113 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5114 if (Result.isInvalid()) return true;
5115 DS.UpdateExprRep(Result.get());
5116 break;
5117 }
5118
5119 default:
5120 // Nothing to do for these decl specs.
5121 break;
5122 }
5123
5124 // It doesn't matter what order we do this in.
5125 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5126 DeclaratorChunk &Chunk = D.getTypeObject(I);
5127
5128 // The only type information in the declarator which can come
5129 // before the declaration name is the base type of a member
5130 // pointer.
5131 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5132 continue;
5133
5134 // Rebuild the scope specifier in-place.
5135 CXXScopeSpec &SS = Chunk.Mem.Scope();
5136 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5137 return true;
5138 }
5139
5140 return false;
5141}
5142
5143Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5144 D.setFunctionDefinitionKind(FDK_Declaration);
5145 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5146
5147 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5148 Dcl && Dcl->getDeclContext()->isFileContext())
5149 Dcl->setTopLevelDeclInObjCContainer();
5150
5151 if (getLangOpts().OpenCL)
5152 setCurrentOpenCLExtensionForDecl(Dcl);
5153
5154 return Dcl;
5155}
5156
5157/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5158/// If T is the name of a class, then each of the following shall have a
5159/// name different from T:
5160/// - every static data member of class T;
5161/// - every member function of class T
5162/// - every member of class T that is itself a type;
5163/// \returns true if the declaration name violates these rules.
5164bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5165 DeclarationNameInfo NameInfo) {
5166 DeclarationName Name = NameInfo.getName();
5167
5168 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5169 while (Record && Record->isAnonymousStructOrUnion())
5170 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5171 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5172 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5173 return true;
5174 }
5175
5176 return false;
5177}
5178
5179/// \brief Diagnose a declaration whose declarator-id has the given
5180/// nested-name-specifier.
5181///
5182/// \param SS The nested-name-specifier of the declarator-id.
5183///
5184/// \param DC The declaration context to which the nested-name-specifier
5185/// resolves.
5186///
5187/// \param Name The name of the entity being declared.
5188///
5189/// \param Loc The location of the name of the entity being declared.
5190///
5191/// \returns true if we cannot safely recover from this error, false otherwise.
5192bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5193 DeclarationName Name,
5194 SourceLocation Loc) {
5195 DeclContext *Cur = CurContext;
5196 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5197 Cur = Cur->getParent();
5198
5199 // If the user provided a superfluous scope specifier that refers back to the
5200 // class in which the entity is already declared, diagnose and ignore it.
5201 //
5202 // class X {
5203 // void X::f();
5204 // };
5205 //
5206 // Note, it was once ill-formed to give redundant qualification in all
5207 // contexts, but that rule was removed by DR482.
5208 if (Cur->Equals(DC)) {
5209 if (Cur->isRecord()) {
5210 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5211 : diag::err_member_extra_qualification)
5212 << Name << FixItHint::CreateRemoval(SS.getRange());
5213 SS.clear();
5214 } else {
5215 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5216 }
5217 return false;
5218 }
5219
5220 // Check whether the qualifying scope encloses the scope of the original
5221 // declaration.
5222 if (!Cur->Encloses(DC)) {
5223 if (Cur->isRecord())
5224 Diag(Loc, diag::err_member_qualification)
5225 << Name << SS.getRange();
5226 else if (isa<TranslationUnitDecl>(DC))
5227 Diag(Loc, diag::err_invalid_declarator_global_scope)
5228 << Name << SS.getRange();
5229 else if (isa<FunctionDecl>(Cur))
5230 Diag(Loc, diag::err_invalid_declarator_in_function)
5231 << Name << SS.getRange();
5232 else if (isa<BlockDecl>(Cur))
5233 Diag(Loc, diag::err_invalid_declarator_in_block)
5234 << Name << SS.getRange();
5235 else
5236 Diag(Loc, diag::err_invalid_declarator_scope)
5237 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5238
5239 return true;
5240 }
5241
5242 if (Cur->isRecord()) {
5243 // Cannot qualify members within a class.
5244 Diag(Loc, diag::err_member_qualification)
5245 << Name << SS.getRange();
5246 SS.clear();
5247
5248 // C++ constructors and destructors with incorrect scopes can break
5249 // our AST invariants by having the wrong underlying types. If
5250 // that's the case, then drop this declaration entirely.
5251 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5252 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5253 !Context.hasSameType(Name.getCXXNameType(),
5254 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5255 return true;
5256
5257 return false;
5258 }
5259
5260 // C++11 [dcl.meaning]p1:
5261 // [...] "The nested-name-specifier of the qualified declarator-id shall
5262 // not begin with a decltype-specifer"
5263 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5264 while (SpecLoc.getPrefix())
5265 SpecLoc = SpecLoc.getPrefix();
5266 if (dyn_cast_or_null<DecltypeType>(
5267 SpecLoc.getNestedNameSpecifier()->getAsType()))
5268 Diag(Loc, diag::err_decltype_in_declarator)
5269 << SpecLoc.getTypeLoc().getSourceRange();
5270
5271 return false;
5272}
5273
5274NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5275 MultiTemplateParamsArg TemplateParamLists) {
5276 // TODO: consider using NameInfo for diagnostic.
5277 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5278 DeclarationName Name = NameInfo.getName();
5279
5280 // All of these full declarators require an identifier. If it doesn't have
5281 // one, the ParsedFreeStandingDeclSpec action should be used.
5282 if (D.isDecompositionDeclarator()) {
5283 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5284 } else if (!Name) {
5285 if (!D.isInvalidType()) // Reject this if we think it is valid.
5286 Diag(D.getDeclSpec().getLocStart(),
5287 diag::err_declarator_need_ident)
5288 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5289 return nullptr;
5290 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5291 return nullptr;
5292
5293 // The scope passed in may not be a decl scope. Zip up the scope tree until
5294 // we find one that is.
5295 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5296 (S->getFlags() & Scope::TemplateParamScope) != 0)
5297 S = S->getParent();
5298
5299 DeclContext *DC = CurContext;
5300 if (D.getCXXScopeSpec().isInvalid())
5301 D.setInvalidType();
5302 else if (D.getCXXScopeSpec().isSet()) {
5303 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5304 UPPC_DeclarationQualifier))
5305 return nullptr;
5306
5307 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5308 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5309 if (!DC || isa<EnumDecl>(DC)) {
5310 // If we could not compute the declaration context, it's because the
5311 // declaration context is dependent but does not refer to a class,
5312 // class template, or class template partial specialization. Complain
5313 // and return early, to avoid the coming semantic disaster.
5314 Diag(D.getIdentifierLoc(),
5315 diag::err_template_qualified_declarator_no_match)
5316 << D.getCXXScopeSpec().getScopeRep()
5317 << D.getCXXScopeSpec().getRange();
5318 return nullptr;
5319 }
5320 bool IsDependentContext = DC->isDependentContext();
5321
5322 if (!IsDependentContext &&
5323 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5324 return nullptr;
5325
5326 // If a class is incomplete, do not parse entities inside it.
5327 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5328 Diag(D.getIdentifierLoc(),
5329 diag::err_member_def_undefined_record)
5330 << Name << DC << D.getCXXScopeSpec().getRange();
5331 return nullptr;
5332 }
5333 if (!D.getDeclSpec().isFriendSpecified()) {
5334 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5335 Name, D.getIdentifierLoc())) {
5336 if (DC->isRecord())
5337 return nullptr;
5338
5339 D.setInvalidType();
5340 }
5341 }
5342
5343 // Check whether we need to rebuild the type of the given
5344 // declaration in the current instantiation.
5345 if (EnteringContext && IsDependentContext &&
5346 TemplateParamLists.size() != 0) {
5347 ContextRAII SavedContext(*this, DC);
5348 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5349 D.setInvalidType();
5350 }
5351 }
5352
5353 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5354 QualType R = TInfo->getType();
5355
5356 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5357 UPPC_DeclarationType))
5358 D.setInvalidType();
5359
5360 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5361 forRedeclarationInCurContext());
5362
5363 // See if this is a redefinition of a variable in the same scope.
5364 if (!D.getCXXScopeSpec().isSet()) {
5365 bool IsLinkageLookup = false;
5366 bool CreateBuiltins = false;
5367
5368 // If the declaration we're planning to build will be a function
5369 // or object with linkage, then look for another declaration with
5370 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5371 //
5372 // If the declaration we're planning to build will be declared with
5373 // external linkage in the translation unit, create any builtin with
5374 // the same name.
5375 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5376 /* Do nothing*/;
5377 else if (CurContext->isFunctionOrMethod() &&
5378 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5379 R->isFunctionType())) {
5380 IsLinkageLookup = true;
5381 CreateBuiltins =
5382 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5383 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5384 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5385 CreateBuiltins = true;
5386
5387 if (IsLinkageLookup) {
5388 Previous.clear(LookupRedeclarationWithLinkage);
5389 Previous.setRedeclarationKind(ForExternalRedeclaration);
5390 }
5391
5392 LookupName(Previous, S, CreateBuiltins);
5393 } else { // Something like "int foo::x;"
5394 LookupQualifiedName(Previous, DC);
5395
5396 // C++ [dcl.meaning]p1:
5397 // When the declarator-id is qualified, the declaration shall refer to a
5398 // previously declared member of the class or namespace to which the
5399 // qualifier refers (or, in the case of a namespace, of an element of the
5400 // inline namespace set of that namespace (7.3.1)) or to a specialization
5401 // thereof; [...]
5402 //
5403 // Note that we already checked the context above, and that we do not have
5404 // enough information to make sure that Previous contains the declaration
5405 // we want to match. For example, given:
5406 //
5407 // class X {
5408 // void f();
5409 // void f(float);
5410 // };
5411 //
5412 // void X::f(int) { } // ill-formed
5413 //
5414 // In this case, Previous will point to the overload set
5415 // containing the two f's declared in X, but neither of them
5416 // matches.
5417
5418 // C++ [dcl.meaning]p1:
5419 // [...] the member shall not merely have been introduced by a
5420 // using-declaration in the scope of the class or namespace nominated by
5421 // the nested-name-specifier of the declarator-id.
5422 RemoveUsingDecls(Previous);
5423 }
5424
5425 if (Previous.isSingleResult() &&
5426 Previous.getFoundDecl()->isTemplateParameter()) {
5427 // Maybe we will complain about the shadowed template parameter.
5428 if (!D.isInvalidType())
5429 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5430 Previous.getFoundDecl());
5431
5432 // Just pretend that we didn't see the previous declaration.
5433 Previous.clear();
5434 }
5435
5436 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5437 // Forget that the previous declaration is the injected-class-name.
5438 Previous.clear();
5439
5440 // In C++, the previous declaration we find might be a tag type
5441 // (class or enum). In this case, the new declaration will hide the
5442 // tag type. Note that this applies to functions, function templates, and
5443 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5444 if (Previous.isSingleTagDecl() &&
5445 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5446 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5447 Previous.clear();
5448
5449 // Check that there are no default arguments other than in the parameters
5450 // of a function declaration (C++ only).
5451 if (getLangOpts().CPlusPlus)
5452 CheckExtraCXXDefaultArguments(D);
5453
5454 NamedDecl *New;
5455
5456 bool AddToScope = true;
5457 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5458 if (TemplateParamLists.size()) {
5459 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5460 return nullptr;
5461 }
5462
5463 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5464 } else if (R->isFunctionType()) {
5465 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5466 TemplateParamLists,
5467 AddToScope);
5468 } else {
5469 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5470 AddToScope);
5471 }
5472
5473 if (!New)
5474 return nullptr;
5475
5476 // If this has an identifier and is not a function template specialization,
5477 // add it to the scope stack.
5478 if (New->getDeclName() && AddToScope) {
5479 // Only make a locally-scoped extern declaration visible if it is the first
5480 // declaration of this entity. Qualified lookup for such an entity should
5481 // only find this declaration if there is no visible declaration of it.
5482 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5483 PushOnScopeChains(New, S, AddToContext);
5484 if (!AddToContext)
5485 CurContext->addHiddenDecl(New);
5486 }
5487
5488 if (isInOpenMPDeclareTargetContext())
5489 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5490
5491 return New;
5492}
5493
5494/// Helper method to turn variable array types into constant array
5495/// types in certain situations which would otherwise be errors (for
5496/// GCC compatibility).
5497static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5498 ASTContext &Context,
5499 bool &SizeIsNegative,
5500 llvm::APSInt &Oversized) {
5501 // This method tries to turn a variable array into a constant
5502 // array even when the size isn't an ICE. This is necessary
5503 // for compatibility with code that depends on gcc's buggy
5504 // constant expression folding, like struct {char x[(int)(char*)2];}
5505 SizeIsNegative = false;
5506 Oversized = 0;
5507
5508 if (T->isDependentType())
5509 return QualType();
5510
5511 QualifierCollector Qs;
5512 const Type *Ty = Qs.strip(T);
5513
5514 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5515 QualType Pointee = PTy->getPointeeType();
5516 QualType FixedType =
5517 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5518 Oversized);
5519 if (FixedType.isNull()) return FixedType;
5520 FixedType = Context.getPointerType(FixedType);
5521 return Qs.apply(Context, FixedType);
5522 }
5523 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5524 QualType Inner = PTy->getInnerType();
5525 QualType FixedType =
5526 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5527 Oversized);
5528 if (FixedType.isNull()) return FixedType;
5529 FixedType = Context.getParenType(FixedType);
5530 return Qs.apply(Context, FixedType);
5531 }
5532
5533 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5534 if (!VLATy)
5535 return QualType();
5536 // FIXME: We should probably handle this case
5537 if (VLATy->getElementType()->isVariablyModifiedType())
5538 return QualType();
5539
5540 llvm::APSInt Res;
5541 if (!VLATy->getSizeExpr() ||
5542 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5543 return QualType();
5544
5545 // Check whether the array size is negative.
5546 if (Res.isSigned() && Res.isNegative()) {
5547 SizeIsNegative = true;
5548 return QualType();
5549 }
5550
5551 // Check whether the array is too large to be addressed.
5552 unsigned ActiveSizeBits
5553 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5554 Res);
5555 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5556 Oversized = Res;
5557 return QualType();
5558 }
5559
5560 return Context.getConstantArrayType(VLATy->getElementType(),
5561 Res, ArrayType::Normal, 0);
5562}
5563
5564static void
5565FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5566 SrcTL = SrcTL.getUnqualifiedLoc();
5567 DstTL = DstTL.getUnqualifiedLoc();
5568 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5569 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5570 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5571 DstPTL.getPointeeLoc());
5572 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5573 return;
5574 }
5575 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5576 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5577 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5578 DstPTL.getInnerLoc());
5579 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5580 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5581 return;
5582 }
5583 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5584 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5585 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5586 TypeLoc DstElemTL = DstATL.getElementLoc();
5587 DstElemTL.initializeFullCopy(SrcElemTL);
5588 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5589 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5590 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5591}
5592
5593/// Helper method to turn variable array types into constant array
5594/// types in certain situations which would otherwise be errors (for
5595/// GCC compatibility).
5596static TypeSourceInfo*
5597TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5598 ASTContext &Context,
5599 bool &SizeIsNegative,
5600 llvm::APSInt &Oversized) {
5601 QualType FixedTy
5602 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5603 SizeIsNegative, Oversized);
5604 if (FixedTy.isNull())
5605 return nullptr;
5606 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5607 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5608 FixedTInfo->getTypeLoc());
5609 return FixedTInfo;
5610}
5611
5612/// \brief Register the given locally-scoped extern "C" declaration so
5613/// that it can be found later for redeclarations. We include any extern "C"
5614/// declaration that is not visible in the translation unit here, not just
5615/// function-scope declarations.
5616void
5617Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5618 if (!getLangOpts().CPlusPlus &&
5619 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5620 // Don't need to track declarations in the TU in C.
5621 return;
5622
5623 // Note that we have a locally-scoped external with this name.
5624 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5625}
5626
5627NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5628 // FIXME: We can have multiple results via __attribute__((overloadable)).
5629 auto Result = Context.getExternCContextDecl()->lookup(Name);
5630 return Result.empty() ? nullptr : *Result.begin();
5631}
5632
5633/// \brief Diagnose function specifiers on a declaration of an identifier that
5634/// does not identify a function.
5635void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5636 // FIXME: We should probably indicate the identifier in question to avoid
5637 // confusion for constructs like "virtual int a(), b;"
5638 if (DS.isVirtualSpecified())
5639 Diag(DS.getVirtualSpecLoc(),
5640 diag::err_virtual_non_function);
5641
5642 if (DS.isExplicitSpecified())
5643 Diag(DS.getExplicitSpecLoc(),
5644 diag::err_explicit_non_function);
5645
5646 if (DS.isNoreturnSpecified())
5647 Diag(DS.getNoreturnSpecLoc(),
5648 diag::err_noreturn_non_function);
5649}
5650
5651NamedDecl*
5652Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5653 TypeSourceInfo *TInfo, LookupResult &Previous) {
5654 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5655 if (D.getCXXScopeSpec().isSet()) {
5656 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5657 << D.getCXXScopeSpec().getRange();
5658 D.setInvalidType();
5659 // Pretend we didn't see the scope specifier.
5660 DC = CurContext;
5661 Previous.clear();
5662 }
5663
5664 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5665
5666 if (D.getDeclSpec().isInlineSpecified())
5667 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5668 << getLangOpts().CPlusPlus17;
5669 if (D.getDeclSpec().isConstexprSpecified())
5670 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5671 << 1;
5672
5673 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5674 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5675 Diag(D.getName().StartLocation,
5676 diag::err_deduction_guide_invalid_specifier)
5677 << "typedef";
5678 else
5679 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5680 << D.getName().getSourceRange();
5681 return nullptr;
5682 }
5683
5684 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5685 if (!NewTD) return nullptr;
5686
5687 // Handle attributes prior to checking for duplicates in MergeVarDecl
5688 ProcessDeclAttributes(S, NewTD, D);
5689
5690 CheckTypedefForVariablyModifiedType(S, NewTD);
5691
5692 bool Redeclaration = D.isRedeclaration();
5693 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5694 D.setRedeclaration(Redeclaration);
5695 return ND;
5696}
5697
5698void
5699Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5700 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5701 // then it shall have block scope.
5702 // Note that variably modified types must be fixed before merging the decl so
5703 // that redeclarations will match.
5704 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5705 QualType T = TInfo->getType();
5706 if (T->isVariablyModifiedType()) {
5707 getCurFunction()->setHasBranchProtectedScope();
5708
5709 if (S->getFnParent() == nullptr) {
5710 bool SizeIsNegative;
5711 llvm::APSInt Oversized;
5712 TypeSourceInfo *FixedTInfo =
5713 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5714 SizeIsNegative,
5715 Oversized);
5716 if (FixedTInfo) {
5717 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5718 NewTD->setTypeSourceInfo(FixedTInfo);
5719 } else {
5720 if (SizeIsNegative)
5721 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5722 else if (T->isVariableArrayType())
5723 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5724 else if (Oversized.getBoolValue())
5725 Diag(NewTD->getLocation(), diag::err_array_too_large)
5726 << Oversized.toString(10);
5727 else
5728 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5729 NewTD->setInvalidDecl();
5730 }
5731 }
5732 }
5733}
5734
5735/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5736/// declares a typedef-name, either using the 'typedef' type specifier or via
5737/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5738NamedDecl*
5739Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5740 LookupResult &Previous, bool &Redeclaration) {
5741
5742 // Find the shadowed declaration before filtering for scope.
5743 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5744
5745 // Merge the decl with the existing one if appropriate. If the decl is
5746 // in an outer scope, it isn't the same thing.
5747 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5748 /*AllowInlineNamespace*/false);
5749 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5750 if (!Previous.empty()) {
5751 Redeclaration = true;
5752 MergeTypedefNameDecl(S, NewTD, Previous);
5753 }
5754
5755 if (ShadowedDecl && !Redeclaration)
5756 CheckShadow(NewTD, ShadowedDecl, Previous);
5757
5758 // If this is the C FILE type, notify the AST context.
5759 if (IdentifierInfo *II = NewTD->getIdentifier())
5760 if (!NewTD->isInvalidDecl() &&
5761 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5762 if (II->isStr("FILE"))
5763 Context.setFILEDecl(NewTD);
5764 else if (II->isStr("jmp_buf"))
5765 Context.setjmp_bufDecl(NewTD);
5766 else if (II->isStr("sigjmp_buf"))
5767 Context.setsigjmp_bufDecl(NewTD);
5768 else if (II->isStr("ucontext_t"))
5769 Context.setucontext_tDecl(NewTD);
5770 }
5771
5772 return NewTD;
5773}
5774
5775/// \brief Determines whether the given declaration is an out-of-scope
5776/// previous declaration.
5777///
5778/// This routine should be invoked when name lookup has found a
5779/// previous declaration (PrevDecl) that is not in the scope where a
5780/// new declaration by the same name is being introduced. If the new
5781/// declaration occurs in a local scope, previous declarations with
5782/// linkage may still be considered previous declarations (C99
5783/// 6.2.2p4-5, C++ [basic.link]p6).
5784///
5785/// \param PrevDecl the previous declaration found by name
5786/// lookup
5787///
5788/// \param DC the context in which the new declaration is being
5789/// declared.
5790///
5791/// \returns true if PrevDecl is an out-of-scope previous declaration
5792/// for a new delcaration with the same name.
5793static bool
5794isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5795 ASTContext &Context) {
5796 if (!PrevDecl)
5797 return false;
5798
5799 if (!PrevDecl->hasLinkage())
5800 return false;
5801
5802 if (Context.getLangOpts().CPlusPlus) {
5803 // C++ [basic.link]p6:
5804 // If there is a visible declaration of an entity with linkage
5805 // having the same name and type, ignoring entities declared
5806 // outside the innermost enclosing namespace scope, the block
5807 // scope declaration declares that same entity and receives the
5808 // linkage of the previous declaration.
5809 DeclContext *OuterContext = DC->getRedeclContext();
5810 if (!OuterContext->isFunctionOrMethod())
5811 // This rule only applies to block-scope declarations.
5812 return false;
5813
5814 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5815 if (PrevOuterContext->isRecord())
5816 // We found a member function: ignore it.
5817 return false;
5818
5819 // Find the innermost enclosing namespace for the new and
5820 // previous declarations.
5821 OuterContext = OuterContext->getEnclosingNamespaceContext();
5822 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5823
5824 // The previous declaration is in a different namespace, so it
5825 // isn't the same function.
5826 if (!OuterContext->Equals(PrevOuterContext))
5827 return false;
5828 }
5829
5830 return true;
5831}
5832
5833static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5834 CXXScopeSpec &SS = D.getCXXScopeSpec();
5835 if (!SS.isSet()) return;
5836 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5837}
5838
5839bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5840 QualType type = decl->getType();
5841 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5842 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5843 // Various kinds of declaration aren't allowed to be __autoreleasing.
5844 unsigned kind = -1U;
5845 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5846 if (var->hasAttr<BlocksAttr>())
5847 kind = 0; // __block
5848 else if (!var->hasLocalStorage())
5849 kind = 1; // global
5850 } else if (isa<ObjCIvarDecl>(decl)) {
5851 kind = 3; // ivar
5852 } else if (isa<FieldDecl>(decl)) {
5853 kind = 2; // field
5854 }
5855
5856 if (kind != -1U) {
5857 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5858 << kind;
5859 }
5860 } else if (lifetime == Qualifiers::OCL_None) {
5861 // Try to infer lifetime.
5862 if (!type->isObjCLifetimeType())
5863 return false;
5864
5865 lifetime = type->getObjCARCImplicitLifetime();
5866 type = Context.getLifetimeQualifiedType(type, lifetime);
5867 decl->setType(type);
5868 }
5869
5870 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5871 // Thread-local variables cannot have lifetime.
5872 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5873 var->getTLSKind()) {
5874 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5875 << var->getType();
5876 return true;
5877 }
5878 }
5879
5880 return false;
5881}
5882
5883static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5884 // Ensure that an auto decl is deduced otherwise the checks below might cache
5885 // the wrong linkage.
5886 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 5886, __extension__ __PRETTY_FUNCTION__))
;
5887
5888 // 'weak' only applies to declarations with external linkage.
5889 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5890 if (!ND.isExternallyVisible()) {
5891 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5892 ND.dropAttr<WeakAttr>();
5893 }
5894 }
5895 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5896 if (ND.isExternallyVisible()) {
5897 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5898 ND.dropAttr<WeakRefAttr>();
5899 ND.dropAttr<AliasAttr>();
5900 }
5901 }
5902
5903 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5904 if (VD->hasInit()) {
5905 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5906 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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 5907, __extension__ __PRETTY_FUNCTION__))
5907 !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-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 5907, __extension__ __PRETTY_FUNCTION__))
;
5908 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5909 VD->dropAttr<AliasAttr>();
5910 }
5911 }
5912 }
5913
5914 // 'selectany' only applies to externally visible variable declarations.
5915 // It does not apply to functions.
5916 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5917 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5918 S.Diag(Attr->getLocation(),
5919 diag::err_attribute_selectany_non_extern_data);
5920 ND.dropAttr<SelectAnyAttr>();
5921 }
5922 }
5923
5924 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5925 // dll attributes require external linkage. Static locals may have external
5926 // linkage but still cannot be explicitly imported or exported.
5927 auto *VD = dyn_cast<VarDecl>(&ND);
5928 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5929 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5930 << &ND << Attr;
5931 ND.setInvalidDecl();
5932 }
5933 }
5934
5935 // Virtual functions cannot be marked as 'notail'.
5936 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5937 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5938 if (MD->isVirtual()) {
5939 S.Diag(ND.getLocation(),
5940 diag::err_invalid_attribute_on_virtual_function)
5941 << Attr;
5942 ND.dropAttr<NotTailCalledAttr>();
5943 }
5944}
5945
5946static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5947 NamedDecl *NewDecl,
5948 bool IsSpecialization,
5949 bool IsDefinition) {
5950 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
5951 return;
5952
5953 bool IsTemplate = false;
5954 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5955 OldDecl = OldTD->getTemplatedDecl();
5956 IsTemplate = true;
5957 if (!IsSpecialization)
5958 IsDefinition = false;
5959 }
5960 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5961 NewDecl = NewTD->getTemplatedDecl();
5962 IsTemplate = true;
5963 }
5964
5965 if (!OldDecl || !NewDecl)
5966 return;
5967
5968 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5969 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5970 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5971 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5972
5973 // dllimport and dllexport are inheritable attributes so we have to exclude
5974 // inherited attribute instances.
5975 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5976 (NewExportAttr && !NewExportAttr->isInherited());
5977
5978 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5979 // the only exception being explicit specializations.
5980 // Implicitly generated declarations are also excluded for now because there
5981 // is no other way to switch these to use dllimport or dllexport.
5982 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5983
5984 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5985 // Allow with a warning for free functions and global variables.
5986 bool JustWarn = false;
5987 if (!OldDecl->isCXXClassMember()) {
5988 auto *VD = dyn_cast<VarDecl>(OldDecl);
5989 if (VD && !VD->getDescribedVarTemplate())
5990 JustWarn = true;
5991 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5992 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5993 JustWarn = true;
5994 }
5995
5996 // We cannot change a declaration that's been used because IR has already
5997 // been emitted. Dllimported functions will still work though (modulo
5998 // address equality) as they can use the thunk.
5999 if (OldDecl->isUsed())
6000 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6001 JustWarn = false;
6002
6003 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6004 : diag::err_attribute_dll_redeclaration;
6005 S.Diag(NewDecl->getLocation(), DiagID)
6006 << NewDecl
6007 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6008 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6009 if (!JustWarn) {
6010 NewDecl->setInvalidDecl();
6011 return;
6012 }
6013 }
6014
6015 // A redeclaration is not allowed to drop a dllimport attribute, the only
6016 // exceptions being inline function definitions (except for function
6017 // templates), local extern declarations, qualified friend declarations or
6018 // special MSVC extension: in the last case, the declaration is treated as if
6019 // it were marked dllexport.
6020 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6021 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6022 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6023 // Ignore static data because out-of-line definitions are diagnosed
6024 // separately.
6025 IsStaticDataMember = VD->isStaticDataMember();
6026 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6027 VarDecl::DeclarationOnly;
6028 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6029 IsInline = FD->isInlined();
6030 IsQualifiedFriend = FD->getQualifier() &&
6031 FD->getFriendObjectKind() == Decl::FOK_Declared;
6032 }
6033
6034 if (OldImportAttr && !HasNewAttr &&
6035 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6036 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6037 if (IsMicrosoft && IsDefinition) {
6038 S.Diag(NewDecl->getLocation(),
6039 diag::warn_redeclaration_without_import_attribute)
6040 << NewDecl;
6041 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6042 NewDecl->dropAttr<DLLImportAttr>();
6043 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6044 NewImportAttr->getRange(), S.Context,
6045 NewImportAttr->getSpellingListIndex()));
6046 } else {
6047 S.Diag(NewDecl->getLocation(),
6048 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6049 << NewDecl << OldImportAttr;
6050 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6051 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6052 OldDecl->dropAttr<DLLImportAttr>();
6053 NewDecl->dropAttr<DLLImportAttr>();
6054 }
6055 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6056 // In MinGW, seeing a function declared inline drops the dllimport
6057 // attribute.
6058 OldDecl->dropAttr<DLLImportAttr>();
6059 NewDecl->dropAttr<DLLImportAttr>();
6060 S.Diag(NewDecl->getLocation(),
6061 diag::warn_dllimport_dropped_from_inline_function)
6062 << NewDecl << OldImportAttr;
6063 }
6064
6065 // A specialization of a class template member function is processed here
6066 // since it's a redeclaration. If the parent class is dllexport, the
6067 // specialization inherits that attribute. This doesn't happen automatically
6068 // since the parent class isn't instantiated until later.
6069 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6070 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6071 !NewImportAttr && !NewExportAttr) {
6072 if (const DLLExportAttr *ParentExportAttr =
6073 MD->getParent()->getAttr<DLLExportAttr>()) {
6074 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6075 NewAttr->setInherited(true);
6076 NewDecl->addAttr(NewAttr);
6077 }
6078 }
6079 }
6080}
6081
6082/// Given that we are within the definition of the given function,
6083/// will that definition behave like C99's 'inline', where the
6084/// definition is discarded except for optimization purposes?
6085static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6086 // Try to avoid calling GetGVALinkageForFunction.
6087
6088 // All cases of this require the 'inline' keyword.
6089 if (!FD->isInlined()) return false;
6090
6091 // This is only possible in C++ with the gnu_inline attribute.
6092 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6093 return false;
6094
6095 // Okay, go ahead and call the relatively-more-expensive function.
6096 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6097}
6098
6099/// Determine whether a variable is extern "C" prior to attaching
6100/// an initializer. We can't just call isExternC() here, because that
6101/// will also compute and cache whether the declaration is externally
6102/// visible, which might change when we attach the initializer.
6103///
6104/// This can only be used if the declaration is known to not be a
6105/// redeclaration of an internal linkage declaration.
6106///
6107/// For instance:
6108///
6109/// auto x = []{};
6110///
6111/// Attaching the initializer here makes this declaration not externally
6112/// visible, because its type has internal linkage.
6113///
6114/// FIXME: This is a hack.
6115template<typename T>
6116static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6117 if (S.getLangOpts().CPlusPlus) {
6118 // In C++, the overloadable attribute negates the effects of extern "C".
6119 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6120 return false;
6121
6122 // So do CUDA's host/device attributes.
6123 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6124 D->template hasAttr<CUDAHostAttr>()))
6125 return false;
6126 }
6127 return D->isExternC();
6128}
6129
6130static bool shouldConsiderLinkage(const VarDecl *VD) {
6131 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6132 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6133 return VD->hasExternalStorage();
6134 if (DC->isFileContext())
6135 return true;
6136 if (DC->isRecord())
6137 return false;
6138 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6138)
;
6139}
6140
6141static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6142 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6143 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6144 isa<OMPDeclareReductionDecl>(DC))
6145 return true;
6146 if (DC->isRecord())
6147 return false;
6148 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6148)
;
6149}
6150
6151static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6152 AttributeList::Kind Kind) {
6153 for (const AttributeList *L = AttrList; L; L = L->getNext())
6154 if (L->getKind() == Kind)
6155 return true;
6156 return false;
6157}
6158
6159static bool hasParsedAttr(Scope *S, const Declarator &PD,
6160 AttributeList::Kind Kind) {
6161 // Check decl attributes on the DeclSpec.
6162 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6163 return true;
6164
6165 // Walk the declarator structure, checking decl attributes that were in a type
6166 // position to the decl itself.
6167 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6168 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6169 return true;
6170 }
6171
6172 // Finally, check attributes on the decl itself.
6173 return hasParsedAttr(S, PD.getAttributes(), Kind);
6174}
6175
6176/// Adjust the \c DeclContext for a function or variable that might be a
6177/// function-local external declaration.
6178bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6179 if (!DC->isFunctionOrMethod())
6180 return false;
6181
6182 // If this is a local extern function or variable declared within a function
6183 // template, don't add it into the enclosing namespace scope until it is
6184 // instantiated; it might have a dependent type right now.
6185 if (DC->isDependentContext())
6186 return true;
6187
6188 // C++11 [basic.link]p7:
6189 // When a block scope declaration of an entity with linkage is not found to
6190 // refer to some other declaration, then that entity is a member of the
6191 // innermost enclosing namespace.
6192 //
6193 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6194 // semantically-enclosing namespace, not a lexically-enclosing one.
6195 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6196 DC = DC->getParent();
6197 return true;
6198}
6199
6200/// \brief Returns true if given declaration has external C language linkage.
6201static bool isDeclExternC(const Decl *D) {
6202 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6203 return FD->isExternC();
6204 if (const auto *VD = dyn_cast<VarDecl>(D))
6205 return VD->isExternC();
6206
6207 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6207)
;
6208}
6209
6210NamedDecl *Sema::ActOnVariableDeclarator(
6211 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6212 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6213 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6214 QualType R = TInfo->getType();
6215 DeclarationName Name = GetNameForDeclarator(D).getName();
6216
6217 IdentifierInfo *II = Name.getAsIdentifierInfo();
6218
6219 if (D.isDecompositionDeclarator()) {
6220 // Take the name of the first declarator as our name for diagnostic
6221 // purposes.
6222 auto &Decomp = D.getDecompositionDeclarator();
6223 if (!Decomp.bindings().empty()) {
6224 II = Decomp.bindings()[0].Name;
6225 Name = II;
6226 }
6227 } else if (!II) {
6228 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6229 return nullptr;
6230 }
6231
6232 if (getLangOpts().OpenCL) {
6233 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6234 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6235 // argument.
6236 if (R->isImageType() || R->isPipeType()) {
6237 Diag(D.getIdentifierLoc(),
6238 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6239 << R;
6240 D.setInvalidType();
6241 return nullptr;
6242 }
6243
6244 // OpenCL v1.2 s6.9.r:
6245 // The event type cannot be used to declare a program scope variable.
6246 // OpenCL v2.0 s6.9.q:
6247 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6248 if (NULL__null == S->getParent()) {
6249 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6250 Diag(D.getIdentifierLoc(),
6251 diag::err_invalid_type_for_program_scope_var) << R;
6252 D.setInvalidType();
6253 return nullptr;
6254 }
6255 }
6256
6257 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6258 QualType NR = R;
6259 while (NR->isPointerType()) {
6260 if (NR->isFunctionPointerType()) {
6261 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6262 D.setInvalidType();
6263 break;
6264 }
6265 NR = NR->getPointeeType();
6266 }
6267
6268 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6269 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6270 // half array type (unless the cl_khr_fp16 extension is enabled).
6271 if (Context.getBaseElementType(R)->isHalfType()) {
6272 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6273 D.setInvalidType();
6274 }
6275 }
6276
6277 if (R->isSamplerT()) {
6278 // OpenCL v1.2 s6.9.b p4:
6279 // The sampler type cannot be used with the __local and __global address
6280 // space qualifiers.
6281 if (R.getAddressSpace() == LangAS::opencl_local ||
6282 R.getAddressSpace() == LangAS::opencl_global) {
6283 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6284 }
6285
6286 // OpenCL v1.2 s6.12.14.1:
6287 // A global sampler must be declared with either the constant address
6288 // space qualifier or with the const qualifier.
6289 if (DC->isTranslationUnit() &&
6290 !(R.getAddressSpace() == LangAS::opencl_constant ||
6291 R.isConstQualified())) {
6292 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6293 D.setInvalidType();
6294 }
6295 }
6296
6297 // OpenCL v1.2 s6.9.r:
6298 // The event type cannot be used with the __local, __constant and __global
6299 // address space qualifiers.
6300 if (R->isEventT()) {
6301 if (R.getAddressSpace() != LangAS::opencl_private) {
6302 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6303 D.setInvalidType();
6304 }
6305 }
6306 }
6307
6308 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6309 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6310
6311 // dllimport globals without explicit storage class are treated as extern. We
6312 // have to change the storage class this early to get the right DeclContext.
6313 if (SC == SC_None && !DC->isRecord() &&
6314 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6315 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6316 SC = SC_Extern;
6317
6318 DeclContext *OriginalDC = DC;
6319 bool IsLocalExternDecl = SC == SC_Extern &&
6320 adjustContextForLocalExternDecl(DC);
6321
6322 if (SCSpec == DeclSpec::SCS_mutable) {
6323 // mutable can only appear on non-static class members, so it's always
6324 // an error here
6325 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6326 D.setInvalidType();
6327 SC = SC_None;
6328 }
6329
6330 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6331 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6332 D.getDeclSpec().getStorageClassSpecLoc())) {
6333 // In C++11, the 'register' storage class specifier is deprecated.
6334 // Suppress the warning in system macros, it's used in macros in some
6335 // popular C system headers, such as in glibc's htonl() macro.
6336 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6337 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6338 : diag::warn_deprecated_register)
6339 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6340 }
6341
6342 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6343
6344 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6345 // C99 6.9p2: The storage-class specifiers auto and register shall not
6346 // appear in the declaration specifiers in an external declaration.
6347 // Global Register+Asm is a GNU extension we support.
6348 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6349 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6350 D.setInvalidType();
6351 }
6352 }
6353
6354 bool IsMemberSpecialization = false;
6355 bool IsVariableTemplateSpecialization = false;
6356 bool IsPartialSpecialization = false;
6357 bool IsVariableTemplate = false;
6358 VarDecl *NewVD = nullptr;
6359 VarTemplateDecl *NewTemplate = nullptr;
6360 TemplateParameterList *TemplateParams = nullptr;
6361 if (!getLangOpts().CPlusPlus) {
6362 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6363 D.getIdentifierLoc(), II,
6364 R, TInfo, SC);
6365
6366 if (R->getContainedDeducedType())
6367 ParsingInitForAutoVars.insert(NewVD);
6368
6369 if (D.isInvalidType())
6370 NewVD->setInvalidDecl();
6371 } else {
6372 bool Invalid = false;
6373
6374 if (DC->isRecord() && !CurContext->isRecord()) {
6375 // This is an out-of-line definition of a static data member.
6376 switch (SC) {
6377 case SC_None:
6378 break;
6379 case SC_Static:
6380 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6381 diag::err_static_out_of_line)
6382 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6383 break;
6384 case SC_Auto:
6385 case SC_Register:
6386 case SC_Extern:
6387 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6388 // to names of variables declared in a block or to function parameters.
6389 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6390 // of class members
6391
6392 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6393 diag::err_storage_class_for_static_member)
6394 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6395 break;
6396 case SC_PrivateExtern:
6397 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6397)
;
6398 }
6399 }
6400
6401 if (SC == SC_Static && CurContext->isRecord()) {
6402 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6403 if (RD->isLocalClass())
6404 Diag(D.getIdentifierLoc(),
6405 diag::err_static_data_member_not_allowed_in_local_class)
6406 << Name << RD->getDeclName();
6407
6408 // C++98 [class.union]p1: If a union contains a static data member,
6409 // the program is ill-formed. C++11 drops this restriction.
6410 if (RD->isUnion())
6411 Diag(D.getIdentifierLoc(),
6412 getLangOpts().CPlusPlus11
6413 ? diag::warn_cxx98_compat_static_data_member_in_union
6414 : diag::ext_static_data_member_in_union) << Name;
6415 // We conservatively disallow static data members in anonymous structs.
6416 else if (!RD->getDeclName())
6417 Diag(D.getIdentifierLoc(),
6418 diag::err_static_data_member_not_allowed_in_anon_struct)
6419 << Name << RD->isUnion();
6420 }
6421 }
6422
6423 // Match up the template parameter lists with the scope specifier, then
6424 // determine whether we have a template or a template specialization.
6425 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6426 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6427 D.getCXXScopeSpec(),
6428 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6429 ? D.getName().TemplateId
6430 : nullptr,
6431 TemplateParamLists,
6432 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6433
6434 if (TemplateParams) {
6435 if (!TemplateParams->size() &&
6436 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6437 // There is an extraneous 'template<>' for this variable. Complain
6438 // about it, but allow the declaration of the variable.
6439 Diag(TemplateParams->getTemplateLoc(),
6440 diag::err_template_variable_noparams)
6441 << II
6442 << SourceRange(TemplateParams->getTemplateLoc(),
6443 TemplateParams->getRAngleLoc());
6444 TemplateParams = nullptr;
6445 } else {
6446 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6447 // This is an explicit specialization or a partial specialization.
6448 // FIXME: Check that we can declare a specialization here.
6449 IsVariableTemplateSpecialization = true;
6450 IsPartialSpecialization = TemplateParams->size() > 0;
6451 } else { // if (TemplateParams->size() > 0)
6452 // This is a template declaration.
6453 IsVariableTemplate = true;
6454
6455 // Check that we can declare a template here.
6456 if (CheckTemplateDeclScope(S, TemplateParams))
6457 return nullptr;
6458
6459 // Only C++1y supports variable templates (N3651).
6460 Diag(D.getIdentifierLoc(),
6461 getLangOpts().CPlusPlus14
6462 ? diag::warn_cxx11_compat_variable_template
6463 : diag::ext_variable_template);
6464 }
6465 }
6466 } else {
6467 assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6469, __extension__ __PRETTY_FUNCTION__))
6468 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6469, __extension__ __PRETTY_FUNCTION__))
6469 "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6469, __extension__ __PRETTY_FUNCTION__))
;
6470 }
6471
6472 if (IsVariableTemplateSpecialization) {
6473 SourceLocation TemplateKWLoc =
6474 TemplateParamLists.size() > 0
6475 ? TemplateParamLists[0]->getTemplateLoc()
6476 : SourceLocation();
6477 DeclResult Res = ActOnVarTemplateSpecialization(
6478 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6479 IsPartialSpecialization);
6480 if (Res.isInvalid())
6481 return nullptr;
6482 NewVD = cast<VarDecl>(Res.get());
6483 AddToScope = false;
6484 } else if (D.isDecompositionDeclarator()) {
6485 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6486 D.getIdentifierLoc(), R, TInfo, SC,
6487 Bindings);
6488 } else
6489 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6490 D.getIdentifierLoc(), II, R, TInfo, SC);
6491
6492 // If this is supposed to be a variable template, create it as such.
6493 if (IsVariableTemplate) {
6494 NewTemplate =
6495 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6496 TemplateParams, NewVD);
6497 NewVD->setDescribedVarTemplate(NewTemplate);
6498 }
6499
6500 // If this decl has an auto type in need of deduction, make a note of the
6501 // Decl so we can diagnose uses of it in its own initializer.
6502 if (R->getContainedDeducedType())
6503 ParsingInitForAutoVars.insert(NewVD);
6504
6505 if (D.isInvalidType() || Invalid) {
6506 NewVD->setInvalidDecl();
6507 if (NewTemplate)
6508 NewTemplate->setInvalidDecl();
6509 }
6510
6511 SetNestedNameSpecifier(NewVD, D);
6512
6513 // If we have any template parameter lists that don't directly belong to
6514 // the variable (matching the scope specifier), store them.
6515 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6516 if (TemplateParamLists.size() > VDTemplateParamLists)
6517 NewVD->setTemplateParameterListsInfo(
6518 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6519
6520 if (D.getDeclSpec().isConstexprSpecified()) {
6521 NewVD->setConstexpr(true);
6522 // C++1z [dcl.spec.constexpr]p1:
6523 // A static data member declared with the constexpr specifier is
6524 // implicitly an inline variable.
6525 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6526 NewVD->setImplicitlyInline();
6527 }
6528 }
6529
6530 if (D.getDeclSpec().isInlineSpecified()) {
6531 if (!getLangOpts().CPlusPlus) {
6532 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6533 << 0;
6534 } else if (CurContext->isFunctionOrMethod()) {
6535 // 'inline' is not allowed on block scope variable declaration.
6536 Diag(D.getDeclSpec().getInlineSpecLoc(),
6537 diag::err_inline_declaration_block_scope) << Name
6538 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6539 } else {
6540 Diag(D.getDeclSpec().getInlineSpecLoc(),
6541 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6542 : diag::ext_inline_variable);
6543 NewVD->setInlineSpecified();
6544 }
6545 }
6546
6547 // Set the lexical context. If the declarator has a C++ scope specifier, the
6548 // lexical context will be different from the semantic context.
6549 NewVD->setLexicalDeclContext(CurContext);
6550 if (NewTemplate)
6551 NewTemplate->setLexicalDeclContext(CurContext);
6552
6553 if (IsLocalExternDecl) {
6554 if (D.isDecompositionDeclarator())
6555 for (auto *B : Bindings)
6556 B->setLocalExternDecl();
6557 else
6558 NewVD->setLocalExternDecl();
6559 }
6560
6561 bool EmitTLSUnsupportedError = false;
6562 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6563 // C++11 [dcl.stc]p4:
6564 // When thread_local is applied to a variable of block scope the
6565 // storage-class-specifier static is implied if it does not appear
6566 // explicitly.
6567 // Core issue: 'static' is not implied if the variable is declared
6568 // 'extern'.
6569 if (NewVD->hasLocalStorage() &&
6570 (SCSpec != DeclSpec::SCS_unspecified ||
6571 TSCS != DeclSpec::TSCS_thread_local ||
6572 !DC->isFunctionOrMethod()))
6573 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6574 diag::err_thread_non_global)
6575 << DeclSpec::getSpecifierName(TSCS);
6576 else if (!Context.getTargetInfo().isTLSSupported()) {
6577 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6578 // Postpone error emission until we've collected attributes required to
6579 // figure out whether it's a host or device variable and whether the
6580 // error should be ignored.
6581 EmitTLSUnsupportedError = true;
6582 // We still need to mark the variable as TLS so it shows up in AST with
6583 // proper storage class for other tools to use even if we're not going
6584 // to emit any code for it.
6585 NewVD->setTSCSpec(TSCS);
6586 } else
6587 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6588 diag::err_thread_unsupported);
6589 } else
6590 NewVD->setTSCSpec(TSCS);
6591 }
6592
6593 // C99 6.7.4p3
6594 // An inline definition of a function with external linkage shall
6595 // not contain a definition of a modifiable object with static or
6596 // thread storage duration...
6597 // We only apply this when the function is required to be defined
6598 // elsewhere, i.e. when the function is not 'extern inline'. Note
6599 // that a local variable with thread storage duration still has to
6600 // be marked 'static'. Also note that it's possible to get these
6601 // semantics in C++ using __attribute__((gnu_inline)).
6602 if (SC == SC_Static && S->getFnParent() != nullptr &&
6603 !NewVD->getType().isConstQualified()) {
6604 FunctionDecl *CurFD = getCurFunctionDecl();
6605 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6606 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6607 diag::warn_static_local_in_extern_inline);
6608 MaybeSuggestAddingStaticToDecl(CurFD);
6609 }
6610 }
6611
6612 if (D.getDeclSpec().isModulePrivateSpecified()) {
6613 if (IsVariableTemplateSpecialization)
6614 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6615 << (IsPartialSpecialization ? 1 : 0)
6616 << FixItHint::CreateRemoval(
6617 D.getDeclSpec().getModulePrivateSpecLoc());
6618 else if (IsMemberSpecialization)
6619 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6620 << 2
6621 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6622 else if (NewVD->hasLocalStorage())
6623 Diag(NewVD->getLocation(), diag::err_module_private_local)
6624 << 0 << NewVD->getDeclName()
6625 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6626 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6627 else {
6628 NewVD->setModulePrivate();
6629 if (NewTemplate)
6630 NewTemplate->setModulePrivate();
6631 for (auto *B : Bindings)
6632 B->setModulePrivate();
6633 }
6634 }
6635
6636 // Handle attributes prior to checking for duplicates in MergeVarDecl
6637 ProcessDeclAttributes(S, NewVD, D);
6638
6639 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6640 if (EmitTLSUnsupportedError &&
6641 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6642 (getLangOpts().OpenMPIsDevice &&
6643 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6644 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6645 diag::err_thread_unsupported);
6646 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6647 // storage [duration]."
6648 if (SC == SC_None && S->getFnParent() != nullptr &&
6649 (NewVD->hasAttr<CUDASharedAttr>() ||
6650 NewVD->hasAttr<CUDAConstantAttr>())) {
6651 NewVD->setStorageClass(SC_Static);
6652 }
6653 }
6654
6655 // Ensure that dllimport globals without explicit storage class are treated as
6656 // extern. The storage class is set above using parsed attributes. Now we can
6657 // check the VarDecl itself.
6658 assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6660, __extension__ __PRETTY_FUNCTION__))
6659 NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6660, __extension__ __PRETTY_FUNCTION__))
6660 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 6660, __extension__ __PRETTY_FUNCTION__))
;
6661
6662 // In auto-retain/release, infer strong retension for variables of
6663 // retainable type.
6664 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6665 NewVD->setInvalidDecl();
6666
6667 // Handle GNU asm-label extension (encoded as an attribute).
6668 if (Expr *E = (Expr*)D.getAsmLabel()) {
6669 // The parser guarantees this is a string.
6670 StringLiteral *SE = cast<StringLiteral>(E);
6671 StringRef Label = SE->getString();
6672 if (S->getFnParent() != nullptr) {
6673 switch (SC) {
6674 case SC_None:
6675 case SC_Auto:
6676 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6677 break;
6678 case SC_Register:
6679 // Local Named register
6680 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6681 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6682 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6683 break;
6684 case SC_Static:
6685 case SC_Extern:
6686 case SC_PrivateExtern:
6687 break;
6688 }
6689 } else if (SC == SC_Register) {
6690 // Global Named register
6691 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6692 const auto &TI = Context.getTargetInfo();
6693 bool HasSizeMismatch;
6694
6695 if (!TI.isValidGCCRegisterName(Label))
6696 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6697 else if (!TI.validateGlobalRegisterVariable(Label,
6698 Context.getTypeSize(R),
6699 HasSizeMismatch))
6700 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6701 else if (HasSizeMismatch)
6702 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6703 }
6704
6705 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6706 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6707 NewVD->setInvalidDecl(true);
6708 }
6709 }
6710
6711 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6712 Context, Label, 0));
6713 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6714 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6715 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6716 if (I != ExtnameUndeclaredIdentifiers.end()) {
6717 if (isDeclExternC(NewVD)) {
6718 NewVD->addAttr(I->second);
6719 ExtnameUndeclaredIdentifiers.erase(I);
6720 } else
6721 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6722 << /*Variable*/1 << NewVD;
6723 }
6724 }
6725
6726 // Find the shadowed declaration before filtering for scope.
6727 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6728 ? getShadowedDeclaration(NewVD, Previous)
6729 : nullptr;
6730
6731 // Don't consider existing declarations that are in a different
6732 // scope and are out-of-semantic-context declarations (if the new
6733 // declaration has linkage).
6734 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6735 D.getCXXScopeSpec().isNotEmpty() ||
6736 IsMemberSpecialization ||
6737 IsVariableTemplateSpecialization);
6738
6739 // Check whether the previous declaration is in the same block scope. This
6740 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6741 if (getLangOpts().CPlusPlus &&
6742 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6743 NewVD->setPreviousDeclInSameBlockScope(
6744 Previous.isSingleResult() && !Previous.isShadowed() &&
6745 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6746
6747 if (!getLangOpts().CPlusPlus) {
6748 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6749 } else {
6750 // If this is an explicit specialization of a static data member, check it.
6751 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6752 CheckMemberSpecialization(NewVD, Previous))
6753 NewVD->setInvalidDecl();
6754
6755 // Merge the decl with the existing one if appropriate.
6756 if (!Previous.empty()) {
6757 if (Previous.isSingleResult() &&
6758 isa<FieldDecl>(Previous.getFoundDecl()) &&
6759 D.getCXXScopeSpec().isSet()) {
6760 // The user tried to define a non-static data member
6761 // out-of-line (C++ [dcl.meaning]p1).
6762 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6763 << D.getCXXScopeSpec().getRange();
6764 Previous.clear();
6765 NewVD->setInvalidDecl();
6766 }
6767 } else if (D.getCXXScopeSpec().isSet()) {
6768 // No previous declaration in the qualifying scope.
6769 Diag(D.getIdentifierLoc(), diag::err_no_member)
6770 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6771 << D.getCXXScopeSpec().getRange();
6772 NewVD->setInvalidDecl();
6773 }
6774
6775 if (!IsVariableTemplateSpecialization)
6776 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6777
6778 if (NewTemplate) {
6779 VarTemplateDecl *PrevVarTemplate =
6780 NewVD->getPreviousDecl()
6781 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6782 : nullptr;
6783
6784 // Check the template parameter list of this declaration, possibly
6785 // merging in the template parameter list from the previous variable
6786 // template declaration.
6787 if (CheckTemplateParameterList(
6788 TemplateParams,
6789 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6790 : nullptr,
6791 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6792 DC->isDependentContext())
6793 ? TPC_ClassTemplateMember
6794 : TPC_VarTemplate))
6795 NewVD->setInvalidDecl();
6796
6797 // If we are providing an explicit specialization of a static variable
6798 // template, make a note of that.
6799 if (PrevVarTemplate &&
6800 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6801 PrevVarTemplate->setMemberSpecialization();
6802 }
6803 }
6804
6805 // Diagnose shadowed variables iff this isn't a redeclaration.
6806 if (ShadowedDecl && !D.isRedeclaration())
6807 CheckShadow(NewVD, ShadowedDecl, Previous);
6808
6809 ProcessPragmaWeak(S, NewVD);
6810
6811 // If this is the first declaration of an extern C variable, update
6812 // the map of such variables.
6813 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6814 isIncompleteDeclExternC(*this, NewVD))
6815 RegisterLocallyScopedExternCDecl(NewVD, S);
6816
6817 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6818 Decl *ManglingContextDecl;
6819 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6820 NewVD->getDeclContext(), ManglingContextDecl)) {
6821 Context.setManglingNumber(
6822 NewVD, MCtx->getManglingNumber(
6823 NewVD, getMSManglingNumber(getLangOpts(), S)));
6824 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6825 }
6826 }
6827
6828 // Special handling of variable named 'main'.
6829 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6830 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6831 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6832
6833 // C++ [basic.start.main]p3
6834 // A program that declares a variable main at global scope is ill-formed.
6835 if (getLangOpts().CPlusPlus)
6836 Diag(D.getLocStart(), diag::err_main_global_variable);
6837
6838 // In C, and external-linkage variable named main results in undefined
6839 // behavior.
6840 else if (NewVD->hasExternalFormalLinkage())
6841 Diag(D.getLocStart(), diag::warn_main_redefined);
6842 }
6843
6844 if (D.isRedeclaration() && !Previous.empty()) {
6845 checkDLLAttributeRedeclaration(
6846 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6847 IsMemberSpecialization, D.isFunctionDefinition());
6848 }
6849
6850 if (NewTemplate) {
6851 if (NewVD->isInvalidDecl())
6852 NewTemplate->setInvalidDecl();
6853 ActOnDocumentableDecl(NewTemplate);
6854 return NewTemplate;
6855 }
6856
6857 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6858 CompleteMemberSpecialization(NewVD, Previous);
6859
6860 return NewVD;
6861}
6862
6863/// Enum describing the %select options in diag::warn_decl_shadow.
6864enum ShadowedDeclKind {
6865 SDK_Local,
6866 SDK_Global,
6867 SDK_StaticMember,
6868 SDK_Field,
6869 SDK_Typedef,
6870 SDK_Using
6871};
6872
6873/// Determine what kind of declaration we're shadowing.
6874static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6875 const DeclContext *OldDC) {
6876 if (isa<TypeAliasDecl>(ShadowedDecl))
6877 return SDK_Using;
6878 else if (isa<TypedefDecl>(ShadowedDecl))
6879 return SDK_Typedef;
6880 else if (isa<RecordDecl>(OldDC))
6881 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6882
6883 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6884}
6885
6886/// Return the location of the capture if the given lambda captures the given
6887/// variable \p VD, or an invalid source location otherwise.
6888static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6889 const VarDecl *VD) {
6890 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6891 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6892 return Capture.getLocation();
6893 }
6894 return SourceLocation();
6895}
6896
6897static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6898 const LookupResult &R) {
6899 // Only diagnose if we're shadowing an unambiguous field or variable.
6900 if (R.getResultKind() != LookupResult::Found)
6901 return false;
6902
6903 // Return false if warning is ignored.
6904 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6905}
6906
6907/// \brief Return the declaration shadowed by the given variable \p D, or null
6908/// if it doesn't shadow any declaration or shadowing warnings are disabled.
6909NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6910 const LookupResult &R) {
6911 if (!shouldWarnIfShadowedDecl(Diags, R))
6912 return nullptr;
6913
6914 // Don't diagnose declarations at file scope.
6915 if (D->hasGlobalStorage())
6916 return nullptr;
6917
6918 NamedDecl *ShadowedDecl = R.getFoundDecl();
6919 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6920 ? ShadowedDecl
6921 : nullptr;
6922}
6923
6924/// \brief Return the declaration shadowed by the given typedef \p D, or null
6925/// if it doesn't shadow any declaration or shadowing warnings are disabled.
6926NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6927 const LookupResult &R) {
6928 // Don't warn if typedef declaration is part of a class
6929 if (D->getDeclContext()->isRecord())
6930 return nullptr;
6931
6932 if (!shouldWarnIfShadowedDecl(Diags, R))
6933 return nullptr;
6934
6935 NamedDecl *ShadowedDecl = R.getFoundDecl();
6936 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6937}
6938
6939/// \brief Diagnose variable or built-in function shadowing. Implements
6940/// -Wshadow.
6941///
6942/// This method is called whenever a VarDecl is added to a "useful"
6943/// scope.
6944///
6945/// \param ShadowedDecl the declaration that is shadowed by the given variable
6946/// \param R the lookup of the name
6947///
6948void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6949 const LookupResult &R) {
6950 DeclContext *NewDC = D->getDeclContext();
6951
6952 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6953 // Fields are not shadowed by variables in C++ static methods.
6954 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6955 if (MD->isStatic())
6956 return;
6957
6958 // Fields shadowed by constructor parameters are a special case. Usually
6959 // the constructor initializes the field with the parameter.
6960 if (isa<CXXConstructorDecl>(NewDC))
6961 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6962 // Remember that this was shadowed so we can either warn about its
6963 // modification or its existence depending on warning settings.
6964 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6965 return;
6966 }
6967 }
6968
6969 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6970 if (shadowedVar->isExternC()) {
6971 // For shadowing external vars, make sure that we point to the global
6972 // declaration, not a locally scoped extern declaration.
6973 for (auto I : shadowedVar->redecls())
6974 if (I->isFileVarDecl()) {
6975 ShadowedDecl = I;
6976 break;
6977 }
6978 }
6979
6980 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6981
6982 unsigned WarningDiag = diag::warn_decl_shadow;
6983 SourceLocation CaptureLoc;
6984 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6985 isa<CXXMethodDecl>(NewDC)) {
6986 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6987 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6988 if (RD->getLambdaCaptureDefault() == LCD_None) {
6989 // Try to avoid warnings for lambdas with an explicit capture list.
6990 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6991 // Warn only when the lambda captures the shadowed decl explicitly.
6992 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6993 if (CaptureLoc.isInvalid())
6994 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6995 } else {
6996 // Remember that this was shadowed so we can avoid the warning if the
6997 // shadowed decl isn't captured and the warning settings allow it.
6998 cast<LambdaScopeInfo>(getCurFunction())
6999 ->ShadowingDecls.push_back(
7000 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7001 return;
7002 }
7003 }
7004
7005 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7006 // A variable can't shadow a local variable in an enclosing scope, if
7007 // they are separated by a non-capturing declaration context.
7008 for (DeclContext *ParentDC = NewDC;
7009 ParentDC && !ParentDC->Equals(OldDC);
7010 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7011 // Only block literals, captured statements, and lambda expressions
7012 // can capture; other scopes don't.
7013 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7014 !isLambdaCallOperator(ParentDC)) {
7015 return;
7016 }
7017 }
7018 }
7019 }
7020 }
7021
7022 // Only warn about certain kinds of shadowing for class members.
7023 if (NewDC && NewDC->isRecord()) {
7024 // In particular, don't warn about shadowing non-class members.
7025 if (!OldDC->isRecord())
7026 return;
7027
7028 // TODO: should we warn about static data members shadowing
7029 // static data members from base classes?
7030
7031 // TODO: don't diagnose for inaccessible shadowed members.
7032 // This is hard to do perfectly because we might friend the
7033 // shadowing context, but that's just a false negative.
7034 }
7035
7036
7037 DeclarationName Name = R.getLookupName();
7038
7039 // Emit warning and note.
7040 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7041 return;
7042 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7043 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7044 if (!CaptureLoc.isInvalid())
7045 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7046 << Name << /*explicitly*/ 1;
7047 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048}
7049
7050/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7051/// when these variables are captured by the lambda.
7052void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7053 for (const auto &Shadow : LSI->ShadowingDecls) {
7054 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7055 // Try to avoid the warning when the shadowed decl isn't captured.
7056 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7057 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7058 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7059 ? diag::warn_decl_shadow_uncaptured_local
7060 : diag::warn_decl_shadow)
7061 << Shadow.VD->getDeclName()
7062 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7063 if (!CaptureLoc.isInvalid())
7064 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7065 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7066 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7067 }
7068}
7069
7070/// \brief Check -Wshadow without the advantage of a previous lookup.
7071void Sema::CheckShadow(Scope *S, VarDecl *D) {
7072 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7073 return;
7074
7075 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7076 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7077 LookupName(R, S);
7078 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7079 CheckShadow(D, ShadowedDecl, R);
7080}
7081
7082/// Check if 'E', which is an expression that is about to be modified, refers
7083/// to a constructor parameter that shadows a field.
7084void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7085 // Quickly ignore expressions that can't be shadowing ctor parameters.
7086 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7087 return;
7088 E = E->IgnoreParenImpCasts();
7089 auto *DRE = dyn_cast<DeclRefExpr>(E);
7090 if (!DRE)
7091 return;
7092 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7093 auto I = ShadowingDecls.find(D);
7094 if (I == ShadowingDecls.end())
7095 return;
7096 const NamedDecl *ShadowedDecl = I->second;
7097 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7098 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7099 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7100 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7101
7102 // Avoid issuing multiple warnings about the same decl.
7103 ShadowingDecls.erase(I);
7104}
7105
7106/// Check for conflict between this global or extern "C" declaration and
7107/// previous global or extern "C" declarations. This is only used in C++.
7108template<typename T>
7109static bool checkGlobalOrExternCConflict(
7110 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7111 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus &&
"only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7111, __extension__ __PRETTY_FUNCTION__))
;
7112 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7113
7114 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7115 // The common case: this global doesn't conflict with any extern "C"
7116 // declaration.
7117 return false;
7118 }
7119
7120 if (Prev) {
7121 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7122 // Both the old and new declarations have C language linkage. This is a
7123 // redeclaration.
7124 Previous.clear();
7125 Previous.addDecl(Prev);
7126 return true;
7127 }
7128
7129 // This is a global, non-extern "C" declaration, and there is a previous
7130 // non-global extern "C" declaration. Diagnose if this is a variable
7131 // declaration.
7132 if (!isa<VarDecl>(ND))
7133 return false;
7134 } else {
7135 // The declaration is extern "C". Check for any declaration in the
7136 // translation unit which might conflict.
7137 if (IsGlobal) {
7138 // We have already performed the lookup into the translation unit.
7139 IsGlobal = false;
7140 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7141 I != E; ++I) {
7142 if (isa<VarDecl>(*I)) {
7143 Prev = *I;
7144 break;
7145 }
7146 }
7147 } else {
7148 DeclContext::lookup_result R =
7149 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7150 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7151 I != E; ++I) {
7152 if (isa<VarDecl>(*I)) {
7153 Prev = *I;
7154 break;
7155 }
7156 // FIXME: If we have any other entity with this name in global scope,
7157 // the declaration is ill-formed, but that is a defect: it breaks the
7158 // 'stat' hack, for instance. Only variables can have mangled name
7159 // clashes with extern "C" declarations, so only they deserve a
7160 // diagnostic.
7161 }
7162 }
7163
7164 if (!Prev)
7165 return false;
7166 }
7167
7168 // Use the first declaration's location to ensure we point at something which
7169 // is lexically inside an extern "C" linkage-spec.
7170 assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose"
) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7170, __extension__ __PRETTY_FUNCTION__))
;
7171 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7172 Prev = FD->getFirstDecl();
7173 else
7174 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7175
7176 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7177 << IsGlobal << ND;
7178 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7179 << IsGlobal;
7180 return false;
7181}
7182
7183/// Apply special rules for handling extern "C" declarations. Returns \c true
7184/// if we have found that this is a redeclaration of some prior entity.
7185///
7186/// Per C++ [dcl.link]p6:
7187/// Two declarations [for a function or variable] with C language linkage
7188/// with the same name that appear in different scopes refer to the same
7189/// [entity]. An entity with C language linkage shall not be declared with
7190/// the same name as an entity in global scope.
7191template<typename T>
7192static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7193 LookupResult &Previous) {
7194 if (!S.getLangOpts().CPlusPlus) {
7195 // In C, when declaring a global variable, look for a corresponding 'extern'
7196 // variable declared in function scope. We don't need this in C++, because
7197 // we find local extern decls in the surrounding file-scope DeclContext.
7198 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7199 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7200 Previous.clear();
7201 Previous.addDecl(Prev);
7202 return true;
7203 }
7204 }
7205 return false;
7206 }
7207
7208 // A declaration in the translation unit can conflict with an extern "C"
7209 // declaration.
7210 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7211 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7212
7213 // An extern "C" declaration can conflict with a declaration in the
7214 // translation unit or can be a redeclaration of an extern "C" declaration
7215 // in another scope.
7216 if (isIncompleteDeclExternC(S,ND))
7217 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7218
7219 // Neither global nor extern "C": nothing to do.
7220 return false;
7221}
7222
7223void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7224 // If the decl is already known invalid, don't check it.
7225 if (NewVD->isInvalidDecl())
7226 return;
7227
7228 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7229 QualType T = TInfo->getType();
7230
7231 // Defer checking an 'auto' type until its initializer is attached.
7232 if (T->isUndeducedType())
7233 return;
7234
7235 if (NewVD->hasAttrs())
7236 CheckAlignasUnderalignment(NewVD);
7237
7238 if (T->isObjCObjectType()) {
7239 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7240 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7241 T = Context.getObjCObjectPointerType(T);
7242 NewVD->setType(T);
7243 }
7244
7245 // Emit an error if an address space was applied to decl with local storage.
7246 // This includes arrays of objects with address space qualifiers, but not
7247 // automatic variables that point to other address spaces.
7248 // ISO/IEC TR 18037 S5.1.2
7249 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7250 T.getAddressSpace() != LangAS::Default) {
7251 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7252 NewVD->setInvalidDecl();
7253 return;
7254 }
7255
7256 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7257 // scope.
7258 if (getLangOpts().OpenCLVersion == 120 &&
7259 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7260 NewVD->isStaticLocal()) {
7261 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7262 NewVD->setInvalidDecl();
7263 return;
7264 }
7265
7266 if (getLangOpts().OpenCL) {
7267 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7268 if (NewVD->hasAttr<BlocksAttr>()) {
7269 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7270 return;
7271 }
7272
7273 if (T->isBlockPointerType()) {
7274 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7275 // can't use 'extern' storage class.
7276 if (!T.isConstQualified()) {
7277 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7278 << 0 /*const*/;
7279 NewVD->setInvalidDecl();
7280 return;
7281 }
7282 if (NewVD->hasExternalStorage()) {
7283 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7284 NewVD->setInvalidDecl();
7285 return;
7286 }
7287 }
7288 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7289 // __constant address space.
7290 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7291 // variables inside a function can also be declared in the global
7292 // address space.
7293 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7294 NewVD->hasExternalStorage()) {
7295 if (!T->isSamplerT() &&
7296 !(T.getAddressSpace() == LangAS::opencl_constant ||
7297 (T.getAddressSpace() == LangAS::opencl_global &&
7298 getLangOpts().OpenCLVersion == 200))) {
7299 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7300 if (getLangOpts().OpenCLVersion == 200)
7301 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7302 << Scope << "global or constant";
7303 else
7304 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7305 << Scope << "constant";
7306 NewVD->setInvalidDecl();
7307 return;
7308 }
7309 } else {
7310 if (T.getAddressSpace() == LangAS::opencl_global) {
7311 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7312 << 1 /*is any function*/ << "global";
7313 NewVD->setInvalidDecl();
7314 return;
7315 }
7316 if (T.getAddressSpace() == LangAS::opencl_constant ||
7317 T.getAddressSpace() == LangAS::opencl_local) {
7318 FunctionDecl *FD = getCurFunctionDecl();
7319 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7320 // in functions.
7321 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7322 if (T.getAddressSpace() == LangAS::opencl_constant)
7323 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7324 << 0 /*non-kernel only*/ << "constant";
7325 else
7326 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7327 << 0 /*non-kernel only*/ << "local";
7328 NewVD->setInvalidDecl();
7329 return;
7330 }
7331 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7332 // in the outermost scope of a kernel function.
7333 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7334 if (!getCurScope()->isFunctionScope()) {
7335 if (T.getAddressSpace() == LangAS::opencl_constant)
7336 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7337 << "constant";
7338 else
7339 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7340 << "local";
7341 NewVD->setInvalidDecl();
7342 return;
7343 }
7344 }
7345 } else if (T.getAddressSpace() != LangAS::opencl_private) {
7346 // Do not allow other address spaces on automatic variable.
7347 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7348 NewVD->setInvalidDecl();
7349 return;
7350 }
7351 }
7352 }
7353
7354 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7355 && !NewVD->hasAttr<BlocksAttr>()) {
7356 if (getLangOpts().getGC() != LangOptions::NonGC)
7357 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7358 else {
7359 assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ?
void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount",
"/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7359, __extension__ __PRETTY_FUNCTION__))
;
7360 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7361 }
7362 }
7363
7364 bool isVM = T->isVariablyModifiedType();
7365 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7366 NewVD->hasAttr<BlocksAttr>())
7367 getCurFunction()->setHasBranchProtectedScope();
7368
7369 if ((isVM && NewVD->hasLinkage()) ||
7370 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7371 bool SizeIsNegative;
7372 llvm::APSInt Oversized;
7373 TypeSourceInfo *FixedTInfo =
7374 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7375 SizeIsNegative, Oversized);
7376 if (!FixedTInfo && T->isVariableArrayType()) {
7377 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7378 // FIXME: This won't give the correct result for
7379 // int a[10][n];
7380 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7381
7382 if (NewVD->isFileVarDecl())
7383 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7384 << SizeRange;
7385 else if (NewVD->isStaticLocal())
7386 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7387 << SizeRange;
7388 else
7389 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7390 << SizeRange;
7391 NewVD->setInvalidDecl();
7392 return;
7393 }
7394
7395 if (!FixedTInfo) {
7396 if (NewVD->isFileVarDecl())
7397 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7398 else
7399 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7400 NewVD->setInvalidDecl();
7401 return;
7402 }
7403
7404 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7405 NewVD->setType(FixedTInfo->getType());
7406 NewVD->setTypeSourceInfo(FixedTInfo);
7407 }
7408
7409 if (T->isVoidType()) {
7410 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7411 // of objects and functions.
7412 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7413 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7414 << T;
7415 NewVD->setInvalidDecl();
7416 return;
7417 }
7418 }
7419
7420 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7421 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7422 NewVD->setInvalidDecl();
7423 return;
7424 }
7425
7426 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7427 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7428 NewVD->setInvalidDecl();
7429 return;
7430 }
7431
7432 if (NewVD->isConstexpr() && !T->isDependentType() &&
7433 RequireLiteralType(NewVD->getLocation(), T,
7434 diag::err_constexpr_var_non_literal)) {
7435 NewVD->setInvalidDecl();
7436 return;
7437 }
7438}
7439
7440/// \brief Perform semantic checking on a newly-created variable
7441/// declaration.
7442///
7443/// This routine performs all of the type-checking required for a
7444/// variable declaration once it has been built. It is used both to
7445/// check variables after they have been parsed and their declarators
7446/// have been translated into a declaration, and to check variables
7447/// that have been instantiated from a template.
7448///
7449/// Sets NewVD->isInvalidDecl() if an error was encountered.
7450///
7451/// Returns true if the variable declaration is a redeclaration.
7452bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7453 CheckVariableDeclarationType(NewVD);
7454
7455 // If the decl is already known invalid, don't check it.
7456 if (NewVD->isInvalidDecl())
7457 return false;
7458
7459 // If we did not find anything by this name, look for a non-visible
7460 // extern "C" declaration with the same name.
7461 if (Previous.empty() &&
7462 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7463 Previous.setShadowed();
7464
7465 if (!Previous.empty()) {
7466 MergeVarDecl(NewVD, Previous);
7467 return true;
7468 }
7469 return false;
7470}
7471
7472namespace {
7473struct FindOverriddenMethod {
7474 Sema *S;
7475 CXXMethodDecl *Method;
7476
7477 /// Member lookup function that determines whether a given C++
7478 /// method overrides a method in a base class, to be used with
7479 /// CXXRecordDecl::lookupInBases().
7480 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7481 RecordDecl *BaseRecord =
7482 Specifier->getType()->getAs<RecordType>()->getDecl();
7483
7484 DeclarationName Name = Method->getDeclName();
7485
7486 // FIXME: Do we care about other names here too?
7487 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7488 // We really want to find the base class destructor here.
7489 QualType T = S->Context.getTypeDeclType(BaseRecord);
7490 CanQualType CT = S->Context.getCanonicalType(T);
7491
7492 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7493 }
7494
7495 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7496 Path.Decls = Path.Decls.slice(1)) {
7497 NamedDecl *D = Path.Decls.front();
7498 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7499 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7500 return true;
7501 }
7502 }
7503
7504 return false;
7505 }
7506};
7507
7508enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7509} // end anonymous namespace
7510
7511/// \brief Report an error regarding overriding, along with any relevant
7512/// overriden methods.
7513///
7514/// \param DiagID the primary error to report.
7515/// \param MD the overriding method.
7516/// \param OEK which overrides to include as notes.
7517static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7518 OverrideErrorKind OEK = OEK_All) {
7519 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7520 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7521 // This check (& the OEK parameter) could be replaced by a predicate, but
7522 // without lambdas that would be overkill. This is still nicer than writing
7523 // out the diag loop 3 times.
7524 if ((OEK == OEK_All) ||
7525 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7526 (OEK == OEK_Deleted && O->isDeleted()))
7527 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7528 }
7529}
7530
7531/// AddOverriddenMethods - See if a method overrides any in the base classes,
7532/// and if so, check that it's a valid override and remember it.
7533bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7534 // Look for methods in base classes that this method might override.
7535 CXXBasePaths Paths;
7536 FindOverriddenMethod FOM;
7537 FOM.Method = MD;
7538 FOM.S = this;
7539 bool hasDeletedOverridenMethods = false;
7540 bool hasNonDeletedOverridenMethods = false;
7541 bool AddedAny = false;
7542 if (DC->lookupInBases(FOM, Paths)) {
7543 for (auto *I : Paths.found_decls()) {
7544 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7545 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7546 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7547 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7548 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7549 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7550 hasDeletedOverridenMethods |= OldMD->isDeleted();
7551 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7552 AddedAny = true;
7553 }
7554 }
7555 }
7556 }
7557
7558 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7559 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7560 }
7561 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7562 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7563 }
7564
7565 return AddedAny;
7566}
7567
7568namespace {
7569 // Struct for holding all of the extra arguments needed by
7570 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7571 struct ActOnFDArgs {
7572 Scope *S;
7573 Declarator &D;
7574 MultiTemplateParamsArg TemplateParamLists;
7575 bool AddToScope;
7576 };
7577} // end anonymous namespace
7578
7579namespace {
7580
7581// Callback to only accept typo corrections that have a non-zero edit distance.
7582// Also only accept corrections that have the same parent decl.
7583class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7584 public:
7585 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7586 CXXRecordDecl *Parent)
7587 : Context(Context), OriginalFD(TypoFD),
7588 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7589
7590 bool ValidateCandidate(const TypoCorrection &candidate) override {
7591 if (candidate.getEditDistance() == 0)
7592 return false;
7593
7594 SmallVector<unsigned, 1> MismatchedParams;
7595 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7596 CDeclEnd = candidate.end();
7597 CDecl != CDeclEnd; ++CDecl) {
7598 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7599
7600 if (FD && !FD->hasBody() &&
7601 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7603 CXXRecordDecl *Parent = MD->getParent();
7604 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7605 return true;
7606 } else if (!ExpectedParent) {
7607 return true;
7608 }
7609 }
7610 }
7611
7612 return false;
7613 }
7614
7615 private:
7616 ASTContext &Context;
7617 FunctionDecl *OriginalFD;
7618 CXXRecordDecl *ExpectedParent;
7619};
7620
7621} // end anonymous namespace
7622
7623void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7624 TypoCorrectedFunctionDefinitions.insert(F);
7625}
7626
7627/// \brief Generate diagnostics for an invalid function redeclaration.
7628///
7629/// This routine handles generating the diagnostic messages for an invalid
7630/// function redeclaration, including finding possible similar declarations
7631/// or performing typo correction if there are no previous declarations with
7632/// the same name.
7633///
7634/// Returns a NamedDecl iff typo correction was performed and substituting in
7635/// the new declaration name does not cause new errors.
7636static NamedDecl *DiagnoseInvalidRedeclaration(
7637 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7638 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7639 DeclarationName Name = NewFD->getDeclName();
7640 DeclContext *NewDC = NewFD->getDeclContext();
7641 SmallVector<unsigned, 1> MismatchedParams;
7642 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7643 TypoCorrection Correction;
7644 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7645 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7646 : diag::err_member_decl_does_not_match;
7647 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7648 IsLocalFriend ? Sema::LookupLocalFriendName
7649 : Sema::LookupOrdinaryName,
7650 Sema::ForVisibleRedeclaration);
7651
7652 NewFD->setInvalidDecl();
7653 if (IsLocalFriend)
7654 SemaRef.LookupName(Prev, S);
7655 else
7656 SemaRef.LookupQualifiedName(Prev, NewDC);
7657 assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7658, __extension__ __PRETTY_FUNCTION__))
7658 "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7658, __extension__ __PRETTY_FUNCTION__))
;
7659 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7660 if (!Prev.empty()) {
7661 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7662 Func != FuncEnd; ++Func) {
7663 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7664 if (FD &&
7665 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7666 // Add 1 to the index so that 0 can mean the mismatch didn't
7667 // involve a parameter
7668 unsigned ParamNum =
7669 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7670 NearMatches.push_back(std::make_pair(FD, ParamNum));
7671 }
7672 }
7673 // If the qualified name lookup yielded nothing, try typo correction
7674 } else if ((Correction = SemaRef.CorrectTypo(
7675 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7676 &ExtraArgs.D.getCXXScopeSpec(),
7677 llvm::make_unique<DifferentNameValidatorCCC>(
7678 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7679 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7680 // Set up everything for the call to ActOnFunctionDeclarator
7681 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7682 ExtraArgs.D.getIdentifierLoc());
7683 Previous.clear();
7684 Previous.setLookupName(Correction.getCorrection());
7685 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7686 CDeclEnd = Correction.end();
7687 CDecl != CDeclEnd; ++CDecl) {
7688 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7689 if (FD && !FD->hasBody() &&
7690 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7691 Previous.addDecl(FD);
7692 }
7693 }
7694 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7695
7696 NamedDecl *Result;
7697 // Retry building the function declaration with the new previous
7698 // declarations, and with errors suppressed.
7699 {
7700 // Trap errors.
7701 Sema::SFINAETrap Trap(SemaRef);
7702
7703 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7704 // pieces need to verify the typo-corrected C++ declaration and hopefully
7705 // eliminate the need for the parameter pack ExtraArgs.
7706 Result = SemaRef.ActOnFunctionDeclarator(
7707 ExtraArgs.S, ExtraArgs.D,
7708 Correction.getCorrectionDecl()->getDeclContext(),
7709 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7710 ExtraArgs.AddToScope);
7711
7712 if (Trap.hasErrorOccurred())
7713 Result = nullptr;
7714 }
7715
7716 if (Result) {
7717 // Determine which correction we picked.
7718 Decl *Canonical = Result->getCanonicalDecl();
7719 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7720 I != E; ++I)
7721 if ((*I)->getCanonicalDecl() == Canonical)
7722 Correction.setCorrectionDecl(*I);
7723
7724 // Let Sema know about the correction.
7725 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7726 SemaRef.diagnoseTypo(
7727 Correction,
7728 SemaRef.PDiag(IsLocalFriend
7729 ? diag::err_no_matching_local_friend_suggest
7730 : diag::err_member_decl_does_not_match_suggest)
7731 << Name << NewDC << IsDefinition);
7732 return Result;
7733 }
7734
7735 // Pretend the typo correction never occurred
7736 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7737 ExtraArgs.D.getIdentifierLoc());
7738 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7739 Previous.clear();
7740 Previous.setLookupName(Name);
7741 }
7742
7743 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7744 << Name << NewDC << IsDefinition << NewFD->getLocation();
7745
7746 bool NewFDisConst = false;
7747 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7748 NewFDisConst = NewMD->isConst();
7749
7750 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7751 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7752 NearMatch != NearMatchEnd; ++NearMatch) {
7753 FunctionDecl *FD = NearMatch->first;
7754 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7755 bool FDisConst = MD && MD->isConst();
7756 bool IsMember = MD || !IsLocalFriend;
7757
7758 // FIXME: These notes are poorly worded for the local friend case.
7759 if (unsigned Idx = NearMatch->second) {
7760 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7761 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7762 if (Loc.isInvalid()) Loc = FD->getLocation();
7763 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7764 : diag::note_local_decl_close_param_match)
7765 << Idx << FDParam->getType()
7766 << NewFD->getParamDecl(Idx - 1)->getType();
7767 } else if (FDisConst != NewFDisConst) {
7768 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7769 << NewFDisConst << FD->getSourceRange().getEnd();
7770 } else
7771 SemaRef.Diag(FD->getLocation(),
7772 IsMember ? diag::note_member_def_close_match
7773 : diag::note_local_decl_close_match);
7774 }
7775 return nullptr;
7776}
7777
7778static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7779 switch (D.getDeclSpec().getStorageClassSpec()) {
7780 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7780)
;
7781 case DeclSpec::SCS_auto:
7782 case DeclSpec::SCS_register:
7783 case DeclSpec::SCS_mutable:
7784 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7785 diag::err_typecheck_sclass_func);
7786 D.getMutableDeclSpec().ClearStorageClassSpecs();
7787 D.setInvalidType();
7788 break;
7789 case DeclSpec::SCS_unspecified: break;
7790 case DeclSpec::SCS_extern:
7791 if (D.getDeclSpec().isExternInLinkageSpec())
7792 return SC_None;
7793 return SC_Extern;
7794 case DeclSpec::SCS_static: {
7795 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7796 // C99 6.7.1p5:
7797 // The declaration of an identifier for a function that has
7798 // block scope shall have no explicit storage-class specifier
7799 // other than extern
7800 // See also (C++ [dcl.stc]p4).
7801 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7802 diag::err_static_block_func);
7803 break;
7804 } else
7805 return SC_Static;
7806 }
7807 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7808 }
7809
7810 // No explicit storage class has already been returned
7811 return SC_None;
7812}
7813
7814static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7815 DeclContext *DC, QualType &R,
7816 TypeSourceInfo *TInfo,
7817 StorageClass SC,
7818 bool &IsVirtualOkay) {
7819 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7820 DeclarationName Name = NameInfo.getName();
7821
7822 FunctionDecl *NewFD = nullptr;
7823 bool isInline = D.getDeclSpec().isInlineSpecified();
7824
7825 if (!SemaRef.getLangOpts().CPlusPlus) {
7826 // Determine whether the function was written with a
7827 // prototype. This true when:
7828 // - there is a prototype in the declarator, or
7829 // - the type R of the function is some kind of typedef or other non-
7830 // attributed reference to a type name (which eventually refers to a
7831 // function type).
7832 bool HasPrototype =
7833 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7834 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7835
7836 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7837 D.getLocStart(), NameInfo, R,
7838 TInfo, SC, isInline,
7839 HasPrototype, false);
7840 if (D.isInvalidType())
7841 NewFD->setInvalidDecl();
7842
7843 return NewFD;
7844 }
7845
7846 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7847 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7848
7849 // Check that the return type is not an abstract class type.
7850 // For record types, this is done by the AbstractClassUsageDiagnoser once
7851 // the class has been completely parsed.
7852 if (!DC->isRecord() &&
7853 SemaRef.RequireNonAbstractType(
7854 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7855 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7856 D.setInvalidType();
7857
7858 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7859 // This is a C++ constructor declaration.
7860 assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7861, __extension__ __PRETTY_FUNCTION__))
7861 "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaDecl.cpp"
, 7861, __extension__ __PRETTY_FUNCTION__))
;
7862
7863 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7864 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7865 D.getLocStart(), NameInfo,
7866 R, TInfo, isExplicit, isInline,
7867 /*isImplicitlyDeclared=*/false,
7868 isConstexpr);
7869
7870 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7871 // This is a C++ destructor declaration.
7872 if (DC->isRecord()) {
7873 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7874 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7875 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7876 SemaRef.Context, Record,
7877 D.getLocStart(),
7878 NameInfo, R, TInfo, isInline,
7879 /*isImplicitlyDeclared=*/false);
7880
7881 // If the class is complete, then we now create the implicit exception
7882 // specification. If the class is incomplete or dependent, we can't do
7883 // it yet.
7884 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7885 Record->getDefinition() && !Record->isBeingDefined() &&
7886 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7887 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7888 }
7889
7890 IsVirtualOkay = true;
7891 return NewDD;
7892
7893 } else {
7894 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7895 D.setInvalidType();
7896
7897 // Create a FunctionDecl to satisfy the function definition parsing
7898 // code path.
7899 return FunctionDecl::Create(SemaRef.Context, DC,
7900 D.getLocStart(),
7901 D.getIdentifierLoc(), Name, R, TInfo,
7902 SC, isInline,
7903 /*hasPrototype=*/true, isConstexpr);
7904 }
7905
7906 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7907 if (!DC->isRecord()) {
7908 SemaRef.Diag(D.getIdentifierLoc(),
7909 diag::err_conv_function_not_member);
7910 return nullptr;
7911 }
7912
7913 SemaRef.CheckConversionDeclarator(D, R, SC);
7914 IsVirtualOkay = true;
7915 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7916 D.getLocStart(), NameInfo,
7917 R, TInfo, isInline, isExplicit,
7918 isConstexpr, SourceLocation());
7919
7920 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7921 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7922
7923 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7924 isExplicit, NameInfo, R, TInfo,
7925 D.getLocEnd());
7926 } else if (DC->isRecord()) {
7927 // If the name of the function is the same as the name of the record,
7928 // then this must be an invalid constructor that has a return type.
7929 // (The parser checks for a return type and makes the declarator a
7930 // constructor if it has no return type).
7931 if (Name.getAsIdentifierInfo() &&
7932 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7933 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7934 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7935 << SourceRange(D.getIdentifierLoc());
7936 return nullptr;
7937 }
7938
7939 // This is a C++ method declaration.
7940 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7941 cast<CXXRecordDecl>(DC),
7942 D.getLocStart(), NameInfo, R,
7943 TInfo, SC, isInline,
7944 isConstexpr, SourceLocation());
7945 IsVirtualOkay = !Ret->isStatic();
7946 return Ret;
7947 } else {
7948 bool isFriend =
7949 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7950 if (!isFriend && SemaRef.CurContext->isRecord())
7951 return nullptr;
7952
7953 // Determine whether the function was written with a
7954 // prototype. This true when:
7955 // - we're in C++ (where every function has a prototype),
7956 return FunctionDecl::Create(SemaRef.Context, DC,
7957 D.getLocStart(),
7958 NameInfo, R, TInfo, SC, isInline,
7959 true/*HasPrototype*/, isConstexpr);
7960 }
7961}
7962
7963enum OpenCLParamType {
7964 ValidKernelParam,
7965 PtrPtrKernelParam,
7966 PtrKernelParam,
7967 InvalidAddrSpacePtrKernelParam,
7968 InvalidKernelParam,
7969 RecordKernelParam
7970};
7971
7972static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7973 if (PT->isPointerType()) {
7974 QualType PointeeType = PT->getPointeeType();
7975 if (PointeeType->isPointerType())
7976 return PtrPtrKernelParam;
7977 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7978 PointeeType.getAddressSpace() == LangAS::opencl_private ||
7979 PointeeType.getAddressSpace() == LangAS::Default)
7980 return InvalidAddrSpacePtrKernelParam;
7981 return PtrKernelParam;
7982 }
7983
7984 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7985 // be used as builtin types.
7986
7987 if (PT->isImageType())
7988 return PtrKernelParam;
7989
7990 <