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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.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/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
31 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Parse/ParseDiagnostic.h"
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Triple.h"
44 #include <algorithm>
45 #include <cstring>
46 #include <functional>
47 using namespace clang;
48 using namespace sema;
49
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)50 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51 if (OwnedType) {
52 Decl *Group[2] = { OwnedType, Ptr };
53 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54 }
55
56 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
57 }
58
59 namespace {
60
61 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62 public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false)63 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
64 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
65 WantExpressionKeywords = false;
66 WantCXXNamedCasts = false;
67 WantRemainingKeywords = false;
68 }
69
ValidateCandidate(const TypoCorrection & candidate)70 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
71 if (NamedDecl *ND = candidate.getCorrectionDecl())
72 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
73 (AllowInvalidDecl || !ND->isInvalidDecl());
74 else
75 return !WantClassName && candidate.isKeyword();
76 }
77
78 private:
79 bool AllowInvalidDecl;
80 bool WantClassName;
81 };
82
83 }
84
85 /// \brief Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const86 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
87 switch (Kind) {
88 // FIXME: Take into account the current language when deciding whether a
89 // token kind is a valid type specifier
90 case tok::kw_short:
91 case tok::kw_long:
92 case tok::kw___int64:
93 case tok::kw___int128:
94 case tok::kw_signed:
95 case tok::kw_unsigned:
96 case tok::kw_void:
97 case tok::kw_char:
98 case tok::kw_int:
99 case tok::kw_half:
100 case tok::kw_float:
101 case tok::kw_double:
102 case tok::kw_wchar_t:
103 case tok::kw_bool:
104 case tok::kw___underlying_type:
105 return true;
106
107 case tok::annot_typename:
108 case tok::kw_char16_t:
109 case tok::kw_char32_t:
110 case tok::kw_typeof:
111 case tok::kw_decltype:
112 return getLangOpts().CPlusPlus;
113
114 default:
115 break;
116 }
117
118 return false;
119 }
120
121 /// \brief If the identifier refers to a type name within this scope,
122 /// return the declaration of that type.
123 ///
124 /// This routine performs ordinary name lookup of the identifier II
125 /// within the given scope, with optional C++ scope specifier SS, to
126 /// determine whether the name refers to a type. If so, returns an
127 /// opaque pointer (actually a QualType) corresponding to that
128 /// type. Otherwise, returns NULL.
129 ///
130 /// If name lookup results in an ambiguity, this routine will complain
131 /// and then return NULL.
getTypeName(IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec * SS,bool isClassName,bool HasTrailingDot,ParsedType ObjectTypePtr,bool IsCtorOrDtorName,bool WantNontrivialTypeSourceInfo,IdentifierInfo ** CorrectedII)132 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
133 Scope *S, CXXScopeSpec *SS,
134 bool isClassName, bool HasTrailingDot,
135 ParsedType ObjectTypePtr,
136 bool IsCtorOrDtorName,
137 bool WantNontrivialTypeSourceInfo,
138 IdentifierInfo **CorrectedII) {
139 // Determine where we will perform name lookup.
140 DeclContext *LookupCtx = 0;
141 if (ObjectTypePtr) {
142 QualType ObjectType = ObjectTypePtr.get();
143 if (ObjectType->isRecordType())
144 LookupCtx = computeDeclContext(ObjectType);
145 } else if (SS && SS->isNotEmpty()) {
146 LookupCtx = computeDeclContext(*SS, false);
147
148 if (!LookupCtx) {
149 if (isDependentScopeSpecifier(*SS)) {
150 // C++ [temp.res]p3:
151 // A qualified-id that refers to a type and in which the
152 // nested-name-specifier depends on a template-parameter (14.6.2)
153 // shall be prefixed by the keyword typename to indicate that the
154 // qualified-id denotes a type, forming an
155 // elaborated-type-specifier (7.1.5.3).
156 //
157 // We therefore do not perform any name lookup if the result would
158 // refer to a member of an unknown specialization.
159 if (!isClassName && !IsCtorOrDtorName)
160 return ParsedType();
161
162 // We know from the grammar that this name refers to a type,
163 // so build a dependent node to describe the type.
164 if (WantNontrivialTypeSourceInfo)
165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166
167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
168 QualType T =
169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
170 II, NameLoc);
171
172 return ParsedType::make(T);
173 }
174
175 return ParsedType();
176 }
177
178 if (!LookupCtx->isDependentContext() &&
179 RequireCompleteDeclContext(*SS, LookupCtx))
180 return ParsedType();
181 }
182
183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184 // lookup for class-names.
185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186 LookupOrdinaryName;
187 LookupResult Result(*this, &II, NameLoc, Kind);
188 if (LookupCtx) {
189 // Perform "qualified" name lookup into the declaration context we
190 // computed, which is either the type of the base of a member access
191 // expression or the declaration context associated with a prior
192 // nested-name-specifier.
193 LookupQualifiedName(Result, LookupCtx);
194
195 if (ObjectTypePtr && Result.empty()) {
196 // C++ [basic.lookup.classref]p3:
197 // If the unqualified-id is ~type-name, the type-name is looked up
198 // in the context of the entire postfix-expression. If the type T of
199 // the object expression is of a class type C, the type-name is also
200 // looked up in the scope of class C. At least one of the lookups shall
201 // find a name that refers to (possibly cv-qualified) T.
202 LookupName(Result, S);
203 }
204 } else {
205 // Perform unqualified name lookup.
206 LookupName(Result, S);
207 }
208
209 NamedDecl *IIDecl = 0;
210 switch (Result.getResultKind()) {
211 case LookupResult::NotFound:
212 case LookupResult::NotFoundInCurrentInstantiation:
213 if (CorrectedII) {
214 TypeNameValidatorCCC Validator(true, isClassName);
215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
216 Kind, S, SS, Validator);
217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218 TemplateTy Template;
219 bool MemberOfUnknownSpecialization;
220 UnqualifiedId TemplateName;
221 TemplateName.setIdentifier(NewII, NameLoc);
222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223 CXXScopeSpec NewSS, *NewSSPtr = SS;
224 if (SS && NNS) {
225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226 NewSSPtr = &NewSS;
227 }
228 if (Correction && (NNS || NewII != &II) &&
229 // Ignore a correction to a template type as the to-be-corrected
230 // identifier is not a template (typo correction for template names
231 // is handled elsewhere).
232 !(getLangOpts().CPlusPlus && NewSSPtr &&
233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234 false, Template, MemberOfUnknownSpecialization))) {
235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236 isClassName, HasTrailingDot, ObjectTypePtr,
237 IsCtorOrDtorName,
238 WantNontrivialTypeSourceInfo);
239 if (Ty) {
240 std::string CorrectedStr(Correction.getAsString(getLangOpts()));
241 std::string CorrectedQuotedStr(
242 Correction.getQuoted(getLangOpts()));
243 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
244 << Result.getLookupName() << CorrectedQuotedStr << isClassName
245 << FixItHint::CreateReplacement(SourceRange(NameLoc),
246 CorrectedStr);
247 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
248 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
249 << CorrectedQuotedStr;
250
251 if (SS && NNS)
252 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
253 *CorrectedII = NewII;
254 return Ty;
255 }
256 }
257 }
258 // If typo correction failed or was not performed, fall through
259 case LookupResult::FoundOverloaded:
260 case LookupResult::FoundUnresolvedValue:
261 Result.suppressDiagnostics();
262 return ParsedType();
263
264 case LookupResult::Ambiguous:
265 // Recover from type-hiding ambiguities by hiding the type. We'll
266 // do the lookup again when looking for an object, and we can
267 // diagnose the error then. If we don't do this, then the error
268 // about hiding the type will be immediately followed by an error
269 // that only makes sense if the identifier was treated like a type.
270 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
271 Result.suppressDiagnostics();
272 return ParsedType();
273 }
274
275 // Look to see if we have a type anywhere in the list of results.
276 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
277 Res != ResEnd; ++Res) {
278 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
279 if (!IIDecl ||
280 (*Res)->getLocation().getRawEncoding() <
281 IIDecl->getLocation().getRawEncoding())
282 IIDecl = *Res;
283 }
284 }
285
286 if (!IIDecl) {
287 // None of the entities we found is a type, so there is no way
288 // to even assume that the result is a type. In this case, don't
289 // complain about the ambiguity. The parser will either try to
290 // perform this lookup again (e.g., as an object name), which
291 // will produce the ambiguity, or will complain that it expected
292 // a type name.
293 Result.suppressDiagnostics();
294 return ParsedType();
295 }
296
297 // We found a type within the ambiguous lookup; diagnose the
298 // ambiguity and then return that type. This might be the right
299 // answer, or it might not be, but it suppresses any attempt to
300 // perform the name lookup again.
301 break;
302
303 case LookupResult::Found:
304 IIDecl = Result.getFoundDecl();
305 break;
306 }
307
308 assert(IIDecl && "Didn't find decl");
309
310 QualType T;
311 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
312 DiagnoseUseOfDecl(IIDecl, NameLoc);
313
314 if (T.isNull())
315 T = Context.getTypeDeclType(TD);
316
317 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
318 // constructor or destructor name (in such a case, the scope specifier
319 // will be attached to the enclosing Expr or Decl node).
320 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
321 if (WantNontrivialTypeSourceInfo) {
322 // Construct a type with type-source information.
323 TypeLocBuilder Builder;
324 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
325
326 T = getElaboratedType(ETK_None, *SS, T);
327 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
328 ElabTL.setElaboratedKeywordLoc(SourceLocation());
329 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
330 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
331 } else {
332 T = getElaboratedType(ETK_None, *SS, T);
333 }
334 }
335 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
336 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
337 if (!HasTrailingDot)
338 T = Context.getObjCInterfaceType(IDecl);
339 }
340
341 if (T.isNull()) {
342 // If it's not plausibly a type, suppress diagnostics.
343 Result.suppressDiagnostics();
344 return ParsedType();
345 }
346 return ParsedType::make(T);
347 }
348
349 /// isTagName() - This method is called *for error recovery purposes only*
350 /// to determine if the specified name is a valid tag name ("struct foo"). If
351 /// so, this returns the TST for the tag corresponding to it (TST_enum,
352 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
353 /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)354 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
355 // Do a tag name lookup in this scope.
356 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
357 LookupName(R, S, false);
358 R.suppressDiagnostics();
359 if (R.getResultKind() == LookupResult::Found)
360 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
361 switch (TD->getTagKind()) {
362 case TTK_Struct: return DeclSpec::TST_struct;
363 case TTK_Interface: return DeclSpec::TST_interface;
364 case TTK_Union: return DeclSpec::TST_union;
365 case TTK_Class: return DeclSpec::TST_class;
366 case TTK_Enum: return DeclSpec::TST_enum;
367 }
368 }
369
370 return DeclSpec::TST_unspecified;
371 }
372
373 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
374 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
375 /// then downgrade the missing typename error to a warning.
376 /// This is needed for MSVC compatibility; Example:
377 /// @code
378 /// template<class T> class A {
379 /// public:
380 /// typedef int TYPE;
381 /// };
382 /// template<class T> class B : public A<T> {
383 /// public:
384 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
385 /// };
386 /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)387 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
388 if (CurContext->isRecord()) {
389 const Type *Ty = SS->getScopeRep()->getAsType();
390
391 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
392 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
393 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
394 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
395 return true;
396 return S->isFunctionPrototypeScope();
397 }
398 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
399 }
400
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType)401 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
402 SourceLocation IILoc,
403 Scope *S,
404 CXXScopeSpec *SS,
405 ParsedType &SuggestedType) {
406 // We don't have anything to suggest (yet).
407 SuggestedType = ParsedType();
408
409 // There may have been a typo in the name of the type. Look up typo
410 // results, in case we have something that we can suggest.
411 TypeNameValidatorCCC Validator(false);
412 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
413 LookupOrdinaryName, S, SS,
414 Validator)) {
415 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
416 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
417
418 if (Corrected.isKeyword()) {
419 // We corrected to a keyword.
420 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
421 if (!isSimpleTypeSpecifier(NewII->getTokenID()))
422 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
423 Diag(IILoc, diag::err_unknown_typename_suggest)
424 << II << CorrectedQuotedStr
425 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
426 II = NewII;
427 } else {
428 NamedDecl *Result = Corrected.getCorrectionDecl();
429 // We found a similarly-named type or interface; suggest that.
430 if (!SS || !SS->isSet())
431 Diag(IILoc, diag::err_unknown_typename_suggest)
432 << II << CorrectedQuotedStr
433 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
434 else if (DeclContext *DC = computeDeclContext(*SS, false))
435 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
436 << II << DC << CorrectedQuotedStr << SS->getRange()
437 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
438 CorrectedStr);
439 else
440 llvm_unreachable("could not have corrected a typo here");
441
442 Diag(Result->getLocation(), diag::note_previous_decl)
443 << CorrectedQuotedStr;
444
445 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
446 false, false, ParsedType(),
447 /*IsCtorOrDtorName=*/false,
448 /*NonTrivialTypeSourceInfo=*/true);
449 }
450 return true;
451 }
452
453 if (getLangOpts().CPlusPlus) {
454 // See if II is a class template that the user forgot to pass arguments to.
455 UnqualifiedId Name;
456 Name.setIdentifier(II, IILoc);
457 CXXScopeSpec EmptySS;
458 TemplateTy TemplateResult;
459 bool MemberOfUnknownSpecialization;
460 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
461 Name, ParsedType(), true, TemplateResult,
462 MemberOfUnknownSpecialization) == TNK_Type_template) {
463 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
464 Diag(IILoc, diag::err_template_missing_args) << TplName;
465 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
466 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
467 << TplDecl->getTemplateParameters()->getSourceRange();
468 }
469 return true;
470 }
471 }
472
473 // FIXME: Should we move the logic that tries to recover from a missing tag
474 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
475
476 if (!SS || (!SS->isSet() && !SS->isInvalid()))
477 Diag(IILoc, diag::err_unknown_typename) << II;
478 else if (DeclContext *DC = computeDeclContext(*SS, false))
479 Diag(IILoc, diag::err_typename_nested_not_found)
480 << II << DC << SS->getRange();
481 else if (isDependentScopeSpecifier(*SS)) {
482 unsigned DiagID = diag::err_typename_missing;
483 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
484 DiagID = diag::warn_typename_missing;
485
486 Diag(SS->getRange().getBegin(), DiagID)
487 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
488 << SourceRange(SS->getRange().getBegin(), IILoc)
489 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
490 SuggestedType = ActOnTypenameType(S, SourceLocation(),
491 *SS, *II, IILoc).get();
492 } else {
493 assert(SS && SS->isInvalid() &&
494 "Invalid scope specifier has already been diagnosed");
495 }
496
497 return true;
498 }
499
500 /// \brief Determine whether the given result set contains either a type name
501 /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)502 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
503 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
504 NextToken.is(tok::less);
505
506 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
507 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
508 return true;
509
510 if (CheckTemplate && isa<TemplateDecl>(*I))
511 return true;
512 }
513
514 return false;
515 }
516
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)517 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
518 Scope *S, CXXScopeSpec &SS,
519 IdentifierInfo *&Name,
520 SourceLocation NameLoc) {
521 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
522 SemaRef.LookupParsedName(R, S, &SS);
523 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
524 const char *TagName = 0;
525 const char *FixItTagName = 0;
526 switch (Tag->getTagKind()) {
527 case TTK_Class:
528 TagName = "class";
529 FixItTagName = "class ";
530 break;
531
532 case TTK_Enum:
533 TagName = "enum";
534 FixItTagName = "enum ";
535 break;
536
537 case TTK_Struct:
538 TagName = "struct";
539 FixItTagName = "struct ";
540 break;
541
542 case TTK_Interface:
543 TagName = "__interface";
544 FixItTagName = "__interface ";
545 break;
546
547 case TTK_Union:
548 TagName = "union";
549 FixItTagName = "union ";
550 break;
551 }
552
553 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
554 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
555 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
556
557 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
558 I != IEnd; ++I)
559 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
560 << Name << TagName;
561
562 // Replace lookup results with just the tag decl.
563 Result.clear(Sema::LookupTagName);
564 SemaRef.LookupParsedName(Result, S, &SS);
565 return true;
566 }
567
568 return false;
569 }
570
571 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNestedType(Sema & S,CXXScopeSpec & SS,QualType T,SourceLocation NameLoc)572 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
573 QualType T, SourceLocation NameLoc) {
574 ASTContext &Context = S.Context;
575
576 TypeLocBuilder Builder;
577 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
578
579 T = S.getElaboratedType(ETK_None, SS, T);
580 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
581 ElabTL.setElaboratedKeywordLoc(SourceLocation());
582 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
583 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
584 }
585
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC)586 Sema::NameClassification Sema::ClassifyName(Scope *S,
587 CXXScopeSpec &SS,
588 IdentifierInfo *&Name,
589 SourceLocation NameLoc,
590 const Token &NextToken,
591 bool IsAddressOfOperand,
592 CorrectionCandidateCallback *CCC) {
593 DeclarationNameInfo NameInfo(Name, NameLoc);
594 ObjCMethodDecl *CurMethod = getCurMethodDecl();
595
596 if (NextToken.is(tok::coloncolon)) {
597 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
598 QualType(), false, SS, 0, false);
599
600 }
601
602 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
603 LookupParsedName(Result, S, &SS, !CurMethod);
604
605 // Perform lookup for Objective-C instance variables (including automatically
606 // synthesized instance variables), if we're in an Objective-C method.
607 // FIXME: This lookup really, really needs to be folded in to the normal
608 // unqualified lookup mechanism.
609 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
610 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
611 if (E.get() || E.isInvalid())
612 return E;
613 }
614
615 bool SecondTry = false;
616 bool IsFilteredTemplateName = false;
617
618 Corrected:
619 switch (Result.getResultKind()) {
620 case LookupResult::NotFound:
621 // If an unqualified-id is followed by a '(', then we have a function
622 // call.
623 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
624 // In C++, this is an ADL-only call.
625 // FIXME: Reference?
626 if (getLangOpts().CPlusPlus)
627 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
628
629 // C90 6.3.2.2:
630 // If the expression that precedes the parenthesized argument list in a
631 // function call consists solely of an identifier, and if no
632 // declaration is visible for this identifier, the identifier is
633 // implicitly declared exactly as if, in the innermost block containing
634 // the function call, the declaration
635 //
636 // extern int identifier ();
637 //
638 // appeared.
639 //
640 // We also allow this in C99 as an extension.
641 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
642 Result.addDecl(D);
643 Result.resolveKind();
644 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
645 }
646 }
647
648 // In C, we first see whether there is a tag type by the same name, in
649 // which case it's likely that the user just forget to write "enum",
650 // "struct", or "union".
651 if (!getLangOpts().CPlusPlus && !SecondTry &&
652 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
653 break;
654 }
655
656 // Perform typo correction to determine if there is another name that is
657 // close to this name.
658 if (!SecondTry && CCC) {
659 SecondTry = true;
660 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
661 Result.getLookupKind(), S,
662 &SS, *CCC)) {
663 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
664 unsigned QualifiedDiag = diag::err_no_member_suggest;
665 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
666 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
667
668 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
669 NamedDecl *UnderlyingFirstDecl
670 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
671 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
673 UnqualifiedDiag = diag::err_no_template_suggest;
674 QualifiedDiag = diag::err_no_member_template_suggest;
675 } else if (UnderlyingFirstDecl &&
676 (isa<TypeDecl>(UnderlyingFirstDecl) ||
677 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
678 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
679 UnqualifiedDiag = diag::err_unknown_typename_suggest;
680 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
681 }
682
683 if (SS.isEmpty())
684 Diag(NameLoc, UnqualifiedDiag)
685 << Name << CorrectedQuotedStr
686 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
687 else // FIXME: is this even reachable? Test it.
688 Diag(NameLoc, QualifiedDiag)
689 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
690 << SS.getRange()
691 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
692 CorrectedStr);
693
694 // Update the name, so that the caller has the new name.
695 Name = Corrected.getCorrectionAsIdentifierInfo();
696
697 // Typo correction corrected to a keyword.
698 if (Corrected.isKeyword())
699 return Corrected.getCorrectionAsIdentifierInfo();
700
701 // Also update the LookupResult...
702 // FIXME: This should probably go away at some point
703 Result.clear();
704 Result.setLookupName(Corrected.getCorrection());
705 if (FirstDecl) {
706 Result.addDecl(FirstDecl);
707 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
708 << CorrectedQuotedStr;
709 }
710
711 // If we found an Objective-C instance variable, let
712 // LookupInObjCMethod build the appropriate expression to
713 // reference the ivar.
714 // FIXME: This is a gross hack.
715 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
716 Result.clear();
717 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
718 return E;
719 }
720
721 goto Corrected;
722 }
723 }
724
725 // We failed to correct; just fall through and let the parser deal with it.
726 Result.suppressDiagnostics();
727 return NameClassification::Unknown();
728
729 case LookupResult::NotFoundInCurrentInstantiation: {
730 // We performed name lookup into the current instantiation, and there were
731 // dependent bases, so we treat this result the same way as any other
732 // dependent nested-name-specifier.
733
734 // C++ [temp.res]p2:
735 // A name used in a template declaration or definition and that is
736 // dependent on a template-parameter is assumed not to name a type
737 // unless the applicable name lookup finds a type name or the name is
738 // qualified by the keyword typename.
739 //
740 // FIXME: If the next token is '<', we might want to ask the parser to
741 // perform some heroics to see if we actually have a
742 // template-argument-list, which would indicate a missing 'template'
743 // keyword here.
744 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
745 NameInfo, IsAddressOfOperand,
746 /*TemplateArgs=*/0);
747 }
748
749 case LookupResult::Found:
750 case LookupResult::FoundOverloaded:
751 case LookupResult::FoundUnresolvedValue:
752 break;
753
754 case LookupResult::Ambiguous:
755 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
756 hasAnyAcceptableTemplateNames(Result)) {
757 // C++ [temp.local]p3:
758 // A lookup that finds an injected-class-name (10.2) can result in an
759 // ambiguity in certain cases (for example, if it is found in more than
760 // one base class). If all of the injected-class-names that are found
761 // refer to specializations of the same class template, and if the name
762 // is followed by a template-argument-list, the reference refers to the
763 // class template itself and not a specialization thereof, and is not
764 // ambiguous.
765 //
766 // This filtering can make an ambiguous result into an unambiguous one,
767 // so try again after filtering out template names.
768 FilterAcceptableTemplateNames(Result);
769 if (!Result.isAmbiguous()) {
770 IsFilteredTemplateName = true;
771 break;
772 }
773 }
774
775 // Diagnose the ambiguity and return an error.
776 return NameClassification::Error();
777 }
778
779 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
781 // C++ [temp.names]p3:
782 // After name lookup (3.4) finds that a name is a template-name or that
783 // an operator-function-id or a literal- operator-id refers to a set of
784 // overloaded functions any member of which is a function template if
785 // this is followed by a <, the < is always taken as the delimiter of a
786 // template-argument-list and never as the less-than operator.
787 if (!IsFilteredTemplateName)
788 FilterAcceptableTemplateNames(Result);
789
790 if (!Result.empty()) {
791 bool IsFunctionTemplate;
792 TemplateName Template;
793 if (Result.end() - Result.begin() > 1) {
794 IsFunctionTemplate = true;
795 Template = Context.getOverloadedTemplateName(Result.begin(),
796 Result.end());
797 } else {
798 TemplateDecl *TD
799 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
800 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
801
802 if (SS.isSet() && !SS.isInvalid())
803 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
804 /*TemplateKeyword=*/false,
805 TD);
806 else
807 Template = TemplateName(TD);
808 }
809
810 if (IsFunctionTemplate) {
811 // Function templates always go through overload resolution, at which
812 // point we'll perform the various checks (e.g., accessibility) we need
813 // to based on which function we selected.
814 Result.suppressDiagnostics();
815
816 return NameClassification::FunctionTemplate(Template);
817 }
818
819 return NameClassification::TypeTemplate(Template);
820 }
821 }
822
823 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
824 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
825 DiagnoseUseOfDecl(Type, NameLoc);
826 QualType T = Context.getTypeDeclType(Type);
827 if (SS.isNotEmpty())
828 return buildNestedType(*this, SS, T, NameLoc);
829 return ParsedType::make(T);
830 }
831
832 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
833 if (!Class) {
834 // FIXME: It's unfortunate that we don't have a Type node for handling this.
835 if (ObjCCompatibleAliasDecl *Alias
836 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
837 Class = Alias->getClassInterface();
838 }
839
840 if (Class) {
841 DiagnoseUseOfDecl(Class, NameLoc);
842
843 if (NextToken.is(tok::period)) {
844 // Interface. <something> is parsed as a property reference expression.
845 // Just return "unknown" as a fall-through for now.
846 Result.suppressDiagnostics();
847 return NameClassification::Unknown();
848 }
849
850 QualType T = Context.getObjCInterfaceType(Class);
851 return ParsedType::make(T);
852 }
853
854 // We can have a type template here if we're classifying a template argument.
855 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
856 return NameClassification::TypeTemplate(
857 TemplateName(cast<TemplateDecl>(FirstDecl)));
858
859 // Check for a tag type hidden by a non-type decl in a few cases where it
860 // seems likely a type is wanted instead of the non-type that was found.
861 if (!getLangOpts().ObjC1) {
862 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
863 if ((NextToken.is(tok::identifier) ||
864 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
865 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
866 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
867 DiagnoseUseOfDecl(Type, NameLoc);
868 QualType T = Context.getTypeDeclType(Type);
869 if (SS.isNotEmpty())
870 return buildNestedType(*this, SS, T, NameLoc);
871 return ParsedType::make(T);
872 }
873 }
874
875 if (FirstDecl->isCXXClassMember())
876 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
877
878 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
879 return BuildDeclarationNameExpr(SS, Result, ADL);
880 }
881
882 // Determines the context to return to after temporarily entering a
883 // context. This depends in an unnecessarily complicated way on the
884 // exact ordering of callbacks from the parser.
getContainingDC(DeclContext * DC)885 DeclContext *Sema::getContainingDC(DeclContext *DC) {
886
887 // Functions defined inline within classes aren't parsed until we've
888 // finished parsing the top-level class, so the top-level class is
889 // the context we'll need to return to.
890 if (isa<FunctionDecl>(DC)) {
891 DC = DC->getLexicalParent();
892
893 // A function not defined within a class will always return to its
894 // lexical context.
895 if (!isa<CXXRecordDecl>(DC))
896 return DC;
897
898 // A C++ inline method/friend is parsed *after* the topmost class
899 // it was declared in is fully parsed ("complete"); the topmost
900 // class is the context we need to return to.
901 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
902 DC = RD;
903
904 // Return the declaration context of the topmost class the inline method is
905 // declared in.
906 return DC;
907 }
908
909 return DC->getLexicalParent();
910 }
911
PushDeclContext(Scope * S,DeclContext * DC)912 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
913 assert(getContainingDC(DC) == CurContext &&
914 "The next DeclContext should be lexically contained in the current one.");
915 CurContext = DC;
916 S->setEntity(DC);
917 }
918
PopDeclContext()919 void Sema::PopDeclContext() {
920 assert(CurContext && "DeclContext imbalance!");
921
922 CurContext = getContainingDC(CurContext);
923 assert(CurContext && "Popped translation unit!");
924 }
925
926 /// EnterDeclaratorContext - Used when we must lookup names in the context
927 /// of a declarator's nested name specifier.
928 ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)929 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
930 // C++0x [basic.lookup.unqual]p13:
931 // A name used in the definition of a static data member of class
932 // X (after the qualified-id of the static member) is looked up as
933 // if the name was used in a member function of X.
934 // C++0x [basic.lookup.unqual]p14:
935 // If a variable member of a namespace is defined outside of the
936 // scope of its namespace then any name used in the definition of
937 // the variable member (after the declarator-id) is looked up as
938 // if the definition of the variable member occurred in its
939 // namespace.
940 // Both of these imply that we should push a scope whose context
941 // is the semantic context of the declaration. We can't use
942 // PushDeclContext here because that context is not necessarily
943 // lexically contained in the current context. Fortunately,
944 // the containing scope should have the appropriate information.
945
946 assert(!S->getEntity() && "scope already has entity");
947
948 #ifndef NDEBUG
949 Scope *Ancestor = S->getParent();
950 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
951 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
952 #endif
953
954 CurContext = DC;
955 S->setEntity(DC);
956 }
957
ExitDeclaratorContext(Scope * S)958 void Sema::ExitDeclaratorContext(Scope *S) {
959 assert(S->getEntity() == CurContext && "Context imbalance!");
960
961 // Switch back to the lexical context. The safety of this is
962 // enforced by an assert in EnterDeclaratorContext.
963 Scope *Ancestor = S->getParent();
964 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
965 CurContext = (DeclContext*) Ancestor->getEntity();
966
967 // We don't need to do anything with the scope, which is going to
968 // disappear.
969 }
970
971
ActOnReenterFunctionContext(Scope * S,Decl * D)972 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
973 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
974 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
975 // We assume that the caller has already called
976 // ActOnReenterTemplateScope
977 FD = TFD->getTemplatedDecl();
978 }
979 if (!FD)
980 return;
981
982 // Same implementation as PushDeclContext, but enters the context
983 // from the lexical parent, rather than the top-level class.
984 assert(CurContext == FD->getLexicalParent() &&
985 "The next DeclContext should be lexically contained in the current one.");
986 CurContext = FD;
987 S->setEntity(CurContext);
988
989 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
990 ParmVarDecl *Param = FD->getParamDecl(P);
991 // If the parameter has an identifier, then add it to the scope
992 if (Param->getIdentifier()) {
993 S->AddDecl(Param);
994 IdResolver.AddDecl(Param);
995 }
996 }
997 }
998
999
ActOnExitFunctionContext()1000 void Sema::ActOnExitFunctionContext() {
1001 // Same implementation as PopDeclContext, but returns to the lexical parent,
1002 // rather than the top-level class.
1003 assert(CurContext && "DeclContext imbalance!");
1004 CurContext = CurContext->getLexicalParent();
1005 assert(CurContext && "Popped translation unit!");
1006 }
1007
1008
1009 /// \brief Determine whether we allow overloading of the function
1010 /// PrevDecl with another declaration.
1011 ///
1012 /// This routine determines whether overloading is possible, not
1013 /// whether some new function is actually an overload. It will return
1014 /// true in C++ (where we can always provide overloads) or, as an
1015 /// extension, in C when the previous function is already an
1016 /// overloaded function declaration or has the "overloadable"
1017 /// attribute.
AllowOverloadingOfFunction(LookupResult & Previous,ASTContext & Context)1018 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1019 ASTContext &Context) {
1020 if (Context.getLangOpts().CPlusPlus)
1021 return true;
1022
1023 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1024 return true;
1025
1026 return (Previous.getResultKind() == LookupResult::Found
1027 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1028 }
1029
1030 /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1031 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1032 // Move up the scope chain until we find the nearest enclosing
1033 // non-transparent context. The declaration will be introduced into this
1034 // scope.
1035 while (S->getEntity() &&
1036 ((DeclContext *)S->getEntity())->isTransparentContext())
1037 S = S->getParent();
1038
1039 // Add scoped declarations into their context, so that they can be
1040 // found later. Declarations without a context won't be inserted
1041 // into any context.
1042 if (AddToContext)
1043 CurContext->addDecl(D);
1044
1045 // Out-of-line definitions shouldn't be pushed into scope in C++.
1046 // Out-of-line variable and function definitions shouldn't even in C.
1047 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
1048 D->isOutOfLine() &&
1049 !D->getDeclContext()->getRedeclContext()->Equals(
1050 D->getLexicalDeclContext()->getRedeclContext()))
1051 return;
1052
1053 // Template instantiations should also not be pushed into scope.
1054 if (isa<FunctionDecl>(D) &&
1055 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1056 return;
1057
1058 // If this replaces anything in the current scope,
1059 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1060 IEnd = IdResolver.end();
1061 for (; I != IEnd; ++I) {
1062 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1063 S->RemoveDecl(*I);
1064 IdResolver.RemoveDecl(*I);
1065
1066 // Should only need to replace one decl.
1067 break;
1068 }
1069 }
1070
1071 S->AddDecl(D);
1072
1073 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1074 // Implicitly-generated labels may end up getting generated in an order that
1075 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1076 // the label at the appropriate place in the identifier chain.
1077 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1078 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1079 if (IDC == CurContext) {
1080 if (!S->isDeclScope(*I))
1081 continue;
1082 } else if (IDC->Encloses(CurContext))
1083 break;
1084 }
1085
1086 IdResolver.InsertDeclAfter(I, D);
1087 } else {
1088 IdResolver.AddDecl(D);
1089 }
1090 }
1091
pushExternalDeclIntoScope(NamedDecl * D,DeclarationName Name)1092 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1093 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1094 TUScope->AddDecl(D);
1095 }
1096
isDeclInScope(NamedDecl * & D,DeclContext * Ctx,Scope * S,bool ExplicitInstantiationOrSpecialization)1097 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1098 bool ExplicitInstantiationOrSpecialization) {
1099 return IdResolver.isDeclInScope(D, Ctx, S,
1100 ExplicitInstantiationOrSpecialization);
1101 }
1102
getScopeForDeclContext(Scope * S,DeclContext * DC)1103 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1104 DeclContext *TargetDC = DC->getPrimaryContext();
1105 do {
1106 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1107 if (ScopeDC->getPrimaryContext() == TargetDC)
1108 return S;
1109 } while ((S = S->getParent()));
1110
1111 return 0;
1112 }
1113
1114 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1115 DeclContext*,
1116 ASTContext&);
1117
1118 /// Filters out lookup results that don't fall within the given scope
1119 /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool ExplicitInstantiationOrSpecialization)1120 void Sema::FilterLookupForScope(LookupResult &R,
1121 DeclContext *Ctx, Scope *S,
1122 bool ConsiderLinkage,
1123 bool ExplicitInstantiationOrSpecialization) {
1124 LookupResult::Filter F = R.makeFilter();
1125 while (F.hasNext()) {
1126 NamedDecl *D = F.next();
1127
1128 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1129 continue;
1130
1131 if (ConsiderLinkage &&
1132 isOutOfScopePreviousDeclaration(D, Ctx, Context))
1133 continue;
1134
1135 F.erase();
1136 }
1137
1138 F.done();
1139 }
1140
isUsingDecl(NamedDecl * D)1141 static bool isUsingDecl(NamedDecl *D) {
1142 return isa<UsingShadowDecl>(D) ||
1143 isa<UnresolvedUsingTypenameDecl>(D) ||
1144 isa<UnresolvedUsingValueDecl>(D);
1145 }
1146
1147 /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1148 static void RemoveUsingDecls(LookupResult &R) {
1149 LookupResult::Filter F = R.makeFilter();
1150 while (F.hasNext())
1151 if (isUsingDecl(F.next()))
1152 F.erase();
1153
1154 F.done();
1155 }
1156
1157 /// \brief Check for this common pattern:
1158 /// @code
1159 /// class S {
1160 /// S(const S&); // DO NOT IMPLEMENT
1161 /// void operator=(const S&); // DO NOT IMPLEMENT
1162 /// };
1163 /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1164 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1165 // FIXME: Should check for private access too but access is set after we get
1166 // the decl here.
1167 if (D->doesThisDeclarationHaveABody())
1168 return false;
1169
1170 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1171 return CD->isCopyConstructor();
1172 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1173 return Method->isCopyAssignmentOperator();
1174 return false;
1175 }
1176
1177 // We need this to handle
1178 //
1179 // typedef struct {
1180 // void *foo() { return 0; }
1181 // } A;
1182 //
1183 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1184 // for example. If 'A', foo will have external linkage. If we have '*A',
1185 // foo will have no linkage. Since we can't know untill we get to the end
1186 // of the typedef, this function finds out if D might have non external linkage.
1187 // Callers should verify at the end of the TU if it D has external linkage or
1188 // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1189 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1190 const DeclContext *DC = D->getDeclContext();
1191 while (!DC->isTranslationUnit()) {
1192 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1193 if (!RD->hasNameForLinkage())
1194 return true;
1195 }
1196 DC = DC->getParent();
1197 }
1198
1199 return !D->hasExternalLinkage();
1200 }
1201
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1202 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1203 assert(D);
1204
1205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1206 return false;
1207
1208 // Ignore class templates.
1209 if (D->getDeclContext()->isDependentContext() ||
1210 D->getLexicalDeclContext()->isDependentContext())
1211 return false;
1212
1213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1214 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1215 return false;
1216
1217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1218 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1219 return false;
1220 } else {
1221 // 'static inline' functions are used in headers; don't warn.
1222 if (FD->getStorageClass() == SC_Static &&
1223 FD->isInlineSpecified())
1224 return false;
1225 }
1226
1227 if (FD->doesThisDeclarationHaveABody() &&
1228 Context.DeclMustBeEmitted(FD))
1229 return false;
1230 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1231 // Don't warn on variables of const-qualified or reference type, since their
1232 // values can be used even if though they're not odr-used, and because const
1233 // qualified variables can appear in headers in contexts where they're not
1234 // intended to be used.
1235 // FIXME: Use more principled rules for these exemptions.
1236 if (!VD->isFileVarDecl() ||
1237 VD->getType().isConstQualified() ||
1238 VD->getType()->isReferenceType() ||
1239 Context.DeclMustBeEmitted(VD))
1240 return false;
1241
1242 if (VD->isStaticDataMember() &&
1243 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1244 return false;
1245
1246 } else {
1247 return false;
1248 }
1249
1250 // Only warn for unused decls internal to the translation unit.
1251 return mightHaveNonExternalLinkage(D);
1252 }
1253
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1254 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1255 if (!D)
1256 return;
1257
1258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1259 const FunctionDecl *First = FD->getFirstDeclaration();
1260 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1261 return; // First should already be in the vector.
1262 }
1263
1264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1265 const VarDecl *First = VD->getFirstDeclaration();
1266 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1267 return; // First should already be in the vector.
1268 }
1269
1270 if (ShouldWarnIfUnusedFileScopedDecl(D))
1271 UnusedFileScopedDecls.push_back(D);
1272 }
1273
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1274 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1275 if (D->isInvalidDecl())
1276 return false;
1277
1278 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1279 return false;
1280
1281 if (isa<LabelDecl>(D))
1282 return true;
1283
1284 // White-list anything that isn't a local variable.
1285 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1286 !D->getDeclContext()->isFunctionOrMethod())
1287 return false;
1288
1289 // Types of valid local variables should be complete, so this should succeed.
1290 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1291
1292 // White-list anything with an __attribute__((unused)) type.
1293 QualType Ty = VD->getType();
1294
1295 // Only look at the outermost level of typedef.
1296 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1297 if (TT->getDecl()->hasAttr<UnusedAttr>())
1298 return false;
1299 }
1300
1301 // If we failed to complete the type for some reason, or if the type is
1302 // dependent, don't diagnose the variable.
1303 if (Ty->isIncompleteType() || Ty->isDependentType())
1304 return false;
1305
1306 if (const TagType *TT = Ty->getAs<TagType>()) {
1307 const TagDecl *Tag = TT->getDecl();
1308 if (Tag->hasAttr<UnusedAttr>())
1309 return false;
1310
1311 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1312 if (!RD->hasTrivialDestructor())
1313 return false;
1314
1315 if (const Expr *Init = VD->getInit()) {
1316 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1317 Init = Cleanups->getSubExpr();
1318 const CXXConstructExpr *Construct =
1319 dyn_cast<CXXConstructExpr>(Init);
1320 if (Construct && !Construct->isElidable()) {
1321 CXXConstructorDecl *CD = Construct->getConstructor();
1322 if (!CD->isTrivial())
1323 return false;
1324 }
1325 }
1326 }
1327 }
1328
1329 // TODO: __attribute__((unused)) templates?
1330 }
1331
1332 return true;
1333 }
1334
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)1335 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1336 FixItHint &Hint) {
1337 if (isa<LabelDecl>(D)) {
1338 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1339 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1340 if (AfterColon.isInvalid())
1341 return;
1342 Hint = FixItHint::CreateRemoval(CharSourceRange::
1343 getCharRange(D->getLocStart(), AfterColon));
1344 }
1345 return;
1346 }
1347
1348 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1349 /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D)1350 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1351 FixItHint Hint;
1352 if (!ShouldDiagnoseUnusedDecl(D))
1353 return;
1354
1355 GenerateFixForUnusedDecl(D, Context, Hint);
1356
1357 unsigned DiagID;
1358 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1359 DiagID = diag::warn_unused_exception_param;
1360 else if (isa<LabelDecl>(D))
1361 DiagID = diag::warn_unused_label;
1362 else
1363 DiagID = diag::warn_unused_variable;
1364
1365 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1366 }
1367
CheckPoppedLabel(LabelDecl * L,Sema & S)1368 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1369 // Verify that we have no forward references left. If so, there was a goto
1370 // or address of a label taken, but no definition of it. Label fwd
1371 // definitions are indicated with a null substmt.
1372 if (L->getStmt() == 0)
1373 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1374 }
1375
ActOnPopScope(SourceLocation Loc,Scope * S)1376 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1377 if (S->decl_empty()) return;
1378 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1379 "Scope shouldn't contain decls!");
1380
1381 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1382 I != E; ++I) {
1383 Decl *TmpD = (*I);
1384 assert(TmpD && "This decl didn't get pushed??");
1385
1386 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1387 NamedDecl *D = cast<NamedDecl>(TmpD);
1388
1389 if (!D->getDeclName()) continue;
1390
1391 // Diagnose unused variables in this scope.
1392 if (!S->hasErrorOccurred())
1393 DiagnoseUnusedDecl(D);
1394
1395 // If this was a forward reference to a label, verify it was defined.
1396 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1397 CheckPoppedLabel(LD, *this);
1398
1399 // Remove this name from our lexical scope.
1400 IdResolver.RemoveDecl(D);
1401 }
1402 }
1403
ActOnStartFunctionDeclarator()1404 void Sema::ActOnStartFunctionDeclarator() {
1405 ++InFunctionDeclarator;
1406 }
1407
ActOnEndFunctionDeclarator()1408 void Sema::ActOnEndFunctionDeclarator() {
1409 assert(InFunctionDeclarator);
1410 --InFunctionDeclarator;
1411 }
1412
1413 /// \brief Look for an Objective-C class in the translation unit.
1414 ///
1415 /// \param Id The name of the Objective-C class we're looking for. If
1416 /// typo-correction fixes this name, the Id will be updated
1417 /// to the fixed name.
1418 ///
1419 /// \param IdLoc The location of the name in the translation unit.
1420 ///
1421 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1422 /// if there is no class with the given name.
1423 ///
1424 /// \returns The declaration of the named Objective-C class, or NULL if the
1425 /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)1426 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1427 SourceLocation IdLoc,
1428 bool DoTypoCorrection) {
1429 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1430 // creation from this context.
1431 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1432
1433 if (!IDecl && DoTypoCorrection) {
1434 // Perform typo correction at the given location, but only if we
1435 // find an Objective-C class name.
1436 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1437 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1438 LookupOrdinaryName, TUScope, NULL,
1439 Validator)) {
1440 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1441 Diag(IdLoc, diag::err_undef_interface_suggest)
1442 << Id << IDecl->getDeclName()
1443 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1444 Diag(IDecl->getLocation(), diag::note_previous_decl)
1445 << IDecl->getDeclName();
1446
1447 Id = IDecl->getIdentifier();
1448 }
1449 }
1450 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1451 // This routine must always return a class definition, if any.
1452 if (Def && Def->getDefinition())
1453 Def = Def->getDefinition();
1454 return Def;
1455 }
1456
1457 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1458 /// from S, where a non-field would be declared. This routine copes
1459 /// with the difference between C and C++ scoping rules in structs and
1460 /// unions. For example, the following code is well-formed in C but
1461 /// ill-formed in C++:
1462 /// @code
1463 /// struct S6 {
1464 /// enum { BAR } e;
1465 /// };
1466 ///
1467 /// void test_S6() {
1468 /// struct S6 a;
1469 /// a.e = BAR;
1470 /// }
1471 /// @endcode
1472 /// For the declaration of BAR, this routine will return a different
1473 /// scope. The scope S will be the scope of the unnamed enumeration
1474 /// within S6. In C++, this routine will return the scope associated
1475 /// with S6, because the enumeration's scope is a transparent
1476 /// context but structures can contain non-field names. In C, this
1477 /// routine will return the translation unit scope, since the
1478 /// enumeration's scope is a transparent context and structures cannot
1479 /// contain non-field names.
getNonFieldDeclScope(Scope * S)1480 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1481 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1482 (S->getEntity() &&
1483 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1484 (S->isClassScope() && !getLangOpts().CPlusPlus))
1485 S = S->getParent();
1486 return S;
1487 }
1488
1489 /// \brief Looks up the declaration of "struct objc_super" and
1490 /// saves it for later use in building builtin declaration of
1491 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1492 /// pre-existing declaration exists no action takes place.
LookupPredefedObjCSuperType(Sema & ThisSema,Scope * S,IdentifierInfo * II)1493 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1494 IdentifierInfo *II) {
1495 if (!II->isStr("objc_msgSendSuper"))
1496 return;
1497 ASTContext &Context = ThisSema.Context;
1498
1499 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1500 SourceLocation(), Sema::LookupTagName);
1501 ThisSema.LookupName(Result, S);
1502 if (Result.getResultKind() == LookupResult::Found)
1503 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1504 Context.setObjCSuperType(Context.getTagDeclType(TD));
1505 }
1506
1507 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1508 /// file scope. lazily create a decl for it. ForRedeclaration is true
1509 /// if we're creating this built-in in anticipation of redeclaring the
1510 /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned bid,Scope * S,bool ForRedeclaration,SourceLocation Loc)1511 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1512 Scope *S, bool ForRedeclaration,
1513 SourceLocation Loc) {
1514 LookupPredefedObjCSuperType(*this, S, II);
1515
1516 Builtin::ID BID = (Builtin::ID)bid;
1517
1518 ASTContext::GetBuiltinTypeError Error;
1519 QualType R = Context.GetBuiltinType(BID, Error);
1520 switch (Error) {
1521 case ASTContext::GE_None:
1522 // Okay
1523 break;
1524
1525 case ASTContext::GE_Missing_stdio:
1526 if (ForRedeclaration)
1527 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1528 << Context.BuiltinInfo.GetName(BID);
1529 return 0;
1530
1531 case ASTContext::GE_Missing_setjmp:
1532 if (ForRedeclaration)
1533 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1534 << Context.BuiltinInfo.GetName(BID);
1535 return 0;
1536
1537 case ASTContext::GE_Missing_ucontext:
1538 if (ForRedeclaration)
1539 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1540 << Context.BuiltinInfo.GetName(BID);
1541 return 0;
1542 }
1543
1544 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1545 Diag(Loc, diag::ext_implicit_lib_function_decl)
1546 << Context.BuiltinInfo.GetName(BID)
1547 << R;
1548 if (Context.BuiltinInfo.getHeaderName(BID) &&
1549 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1550 != DiagnosticsEngine::Ignored)
1551 Diag(Loc, diag::note_please_include_header)
1552 << Context.BuiltinInfo.getHeaderName(BID)
1553 << Context.BuiltinInfo.GetName(BID);
1554 }
1555
1556 FunctionDecl *New = FunctionDecl::Create(Context,
1557 Context.getTranslationUnitDecl(),
1558 Loc, Loc, II, R, /*TInfo=*/0,
1559 SC_Extern,
1560 SC_None, false,
1561 /*hasPrototype=*/true);
1562 New->setImplicit();
1563
1564 // Create Decl objects for each parameter, adding them to the
1565 // FunctionDecl.
1566 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1567 SmallVector<ParmVarDecl*, 16> Params;
1568 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1569 ParmVarDecl *parm =
1570 ParmVarDecl::Create(Context, New, SourceLocation(),
1571 SourceLocation(), 0,
1572 FT->getArgType(i), /*TInfo=*/0,
1573 SC_None, SC_None, 0);
1574 parm->setScopeInfo(0, i);
1575 Params.push_back(parm);
1576 }
1577 New->setParams(Params);
1578 }
1579
1580 AddKnownFunctionAttributes(New);
1581
1582 // TUScope is the translation-unit scope to insert this function into.
1583 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1584 // relate Scopes to DeclContexts, and probably eliminate CurContext
1585 // entirely, but we're not there yet.
1586 DeclContext *SavedContext = CurContext;
1587 CurContext = Context.getTranslationUnitDecl();
1588 PushOnScopeChains(New, TUScope);
1589 CurContext = SavedContext;
1590 return New;
1591 }
1592
1593 /// \brief Filter out any previous declarations that the given declaration
1594 /// should not consider because they are not permitted to conflict, e.g.,
1595 /// because they come from hidden sub-modules and do not refer to the same
1596 /// entity.
filterNonConflictingPreviousDecls(ASTContext & context,NamedDecl * decl,LookupResult & previous)1597 static void filterNonConflictingPreviousDecls(ASTContext &context,
1598 NamedDecl *decl,
1599 LookupResult &previous){
1600 // This is only interesting when modules are enabled.
1601 if (!context.getLangOpts().Modules)
1602 return;
1603
1604 // Empty sets are uninteresting.
1605 if (previous.empty())
1606 return;
1607
1608 // If this declaration has external
1609 bool hasExternalLinkage = decl->hasExternalLinkage();
1610
1611 LookupResult::Filter filter = previous.makeFilter();
1612 while (filter.hasNext()) {
1613 NamedDecl *old = filter.next();
1614
1615 // Non-hidden declarations are never ignored.
1616 if (!old->isHidden())
1617 continue;
1618
1619 // If either has no-external linkage, ignore the old declaration.
1620 if (!hasExternalLinkage || old->getLinkage() != ExternalLinkage)
1621 filter.erase();
1622 }
1623
1624 filter.done();
1625 }
1626
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)1627 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1628 QualType OldType;
1629 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1630 OldType = OldTypedef->getUnderlyingType();
1631 else
1632 OldType = Context.getTypeDeclType(Old);
1633 QualType NewType = New->getUnderlyingType();
1634
1635 if (NewType->isVariablyModifiedType()) {
1636 // Must not redefine a typedef with a variably-modified type.
1637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1638 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1639 << Kind << NewType;
1640 if (Old->getLocation().isValid())
1641 Diag(Old->getLocation(), diag::note_previous_definition);
1642 New->setInvalidDecl();
1643 return true;
1644 }
1645
1646 if (OldType != NewType &&
1647 !OldType->isDependentType() &&
1648 !NewType->isDependentType() &&
1649 !Context.hasSameType(OldType, NewType)) {
1650 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1651 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1652 << Kind << NewType << OldType;
1653 if (Old->getLocation().isValid())
1654 Diag(Old->getLocation(), diag::note_previous_definition);
1655 New->setInvalidDecl();
1656 return true;
1657 }
1658 return false;
1659 }
1660
1661 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1662 /// same name and scope as a previous declaration 'Old'. Figure out
1663 /// how to resolve this situation, merging decls or emitting
1664 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1665 ///
MergeTypedefNameDecl(TypedefNameDecl * New,LookupResult & OldDecls)1666 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1667 // If the new decl is known invalid already, don't bother doing any
1668 // merging checks.
1669 if (New->isInvalidDecl()) return;
1670
1671 // Allow multiple definitions for ObjC built-in typedefs.
1672 // FIXME: Verify the underlying types are equivalent!
1673 if (getLangOpts().ObjC1) {
1674 const IdentifierInfo *TypeID = New->getIdentifier();
1675 switch (TypeID->getLength()) {
1676 default: break;
1677 case 2:
1678 {
1679 if (!TypeID->isStr("id"))
1680 break;
1681 QualType T = New->getUnderlyingType();
1682 if (!T->isPointerType())
1683 break;
1684 if (!T->isVoidPointerType()) {
1685 QualType PT = T->getAs<PointerType>()->getPointeeType();
1686 if (!PT->isStructureType())
1687 break;
1688 }
1689 Context.setObjCIdRedefinitionType(T);
1690 // Install the built-in type for 'id', ignoring the current definition.
1691 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1692 return;
1693 }
1694 case 5:
1695 if (!TypeID->isStr("Class"))
1696 break;
1697 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1698 // Install the built-in type for 'Class', ignoring the current definition.
1699 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1700 return;
1701 case 3:
1702 if (!TypeID->isStr("SEL"))
1703 break;
1704 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1705 // Install the built-in type for 'SEL', ignoring the current definition.
1706 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1707 return;
1708 }
1709 // Fall through - the typedef name was not a builtin type.
1710 }
1711
1712 // Verify the old decl was also a type.
1713 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1714 if (!Old) {
1715 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1716 << New->getDeclName();
1717
1718 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1719 if (OldD->getLocation().isValid())
1720 Diag(OldD->getLocation(), diag::note_previous_definition);
1721
1722 return New->setInvalidDecl();
1723 }
1724
1725 // If the old declaration is invalid, just give up here.
1726 if (Old->isInvalidDecl())
1727 return New->setInvalidDecl();
1728
1729 // If the typedef types are not identical, reject them in all languages and
1730 // with any extensions enabled.
1731 if (isIncompatibleTypedef(Old, New))
1732 return;
1733
1734 // The types match. Link up the redeclaration chain if the old
1735 // declaration was a typedef.
1736 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1737 New->setPreviousDeclaration(Typedef);
1738
1739 if (getLangOpts().MicrosoftExt)
1740 return;
1741
1742 if (getLangOpts().CPlusPlus) {
1743 // C++ [dcl.typedef]p2:
1744 // In a given non-class scope, a typedef specifier can be used to
1745 // redefine the name of any type declared in that scope to refer
1746 // to the type to which it already refers.
1747 if (!isa<CXXRecordDecl>(CurContext))
1748 return;
1749
1750 // C++0x [dcl.typedef]p4:
1751 // In a given class scope, a typedef specifier can be used to redefine
1752 // any class-name declared in that scope that is not also a typedef-name
1753 // to refer to the type to which it already refers.
1754 //
1755 // This wording came in via DR424, which was a correction to the
1756 // wording in DR56, which accidentally banned code like:
1757 //
1758 // struct S {
1759 // typedef struct A { } A;
1760 // };
1761 //
1762 // in the C++03 standard. We implement the C++0x semantics, which
1763 // allow the above but disallow
1764 //
1765 // struct S {
1766 // typedef int I;
1767 // typedef int I;
1768 // };
1769 //
1770 // since that was the intent of DR56.
1771 if (!isa<TypedefNameDecl>(Old))
1772 return;
1773
1774 Diag(New->getLocation(), diag::err_redefinition)
1775 << New->getDeclName();
1776 Diag(Old->getLocation(), diag::note_previous_definition);
1777 return New->setInvalidDecl();
1778 }
1779
1780 // Modules always permit redefinition of typedefs, as does C11.
1781 if (getLangOpts().Modules || getLangOpts().C11)
1782 return;
1783
1784 // If we have a redefinition of a typedef in C, emit a warning. This warning
1785 // is normally mapped to an error, but can be controlled with
1786 // -Wtypedef-redefinition. If either the original or the redefinition is
1787 // in a system header, don't emit this for compatibility with GCC.
1788 if (getDiagnostics().getSuppressSystemWarnings() &&
1789 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1790 Context.getSourceManager().isInSystemHeader(New->getLocation())))
1791 return;
1792
1793 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1794 << New->getDeclName();
1795 Diag(Old->getLocation(), diag::note_previous_definition);
1796 return;
1797 }
1798
1799 /// DeclhasAttr - returns true if decl Declaration already has the target
1800 /// attribute.
1801 static bool
DeclHasAttr(const Decl * D,const Attr * A)1802 DeclHasAttr(const Decl *D, const Attr *A) {
1803 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1804 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1805 // responsible for making sure they are consistent.
1806 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1807 if (AA)
1808 return false;
1809
1810 // The following thread safety attributes can also be duplicated.
1811 switch (A->getKind()) {
1812 case attr::ExclusiveLocksRequired:
1813 case attr::SharedLocksRequired:
1814 case attr::LocksExcluded:
1815 case attr::ExclusiveLockFunction:
1816 case attr::SharedLockFunction:
1817 case attr::UnlockFunction:
1818 case attr::ExclusiveTrylockFunction:
1819 case attr::SharedTrylockFunction:
1820 case attr::GuardedBy:
1821 case attr::PtGuardedBy:
1822 case attr::AcquiredBefore:
1823 case attr::AcquiredAfter:
1824 return false;
1825 default:
1826 ;
1827 }
1828
1829 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1830 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1831 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1832 if ((*i)->getKind() == A->getKind()) {
1833 if (Ann) {
1834 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1835 return true;
1836 continue;
1837 }
1838 // FIXME: Don't hardcode this check
1839 if (OA && isa<OwnershipAttr>(*i))
1840 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1841 return true;
1842 }
1843
1844 return false;
1845 }
1846
isAttributeTargetADefinition(Decl * D)1847 static bool isAttributeTargetADefinition(Decl *D) {
1848 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1849 return VD->isThisDeclarationADefinition();
1850 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1851 return TD->isCompleteDefinition() || TD->isBeingDefined();
1852 return true;
1853 }
1854
1855 /// Merge alignment attributes from \p Old to \p New, taking into account the
1856 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1857 ///
1858 /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)1859 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1860 // Look for alignas attributes on Old, and pick out whichever attribute
1861 // specifies the strictest alignment requirement.
1862 AlignedAttr *OldAlignasAttr = 0;
1863 AlignedAttr *OldStrictestAlignAttr = 0;
1864 unsigned OldAlign = 0;
1865 for (specific_attr_iterator<AlignedAttr>
1866 I = Old->specific_attr_begin<AlignedAttr>(),
1867 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1868 // FIXME: We have no way of representing inherited dependent alignments
1869 // in a case like:
1870 // template<int A, int B> struct alignas(A) X;
1871 // template<int A, int B> struct alignas(B) X {};
1872 // For now, we just ignore any alignas attributes which are not on the
1873 // definition in such a case.
1874 if (I->isAlignmentDependent())
1875 return false;
1876
1877 if (I->isAlignas())
1878 OldAlignasAttr = *I;
1879
1880 unsigned Align = I->getAlignment(S.Context);
1881 if (Align > OldAlign) {
1882 OldAlign = Align;
1883 OldStrictestAlignAttr = *I;
1884 }
1885 }
1886
1887 // Look for alignas attributes on New.
1888 AlignedAttr *NewAlignasAttr = 0;
1889 unsigned NewAlign = 0;
1890 for (specific_attr_iterator<AlignedAttr>
1891 I = New->specific_attr_begin<AlignedAttr>(),
1892 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1893 if (I->isAlignmentDependent())
1894 return false;
1895
1896 if (I->isAlignas())
1897 NewAlignasAttr = *I;
1898
1899 unsigned Align = I->getAlignment(S.Context);
1900 if (Align > NewAlign)
1901 NewAlign = Align;
1902 }
1903
1904 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1905 // Both declarations have 'alignas' attributes. We require them to match.
1906 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1907 // fall short. (If two declarations both have alignas, they must both match
1908 // every definition, and so must match each other if there is a definition.)
1909
1910 // If either declaration only contains 'alignas(0)' specifiers, then it
1911 // specifies the natural alignment for the type.
1912 if (OldAlign == 0 || NewAlign == 0) {
1913 QualType Ty;
1914 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1915 Ty = VD->getType();
1916 else
1917 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1918
1919 if (OldAlign == 0)
1920 OldAlign = S.Context.getTypeAlign(Ty);
1921 if (NewAlign == 0)
1922 NewAlign = S.Context.getTypeAlign(Ty);
1923 }
1924
1925 if (OldAlign != NewAlign) {
1926 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1927 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1928 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1929 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1930 }
1931 }
1932
1933 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1934 // C++11 [dcl.align]p6:
1935 // if any declaration of an entity has an alignment-specifier,
1936 // every defining declaration of that entity shall specify an
1937 // equivalent alignment.
1938 // C11 6.7.5/7:
1939 // If the definition of an object does not have an alignment
1940 // specifier, any other declaration of that object shall also
1941 // have no alignment specifier.
1942 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1943 << OldAlignasAttr->isC11();
1944 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1945 << OldAlignasAttr->isC11();
1946 }
1947
1948 bool AnyAdded = false;
1949
1950 // Ensure we have an attribute representing the strictest alignment.
1951 if (OldAlign > NewAlign) {
1952 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1953 Clone->setInherited(true);
1954 New->addAttr(Clone);
1955 AnyAdded = true;
1956 }
1957
1958 // Ensure we have an alignas attribute if the old declaration had one.
1959 if (OldAlignasAttr && !NewAlignasAttr &&
1960 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1961 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1962 Clone->setInherited(true);
1963 New->addAttr(Clone);
1964 AnyAdded = true;
1965 }
1966
1967 return AnyAdded;
1968 }
1969
mergeDeclAttribute(Sema & S,NamedDecl * D,InheritableAttr * Attr,bool Override)1970 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1971 bool Override) {
1972 InheritableAttr *NewAttr = NULL;
1973 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1974 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1975 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1976 AA->getIntroduced(), AA->getDeprecated(),
1977 AA->getObsoleted(), AA->getUnavailable(),
1978 AA->getMessage(), Override,
1979 AttrSpellingListIndex);
1980 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1981 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1982 AttrSpellingListIndex);
1983 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1984 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1985 AttrSpellingListIndex);
1986 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1987 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1988 AttrSpellingListIndex);
1989 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1990 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1991 AttrSpellingListIndex);
1992 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1993 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1994 FA->getFormatIdx(), FA->getFirstArg(),
1995 AttrSpellingListIndex);
1996 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1997 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1998 AttrSpellingListIndex);
1999 else if (isa<AlignedAttr>(Attr))
2000 // AlignedAttrs are handled separately, because we need to handle all
2001 // such attributes on a declaration at the same time.
2002 NewAttr = 0;
2003 else if (!DeclHasAttr(D, Attr))
2004 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2005
2006 if (NewAttr) {
2007 NewAttr->setInherited(true);
2008 D->addAttr(NewAttr);
2009 return true;
2010 }
2011
2012 return false;
2013 }
2014
getDefinition(const Decl * D)2015 static const Decl *getDefinition(const Decl *D) {
2016 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2017 return TD->getDefinition();
2018 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2019 return VD->getDefinition();
2020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2021 const FunctionDecl* Def;
2022 if (FD->hasBody(Def))
2023 return Def;
2024 }
2025 return NULL;
2026 }
2027
hasAttribute(const Decl * D,attr::Kind Kind)2028 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2029 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2030 I != E; ++I) {
2031 Attr *Attribute = *I;
2032 if (Attribute->getKind() == Kind)
2033 return true;
2034 }
2035 return false;
2036 }
2037
2038 /// checkNewAttributesAfterDef - If we already have a definition, check that
2039 /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2040 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2041 if (!New->hasAttrs())
2042 return;
2043
2044 const Decl *Def = getDefinition(Old);
2045 if (!Def || Def == New)
2046 return;
2047
2048 AttrVec &NewAttributes = New->getAttrs();
2049 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2050 const Attr *NewAttribute = NewAttributes[I];
2051 if (hasAttribute(Def, NewAttribute->getKind())) {
2052 ++I;
2053 continue; // regular attr merging will take care of validating this.
2054 }
2055
2056 if (isa<C11NoReturnAttr>(NewAttribute)) {
2057 // C's _Noreturn is allowed to be added to a function after it is defined.
2058 ++I;
2059 continue;
2060 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2061 if (AA->isAlignas()) {
2062 // C++11 [dcl.align]p6:
2063 // if any declaration of an entity has an alignment-specifier,
2064 // every defining declaration of that entity shall specify an
2065 // equivalent alignment.
2066 // C11 6.7.5/7:
2067 // If the definition of an object does not have an alignment
2068 // specifier, any other declaration of that object shall also
2069 // have no alignment specifier.
2070 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2071 << AA->isC11();
2072 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2073 << AA->isC11();
2074 NewAttributes.erase(NewAttributes.begin() + I);
2075 --E;
2076 continue;
2077 }
2078 }
2079
2080 S.Diag(NewAttribute->getLocation(),
2081 diag::warn_attribute_precede_definition);
2082 S.Diag(Def->getLocation(), diag::note_previous_definition);
2083 NewAttributes.erase(NewAttributes.begin() + I);
2084 --E;
2085 }
2086 }
2087
2088 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)2089 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2090 AvailabilityMergeKind AMK) {
2091 if (!Old->hasAttrs() && !New->hasAttrs())
2092 return;
2093
2094 // attributes declared post-definition are currently ignored
2095 checkNewAttributesAfterDef(*this, New, Old);
2096
2097 if (!Old->hasAttrs())
2098 return;
2099
2100 bool foundAny = New->hasAttrs();
2101
2102 // Ensure that any moving of objects within the allocated map is done before
2103 // we process them.
2104 if (!foundAny) New->setAttrs(AttrVec());
2105
2106 for (specific_attr_iterator<InheritableAttr>
2107 i = Old->specific_attr_begin<InheritableAttr>(),
2108 e = Old->specific_attr_end<InheritableAttr>();
2109 i != e; ++i) {
2110 bool Override = false;
2111 // Ignore deprecated/unavailable/availability attributes if requested.
2112 if (isa<DeprecatedAttr>(*i) ||
2113 isa<UnavailableAttr>(*i) ||
2114 isa<AvailabilityAttr>(*i)) {
2115 switch (AMK) {
2116 case AMK_None:
2117 continue;
2118
2119 case AMK_Redeclaration:
2120 break;
2121
2122 case AMK_Override:
2123 Override = true;
2124 break;
2125 }
2126 }
2127
2128 if (mergeDeclAttribute(*this, New, *i, Override))
2129 foundAny = true;
2130 }
2131
2132 if (mergeAlignedAttrs(*this, New, Old))
2133 foundAny = true;
2134
2135 if (!foundAny) New->dropAttrs();
2136 }
2137
2138 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2139 /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)2140 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2141 const ParmVarDecl *oldDecl,
2142 Sema &S) {
2143 // C++11 [dcl.attr.depend]p2:
2144 // The first declaration of a function shall specify the
2145 // carries_dependency attribute for its declarator-id if any declaration
2146 // of the function specifies the carries_dependency attribute.
2147 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2148 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2149 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2150 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2151 // Find the first declaration of the parameter.
2152 // FIXME: Should we build redeclaration chains for function parameters?
2153 const FunctionDecl *FirstFD =
2154 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration();
2155 const ParmVarDecl *FirstVD =
2156 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2157 S.Diag(FirstVD->getLocation(),
2158 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2159 }
2160
2161 if (!oldDecl->hasAttrs())
2162 return;
2163
2164 bool foundAny = newDecl->hasAttrs();
2165
2166 // Ensure that any moving of objects within the allocated map is
2167 // done before we process them.
2168 if (!foundAny) newDecl->setAttrs(AttrVec());
2169
2170 for (specific_attr_iterator<InheritableParamAttr>
2171 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2172 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2173 if (!DeclHasAttr(newDecl, *i)) {
2174 InheritableAttr *newAttr =
2175 cast<InheritableParamAttr>((*i)->clone(S.Context));
2176 newAttr->setInherited(true);
2177 newDecl->addAttr(newAttr);
2178 foundAny = true;
2179 }
2180 }
2181
2182 if (!foundAny) newDecl->dropAttrs();
2183 }
2184
2185 namespace {
2186
2187 /// Used in MergeFunctionDecl to keep track of function parameters in
2188 /// C.
2189 struct GNUCompatibleParamWarning {
2190 ParmVarDecl *OldParm;
2191 ParmVarDecl *NewParm;
2192 QualType PromotedType;
2193 };
2194
2195 }
2196
2197 /// getSpecialMember - get the special member enum for a method.
getSpecialMember(const CXXMethodDecl * MD)2198 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2199 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2200 if (Ctor->isDefaultConstructor())
2201 return Sema::CXXDefaultConstructor;
2202
2203 if (Ctor->isCopyConstructor())
2204 return Sema::CXXCopyConstructor;
2205
2206 if (Ctor->isMoveConstructor())
2207 return Sema::CXXMoveConstructor;
2208 } else if (isa<CXXDestructorDecl>(MD)) {
2209 return Sema::CXXDestructor;
2210 } else if (MD->isCopyAssignmentOperator()) {
2211 return Sema::CXXCopyAssignment;
2212 } else if (MD->isMoveAssignmentOperator()) {
2213 return Sema::CXXMoveAssignment;
2214 }
2215
2216 return Sema::CXXInvalid;
2217 }
2218
2219 /// canRedefineFunction - checks if a function can be redefined. Currently,
2220 /// only extern inline functions can be redefined, and even then only in
2221 /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)2222 static bool canRedefineFunction(const FunctionDecl *FD,
2223 const LangOptions& LangOpts) {
2224 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2225 !LangOpts.CPlusPlus &&
2226 FD->isInlineSpecified() &&
2227 FD->getStorageClass() == SC_Extern);
2228 }
2229
2230 /// Is the given calling convention the ABI default for the given
2231 /// declaration?
isABIDefaultCC(Sema & S,CallingConv CC,FunctionDecl * D)2232 static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
2233 CallingConv ABIDefaultCC;
2234 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
2235 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
2236 } else {
2237 // Free C function or a static method.
2238 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
2239 }
2240 return ABIDefaultCC == CC;
2241 }
2242
2243 template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)2244 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2245 const DeclContext *DC = Old->getDeclContext();
2246 if (DC->isRecord())
2247 return false;
2248
2249 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2250 if (OldLinkage == CXXLanguageLinkage &&
2251 New->getDeclContext()->isExternCContext())
2252 return true;
2253 if (OldLinkage == CLanguageLinkage &&
2254 New->getDeclContext()->isExternCXXContext())
2255 return true;
2256 return false;
2257 }
2258
2259 /// MergeFunctionDecl - We just parsed a function 'New' from
2260 /// declarator D which has the same name and scope as a previous
2261 /// declaration 'Old'. Figure out how to resolve this situation,
2262 /// merging decls or emitting diagnostics as appropriate.
2263 ///
2264 /// In C++, New and Old must be declarations that are not
2265 /// overloaded. Use IsOverload to determine whether New and Old are
2266 /// overloaded, and to select the Old declaration that New should be
2267 /// merged with.
2268 ///
2269 /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,Decl * OldD,Scope * S)2270 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
2271 // Verify the old decl was also a function.
2272 FunctionDecl *Old = 0;
2273 if (FunctionTemplateDecl *OldFunctionTemplate
2274 = dyn_cast<FunctionTemplateDecl>(OldD))
2275 Old = OldFunctionTemplate->getTemplatedDecl();
2276 else
2277 Old = dyn_cast<FunctionDecl>(OldD);
2278 if (!Old) {
2279 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2280 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2281 Diag(Shadow->getTargetDecl()->getLocation(),
2282 diag::note_using_decl_target);
2283 Diag(Shadow->getUsingDecl()->getLocation(),
2284 diag::note_using_decl) << 0;
2285 return true;
2286 }
2287
2288 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2289 << New->getDeclName();
2290 Diag(OldD->getLocation(), diag::note_previous_definition);
2291 return true;
2292 }
2293
2294 // Determine whether the previous declaration was a definition,
2295 // implicit declaration, or a declaration.
2296 diag::kind PrevDiag;
2297 if (Old->isThisDeclarationADefinition())
2298 PrevDiag = diag::note_previous_definition;
2299 else if (Old->isImplicit())
2300 PrevDiag = diag::note_previous_implicit_declaration;
2301 else
2302 PrevDiag = diag::note_previous_declaration;
2303
2304 QualType OldQType = Context.getCanonicalType(Old->getType());
2305 QualType NewQType = Context.getCanonicalType(New->getType());
2306
2307 // Don't complain about this if we're in GNU89 mode and the old function
2308 // is an extern inline function.
2309 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2310 New->getStorageClass() == SC_Static &&
2311 Old->getStorageClass() != SC_Static &&
2312 !canRedefineFunction(Old, getLangOpts())) {
2313 if (getLangOpts().MicrosoftExt) {
2314 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2315 Diag(Old->getLocation(), PrevDiag);
2316 } else {
2317 Diag(New->getLocation(), diag::err_static_non_static) << New;
2318 Diag(Old->getLocation(), PrevDiag);
2319 return true;
2320 }
2321 }
2322
2323 // If a function is first declared with a calling convention, but is
2324 // later declared or defined without one, the second decl assumes the
2325 // calling convention of the first.
2326 //
2327 // It's OK if a function is first declared without a calling convention,
2328 // but is later declared or defined with the default calling convention.
2329 //
2330 // For the new decl, we have to look at the NON-canonical type to tell the
2331 // difference between a function that really doesn't have a calling
2332 // convention and one that is declared cdecl. That's because in
2333 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
2334 // because it is the default calling convention.
2335 //
2336 // Note also that we DO NOT return at this point, because we still have
2337 // other tests to run.
2338 const FunctionType *OldType = cast<FunctionType>(OldQType);
2339 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
2340 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2341 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2342 bool RequiresAdjustment = false;
2343 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
2344 // Fast path: nothing to do.
2345
2346 // Inherit the CC from the previous declaration if it was specified
2347 // there but not here.
2348 } else if (NewTypeInfo.getCC() == CC_Default) {
2349 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2350 RequiresAdjustment = true;
2351
2352 // Don't complain about mismatches when the default CC is
2353 // effectively the same as the explict one. Only Old decl contains correct
2354 // information about storage class of CXXMethod.
2355 } else if (OldTypeInfo.getCC() == CC_Default &&
2356 isABIDefaultCC(*this, NewTypeInfo.getCC(), Old)) {
2357 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2358 RequiresAdjustment = true;
2359
2360 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
2361 NewTypeInfo.getCC())) {
2362 // Calling conventions really aren't compatible, so complain.
2363 Diag(New->getLocation(), diag::err_cconv_change)
2364 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2365 << (OldTypeInfo.getCC() == CC_Default)
2366 << (OldTypeInfo.getCC() == CC_Default ? "" :
2367 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
2368 Diag(Old->getLocation(), diag::note_previous_declaration);
2369 return true;
2370 }
2371
2372 // FIXME: diagnose the other way around?
2373 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2374 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2375 RequiresAdjustment = true;
2376 }
2377
2378 // Merge regparm attribute.
2379 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2380 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2381 if (NewTypeInfo.getHasRegParm()) {
2382 Diag(New->getLocation(), diag::err_regparm_mismatch)
2383 << NewType->getRegParmType()
2384 << OldType->getRegParmType();
2385 Diag(Old->getLocation(), diag::note_previous_declaration);
2386 return true;
2387 }
2388
2389 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2390 RequiresAdjustment = true;
2391 }
2392
2393 // Merge ns_returns_retained attribute.
2394 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2395 if (NewTypeInfo.getProducesResult()) {
2396 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2397 Diag(Old->getLocation(), diag::note_previous_declaration);
2398 return true;
2399 }
2400
2401 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2402 RequiresAdjustment = true;
2403 }
2404
2405 if (RequiresAdjustment) {
2406 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2407 New->setType(QualType(NewType, 0));
2408 NewQType = Context.getCanonicalType(New->getType());
2409 }
2410
2411 // If this redeclaration makes the function inline, we may need to add it to
2412 // UndefinedButUsed.
2413 if (!Old->isInlined() && New->isInlined() &&
2414 !New->hasAttr<GNUInlineAttr>() &&
2415 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2416 Old->isUsed(false) &&
2417 !Old->isDefined() && !New->isThisDeclarationADefinition())
2418 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2419 SourceLocation()));
2420
2421 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2422 // about it.
2423 if (New->hasAttr<GNUInlineAttr>() &&
2424 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2425 UndefinedButUsed.erase(Old->getCanonicalDecl());
2426 }
2427
2428 if (getLangOpts().CPlusPlus) {
2429 // (C++98 13.1p2):
2430 // Certain function declarations cannot be overloaded:
2431 // -- Function declarations that differ only in the return type
2432 // cannot be overloaded.
2433 QualType OldReturnType = OldType->getResultType();
2434 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2435 QualType ResQT;
2436 if (OldReturnType != NewReturnType) {
2437 if (NewReturnType->isObjCObjectPointerType()
2438 && OldReturnType->isObjCObjectPointerType())
2439 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2440 if (ResQT.isNull()) {
2441 if (New->isCXXClassMember() && New->isOutOfLine())
2442 Diag(New->getLocation(),
2443 diag::err_member_def_does_not_match_ret_type) << New;
2444 else
2445 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2446 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2447 return true;
2448 }
2449 else
2450 NewQType = ResQT;
2451 }
2452
2453 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2454 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2455 if (OldMethod && NewMethod) {
2456 // Preserve triviality.
2457 NewMethod->setTrivial(OldMethod->isTrivial());
2458
2459 // MSVC allows explicit template specialization at class scope:
2460 // 2 CXMethodDecls referring to the same function will be injected.
2461 // We don't want a redeclartion error.
2462 bool IsClassScopeExplicitSpecialization =
2463 OldMethod->isFunctionTemplateSpecialization() &&
2464 NewMethod->isFunctionTemplateSpecialization();
2465 bool isFriend = NewMethod->getFriendObjectKind();
2466
2467 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2468 !IsClassScopeExplicitSpecialization) {
2469 // -- Member function declarations with the same name and the
2470 // same parameter types cannot be overloaded if any of them
2471 // is a static member function declaration.
2472 if (OldMethod->isStatic() || NewMethod->isStatic()) {
2473 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2474 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2475 return true;
2476 }
2477
2478 // C++ [class.mem]p1:
2479 // [...] A member shall not be declared twice in the
2480 // member-specification, except that a nested class or member
2481 // class template can be declared and then later defined.
2482 if (ActiveTemplateInstantiations.empty()) {
2483 unsigned NewDiag;
2484 if (isa<CXXConstructorDecl>(OldMethod))
2485 NewDiag = diag::err_constructor_redeclared;
2486 else if (isa<CXXDestructorDecl>(NewMethod))
2487 NewDiag = diag::err_destructor_redeclared;
2488 else if (isa<CXXConversionDecl>(NewMethod))
2489 NewDiag = diag::err_conv_function_redeclared;
2490 else
2491 NewDiag = diag::err_member_redeclared;
2492
2493 Diag(New->getLocation(), NewDiag);
2494 } else {
2495 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2496 << New << New->getType();
2497 }
2498 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2499
2500 // Complain if this is an explicit declaration of a special
2501 // member that was initially declared implicitly.
2502 //
2503 // As an exception, it's okay to befriend such methods in order
2504 // to permit the implicit constructor/destructor/operator calls.
2505 } else if (OldMethod->isImplicit()) {
2506 if (isFriend) {
2507 NewMethod->setImplicit();
2508 } else {
2509 Diag(NewMethod->getLocation(),
2510 diag::err_definition_of_implicitly_declared_member)
2511 << New << getSpecialMember(OldMethod);
2512 return true;
2513 }
2514 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2515 Diag(NewMethod->getLocation(),
2516 diag::err_definition_of_explicitly_defaulted_member)
2517 << getSpecialMember(OldMethod);
2518 return true;
2519 }
2520 }
2521
2522 // C++11 [dcl.attr.noreturn]p1:
2523 // The first declaration of a function shall specify the noreturn
2524 // attribute if any declaration of that function specifies the noreturn
2525 // attribute.
2526 if (New->hasAttr<CXX11NoReturnAttr>() &&
2527 !Old->hasAttr<CXX11NoReturnAttr>()) {
2528 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2529 diag::err_noreturn_missing_on_first_decl);
2530 Diag(Old->getFirstDeclaration()->getLocation(),
2531 diag::note_noreturn_missing_first_decl);
2532 }
2533
2534 // C++11 [dcl.attr.depend]p2:
2535 // The first declaration of a function shall specify the
2536 // carries_dependency attribute for its declarator-id if any declaration
2537 // of the function specifies the carries_dependency attribute.
2538 if (New->hasAttr<CarriesDependencyAttr>() &&
2539 !Old->hasAttr<CarriesDependencyAttr>()) {
2540 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2541 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2542 Diag(Old->getFirstDeclaration()->getLocation(),
2543 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2544 }
2545
2546 // (C++98 8.3.5p3):
2547 // All declarations for a function shall agree exactly in both the
2548 // return type and the parameter-type-list.
2549 // We also want to respect all the extended bits except noreturn.
2550
2551 // noreturn should now match unless the old type info didn't have it.
2552 QualType OldQTypeForComparison = OldQType;
2553 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2554 assert(OldQType == QualType(OldType, 0));
2555 const FunctionType *OldTypeForComparison
2556 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2557 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2558 assert(OldQTypeForComparison.isCanonical());
2559 }
2560
2561 if (haveIncompatibleLanguageLinkages(Old, New)) {
2562 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2563 Diag(Old->getLocation(), PrevDiag);
2564 return true;
2565 }
2566
2567 if (OldQTypeForComparison == NewQType)
2568 return MergeCompatibleFunctionDecls(New, Old, S);
2569
2570 // Fall through for conflicting redeclarations and redefinitions.
2571 }
2572
2573 // C: Function types need to be compatible, not identical. This handles
2574 // duplicate function decls like "void f(int); void f(enum X);" properly.
2575 if (!getLangOpts().CPlusPlus &&
2576 Context.typesAreCompatible(OldQType, NewQType)) {
2577 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2578 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2579 const FunctionProtoType *OldProto = 0;
2580 if (isa<FunctionNoProtoType>(NewFuncType) &&
2581 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2582 // The old declaration provided a function prototype, but the
2583 // new declaration does not. Merge in the prototype.
2584 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2585 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2586 OldProto->arg_type_end());
2587 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2588 ParamTypes,
2589 OldProto->getExtProtoInfo());
2590 New->setType(NewQType);
2591 New->setHasInheritedPrototype();
2592
2593 // Synthesize a parameter for each argument type.
2594 SmallVector<ParmVarDecl*, 16> Params;
2595 for (FunctionProtoType::arg_type_iterator
2596 ParamType = OldProto->arg_type_begin(),
2597 ParamEnd = OldProto->arg_type_end();
2598 ParamType != ParamEnd; ++ParamType) {
2599 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2600 SourceLocation(),
2601 SourceLocation(), 0,
2602 *ParamType, /*TInfo=*/0,
2603 SC_None, SC_None,
2604 0);
2605 Param->setScopeInfo(0, Params.size());
2606 Param->setImplicit();
2607 Params.push_back(Param);
2608 }
2609
2610 New->setParams(Params);
2611 }
2612
2613 return MergeCompatibleFunctionDecls(New, Old, S);
2614 }
2615
2616 // GNU C permits a K&R definition to follow a prototype declaration
2617 // if the declared types of the parameters in the K&R definition
2618 // match the types in the prototype declaration, even when the
2619 // promoted types of the parameters from the K&R definition differ
2620 // from the types in the prototype. GCC then keeps the types from
2621 // the prototype.
2622 //
2623 // If a variadic prototype is followed by a non-variadic K&R definition,
2624 // the K&R definition becomes variadic. This is sort of an edge case, but
2625 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2626 // C99 6.9.1p8.
2627 if (!getLangOpts().CPlusPlus &&
2628 Old->hasPrototype() && !New->hasPrototype() &&
2629 New->getType()->getAs<FunctionProtoType>() &&
2630 Old->getNumParams() == New->getNumParams()) {
2631 SmallVector<QualType, 16> ArgTypes;
2632 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2633 const FunctionProtoType *OldProto
2634 = Old->getType()->getAs<FunctionProtoType>();
2635 const FunctionProtoType *NewProto
2636 = New->getType()->getAs<FunctionProtoType>();
2637
2638 // Determine whether this is the GNU C extension.
2639 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2640 NewProto->getResultType());
2641 bool LooseCompatible = !MergedReturn.isNull();
2642 for (unsigned Idx = 0, End = Old->getNumParams();
2643 LooseCompatible && Idx != End; ++Idx) {
2644 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2645 ParmVarDecl *NewParm = New->getParamDecl(Idx);
2646 if (Context.typesAreCompatible(OldParm->getType(),
2647 NewProto->getArgType(Idx))) {
2648 ArgTypes.push_back(NewParm->getType());
2649 } else if (Context.typesAreCompatible(OldParm->getType(),
2650 NewParm->getType(),
2651 /*CompareUnqualified=*/true)) {
2652 GNUCompatibleParamWarning Warn
2653 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2654 Warnings.push_back(Warn);
2655 ArgTypes.push_back(NewParm->getType());
2656 } else
2657 LooseCompatible = false;
2658 }
2659
2660 if (LooseCompatible) {
2661 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2662 Diag(Warnings[Warn].NewParm->getLocation(),
2663 diag::ext_param_promoted_not_compatible_with_prototype)
2664 << Warnings[Warn].PromotedType
2665 << Warnings[Warn].OldParm->getType();
2666 if (Warnings[Warn].OldParm->getLocation().isValid())
2667 Diag(Warnings[Warn].OldParm->getLocation(),
2668 diag::note_previous_declaration);
2669 }
2670
2671 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2672 OldProto->getExtProtoInfo()));
2673 return MergeCompatibleFunctionDecls(New, Old, S);
2674 }
2675
2676 // Fall through to diagnose conflicting types.
2677 }
2678
2679 // A function that has already been declared has been redeclared or defined
2680 // with a different type- show appropriate diagnostic
2681 if (unsigned BuiltinID = Old->getBuiltinID()) {
2682 // The user has declared a builtin function with an incompatible
2683 // signature.
2684 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2685 // The function the user is redeclaring is a library-defined
2686 // function like 'malloc' or 'printf'. Warn about the
2687 // redeclaration, then pretend that we don't know about this
2688 // library built-in.
2689 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2690 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2691 << Old << Old->getType();
2692 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2693 Old->setInvalidDecl();
2694 return false;
2695 }
2696
2697 PrevDiag = diag::note_previous_builtin_declaration;
2698 }
2699
2700 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2701 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2702 return true;
2703 }
2704
2705 /// \brief Completes the merge of two function declarations that are
2706 /// known to be compatible.
2707 ///
2708 /// This routine handles the merging of attributes and other
2709 /// properties of function declarations form the old declaration to
2710 /// the new declaration, once we know that New is in fact a
2711 /// redeclaration of Old.
2712 ///
2713 /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S)2714 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2715 Scope *S) {
2716 // Merge the attributes
2717 mergeDeclAttributes(New, Old);
2718
2719 // Merge the storage class.
2720 if (Old->getStorageClass() != SC_Extern &&
2721 Old->getStorageClass() != SC_None)
2722 New->setStorageClass(Old->getStorageClass());
2723
2724 // Merge "pure" flag.
2725 if (Old->isPure())
2726 New->setPure();
2727
2728 // Merge "used" flag.
2729 if (Old->isUsed(false))
2730 New->setUsed();
2731
2732 // Merge attributes from the parameters. These can mismatch with K&R
2733 // declarations.
2734 if (New->getNumParams() == Old->getNumParams())
2735 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2736 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2737 *this);
2738
2739 if (getLangOpts().CPlusPlus)
2740 return MergeCXXFunctionDecl(New, Old, S);
2741
2742 // Merge the function types so the we get the composite types for the return
2743 // and argument types.
2744 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2745 if (!Merged.isNull())
2746 New->setType(Merged);
2747
2748 return false;
2749 }
2750
2751
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)2752 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2753 ObjCMethodDecl *oldMethod) {
2754
2755 // Merge the attributes, including deprecated/unavailable
2756 mergeDeclAttributes(newMethod, oldMethod, AMK_Override);
2757
2758 // Merge attributes from the parameters.
2759 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2760 oe = oldMethod->param_end();
2761 for (ObjCMethodDecl::param_iterator
2762 ni = newMethod->param_begin(), ne = newMethod->param_end();
2763 ni != ne && oi != oe; ++ni, ++oi)
2764 mergeParamDeclAttributes(*ni, *oi, *this);
2765
2766 CheckObjCMethodOverride(newMethod, oldMethod);
2767 }
2768
2769 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2770 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
2771 /// emitting diagnostics as appropriate.
2772 ///
2773 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2774 /// to here in AddInitializerToDecl. We can't check them before the initializer
2775 /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old)2776 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2777 if (New->isInvalidDecl() || Old->isInvalidDecl())
2778 return;
2779
2780 QualType MergedT;
2781 if (getLangOpts().CPlusPlus) {
2782 AutoType *AT = New->getType()->getContainedAutoType();
2783 if (AT && !AT->isDeduced()) {
2784 // We don't know what the new type is until the initializer is attached.
2785 return;
2786 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2787 // These could still be something that needs exception specs checked.
2788 return MergeVarDeclExceptionSpecs(New, Old);
2789 }
2790 // C++ [basic.link]p10:
2791 // [...] the types specified by all declarations referring to a given
2792 // object or function shall be identical, except that declarations for an
2793 // array object can specify array types that differ by the presence or
2794 // absence of a major array bound (8.3.4).
2795 else if (Old->getType()->isIncompleteArrayType() &&
2796 New->getType()->isArrayType()) {
2797 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2798 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2799 if (Context.hasSameType(OldArray->getElementType(),
2800 NewArray->getElementType()))
2801 MergedT = New->getType();
2802 } else if (Old->getType()->isArrayType() &&
2803 New->getType()->isIncompleteArrayType()) {
2804 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2805 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2806 if (Context.hasSameType(OldArray->getElementType(),
2807 NewArray->getElementType()))
2808 MergedT = Old->getType();
2809 } else if (New->getType()->isObjCObjectPointerType()
2810 && Old->getType()->isObjCObjectPointerType()) {
2811 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2812 Old->getType());
2813 }
2814 } else {
2815 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2816 }
2817 if (MergedT.isNull()) {
2818 Diag(New->getLocation(), diag::err_redefinition_different_type)
2819 << New->getDeclName() << New->getType() << Old->getType();
2820 Diag(Old->getLocation(), diag::note_previous_definition);
2821 return New->setInvalidDecl();
2822 }
2823 New->setType(MergedT);
2824 }
2825
2826 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2827 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
2828 /// situation, merging decls or emitting diagnostics as appropriate.
2829 ///
2830 /// Tentative definition rules (C99 6.9.2p2) are checked by
2831 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2832 /// definitions here, since the initializer hasn't been attached.
2833 ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)2834 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2835 // If the new decl is already invalid, don't do any other checking.
2836 if (New->isInvalidDecl())
2837 return;
2838
2839 // Verify the old decl was also a variable.
2840 VarDecl *Old = 0;
2841 if (!Previous.isSingleResult() ||
2842 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2843 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2844 << New->getDeclName();
2845 Diag(Previous.getRepresentativeDecl()->getLocation(),
2846 diag::note_previous_definition);
2847 return New->setInvalidDecl();
2848 }
2849
2850 // C++ [class.mem]p1:
2851 // A member shall not be declared twice in the member-specification [...]
2852 //
2853 // Here, we need only consider static data members.
2854 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2855 Diag(New->getLocation(), diag::err_duplicate_member)
2856 << New->getIdentifier();
2857 Diag(Old->getLocation(), diag::note_previous_declaration);
2858 New->setInvalidDecl();
2859 }
2860
2861 mergeDeclAttributes(New, Old);
2862 // Warn if an already-declared variable is made a weak_import in a subsequent
2863 // declaration
2864 if (New->getAttr<WeakImportAttr>() &&
2865 Old->getStorageClass() == SC_None &&
2866 !Old->getAttr<WeakImportAttr>()) {
2867 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2868 Diag(Old->getLocation(), diag::note_previous_definition);
2869 // Remove weak_import attribute on new declaration.
2870 New->dropAttr<WeakImportAttr>();
2871 }
2872
2873 // Merge the types.
2874 MergeVarDeclTypes(New, Old);
2875 if (New->isInvalidDecl())
2876 return;
2877
2878 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2879 if (New->getStorageClass() == SC_Static &&
2880 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2881 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2882 Diag(Old->getLocation(), diag::note_previous_definition);
2883 return New->setInvalidDecl();
2884 }
2885 // C99 6.2.2p4:
2886 // For an identifier declared with the storage-class specifier
2887 // extern in a scope in which a prior declaration of that
2888 // identifier is visible,23) if the prior declaration specifies
2889 // internal or external linkage, the linkage of the identifier at
2890 // the later declaration is the same as the linkage specified at
2891 // the prior declaration. If no prior declaration is visible, or
2892 // if the prior declaration specifies no linkage, then the
2893 // identifier has external linkage.
2894 if (New->hasExternalStorage() && Old->hasLinkage())
2895 /* Okay */;
2896 else if (New->getStorageClass() != SC_Static &&
2897 Old->getStorageClass() == SC_Static) {
2898 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2899 Diag(Old->getLocation(), diag::note_previous_definition);
2900 return New->setInvalidDecl();
2901 }
2902
2903 // Check if extern is followed by non-extern and vice-versa.
2904 if (New->hasExternalStorage() &&
2905 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2906 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2907 Diag(Old->getLocation(), diag::note_previous_definition);
2908 return New->setInvalidDecl();
2909 }
2910 if (Old->hasExternalStorage() &&
2911 New->isLocalVarDecl() && !New->hasLinkage()) {
2912 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2913 Diag(Old->getLocation(), diag::note_previous_definition);
2914 return New->setInvalidDecl();
2915 }
2916
2917 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2918
2919 // FIXME: The test for external storage here seems wrong? We still
2920 // need to check for mismatches.
2921 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2922 // Don't complain about out-of-line definitions of static members.
2923 !(Old->getLexicalDeclContext()->isRecord() &&
2924 !New->getLexicalDeclContext()->isRecord())) {
2925 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2926 Diag(Old->getLocation(), diag::note_previous_definition);
2927 return New->setInvalidDecl();
2928 }
2929
2930 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2931 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2932 Diag(Old->getLocation(), diag::note_previous_definition);
2933 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2934 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2935 Diag(Old->getLocation(), diag::note_previous_definition);
2936 }
2937
2938 // C++ doesn't have tentative definitions, so go right ahead and check here.
2939 const VarDecl *Def;
2940 if (getLangOpts().CPlusPlus &&
2941 New->isThisDeclarationADefinition() == VarDecl::Definition &&
2942 (Def = Old->getDefinition())) {
2943 Diag(New->getLocation(), diag::err_redefinition)
2944 << New->getDeclName();
2945 Diag(Def->getLocation(), diag::note_previous_definition);
2946 New->setInvalidDecl();
2947 return;
2948 }
2949
2950 if (haveIncompatibleLanguageLinkages(Old, New)) {
2951 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2952 Diag(Old->getLocation(), diag::note_previous_definition);
2953 New->setInvalidDecl();
2954 return;
2955 }
2956
2957 // c99 6.2.2 P4.
2958 // For an identifier declared with the storage-class specifier extern in a
2959 // scope in which a prior declaration of that identifier is visible, if
2960 // the prior declaration specifies internal or external linkage, the linkage
2961 // of the identifier at the later declaration is the same as the linkage
2962 // specified at the prior declaration.
2963 // FIXME. revisit this code.
2964 if (New->hasExternalStorage() &&
2965 Old->getLinkage() == InternalLinkage)
2966 New->setStorageClass(Old->getStorageClass());
2967
2968 // Merge "used" flag.
2969 if (Old->isUsed(false))
2970 New->setUsed();
2971
2972 // Keep a chain of previous declarations.
2973 New->setPreviousDeclaration(Old);
2974
2975 // Inherit access appropriately.
2976 New->setAccess(Old->getAccess());
2977 }
2978
2979 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2980 /// no declarator (e.g. "struct foo;") is parsed.
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS)2981 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2982 DeclSpec &DS) {
2983 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
2984 }
2985
2986 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2987 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
2988 /// parameters to cope with template friend declarations.
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation)2989 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2990 DeclSpec &DS,
2991 MultiTemplateParamsArg TemplateParams,
2992 bool IsExplicitInstantiation) {
2993 Decl *TagD = 0;
2994 TagDecl *Tag = 0;
2995 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2996 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2997 DS.getTypeSpecType() == DeclSpec::TST_interface ||
2998 DS.getTypeSpecType() == DeclSpec::TST_union ||
2999 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3000 TagD = DS.getRepAsDecl();
3001
3002 if (!TagD) // We probably had an error
3003 return 0;
3004
3005 // Note that the above type specs guarantee that the
3006 // type rep is a Decl, whereas in many of the others
3007 // it's a Type.
3008 if (isa<TagDecl>(TagD))
3009 Tag = cast<TagDecl>(TagD);
3010 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3011 Tag = CTD->getTemplatedDecl();
3012 }
3013
3014 if (Tag) {
3015 getASTContext().addUnnamedTag(Tag);
3016 Tag->setFreeStanding();
3017 if (Tag->isInvalidDecl())
3018 return Tag;
3019 }
3020
3021 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3022 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3023 // or incomplete types shall not be restrict-qualified."
3024 if (TypeQuals & DeclSpec::TQ_restrict)
3025 Diag(DS.getRestrictSpecLoc(),
3026 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3027 << DS.getSourceRange();
3028 }
3029
3030 if (DS.isConstexprSpecified()) {
3031 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3032 // and definitions of functions and variables.
3033 if (Tag)
3034 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3035 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3036 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3037 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3038 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3039 else
3040 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3041 // Don't emit warnings after this error.
3042 return TagD;
3043 }
3044
3045 DiagnoseFunctionSpecifiers(DS);
3046
3047 if (DS.isFriendSpecified()) {
3048 // If we're dealing with a decl but not a TagDecl, assume that
3049 // whatever routines created it handled the friendship aspect.
3050 if (TagD && !Tag)
3051 return 0;
3052 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3053 }
3054
3055 CXXScopeSpec &SS = DS.getTypeSpecScope();
3056 bool IsExplicitSpecialization =
3057 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3058 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3059 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3060 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3061 // nested-name-specifier unless it is an explicit instantiation
3062 // or an explicit specialization.
3063 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3064 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3065 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3066 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3067 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3068 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3069 << SS.getRange();
3070 return 0;
3071 }
3072
3073 // Track whether this decl-specifier declares anything.
3074 bool DeclaresAnything = true;
3075
3076 // Handle anonymous struct definitions.
3077 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3078 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3079 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3080 if (getLangOpts().CPlusPlus ||
3081 Record->getDeclContext()->isRecord())
3082 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
3083
3084 DeclaresAnything = false;
3085 }
3086 }
3087
3088 // Check for Microsoft C extension: anonymous struct member.
3089 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3090 CurContext->isRecord() &&
3091 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3092 // Handle 2 kinds of anonymous struct:
3093 // struct STRUCT;
3094 // and
3095 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3096 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3097 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3098 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3099 DS.getRepAsType().get()->isStructureType())) {
3100 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3101 << DS.getSourceRange();
3102 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3103 }
3104 }
3105
3106 // Skip all the checks below if we have a type error.
3107 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3108 (TagD && TagD->isInvalidDecl()))
3109 return TagD;
3110
3111 if (getLangOpts().CPlusPlus &&
3112 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3113 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3114 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3115 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3116 DeclaresAnything = false;
3117
3118 if (!DS.isMissingDeclaratorOk()) {
3119 // Customize diagnostic for a typedef missing a name.
3120 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3121 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3122 << DS.getSourceRange();
3123 else
3124 DeclaresAnything = false;
3125 }
3126
3127 if (DS.isModulePrivateSpecified() &&
3128 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3129 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3130 << Tag->getTagKind()
3131 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3132
3133 ActOnDocumentableDecl(TagD);
3134
3135 // C 6.7/2:
3136 // A declaration [...] shall declare at least a declarator [...], a tag,
3137 // or the members of an enumeration.
3138 // C++ [dcl.dcl]p3:
3139 // [If there are no declarators], and except for the declaration of an
3140 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3141 // names into the program, or shall redeclare a name introduced by a
3142 // previous declaration.
3143 if (!DeclaresAnything) {
3144 // In C, we allow this as a (popular) extension / bug. Don't bother
3145 // producing further diagnostics for redundant qualifiers after this.
3146 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3147 return TagD;
3148 }
3149
3150 // C++ [dcl.stc]p1:
3151 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3152 // init-declarator-list of the declaration shall not be empty.
3153 // C++ [dcl.fct.spec]p1:
3154 // If a cv-qualifier appears in a decl-specifier-seq, the
3155 // init-declarator-list of the declaration shall not be empty.
3156 //
3157 // Spurious qualifiers here appear to be valid in C.
3158 unsigned DiagID = diag::warn_standalone_specifier;
3159 if (getLangOpts().CPlusPlus)
3160 DiagID = diag::ext_standalone_specifier;
3161
3162 // Note that a linkage-specification sets a storage class, but
3163 // 'extern "C" struct foo;' is actually valid and not theoretically
3164 // useless.
3165 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3166 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3167 Diag(DS.getStorageClassSpecLoc(), DiagID)
3168 << DeclSpec::getSpecifierName(SCS);
3169
3170 if (DS.isThreadSpecified())
3171 Diag(DS.getThreadSpecLoc(), DiagID) << "__thread";
3172 if (DS.getTypeQualifiers()) {
3173 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3174 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3175 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3176 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3177 // Restrict is covered above.
3178 }
3179
3180 // Warn about ignored type attributes, for example:
3181 // __attribute__((aligned)) struct A;
3182 // Attributes should be placed after tag to apply to type declaration.
3183 if (!DS.getAttributes().empty()) {
3184 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3185 if (TypeSpecType == DeclSpec::TST_class ||
3186 TypeSpecType == DeclSpec::TST_struct ||
3187 TypeSpecType == DeclSpec::TST_interface ||
3188 TypeSpecType == DeclSpec::TST_union ||
3189 TypeSpecType == DeclSpec::TST_enum) {
3190 AttributeList* attrs = DS.getAttributes().getList();
3191 while (attrs) {
3192 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3193 << attrs->getName()
3194 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3195 TypeSpecType == DeclSpec::TST_struct ? 1 :
3196 TypeSpecType == DeclSpec::TST_union ? 2 :
3197 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3198 attrs = attrs->getNext();
3199 }
3200 }
3201 }
3202
3203 return TagD;
3204 }
3205
3206 /// We are trying to inject an anonymous member into the given scope;
3207 /// check if there's an existing declaration that can't be overloaded.
3208 ///
3209 /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,unsigned diagnostic)3210 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3211 Scope *S,
3212 DeclContext *Owner,
3213 DeclarationName Name,
3214 SourceLocation NameLoc,
3215 unsigned diagnostic) {
3216 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3217 Sema::ForRedeclaration);
3218 if (!SemaRef.LookupName(R, S)) return false;
3219
3220 if (R.getAsSingle<TagDecl>())
3221 return false;
3222
3223 // Pick a representative declaration.
3224 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3225 assert(PrevDecl && "Expected a non-null Decl");
3226
3227 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3228 return false;
3229
3230 SemaRef.Diag(NameLoc, diagnostic) << Name;
3231 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3232
3233 return true;
3234 }
3235
3236 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3237 /// anonymous struct or union AnonRecord into the owning context Owner
3238 /// and scope S. This routine will be invoked just after we realize
3239 /// that an unnamed union or struct is actually an anonymous union or
3240 /// struct, e.g.,
3241 ///
3242 /// @code
3243 /// union {
3244 /// int i;
3245 /// float f;
3246 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3247 /// // f into the surrounding scope.x
3248 /// @endcode
3249 ///
3250 /// This routine is recursive, injecting the names of nested anonymous
3251 /// structs/unions into the owning context and scope as well.
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVector<NamedDecl *,2> & Chaining,bool MSAnonStruct)3252 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3253 DeclContext *Owner,
3254 RecordDecl *AnonRecord,
3255 AccessSpecifier AS,
3256 SmallVector<NamedDecl*, 2> &Chaining,
3257 bool MSAnonStruct) {
3258 unsigned diagKind
3259 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3260 : diag::err_anonymous_struct_member_redecl;
3261
3262 bool Invalid = false;
3263
3264 // Look every FieldDecl and IndirectFieldDecl with a name.
3265 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3266 DEnd = AnonRecord->decls_end();
3267 D != DEnd; ++D) {
3268 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3269 cast<NamedDecl>(*D)->getDeclName()) {
3270 ValueDecl *VD = cast<ValueDecl>(*D);
3271 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3272 VD->getLocation(), diagKind)) {
3273 // C++ [class.union]p2:
3274 // The names of the members of an anonymous union shall be
3275 // distinct from the names of any other entity in the
3276 // scope in which the anonymous union is declared.
3277 Invalid = true;
3278 } else {
3279 // C++ [class.union]p2:
3280 // For the purpose of name lookup, after the anonymous union
3281 // definition, the members of the anonymous union are
3282 // considered to have been defined in the scope in which the
3283 // anonymous union is declared.
3284 unsigned OldChainingSize = Chaining.size();
3285 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3286 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3287 PE = IF->chain_end(); PI != PE; ++PI)
3288 Chaining.push_back(*PI);
3289 else
3290 Chaining.push_back(VD);
3291
3292 assert(Chaining.size() >= 2);
3293 NamedDecl **NamedChain =
3294 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3295 for (unsigned i = 0; i < Chaining.size(); i++)
3296 NamedChain[i] = Chaining[i];
3297
3298 IndirectFieldDecl* IndirectField =
3299 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3300 VD->getIdentifier(), VD->getType(),
3301 NamedChain, Chaining.size());
3302
3303 IndirectField->setAccess(AS);
3304 IndirectField->setImplicit();
3305 SemaRef.PushOnScopeChains(IndirectField, S);
3306
3307 // That includes picking up the appropriate access specifier.
3308 if (AS != AS_none) IndirectField->setAccess(AS);
3309
3310 Chaining.resize(OldChainingSize);
3311 }
3312 }
3313 }
3314
3315 return Invalid;
3316 }
3317
3318 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3319 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3320 /// illegal input values are mapped to SC_None.
3321 static StorageClass
StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec)3322 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
3323 switch (StorageClassSpec) {
3324 case DeclSpec::SCS_unspecified: return SC_None;
3325 case DeclSpec::SCS_extern: return SC_Extern;
3326 case DeclSpec::SCS_static: return SC_Static;
3327 case DeclSpec::SCS_auto: return SC_Auto;
3328 case DeclSpec::SCS_register: return SC_Register;
3329 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3330 // Illegal SCSs map to None: error reporting is up to the caller.
3331 case DeclSpec::SCS_mutable: // Fall through.
3332 case DeclSpec::SCS_typedef: return SC_None;
3333 }
3334 llvm_unreachable("unknown storage class specifier");
3335 }
3336
3337 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
3338 /// a StorageClass. Any error reporting is up to the caller:
3339 /// illegal input values are mapped to SC_None.
3340 static StorageClass
StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec)3341 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
3342 switch (StorageClassSpec) {
3343 case DeclSpec::SCS_unspecified: return SC_None;
3344 case DeclSpec::SCS_extern: return SC_Extern;
3345 case DeclSpec::SCS_static: return SC_Static;
3346 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3347 // Illegal SCSs map to None: error reporting is up to the caller.
3348 case DeclSpec::SCS_auto: // Fall through.
3349 case DeclSpec::SCS_mutable: // Fall through.
3350 case DeclSpec::SCS_register: // Fall through.
3351 case DeclSpec::SCS_typedef: return SC_None;
3352 }
3353 llvm_unreachable("unknown storage class specifier");
3354 }
3355
3356 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3357 /// anonymous structure or union. Anonymous unions are a C++ feature
3358 /// (C++ [class.union]) and a C11 feature; anonymous structures
3359 /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record)3360 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3361 AccessSpecifier AS,
3362 RecordDecl *Record) {
3363 DeclContext *Owner = Record->getDeclContext();
3364
3365 // Diagnose whether this anonymous struct/union is an extension.
3366 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3367 Diag(Record->getLocation(), diag::ext_anonymous_union);
3368 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3369 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3370 else if (!Record->isUnion() && !getLangOpts().C11)
3371 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3372
3373 // C and C++ require different kinds of checks for anonymous
3374 // structs/unions.
3375 bool Invalid = false;
3376 if (getLangOpts().CPlusPlus) {
3377 const char* PrevSpec = 0;
3378 unsigned DiagID;
3379 if (Record->isUnion()) {
3380 // C++ [class.union]p6:
3381 // Anonymous unions declared in a named namespace or in the
3382 // global namespace shall be declared static.
3383 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3384 (isa<TranslationUnitDecl>(Owner) ||
3385 (isa<NamespaceDecl>(Owner) &&
3386 cast<NamespaceDecl>(Owner)->getDeclName()))) {
3387 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3388 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3389
3390 // Recover by adding 'static'.
3391 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3392 PrevSpec, DiagID);
3393 }
3394 // C++ [class.union]p6:
3395 // A storage class is not allowed in a declaration of an
3396 // anonymous union in a class scope.
3397 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3398 isa<RecordDecl>(Owner)) {
3399 Diag(DS.getStorageClassSpecLoc(),
3400 diag::err_anonymous_union_with_storage_spec)
3401 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3402
3403 // Recover by removing the storage specifier.
3404 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3405 SourceLocation(),
3406 PrevSpec, DiagID);
3407 }
3408 }
3409
3410 // Ignore const/volatile/restrict qualifiers.
3411 if (DS.getTypeQualifiers()) {
3412 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3413 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3414 << Record->isUnion() << 0
3415 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3416 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3417 Diag(DS.getVolatileSpecLoc(),
3418 diag::ext_anonymous_struct_union_qualified)
3419 << Record->isUnion() << 1
3420 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3421 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3422 Diag(DS.getRestrictSpecLoc(),
3423 diag::ext_anonymous_struct_union_qualified)
3424 << Record->isUnion() << 2
3425 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3426
3427 DS.ClearTypeQualifiers();
3428 }
3429
3430 // C++ [class.union]p2:
3431 // The member-specification of an anonymous union shall only
3432 // define non-static data members. [Note: nested types and
3433 // functions cannot be declared within an anonymous union. ]
3434 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3435 MemEnd = Record->decls_end();
3436 Mem != MemEnd; ++Mem) {
3437 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3438 // C++ [class.union]p3:
3439 // An anonymous union shall not have private or protected
3440 // members (clause 11).
3441 assert(FD->getAccess() != AS_none);
3442 if (FD->getAccess() != AS_public) {
3443 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3444 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3445 Invalid = true;
3446 }
3447
3448 // C++ [class.union]p1
3449 // An object of a class with a non-trivial constructor, a non-trivial
3450 // copy constructor, a non-trivial destructor, or a non-trivial copy
3451 // assignment operator cannot be a member of a union, nor can an
3452 // array of such objects.
3453 if (CheckNontrivialField(FD))
3454 Invalid = true;
3455 } else if ((*Mem)->isImplicit()) {
3456 // Any implicit members are fine.
3457 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3458 // This is a type that showed up in an
3459 // elaborated-type-specifier inside the anonymous struct or
3460 // union, but which actually declares a type outside of the
3461 // anonymous struct or union. It's okay.
3462 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3463 if (!MemRecord->isAnonymousStructOrUnion() &&
3464 MemRecord->getDeclName()) {
3465 // Visual C++ allows type definition in anonymous struct or union.
3466 if (getLangOpts().MicrosoftExt)
3467 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3468 << (int)Record->isUnion();
3469 else {
3470 // This is a nested type declaration.
3471 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3472 << (int)Record->isUnion();
3473 Invalid = true;
3474 }
3475 } else {
3476 // This is an anonymous type definition within another anonymous type.
3477 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3478 // not part of standard C++.
3479 Diag(MemRecord->getLocation(),
3480 diag::ext_anonymous_record_with_anonymous_type)
3481 << (int)Record->isUnion();
3482 }
3483 } else if (isa<AccessSpecDecl>(*Mem)) {
3484 // Any access specifier is fine.
3485 } else {
3486 // We have something that isn't a non-static data
3487 // member. Complain about it.
3488 unsigned DK = diag::err_anonymous_record_bad_member;
3489 if (isa<TypeDecl>(*Mem))
3490 DK = diag::err_anonymous_record_with_type;
3491 else if (isa<FunctionDecl>(*Mem))
3492 DK = diag::err_anonymous_record_with_function;
3493 else if (isa<VarDecl>(*Mem))
3494 DK = diag::err_anonymous_record_with_static;
3495
3496 // Visual C++ allows type definition in anonymous struct or union.
3497 if (getLangOpts().MicrosoftExt &&
3498 DK == diag::err_anonymous_record_with_type)
3499 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3500 << (int)Record->isUnion();
3501 else {
3502 Diag((*Mem)->getLocation(), DK)
3503 << (int)Record->isUnion();
3504 Invalid = true;
3505 }
3506 }
3507 }
3508 }
3509
3510 if (!Record->isUnion() && !Owner->isRecord()) {
3511 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3512 << (int)getLangOpts().CPlusPlus;
3513 Invalid = true;
3514 }
3515
3516 // Mock up a declarator.
3517 Declarator Dc(DS, Declarator::MemberContext);
3518 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3519 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3520
3521 // Create a declaration for this anonymous struct/union.
3522 NamedDecl *Anon = 0;
3523 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3524 Anon = FieldDecl::Create(Context, OwningClass,
3525 DS.getLocStart(),
3526 Record->getLocation(),
3527 /*IdentifierInfo=*/0,
3528 Context.getTypeDeclType(Record),
3529 TInfo,
3530 /*BitWidth=*/0, /*Mutable=*/false,
3531 /*InitStyle=*/ICIS_NoInit);
3532 Anon->setAccess(AS);
3533 if (getLangOpts().CPlusPlus)
3534 FieldCollector->Add(cast<FieldDecl>(Anon));
3535 } else {
3536 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3537 assert(SCSpec != DeclSpec::SCS_typedef &&
3538 "Parser allowed 'typedef' as storage class VarDecl.");
3539 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3540 if (SCSpec == DeclSpec::SCS_mutable) {
3541 // mutable can only appear on non-static class members, so it's always
3542 // an error here
3543 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3544 Invalid = true;
3545 SC = SC_None;
3546 }
3547 SCSpec = DS.getStorageClassSpecAsWritten();
3548 VarDecl::StorageClass SCAsWritten
3549 = StorageClassSpecToVarDeclStorageClass(SCSpec);
3550
3551 Anon = VarDecl::Create(Context, Owner,
3552 DS.getLocStart(),
3553 Record->getLocation(), /*IdentifierInfo=*/0,
3554 Context.getTypeDeclType(Record),
3555 TInfo, SC, SCAsWritten);
3556
3557 // Default-initialize the implicit variable. This initialization will be
3558 // trivial in almost all cases, except if a union member has an in-class
3559 // initializer:
3560 // union { int n = 0; };
3561 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3562 }
3563 Anon->setImplicit();
3564
3565 // Add the anonymous struct/union object to the current
3566 // context. We'll be referencing this object when we refer to one of
3567 // its members.
3568 Owner->addDecl(Anon);
3569
3570 // Inject the members of the anonymous struct/union into the owning
3571 // context and into the identifier resolver chain for name lookup
3572 // purposes.
3573 SmallVector<NamedDecl*, 2> Chain;
3574 Chain.push_back(Anon);
3575
3576 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3577 Chain, false))
3578 Invalid = true;
3579
3580 // Mark this as an anonymous struct/union type. Note that we do not
3581 // do this until after we have already checked and injected the
3582 // members of this anonymous struct/union type, because otherwise
3583 // the members could be injected twice: once by DeclContext when it
3584 // builds its lookup table, and once by
3585 // InjectAnonymousStructOrUnionMembers.
3586 Record->setAnonymousStructOrUnion(true);
3587
3588 if (Invalid)
3589 Anon->setInvalidDecl();
3590
3591 return Anon;
3592 }
3593
3594 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3595 /// Microsoft C anonymous structure.
3596 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3597 /// Example:
3598 ///
3599 /// struct A { int a; };
3600 /// struct B { struct A; int b; };
3601 ///
3602 /// void foo() {
3603 /// B var;
3604 /// var.a = 3;
3605 /// }
3606 ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)3607 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3608 RecordDecl *Record) {
3609
3610 // If there is no Record, get the record via the typedef.
3611 if (!Record)
3612 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3613
3614 // Mock up a declarator.
3615 Declarator Dc(DS, Declarator::TypeNameContext);
3616 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3617 assert(TInfo && "couldn't build declarator info for anonymous struct");
3618
3619 // Create a declaration for this anonymous struct.
3620 NamedDecl* Anon = FieldDecl::Create(Context,
3621 cast<RecordDecl>(CurContext),
3622 DS.getLocStart(),
3623 DS.getLocStart(),
3624 /*IdentifierInfo=*/0,
3625 Context.getTypeDeclType(Record),
3626 TInfo,
3627 /*BitWidth=*/0, /*Mutable=*/false,
3628 /*InitStyle=*/ICIS_NoInit);
3629 Anon->setImplicit();
3630
3631 // Add the anonymous struct object to the current context.
3632 CurContext->addDecl(Anon);
3633
3634 // Inject the members of the anonymous struct into the current
3635 // context and into the identifier resolver chain for name lookup
3636 // purposes.
3637 SmallVector<NamedDecl*, 2> Chain;
3638 Chain.push_back(Anon);
3639
3640 RecordDecl *RecordDef = Record->getDefinition();
3641 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3642 RecordDef, AS_none,
3643 Chain, true))
3644 Anon->setInvalidDecl();
3645
3646 return Anon;
3647 }
3648
3649 /// GetNameForDeclarator - Determine the full declaration name for the
3650 /// given Declarator.
GetNameForDeclarator(Declarator & D)3651 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3652 return GetNameFromUnqualifiedId(D.getName());
3653 }
3654
3655 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3656 DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)3657 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3658 DeclarationNameInfo NameInfo;
3659 NameInfo.setLoc(Name.StartLocation);
3660
3661 switch (Name.getKind()) {
3662
3663 case UnqualifiedId::IK_ImplicitSelfParam:
3664 case UnqualifiedId::IK_Identifier:
3665 NameInfo.setName(Name.Identifier);
3666 NameInfo.setLoc(Name.StartLocation);
3667 return NameInfo;
3668
3669 case UnqualifiedId::IK_OperatorFunctionId:
3670 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3671 Name.OperatorFunctionId.Operator));
3672 NameInfo.setLoc(Name.StartLocation);
3673 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3674 = Name.OperatorFunctionId.SymbolLocations[0];
3675 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3676 = Name.EndLocation.getRawEncoding();
3677 return NameInfo;
3678
3679 case UnqualifiedId::IK_LiteralOperatorId:
3680 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3681 Name.Identifier));
3682 NameInfo.setLoc(Name.StartLocation);
3683 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3684 return NameInfo;
3685
3686 case UnqualifiedId::IK_ConversionFunctionId: {
3687 TypeSourceInfo *TInfo;
3688 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3689 if (Ty.isNull())
3690 return DeclarationNameInfo();
3691 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3692 Context.getCanonicalType(Ty)));
3693 NameInfo.setLoc(Name.StartLocation);
3694 NameInfo.setNamedTypeInfo(TInfo);
3695 return NameInfo;
3696 }
3697
3698 case UnqualifiedId::IK_ConstructorName: {
3699 TypeSourceInfo *TInfo;
3700 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3701 if (Ty.isNull())
3702 return DeclarationNameInfo();
3703 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3704 Context.getCanonicalType(Ty)));
3705 NameInfo.setLoc(Name.StartLocation);
3706 NameInfo.setNamedTypeInfo(TInfo);
3707 return NameInfo;
3708 }
3709
3710 case UnqualifiedId::IK_ConstructorTemplateId: {
3711 // In well-formed code, we can only have a constructor
3712 // template-id that refers to the current context, so go there
3713 // to find the actual type being constructed.
3714 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3715 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3716 return DeclarationNameInfo();
3717
3718 // Determine the type of the class being constructed.
3719 QualType CurClassType = Context.getTypeDeclType(CurClass);
3720
3721 // FIXME: Check two things: that the template-id names the same type as
3722 // CurClassType, and that the template-id does not occur when the name
3723 // was qualified.
3724
3725 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3726 Context.getCanonicalType(CurClassType)));
3727 NameInfo.setLoc(Name.StartLocation);
3728 // FIXME: should we retrieve TypeSourceInfo?
3729 NameInfo.setNamedTypeInfo(0);
3730 return NameInfo;
3731 }
3732
3733 case UnqualifiedId::IK_DestructorName: {
3734 TypeSourceInfo *TInfo;
3735 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3736 if (Ty.isNull())
3737 return DeclarationNameInfo();
3738 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3739 Context.getCanonicalType(Ty)));
3740 NameInfo.setLoc(Name.StartLocation);
3741 NameInfo.setNamedTypeInfo(TInfo);
3742 return NameInfo;
3743 }
3744
3745 case UnqualifiedId::IK_TemplateId: {
3746 TemplateName TName = Name.TemplateId->Template.get();
3747 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3748 return Context.getNameForTemplate(TName, TNameLoc);
3749 }
3750
3751 } // switch (Name.getKind())
3752
3753 llvm_unreachable("Unknown name kind");
3754 }
3755
getCoreType(QualType Ty)3756 static QualType getCoreType(QualType Ty) {
3757 do {
3758 if (Ty->isPointerType() || Ty->isReferenceType())
3759 Ty = Ty->getPointeeType();
3760 else if (Ty->isArrayType())
3761 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3762 else
3763 return Ty.withoutLocalFastQualifiers();
3764 } while (true);
3765 }
3766
3767 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3768 /// and Definition have "nearly" matching parameters. This heuristic is
3769 /// used to improve diagnostics in the case where an out-of-line function
3770 /// definition doesn't match any declaration within the class or namespace.
3771 /// Also sets Params to the list of indices to the parameters that differ
3772 /// between the declaration and the definition. If hasSimilarParameters
3773 /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)3774 static bool hasSimilarParameters(ASTContext &Context,
3775 FunctionDecl *Declaration,
3776 FunctionDecl *Definition,
3777 SmallVectorImpl<unsigned> &Params) {
3778 Params.clear();
3779 if (Declaration->param_size() != Definition->param_size())
3780 return false;
3781 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3782 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3783 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3784
3785 // The parameter types are identical
3786 if (Context.hasSameType(DefParamTy, DeclParamTy))
3787 continue;
3788
3789 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3790 QualType DefParamBaseTy = getCoreType(DefParamTy);
3791 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3792 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3793
3794 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3795 (DeclTyName && DeclTyName == DefTyName))
3796 Params.push_back(Idx);
3797 else // The two parameters aren't even close
3798 return false;
3799 }
3800
3801 return true;
3802 }
3803
3804 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3805 /// declarator needs to be rebuilt in the current instantiation.
3806 /// Any bits of declarator which appear before the name are valid for
3807 /// consideration here. That's specifically the type in the decl spec
3808 /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)3809 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3810 DeclarationName Name) {
3811 // The types we specifically need to rebuild are:
3812 // - typenames, typeofs, and decltypes
3813 // - types which will become injected class names
3814 // Of course, we also need to rebuild any type referencing such a
3815 // type. It's safest to just say "dependent", but we call out a
3816 // few cases here.
3817
3818 DeclSpec &DS = D.getMutableDeclSpec();
3819 switch (DS.getTypeSpecType()) {
3820 case DeclSpec::TST_typename:
3821 case DeclSpec::TST_typeofType:
3822 case DeclSpec::TST_underlyingType:
3823 case DeclSpec::TST_atomic: {
3824 // Grab the type from the parser.
3825 TypeSourceInfo *TSI = 0;
3826 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3827 if (T.isNull() || !T->isDependentType()) break;
3828
3829 // Make sure there's a type source info. This isn't really much
3830 // of a waste; most dependent types should have type source info
3831 // attached already.
3832 if (!TSI)
3833 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3834
3835 // Rebuild the type in the current instantiation.
3836 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3837 if (!TSI) return true;
3838
3839 // Store the new type back in the decl spec.
3840 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3841 DS.UpdateTypeRep(LocType);
3842 break;
3843 }
3844
3845 case DeclSpec::TST_decltype:
3846 case DeclSpec::TST_typeofExpr: {
3847 Expr *E = DS.getRepAsExpr();
3848 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3849 if (Result.isInvalid()) return true;
3850 DS.UpdateExprRep(Result.get());
3851 break;
3852 }
3853
3854 default:
3855 // Nothing to do for these decl specs.
3856 break;
3857 }
3858
3859 // It doesn't matter what order we do this in.
3860 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3861 DeclaratorChunk &Chunk = D.getTypeObject(I);
3862
3863 // The only type information in the declarator which can come
3864 // before the declaration name is the base type of a member
3865 // pointer.
3866 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3867 continue;
3868
3869 // Rebuild the scope specifier in-place.
3870 CXXScopeSpec &SS = Chunk.Mem.Scope();
3871 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3872 return true;
3873 }
3874
3875 return false;
3876 }
3877
ActOnDeclarator(Scope * S,Declarator & D)3878 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3879 D.setFunctionDefinitionKind(FDK_Declaration);
3880 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
3881
3882 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3883 Dcl && Dcl->getDeclContext()->isFileContext())
3884 Dcl->setTopLevelDeclInObjCContainer();
3885
3886 return Dcl;
3887 }
3888
3889 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3890 /// If T is the name of a class, then each of the following shall have a
3891 /// name different from T:
3892 /// - every static data member of class T;
3893 /// - every member function of class T
3894 /// - every member of class T that is itself a type;
3895 /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)3896 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3897 DeclarationNameInfo NameInfo) {
3898 DeclarationName Name = NameInfo.getName();
3899
3900 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3901 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3902 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3903 return true;
3904 }
3905
3906 return false;
3907 }
3908
3909 /// \brief Diagnose a declaration whose declarator-id has the given
3910 /// nested-name-specifier.
3911 ///
3912 /// \param SS The nested-name-specifier of the declarator-id.
3913 ///
3914 /// \param DC The declaration context to which the nested-name-specifier
3915 /// resolves.
3916 ///
3917 /// \param Name The name of the entity being declared.
3918 ///
3919 /// \param Loc The location of the name of the entity being declared.
3920 ///
3921 /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc)3922 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3923 DeclarationName Name,
3924 SourceLocation Loc) {
3925 DeclContext *Cur = CurContext;
3926 while (isa<LinkageSpecDecl>(Cur))
3927 Cur = Cur->getParent();
3928
3929 // C++ [dcl.meaning]p1:
3930 // A declarator-id shall not be qualified except for the definition
3931 // of a member function (9.3) or static data member (9.4) outside of
3932 // its class, the definition or explicit instantiation of a function
3933 // or variable member of a namespace outside of its namespace, or the
3934 // definition of an explicit specialization outside of its namespace,
3935 // or the declaration of a friend function that is a member of
3936 // another class or namespace (11.3). [...]
3937
3938 // The user provided a superfluous scope specifier that refers back to the
3939 // class or namespaces in which the entity is already declared.
3940 //
3941 // class X {
3942 // void X::f();
3943 // };
3944 if (Cur->Equals(DC)) {
3945 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
3946 : diag::err_member_extra_qualification)
3947 << Name << FixItHint::CreateRemoval(SS.getRange());
3948 SS.clear();
3949 return false;
3950 }
3951
3952 // Check whether the qualifying scope encloses the scope of the original
3953 // declaration.
3954 if (!Cur->Encloses(DC)) {
3955 if (Cur->isRecord())
3956 Diag(Loc, diag::err_member_qualification)
3957 << Name << SS.getRange();
3958 else if (isa<TranslationUnitDecl>(DC))
3959 Diag(Loc, diag::err_invalid_declarator_global_scope)
3960 << Name << SS.getRange();
3961 else if (isa<FunctionDecl>(Cur))
3962 Diag(Loc, diag::err_invalid_declarator_in_function)
3963 << Name << SS.getRange();
3964 else
3965 Diag(Loc, diag::err_invalid_declarator_scope)
3966 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3967
3968 return true;
3969 }
3970
3971 if (Cur->isRecord()) {
3972 // Cannot qualify members within a class.
3973 Diag(Loc, diag::err_member_qualification)
3974 << Name << SS.getRange();
3975 SS.clear();
3976
3977 // C++ constructors and destructors with incorrect scopes can break
3978 // our AST invariants by having the wrong underlying types. If
3979 // that's the case, then drop this declaration entirely.
3980 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3981 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3982 !Context.hasSameType(Name.getCXXNameType(),
3983 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3984 return true;
3985
3986 return false;
3987 }
3988
3989 // C++11 [dcl.meaning]p1:
3990 // [...] "The nested-name-specifier of the qualified declarator-id shall
3991 // not begin with a decltype-specifer"
3992 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3993 while (SpecLoc.getPrefix())
3994 SpecLoc = SpecLoc.getPrefix();
3995 if (dyn_cast_or_null<DecltypeType>(
3996 SpecLoc.getNestedNameSpecifier()->getAsType()))
3997 Diag(Loc, diag::err_decltype_in_declarator)
3998 << SpecLoc.getTypeLoc().getSourceRange();
3999
4000 return false;
4001 }
4002
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)4003 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4004 MultiTemplateParamsArg TemplateParamLists) {
4005 // TODO: consider using NameInfo for diagnostic.
4006 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4007 DeclarationName Name = NameInfo.getName();
4008
4009 // All of these full declarators require an identifier. If it doesn't have
4010 // one, the ParsedFreeStandingDeclSpec action should be used.
4011 if (!Name) {
4012 if (!D.isInvalidType()) // Reject this if we think it is valid.
4013 Diag(D.getDeclSpec().getLocStart(),
4014 diag::err_declarator_need_ident)
4015 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4016 return 0;
4017 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4018 return 0;
4019
4020 // The scope passed in may not be a decl scope. Zip up the scope tree until
4021 // we find one that is.
4022 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4023 (S->getFlags() & Scope::TemplateParamScope) != 0)
4024 S = S->getParent();
4025
4026 DeclContext *DC = CurContext;
4027 if (D.getCXXScopeSpec().isInvalid())
4028 D.setInvalidType();
4029 else if (D.getCXXScopeSpec().isSet()) {
4030 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4031 UPPC_DeclarationQualifier))
4032 return 0;
4033
4034 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4035 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4036 if (!DC) {
4037 // If we could not compute the declaration context, it's because the
4038 // declaration context is dependent but does not refer to a class,
4039 // class template, or class template partial specialization. Complain
4040 // and return early, to avoid the coming semantic disaster.
4041 Diag(D.getIdentifierLoc(),
4042 diag::err_template_qualified_declarator_no_match)
4043 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4044 << D.getCXXScopeSpec().getRange();
4045 return 0;
4046 }
4047 bool IsDependentContext = DC->isDependentContext();
4048
4049 if (!IsDependentContext &&
4050 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4051 return 0;
4052
4053 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4054 Diag(D.getIdentifierLoc(),
4055 diag::err_member_def_undefined_record)
4056 << Name << DC << D.getCXXScopeSpec().getRange();
4057 D.setInvalidType();
4058 } else if (!D.getDeclSpec().isFriendSpecified()) {
4059 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4060 Name, D.getIdentifierLoc())) {
4061 if (DC->isRecord())
4062 return 0;
4063
4064 D.setInvalidType();
4065 }
4066 }
4067
4068 // Check whether we need to rebuild the type of the given
4069 // declaration in the current instantiation.
4070 if (EnteringContext && IsDependentContext &&
4071 TemplateParamLists.size() != 0) {
4072 ContextRAII SavedContext(*this, DC);
4073 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4074 D.setInvalidType();
4075 }
4076 }
4077
4078 if (DiagnoseClassNameShadow(DC, NameInfo))
4079 // If this is a typedef, we'll end up spewing multiple diagnostics.
4080 // Just return early; it's safer.
4081 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4082 return 0;
4083
4084 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4085 QualType R = TInfo->getType();
4086
4087 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4088 UPPC_DeclarationType))
4089 D.setInvalidType();
4090
4091 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4092 ForRedeclaration);
4093
4094 // See if this is a redefinition of a variable in the same scope.
4095 if (!D.getCXXScopeSpec().isSet()) {
4096 bool IsLinkageLookup = false;
4097
4098 // If the declaration we're planning to build will be a function
4099 // or object with linkage, then look for another declaration with
4100 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4101 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4102 /* Do nothing*/;
4103 else if (R->isFunctionType()) {
4104 if (CurContext->isFunctionOrMethod() ||
4105 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4106 IsLinkageLookup = true;
4107 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
4108 IsLinkageLookup = true;
4109 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4110 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4111 IsLinkageLookup = true;
4112
4113 if (IsLinkageLookup)
4114 Previous.clear(LookupRedeclarationWithLinkage);
4115
4116 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
4117 } else { // Something like "int foo::x;"
4118 LookupQualifiedName(Previous, DC);
4119
4120 // C++ [dcl.meaning]p1:
4121 // When the declarator-id is qualified, the declaration shall refer to a
4122 // previously declared member of the class or namespace to which the
4123 // qualifier refers (or, in the case of a namespace, of an element of the
4124 // inline namespace set of that namespace (7.3.1)) or to a specialization
4125 // thereof; [...]
4126 //
4127 // Note that we already checked the context above, and that we do not have
4128 // enough information to make sure that Previous contains the declaration
4129 // we want to match. For example, given:
4130 //
4131 // class X {
4132 // void f();
4133 // void f(float);
4134 // };
4135 //
4136 // void X::f(int) { } // ill-formed
4137 //
4138 // In this case, Previous will point to the overload set
4139 // containing the two f's declared in X, but neither of them
4140 // matches.
4141
4142 // C++ [dcl.meaning]p1:
4143 // [...] the member shall not merely have been introduced by a
4144 // using-declaration in the scope of the class or namespace nominated by
4145 // the nested-name-specifier of the declarator-id.
4146 RemoveUsingDecls(Previous);
4147 }
4148
4149 if (Previous.isSingleResult() &&
4150 Previous.getFoundDecl()->isTemplateParameter()) {
4151 // Maybe we will complain about the shadowed template parameter.
4152 if (!D.isInvalidType())
4153 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4154 Previous.getFoundDecl());
4155
4156 // Just pretend that we didn't see the previous declaration.
4157 Previous.clear();
4158 }
4159
4160 // In C++, the previous declaration we find might be a tag type
4161 // (class or enum). In this case, the new declaration will hide the
4162 // tag type. Note that this does does not apply if we're declaring a
4163 // typedef (C++ [dcl.typedef]p4).
4164 if (Previous.isSingleTagDecl() &&
4165 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4166 Previous.clear();
4167
4168 // Check that there are no default arguments other than in the parameters
4169 // of a function declaration (C++ only).
4170 if (getLangOpts().CPlusPlus)
4171 CheckExtraCXXDefaultArguments(D);
4172
4173 NamedDecl *New;
4174
4175 bool AddToScope = true;
4176 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4177 if (TemplateParamLists.size()) {
4178 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4179 return 0;
4180 }
4181
4182 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4183 } else if (R->isFunctionType()) {
4184 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4185 TemplateParamLists,
4186 AddToScope);
4187 } else {
4188 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
4189 TemplateParamLists);
4190 }
4191
4192 if (New == 0)
4193 return 0;
4194
4195 // If this has an identifier and is not an invalid redeclaration or
4196 // function template specialization, add it to the scope stack.
4197 if (New->getDeclName() && AddToScope &&
4198 !(D.isRedeclaration() && New->isInvalidDecl()))
4199 PushOnScopeChains(New, S);
4200
4201 return New;
4202 }
4203
4204 /// Helper method to turn variable array types into constant array
4205 /// types in certain situations which would otherwise be errors (for
4206 /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)4207 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4208 ASTContext &Context,
4209 bool &SizeIsNegative,
4210 llvm::APSInt &Oversized) {
4211 // This method tries to turn a variable array into a constant
4212 // array even when the size isn't an ICE. This is necessary
4213 // for compatibility with code that depends on gcc's buggy
4214 // constant expression folding, like struct {char x[(int)(char*)2];}
4215 SizeIsNegative = false;
4216 Oversized = 0;
4217
4218 if (T->isDependentType())
4219 return QualType();
4220
4221 QualifierCollector Qs;
4222 const Type *Ty = Qs.strip(T);
4223
4224 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4225 QualType Pointee = PTy->getPointeeType();
4226 QualType FixedType =
4227 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4228 Oversized);
4229 if (FixedType.isNull()) return FixedType;
4230 FixedType = Context.getPointerType(FixedType);
4231 return Qs.apply(Context, FixedType);
4232 }
4233 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4234 QualType Inner = PTy->getInnerType();
4235 QualType FixedType =
4236 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4237 Oversized);
4238 if (FixedType.isNull()) return FixedType;
4239 FixedType = Context.getParenType(FixedType);
4240 return Qs.apply(Context, FixedType);
4241 }
4242
4243 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4244 if (!VLATy)
4245 return QualType();
4246 // FIXME: We should probably handle this case
4247 if (VLATy->getElementType()->isVariablyModifiedType())
4248 return QualType();
4249
4250 llvm::APSInt Res;
4251 if (!VLATy->getSizeExpr() ||
4252 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4253 return QualType();
4254
4255 // Check whether the array size is negative.
4256 if (Res.isSigned() && Res.isNegative()) {
4257 SizeIsNegative = true;
4258 return QualType();
4259 }
4260
4261 // Check whether the array is too large to be addressed.
4262 unsigned ActiveSizeBits
4263 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4264 Res);
4265 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4266 Oversized = Res;
4267 return QualType();
4268 }
4269
4270 return Context.getConstantArrayType(VLATy->getElementType(),
4271 Res, ArrayType::Normal, 0);
4272 }
4273
4274 static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)4275 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4276 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4277 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4278 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4279 DstPTL.getPointeeLoc());
4280 DstPTL.setStarLoc(SrcPTL.getStarLoc());
4281 return;
4282 }
4283 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4284 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4285 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4286 DstPTL.getInnerLoc());
4287 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4288 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4289 return;
4290 }
4291 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4292 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4293 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4294 TypeLoc DstElemTL = DstATL.getElementLoc();
4295 DstElemTL.initializeFullCopy(SrcElemTL);
4296 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4297 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4298 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4299 }
4300
4301 /// Helper method to turn variable array types into constant array
4302 /// types in certain situations which would otherwise be errors (for
4303 /// GCC compatibility).
4304 static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)4305 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4306 ASTContext &Context,
4307 bool &SizeIsNegative,
4308 llvm::APSInt &Oversized) {
4309 QualType FixedTy
4310 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4311 SizeIsNegative, Oversized);
4312 if (FixedTy.isNull())
4313 return 0;
4314 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4315 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4316 FixedTInfo->getTypeLoc());
4317 return FixedTInfo;
4318 }
4319
4320 /// \brief Register the given locally-scoped extern "C" declaration so
4321 /// that it can be found later for redeclarations
4322 void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,const LookupResult & Previous,Scope * S)4323 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
4324 const LookupResult &Previous,
4325 Scope *S) {
4326 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
4327 "Decl is not a locally-scoped decl!");
4328 // Note that we have a locally-scoped external with this name.
4329 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4330
4331 if (!Previous.isSingleResult())
4332 return;
4333
4334 NamedDecl *PrevDecl = Previous.getFoundDecl();
4335
4336 // If there was a previous declaration of this entity, it may be in
4337 // our identifier chain. Update the identifier chain with the new
4338 // declaration.
4339 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
4340 // The previous declaration was found on the identifer resolver
4341 // chain, so remove it from its scope.
4342
4343 if (S->isDeclScope(PrevDecl)) {
4344 // Special case for redeclarations in the SAME scope.
4345 // Because this declaration is going to be added to the identifier chain
4346 // later, we should temporarily take it OFF the chain.
4347 IdResolver.RemoveDecl(ND);
4348
4349 } else {
4350 // Find the scope for the original declaration.
4351 while (S && !S->isDeclScope(PrevDecl))
4352 S = S->getParent();
4353 }
4354
4355 if (S)
4356 S->RemoveDecl(PrevDecl);
4357 }
4358 }
4359
4360 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
findLocallyScopedExternCDecl(DeclarationName Name)4361 Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4362 if (ExternalSource) {
4363 // Load locally-scoped external decls from the external source.
4364 SmallVector<NamedDecl *, 4> Decls;
4365 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4366 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4367 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4368 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4369 if (Pos == LocallyScopedExternCDecls.end())
4370 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4371 }
4372 }
4373
4374 return LocallyScopedExternCDecls.find(Name);
4375 }
4376
4377 /// \brief Diagnose function specifiers on a declaration of an identifier that
4378 /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)4379 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4380 // FIXME: We should probably indicate the identifier in question to avoid
4381 // confusion for constructs like "inline int a(), b;"
4382 if (DS.isInlineSpecified())
4383 Diag(DS.getInlineSpecLoc(),
4384 diag::err_inline_non_function);
4385
4386 if (DS.isVirtualSpecified())
4387 Diag(DS.getVirtualSpecLoc(),
4388 diag::err_virtual_non_function);
4389
4390 if (DS.isExplicitSpecified())
4391 Diag(DS.getExplicitSpecLoc(),
4392 diag::err_explicit_non_function);
4393
4394 if (DS.isNoreturnSpecified())
4395 Diag(DS.getNoreturnSpecLoc(),
4396 diag::err_noreturn_non_function);
4397 }
4398
4399 NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)4400 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4401 TypeSourceInfo *TInfo, LookupResult &Previous) {
4402 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4403 if (D.getCXXScopeSpec().isSet()) {
4404 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4405 << D.getCXXScopeSpec().getRange();
4406 D.setInvalidType();
4407 // Pretend we didn't see the scope specifier.
4408 DC = CurContext;
4409 Previous.clear();
4410 }
4411
4412 DiagnoseFunctionSpecifiers(D.getDeclSpec());
4413
4414 if (D.getDeclSpec().isThreadSpecified())
4415 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4416 if (D.getDeclSpec().isConstexprSpecified())
4417 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4418 << 1;
4419
4420 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4421 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4422 << D.getName().getSourceRange();
4423 return 0;
4424 }
4425
4426 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4427 if (!NewTD) return 0;
4428
4429 // Handle attributes prior to checking for duplicates in MergeVarDecl
4430 ProcessDeclAttributes(S, NewTD, D);
4431
4432 CheckTypedefForVariablyModifiedType(S, NewTD);
4433
4434 bool Redeclaration = D.isRedeclaration();
4435 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4436 D.setRedeclaration(Redeclaration);
4437 return ND;
4438 }
4439
4440 void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)4441 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4442 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4443 // then it shall have block scope.
4444 // Note that variably modified types must be fixed before merging the decl so
4445 // that redeclarations will match.
4446 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4447 QualType T = TInfo->getType();
4448 if (T->isVariablyModifiedType()) {
4449 getCurFunction()->setHasBranchProtectedScope();
4450
4451 if (S->getFnParent() == 0) {
4452 bool SizeIsNegative;
4453 llvm::APSInt Oversized;
4454 TypeSourceInfo *FixedTInfo =
4455 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4456 SizeIsNegative,
4457 Oversized);
4458 if (FixedTInfo) {
4459 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4460 NewTD->setTypeSourceInfo(FixedTInfo);
4461 } else {
4462 if (SizeIsNegative)
4463 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4464 else if (T->isVariableArrayType())
4465 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4466 else if (Oversized.getBoolValue())
4467 Diag(NewTD->getLocation(), diag::err_array_too_large)
4468 << Oversized.toString(10);
4469 else
4470 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4471 NewTD->setInvalidDecl();
4472 }
4473 }
4474 }
4475 }
4476
4477
4478 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4479 /// declares a typedef-name, either using the 'typedef' type specifier or via
4480 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4481 NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)4482 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4483 LookupResult &Previous, bool &Redeclaration) {
4484 // Merge the decl with the existing one if appropriate. If the decl is
4485 // in an outer scope, it isn't the same thing.
4486 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4487 /*ExplicitInstantiationOrSpecialization=*/false);
4488 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4489 if (!Previous.empty()) {
4490 Redeclaration = true;
4491 MergeTypedefNameDecl(NewTD, Previous);
4492 }
4493
4494 // If this is the C FILE type, notify the AST context.
4495 if (IdentifierInfo *II = NewTD->getIdentifier())
4496 if (!NewTD->isInvalidDecl() &&
4497 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4498 if (II->isStr("FILE"))
4499 Context.setFILEDecl(NewTD);
4500 else if (II->isStr("jmp_buf"))
4501 Context.setjmp_bufDecl(NewTD);
4502 else if (II->isStr("sigjmp_buf"))
4503 Context.setsigjmp_bufDecl(NewTD);
4504 else if (II->isStr("ucontext_t"))
4505 Context.setucontext_tDecl(NewTD);
4506 }
4507
4508 return NewTD;
4509 }
4510
4511 /// \brief Determines whether the given declaration is an out-of-scope
4512 /// previous declaration.
4513 ///
4514 /// This routine should be invoked when name lookup has found a
4515 /// previous declaration (PrevDecl) that is not in the scope where a
4516 /// new declaration by the same name is being introduced. If the new
4517 /// declaration occurs in a local scope, previous declarations with
4518 /// linkage may still be considered previous declarations (C99
4519 /// 6.2.2p4-5, C++ [basic.link]p6).
4520 ///
4521 /// \param PrevDecl the previous declaration found by name
4522 /// lookup
4523 ///
4524 /// \param DC the context in which the new declaration is being
4525 /// declared.
4526 ///
4527 /// \returns true if PrevDecl is an out-of-scope previous declaration
4528 /// for a new delcaration with the same name.
4529 static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)4530 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4531 ASTContext &Context) {
4532 if (!PrevDecl)
4533 return false;
4534
4535 if (!PrevDecl->hasLinkage())
4536 return false;
4537
4538 if (Context.getLangOpts().CPlusPlus) {
4539 // C++ [basic.link]p6:
4540 // If there is a visible declaration of an entity with linkage
4541 // having the same name and type, ignoring entities declared
4542 // outside the innermost enclosing namespace scope, the block
4543 // scope declaration declares that same entity and receives the
4544 // linkage of the previous declaration.
4545 DeclContext *OuterContext = DC->getRedeclContext();
4546 if (!OuterContext->isFunctionOrMethod())
4547 // This rule only applies to block-scope declarations.
4548 return false;
4549
4550 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4551 if (PrevOuterContext->isRecord())
4552 // We found a member function: ignore it.
4553 return false;
4554
4555 // Find the innermost enclosing namespace for the new and
4556 // previous declarations.
4557 OuterContext = OuterContext->getEnclosingNamespaceContext();
4558 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4559
4560 // The previous declaration is in a different namespace, so it
4561 // isn't the same function.
4562 if (!OuterContext->Equals(PrevOuterContext))
4563 return false;
4564 }
4565
4566 return true;
4567 }
4568
SetNestedNameSpecifier(DeclaratorDecl * DD,Declarator & D)4569 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4570 CXXScopeSpec &SS = D.getCXXScopeSpec();
4571 if (!SS.isSet()) return;
4572 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4573 }
4574
inferObjCARCLifetime(ValueDecl * decl)4575 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4576 QualType type = decl->getType();
4577 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4578 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4579 // Various kinds of declaration aren't allowed to be __autoreleasing.
4580 unsigned kind = -1U;
4581 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4582 if (var->hasAttr<BlocksAttr>())
4583 kind = 0; // __block
4584 else if (!var->hasLocalStorage())
4585 kind = 1; // global
4586 } else if (isa<ObjCIvarDecl>(decl)) {
4587 kind = 3; // ivar
4588 } else if (isa<FieldDecl>(decl)) {
4589 kind = 2; // field
4590 }
4591
4592 if (kind != -1U) {
4593 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4594 << kind;
4595 }
4596 } else if (lifetime == Qualifiers::OCL_None) {
4597 // Try to infer lifetime.
4598 if (!type->isObjCLifetimeType())
4599 return false;
4600
4601 lifetime = type->getObjCARCImplicitLifetime();
4602 type = Context.getLifetimeQualifiedType(type, lifetime);
4603 decl->setType(type);
4604 }
4605
4606 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4607 // Thread-local variables cannot have lifetime.
4608 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4609 var->isThreadSpecified()) {
4610 Diag(var->getLocation(), diag::err_arc_thread_ownership)
4611 << var->getType();
4612 return true;
4613 }
4614 }
4615
4616 return false;
4617 }
4618
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)4619 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4620 // 'weak' only applies to declarations with external linkage.
4621 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4622 if (ND.getLinkage() != ExternalLinkage) {
4623 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4624 ND.dropAttr<WeakAttr>();
4625 }
4626 }
4627 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4628 if (ND.hasExternalLinkage()) {
4629 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4630 ND.dropAttr<WeakRefAttr>();
4631 }
4632 }
4633 }
4634
shouldConsiderLinkage(const VarDecl * VD)4635 static bool shouldConsiderLinkage(const VarDecl *VD) {
4636 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4637 if (DC->isFunctionOrMethod())
4638 return VD->hasExternalStorageAsWritten();
4639 if (DC->isFileContext())
4640 return true;
4641 if (DC->isRecord())
4642 return false;
4643 llvm_unreachable("Unexpected context");
4644 }
4645
shouldConsiderLinkage(const FunctionDecl * FD)4646 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4647 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4648 if (DC->isFileContext() || DC->isFunctionOrMethod())
4649 return true;
4650 if (DC->isRecord())
4651 return false;
4652 llvm_unreachable("Unexpected context");
4653 }
4654
4655 NamedDecl*
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists)4656 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4657 TypeSourceInfo *TInfo, LookupResult &Previous,
4658 MultiTemplateParamsArg TemplateParamLists) {
4659 QualType R = TInfo->getType();
4660 DeclarationName Name = GetNameForDeclarator(D).getName();
4661
4662 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4663 assert(SCSpec != DeclSpec::SCS_typedef &&
4664 "Parser allowed 'typedef' as storage class VarDecl.");
4665 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
4666
4667 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16)
4668 {
4669 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4670 // half array type (unless the cl_khr_fp16 extension is enabled).
4671 if (Context.getBaseElementType(R)->isHalfType()) {
4672 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4673 D.setInvalidType();
4674 }
4675 }
4676
4677 if (SCSpec == DeclSpec::SCS_mutable) {
4678 // mutable can only appear on non-static class members, so it's always
4679 // an error here
4680 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4681 D.setInvalidType();
4682 SC = SC_None;
4683 }
4684 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4685 VarDecl::StorageClass SCAsWritten
4686 = StorageClassSpecToVarDeclStorageClass(SCSpec);
4687
4688 IdentifierInfo *II = Name.getAsIdentifierInfo();
4689 if (!II) {
4690 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4691 << Name;
4692 return 0;
4693 }
4694
4695 DiagnoseFunctionSpecifiers(D.getDeclSpec());
4696
4697 if (!DC->isRecord() && S->getFnParent() == 0) {
4698 // C99 6.9p2: The storage-class specifiers auto and register shall not
4699 // appear in the declaration specifiers in an external declaration.
4700 if (SC == SC_Auto || SC == SC_Register) {
4701
4702 // If this is a register variable with an asm label specified, then this
4703 // is a GNU extension.
4704 if (SC == SC_Register && D.getAsmLabel())
4705 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4706 else
4707 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4708 D.setInvalidType();
4709 }
4710 }
4711
4712 if (getLangOpts().OpenCL) {
4713 // Set up the special work-group-local storage class for variables in the
4714 // OpenCL __local address space.
4715 if (R.getAddressSpace() == LangAS::opencl_local) {
4716 SC = SC_OpenCLWorkGroupLocal;
4717 SCAsWritten = SC_OpenCLWorkGroupLocal;
4718 }
4719
4720 // OpenCL v1.2 s6.9.b p4:
4721 // The sampler type cannot be used with the __local and __global address
4722 // space qualifiers.
4723 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
4724 R.getAddressSpace() == LangAS::opencl_global)) {
4725 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
4726 }
4727
4728 // OpenCL 1.2 spec, p6.9 r:
4729 // The event type cannot be used to declare a program scope variable.
4730 // The event type cannot be used with the __local, __constant and __global
4731 // address space qualifiers.
4732 if (R->isEventT()) {
4733 if (S->getParent() == 0) {
4734 Diag(D.getLocStart(), diag::err_event_t_global_var);
4735 D.setInvalidType();
4736 }
4737
4738 if (R.getAddressSpace()) {
4739 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
4740 D.setInvalidType();
4741 }
4742 }
4743 }
4744
4745 bool isExplicitSpecialization = false;
4746 VarDecl *NewVD;
4747 if (!getLangOpts().CPlusPlus) {
4748 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4749 D.getIdentifierLoc(), II,
4750 R, TInfo, SC, SCAsWritten);
4751
4752 if (D.isInvalidType())
4753 NewVD->setInvalidDecl();
4754 } else {
4755 if (DC->isRecord() && !CurContext->isRecord()) {
4756 // This is an out-of-line definition of a static data member.
4757 if (SC == SC_Static) {
4758 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4759 diag::err_static_out_of_line)
4760 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4761 } else if (SC == SC_None)
4762 SC = SC_Static;
4763 }
4764 if (SC == SC_Static && CurContext->isRecord()) {
4765 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4766 if (RD->isLocalClass())
4767 Diag(D.getIdentifierLoc(),
4768 diag::err_static_data_member_not_allowed_in_local_class)
4769 << Name << RD->getDeclName();
4770
4771 // C++98 [class.union]p1: If a union contains a static data member,
4772 // the program is ill-formed. C++11 drops this restriction.
4773 if (RD->isUnion())
4774 Diag(D.getIdentifierLoc(),
4775 getLangOpts().CPlusPlus11
4776 ? diag::warn_cxx98_compat_static_data_member_in_union
4777 : diag::ext_static_data_member_in_union) << Name;
4778 // We conservatively disallow static data members in anonymous structs.
4779 else if (!RD->getDeclName())
4780 Diag(D.getIdentifierLoc(),
4781 diag::err_static_data_member_not_allowed_in_anon_struct)
4782 << Name << RD->isUnion();
4783 }
4784 }
4785
4786 // Match up the template parameter lists with the scope specifier, then
4787 // determine whether we have a template or a template specialization.
4788 isExplicitSpecialization = false;
4789 bool Invalid = false;
4790 if (TemplateParameterList *TemplateParams
4791 = MatchTemplateParametersToScopeSpecifier(
4792 D.getDeclSpec().getLocStart(),
4793 D.getIdentifierLoc(),
4794 D.getCXXScopeSpec(),
4795 TemplateParamLists.data(),
4796 TemplateParamLists.size(),
4797 /*never a friend*/ false,
4798 isExplicitSpecialization,
4799 Invalid)) {
4800 if (TemplateParams->size() > 0) {
4801 // There is no such thing as a variable template.
4802 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4803 << II
4804 << SourceRange(TemplateParams->getTemplateLoc(),
4805 TemplateParams->getRAngleLoc());
4806 return 0;
4807 } else {
4808 // There is an extraneous 'template<>' for this variable. Complain
4809 // about it, but allow the declaration of the variable.
4810 Diag(TemplateParams->getTemplateLoc(),
4811 diag::err_template_variable_noparams)
4812 << II
4813 << SourceRange(TemplateParams->getTemplateLoc(),
4814 TemplateParams->getRAngleLoc());
4815 }
4816 }
4817
4818 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4819 D.getIdentifierLoc(), II,
4820 R, TInfo, SC, SCAsWritten);
4821
4822 // If this decl has an auto type in need of deduction, make a note of the
4823 // Decl so we can diagnose uses of it in its own initializer.
4824 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4825 R->getContainedAutoType())
4826 ParsingInitForAutoVars.insert(NewVD);
4827
4828 if (D.isInvalidType() || Invalid)
4829 NewVD->setInvalidDecl();
4830
4831 SetNestedNameSpecifier(NewVD, D);
4832
4833 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4834 NewVD->setTemplateParameterListsInfo(Context,
4835 TemplateParamLists.size(),
4836 TemplateParamLists.data());
4837 }
4838
4839 if (D.getDeclSpec().isConstexprSpecified())
4840 NewVD->setConstexpr(true);
4841 }
4842
4843 // Set the lexical context. If the declarator has a C++ scope specifier, the
4844 // lexical context will be different from the semantic context.
4845 NewVD->setLexicalDeclContext(CurContext);
4846
4847 if (D.getDeclSpec().isThreadSpecified()) {
4848 if (NewVD->hasLocalStorage())
4849 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4850 else if (!Context.getTargetInfo().isTLSSupported())
4851 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4852 else
4853 NewVD->setThreadSpecified(true);
4854 }
4855
4856 if (D.getDeclSpec().isModulePrivateSpecified()) {
4857 if (isExplicitSpecialization)
4858 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4859 << 2
4860 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4861 else if (NewVD->hasLocalStorage())
4862 Diag(NewVD->getLocation(), diag::err_module_private_local)
4863 << 0 << NewVD->getDeclName()
4864 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4865 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4866 else
4867 NewVD->setModulePrivate();
4868 }
4869
4870 // Handle attributes prior to checking for duplicates in MergeVarDecl
4871 ProcessDeclAttributes(S, NewVD, D);
4872
4873 if (NewVD->hasAttrs())
4874 CheckAlignasUnderalignment(NewVD);
4875
4876 if (getLangOpts().CUDA) {
4877 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
4878 // storage [duration]."
4879 if (SC == SC_None && S->getFnParent() != 0 &&
4880 (NewVD->hasAttr<CUDASharedAttr>() ||
4881 NewVD->hasAttr<CUDAConstantAttr>())) {
4882 NewVD->setStorageClass(SC_Static);
4883 NewVD->setStorageClassAsWritten(SC_Static);
4884 }
4885 }
4886
4887 // In auto-retain/release, infer strong retension for variables of
4888 // retainable type.
4889 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4890 NewVD->setInvalidDecl();
4891
4892 // Handle GNU asm-label extension (encoded as an attribute).
4893 if (Expr *E = (Expr*)D.getAsmLabel()) {
4894 // The parser guarantees this is a string.
4895 StringLiteral *SE = cast<StringLiteral>(E);
4896 StringRef Label = SE->getString();
4897 if (S->getFnParent() != 0) {
4898 switch (SC) {
4899 case SC_None:
4900 case SC_Auto:
4901 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4902 break;
4903 case SC_Register:
4904 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4905 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4906 break;
4907 case SC_Static:
4908 case SC_Extern:
4909 case SC_PrivateExtern:
4910 case SC_OpenCLWorkGroupLocal:
4911 break;
4912 }
4913 }
4914
4915 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4916 Context, Label));
4917 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4918 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4919 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4920 if (I != ExtnameUndeclaredIdentifiers.end()) {
4921 NewVD->addAttr(I->second);
4922 ExtnameUndeclaredIdentifiers.erase(I);
4923 }
4924 }
4925
4926 // Diagnose shadowed variables before filtering for scope.
4927 if (!D.getCXXScopeSpec().isSet())
4928 CheckShadow(S, NewVD, Previous);
4929
4930 // Don't consider existing declarations that are in a different
4931 // scope and are out-of-semantic-context declarations (if the new
4932 // declaration has linkage).
4933 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewVD),
4934 isExplicitSpecialization);
4935
4936 if (!getLangOpts().CPlusPlus) {
4937 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4938 } else {
4939 // Merge the decl with the existing one if appropriate.
4940 if (!Previous.empty()) {
4941 if (Previous.isSingleResult() &&
4942 isa<FieldDecl>(Previous.getFoundDecl()) &&
4943 D.getCXXScopeSpec().isSet()) {
4944 // The user tried to define a non-static data member
4945 // out-of-line (C++ [dcl.meaning]p1).
4946 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4947 << D.getCXXScopeSpec().getRange();
4948 Previous.clear();
4949 NewVD->setInvalidDecl();
4950 }
4951 } else if (D.getCXXScopeSpec().isSet()) {
4952 // No previous declaration in the qualifying scope.
4953 Diag(D.getIdentifierLoc(), diag::err_no_member)
4954 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4955 << D.getCXXScopeSpec().getRange();
4956 NewVD->setInvalidDecl();
4957 }
4958
4959 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4960
4961 // This is an explicit specialization of a static data member. Check it.
4962 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4963 CheckMemberSpecialization(NewVD, Previous))
4964 NewVD->setInvalidDecl();
4965 }
4966
4967 ProcessPragmaWeak(S, NewVD);
4968 checkAttributesAfterMerging(*this, *NewVD);
4969
4970 // If this is a locally-scoped extern C variable, update the map of
4971 // such variables.
4972 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4973 !NewVD->isInvalidDecl())
4974 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4975
4976 return NewVD;
4977 }
4978
4979 /// \brief Diagnose variable or built-in function shadowing. Implements
4980 /// -Wshadow.
4981 ///
4982 /// This method is called whenever a VarDecl is added to a "useful"
4983 /// scope.
4984 ///
4985 /// \param S the scope in which the shadowing name is being declared
4986 /// \param R the lookup of the name
4987 ///
CheckShadow(Scope * S,VarDecl * D,const LookupResult & R)4988 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4989 // Return if warning is ignored.
4990 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4991 DiagnosticsEngine::Ignored)
4992 return;
4993
4994 // Don't diagnose declarations at file scope.
4995 if (D->hasGlobalStorage())
4996 return;
4997
4998 DeclContext *NewDC = D->getDeclContext();
4999
5000 // Only diagnose if we're shadowing an unambiguous field or variable.
5001 if (R.getResultKind() != LookupResult::Found)
5002 return;
5003
5004 NamedDecl* ShadowedDecl = R.getFoundDecl();
5005 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5006 return;
5007
5008 // Fields are not shadowed by variables in C++ static methods.
5009 if (isa<FieldDecl>(ShadowedDecl))
5010 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5011 if (MD->isStatic())
5012 return;
5013
5014 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5015 if (shadowedVar->isExternC()) {
5016 // For shadowing external vars, make sure that we point to the global
5017 // declaration, not a locally scoped extern declaration.
5018 for (VarDecl::redecl_iterator
5019 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5020 I != E; ++I)
5021 if (I->isFileVarDecl()) {
5022 ShadowedDecl = *I;
5023 break;
5024 }
5025 }
5026
5027 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5028
5029 // Only warn about certain kinds of shadowing for class members.
5030 if (NewDC && NewDC->isRecord()) {
5031 // In particular, don't warn about shadowing non-class members.
5032 if (!OldDC->isRecord())
5033 return;
5034
5035 // TODO: should we warn about static data members shadowing
5036 // static data members from base classes?
5037
5038 // TODO: don't diagnose for inaccessible shadowed members.
5039 // This is hard to do perfectly because we might friend the
5040 // shadowing context, but that's just a false negative.
5041 }
5042
5043 // Determine what kind of declaration we're shadowing.
5044 unsigned Kind;
5045 if (isa<RecordDecl>(OldDC)) {
5046 if (isa<FieldDecl>(ShadowedDecl))
5047 Kind = 3; // field
5048 else
5049 Kind = 2; // static data member
5050 } else if (OldDC->isFileContext())
5051 Kind = 1; // global
5052 else
5053 Kind = 0; // local
5054
5055 DeclarationName Name = R.getLookupName();
5056
5057 // Emit warning and note.
5058 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5059 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5060 }
5061
5062 /// \brief Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)5063 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5064 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5065 DiagnosticsEngine::Ignored)
5066 return;
5067
5068 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5069 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5070 LookupName(R, S);
5071 CheckShadow(S, D, R);
5072 }
5073
5074 template<typename T>
mayConflictWithNonVisibleExternC(const T * ND)5075 static bool mayConflictWithNonVisibleExternC(const T *ND) {
5076 const DeclContext *DC = ND->getDeclContext();
5077 if (DC->getRedeclContext()->isTranslationUnit())
5078 return true;
5079
5080 // We know that is the first decl we see, other than function local
5081 // extern C ones. If this is C++ and the decl is not in a extern C context
5082 // it cannot have C language linkage. Avoid calling isExternC in that case.
5083 // We need to this because of code like
5084 //
5085 // namespace { struct bar {}; }
5086 // auto foo = bar();
5087 //
5088 // This code runs before the init of foo is set, and therefore before
5089 // the type of foo is known. Not knowing the type we cannot know its linkage
5090 // unless it is in an extern C block.
5091 if (!DC->isExternCContext()) {
5092 const ASTContext &Context = ND->getASTContext();
5093 if (Context.getLangOpts().CPlusPlus)
5094 return false;
5095 }
5096
5097 return ND->isExternC();
5098 }
5099
5100 /// \brief Perform semantic checking on a newly-created variable
5101 /// declaration.
5102 ///
5103 /// This routine performs all of the type-checking required for a
5104 /// variable declaration once it has been built. It is used both to
5105 /// check variables after they have been parsed and their declarators
5106 /// have been translated into a declaration, and to check variables
5107 /// that have been instantiated from a template.
5108 ///
5109 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5110 ///
5111 /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)5112 bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
5113 LookupResult &Previous) {
5114 // If the decl is already known invalid, don't check it.
5115 if (NewVD->isInvalidDecl())
5116 return false;
5117
5118 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5119 QualType T = TInfo->getType();
5120
5121 if (T->isObjCObjectType()) {
5122 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5123 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5124 T = Context.getObjCObjectPointerType(T);
5125 NewVD->setType(T);
5126 }
5127
5128 // Emit an error if an address space was applied to decl with local storage.
5129 // This includes arrays of objects with address space qualifiers, but not
5130 // automatic variables that point to other address spaces.
5131 // ISO/IEC TR 18037 S5.1.2
5132 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5133 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5134 NewVD->setInvalidDecl();
5135 return false;
5136 }
5137
5138 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5139 // scope.
5140 if ((getLangOpts().OpenCLVersion >= 120)
5141 && NewVD->isStaticLocal()) {
5142 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5143 NewVD->setInvalidDecl();
5144 return false;
5145 }
5146
5147 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5148 && !NewVD->hasAttr<BlocksAttr>()) {
5149 if (getLangOpts().getGC() != LangOptions::NonGC)
5150 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5151 else {
5152 assert(!getLangOpts().ObjCAutoRefCount);
5153 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5154 }
5155 }
5156
5157 bool isVM = T->isVariablyModifiedType();
5158 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5159 NewVD->hasAttr<BlocksAttr>())
5160 getCurFunction()->setHasBranchProtectedScope();
5161
5162 if ((isVM && NewVD->hasLinkage()) ||
5163 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5164 bool SizeIsNegative;
5165 llvm::APSInt Oversized;
5166 TypeSourceInfo *FixedTInfo =
5167 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5168 SizeIsNegative, Oversized);
5169 if (FixedTInfo == 0 && T->isVariableArrayType()) {
5170 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5171 // FIXME: This won't give the correct result for
5172 // int a[10][n];
5173 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5174
5175 if (NewVD->isFileVarDecl())
5176 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5177 << SizeRange;
5178 else if (NewVD->getStorageClass() == SC_Static)
5179 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5180 << SizeRange;
5181 else
5182 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5183 << SizeRange;
5184 NewVD->setInvalidDecl();
5185 return false;
5186 }
5187
5188 if (FixedTInfo == 0) {
5189 if (NewVD->isFileVarDecl())
5190 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5191 else
5192 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5193 NewVD->setInvalidDecl();
5194 return false;
5195 }
5196
5197 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5198 NewVD->setType(FixedTInfo->getType());
5199 NewVD->setTypeSourceInfo(FixedTInfo);
5200 }
5201
5202 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewVD)) {
5203 // Since we did not find anything by this name, look for a non-visible
5204 // extern "C" declaration with the same name.
5205 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5206 = findLocallyScopedExternCDecl(NewVD->getDeclName());
5207 if (Pos != LocallyScopedExternCDecls.end())
5208 Previous.addDecl(Pos->second);
5209 }
5210
5211 // Filter out any non-conflicting previous declarations.
5212 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5213
5214 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
5215 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5216 << T;
5217 NewVD->setInvalidDecl();
5218 return false;
5219 }
5220
5221 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5222 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5223 NewVD->setInvalidDecl();
5224 return false;
5225 }
5226
5227 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5228 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5229 NewVD->setInvalidDecl();
5230 return false;
5231 }
5232
5233 if (NewVD->isConstexpr() && !T->isDependentType() &&
5234 RequireLiteralType(NewVD->getLocation(), T,
5235 diag::err_constexpr_var_non_literal)) {
5236 NewVD->setInvalidDecl();
5237 return false;
5238 }
5239
5240 if (!Previous.empty()) {
5241 MergeVarDecl(NewVD, Previous);
5242 return true;
5243 }
5244 return false;
5245 }
5246
5247 /// \brief Data used with FindOverriddenMethod
5248 struct FindOverriddenMethodData {
5249 Sema *S;
5250 CXXMethodDecl *Method;
5251 };
5252
5253 /// \brief Member lookup function that determines whether a given C++
5254 /// method overrides a method in a base class, to be used with
5255 /// CXXRecordDecl::lookupInBases().
FindOverriddenMethod(const CXXBaseSpecifier * Specifier,CXXBasePath & Path,void * UserData)5256 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5257 CXXBasePath &Path,
5258 void *UserData) {
5259 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5260
5261 FindOverriddenMethodData *Data
5262 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5263
5264 DeclarationName Name = Data->Method->getDeclName();
5265
5266 // FIXME: Do we care about other names here too?
5267 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5268 // We really want to find the base class destructor here.
5269 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5270 CanQualType CT = Data->S->Context.getCanonicalType(T);
5271
5272 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5273 }
5274
5275 for (Path.Decls = BaseRecord->lookup(Name);
5276 !Path.Decls.empty();
5277 Path.Decls = Path.Decls.slice(1)) {
5278 NamedDecl *D = Path.Decls.front();
5279 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5280 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5281 return true;
5282 }
5283 }
5284
5285 return false;
5286 }
5287
5288 namespace {
5289 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5290 }
5291 /// \brief Report an error regarding overriding, along with any relevant
5292 /// overriden methods.
5293 ///
5294 /// \param DiagID the primary error to report.
5295 /// \param MD the overriding method.
5296 /// \param OEK which overrides to include as notes.
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,OverrideErrorKind OEK=OEK_All)5297 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5298 OverrideErrorKind OEK = OEK_All) {
5299 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5300 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5301 E = MD->end_overridden_methods();
5302 I != E; ++I) {
5303 // This check (& the OEK parameter) could be replaced by a predicate, but
5304 // without lambdas that would be overkill. This is still nicer than writing
5305 // out the diag loop 3 times.
5306 if ((OEK == OEK_All) ||
5307 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5308 (OEK == OEK_Deleted && (*I)->isDeleted()))
5309 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5310 }
5311 }
5312
5313 /// AddOverriddenMethods - See if a method overrides any in the base classes,
5314 /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)5315 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5316 // Look for virtual methods in base classes that this method might override.
5317 CXXBasePaths Paths;
5318 FindOverriddenMethodData Data;
5319 Data.Method = MD;
5320 Data.S = this;
5321 bool hasDeletedOverridenMethods = false;
5322 bool hasNonDeletedOverridenMethods = false;
5323 bool AddedAny = false;
5324 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5325 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5326 E = Paths.found_decls_end(); I != E; ++I) {
5327 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5328 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5329 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5330 !CheckOverridingFunctionAttributes(MD, OldMD) &&
5331 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5332 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5333 hasDeletedOverridenMethods |= OldMD->isDeleted();
5334 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5335 AddedAny = true;
5336 }
5337 }
5338 }
5339 }
5340
5341 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5342 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5343 }
5344 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5345 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5346 }
5347
5348 return AddedAny;
5349 }
5350
5351 namespace {
5352 // Struct for holding all of the extra arguments needed by
5353 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5354 struct ActOnFDArgs {
5355 Scope *S;
5356 Declarator &D;
5357 MultiTemplateParamsArg TemplateParamLists;
5358 bool AddToScope;
5359 };
5360 }
5361
5362 namespace {
5363
5364 // Callback to only accept typo corrections that have a non-zero edit distance.
5365 // Also only accept corrections that have the same parent decl.
5366 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5367 public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)5368 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5369 CXXRecordDecl *Parent)
5370 : Context(Context), OriginalFD(TypoFD),
5371 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5372
ValidateCandidate(const TypoCorrection & candidate)5373 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5374 if (candidate.getEditDistance() == 0)
5375 return false;
5376
5377 SmallVector<unsigned, 1> MismatchedParams;
5378 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5379 CDeclEnd = candidate.end();
5380 CDecl != CDeclEnd; ++CDecl) {
5381 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5382
5383 if (FD && !FD->hasBody() &&
5384 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5386 CXXRecordDecl *Parent = MD->getParent();
5387 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5388 return true;
5389 } else if (!ExpectedParent) {
5390 return true;
5391 }
5392 }
5393 }
5394
5395 return false;
5396 }
5397
5398 private:
5399 ASTContext &Context;
5400 FunctionDecl *OriginalFD;
5401 CXXRecordDecl *ExpectedParent;
5402 };
5403
5404 }
5405
5406 /// \brief Generate diagnostics for an invalid function redeclaration.
5407 ///
5408 /// This routine handles generating the diagnostic messages for an invalid
5409 /// function redeclaration, including finding possible similar declarations
5410 /// or performing typo correction if there are no previous declarations with
5411 /// the same name.
5412 ///
5413 /// Returns a NamedDecl iff typo correction was performed and substituting in
5414 /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs)5415 static NamedDecl* DiagnoseInvalidRedeclaration(
5416 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
5417 ActOnFDArgs &ExtraArgs) {
5418 NamedDecl *Result = NULL;
5419 DeclarationName Name = NewFD->getDeclName();
5420 DeclContext *NewDC = NewFD->getDeclContext();
5421 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
5422 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5423 SmallVector<unsigned, 1> MismatchedParams;
5424 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
5425 TypoCorrection Correction;
5426 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
5427 ExtraArgs.D.getDeclSpec().isFriendSpecified());
5428 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
5429 : diag::err_member_def_does_not_match;
5430
5431 NewFD->setInvalidDecl();
5432 SemaRef.LookupQualifiedName(Prev, NewDC);
5433 assert(!Prev.isAmbiguous() &&
5434 "Cannot have an ambiguity in previous-declaration lookup");
5435 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5436 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
5437 MD ? MD->getParent() : 0);
5438 if (!Prev.empty()) {
5439 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
5440 Func != FuncEnd; ++Func) {
5441 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
5442 if (FD &&
5443 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
5444 // Add 1 to the index so that 0 can mean the mismatch didn't
5445 // involve a parameter
5446 unsigned ParamNum =
5447 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
5448 NearMatches.push_back(std::make_pair(FD, ParamNum));
5449 }
5450 }
5451 // If the qualified name lookup yielded nothing, try typo correction
5452 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
5453 Prev.getLookupKind(), 0, 0,
5454 Validator, NewDC))) {
5455 // Trap errors.
5456 Sema::SFINAETrap Trap(SemaRef);
5457
5458 // Set up everything for the call to ActOnFunctionDeclarator
5459 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
5460 ExtraArgs.D.getIdentifierLoc());
5461 Previous.clear();
5462 Previous.setLookupName(Correction.getCorrection());
5463 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
5464 CDeclEnd = Correction.end();
5465 CDecl != CDeclEnd; ++CDecl) {
5466 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5467 if (FD && !FD->hasBody() &&
5468 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
5469 Previous.addDecl(FD);
5470 }
5471 }
5472 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
5473 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
5474 // pieces need to verify the typo-corrected C++ declaraction and hopefully
5475 // eliminate the need for the parameter pack ExtraArgs.
5476 Result = SemaRef.ActOnFunctionDeclarator(
5477 ExtraArgs.S, ExtraArgs.D,
5478 Correction.getCorrectionDecl()->getDeclContext(),
5479 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
5480 ExtraArgs.AddToScope);
5481 if (Trap.hasErrorOccurred()) {
5482 // Pretend the typo correction never occurred
5483 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
5484 ExtraArgs.D.getIdentifierLoc());
5485 ExtraArgs.D.setRedeclaration(wasRedeclaration);
5486 Previous.clear();
5487 Previous.setLookupName(Name);
5488 Result = NULL;
5489 } else {
5490 for (LookupResult::iterator Func = Previous.begin(),
5491 FuncEnd = Previous.end();
5492 Func != FuncEnd; ++Func) {
5493 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
5494 NearMatches.push_back(std::make_pair(FD, 0));
5495 }
5496 }
5497 if (NearMatches.empty()) {
5498 // Ignore the correction if it didn't yield any close FunctionDecl matches
5499 Correction = TypoCorrection();
5500 } else {
5501 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
5502 : diag::err_member_def_does_not_match_suggest;
5503 }
5504 }
5505
5506 if (Correction) {
5507 // FIXME: use Correction.getCorrectionRange() instead of computing the range
5508 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
5509 // turn causes the correction to fully qualify the name. If we fix
5510 // CorrectTypo to minimally qualify then this change should be good.
5511 SourceRange FixItLoc(NewFD->getLocation());
5512 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
5513 if (Correction.getCorrectionSpecifier() && SS.isValid())
5514 FixItLoc.setBegin(SS.getBeginLoc());
5515 SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
5516 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
5517 << FixItHint::CreateReplacement(
5518 FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
5519 } else {
5520 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
5521 << Name << NewDC << NewFD->getLocation();
5522 }
5523
5524 bool NewFDisConst = false;
5525 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
5526 NewFDisConst = NewMD->isConst();
5527
5528 for (SmallVector<std::pair<FunctionDecl *, unsigned>, 1>::iterator
5529 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
5530 NearMatch != NearMatchEnd; ++NearMatch) {
5531 FunctionDecl *FD = NearMatch->first;
5532 bool FDisConst = false;
5533 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
5534 FDisConst = MD->isConst();
5535
5536 if (unsigned Idx = NearMatch->second) {
5537 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
5538 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
5539 if (Loc.isInvalid()) Loc = FD->getLocation();
5540 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
5541 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
5542 } else if (Correction) {
5543 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
5544 << Correction.getQuoted(SemaRef.getLangOpts());
5545 } else if (FDisConst != NewFDisConst) {
5546 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
5547 << NewFDisConst << FD->getSourceRange().getEnd();
5548 } else
5549 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
5550 }
5551 return Result;
5552 }
5553
getFunctionStorageClass(Sema & SemaRef,Declarator & D)5554 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
5555 Declarator &D) {
5556 switch (D.getDeclSpec().getStorageClassSpec()) {
5557 default: llvm_unreachable("Unknown storage class!");
5558 case DeclSpec::SCS_auto:
5559 case DeclSpec::SCS_register:
5560 case DeclSpec::SCS_mutable:
5561 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5562 diag::err_typecheck_sclass_func);
5563 D.setInvalidType();
5564 break;
5565 case DeclSpec::SCS_unspecified: break;
5566 case DeclSpec::SCS_extern: return SC_Extern;
5567 case DeclSpec::SCS_static: {
5568 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5569 // C99 6.7.1p5:
5570 // The declaration of an identifier for a function that has
5571 // block scope shall have no explicit storage-class specifier
5572 // other than extern
5573 // See also (C++ [dcl.stc]p4).
5574 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5575 diag::err_static_block_func);
5576 break;
5577 } else
5578 return SC_Static;
5579 }
5580 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5581 }
5582
5583 // No explicit storage class has already been returned
5584 return SC_None;
5585 }
5586
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,FunctionDecl::StorageClass SC,bool & IsVirtualOkay)5587 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
5588 DeclContext *DC, QualType &R,
5589 TypeSourceInfo *TInfo,
5590 FunctionDecl::StorageClass SC,
5591 bool &IsVirtualOkay) {
5592 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
5593 DeclarationName Name = NameInfo.getName();
5594
5595 FunctionDecl *NewFD = 0;
5596 bool isInline = D.getDeclSpec().isInlineSpecified();
5597 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
5598 FunctionDecl::StorageClass SCAsWritten
5599 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
5600
5601 if (!SemaRef.getLangOpts().CPlusPlus) {
5602 // Determine whether the function was written with a
5603 // prototype. This true when:
5604 // - there is a prototype in the declarator, or
5605 // - the type R of the function is some kind of typedef or other reference
5606 // to a type name (which eventually refers to a function type).
5607 bool HasPrototype =
5608 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
5609 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
5610
5611 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
5612 D.getLocStart(), NameInfo, R,
5613 TInfo, SC, SCAsWritten, isInline,
5614 HasPrototype);
5615 if (D.isInvalidType())
5616 NewFD->setInvalidDecl();
5617
5618 // Set the lexical context.
5619 NewFD->setLexicalDeclContext(SemaRef.CurContext);
5620
5621 return NewFD;
5622 }
5623
5624 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5625 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5626
5627 // Check that the return type is not an abstract class type.
5628 // For record types, this is done by the AbstractClassUsageDiagnoser once
5629 // the class has been completely parsed.
5630 if (!DC->isRecord() &&
5631 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
5632 R->getAs<FunctionType>()->getResultType(),
5633 diag::err_abstract_type_in_decl,
5634 SemaRef.AbstractReturnType))
5635 D.setInvalidType();
5636
5637 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
5638 // This is a C++ constructor declaration.
5639 assert(DC->isRecord() &&
5640 "Constructors can only be declared in a member context");
5641
5642 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
5643 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5644 D.getLocStart(), NameInfo,
5645 R, TInfo, isExplicit, isInline,
5646 /*isImplicitlyDeclared=*/false,
5647 isConstexpr);
5648
5649 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5650 // This is a C++ destructor declaration.
5651 if (DC->isRecord()) {
5652 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
5653 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
5654 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
5655 SemaRef.Context, Record,
5656 D.getLocStart(),
5657 NameInfo, R, TInfo, isInline,
5658 /*isImplicitlyDeclared=*/false);
5659
5660 // If the class is complete, then we now create the implicit exception
5661 // specification. If the class is incomplete or dependent, we can't do
5662 // it yet.
5663 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
5664 Record->getDefinition() && !Record->isBeingDefined() &&
5665 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
5666 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
5667 }
5668
5669 IsVirtualOkay = true;
5670 return NewDD;
5671
5672 } else {
5673 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
5674 D.setInvalidType();
5675
5676 // Create a FunctionDecl to satisfy the function definition parsing
5677 // code path.
5678 return FunctionDecl::Create(SemaRef.Context, DC,
5679 D.getLocStart(),
5680 D.getIdentifierLoc(), Name, R, TInfo,
5681 SC, SCAsWritten, isInline,
5682 /*hasPrototype=*/true, isConstexpr);
5683 }
5684
5685 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
5686 if (!DC->isRecord()) {
5687 SemaRef.Diag(D.getIdentifierLoc(),
5688 diag::err_conv_function_not_member);
5689 return 0;
5690 }
5691
5692 SemaRef.CheckConversionDeclarator(D, R, SC);
5693 IsVirtualOkay = true;
5694 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5695 D.getLocStart(), NameInfo,
5696 R, TInfo, isInline, isExplicit,
5697 isConstexpr, SourceLocation());
5698
5699 } else if (DC->isRecord()) {
5700 // If the name of the function is the same as the name of the record,
5701 // then this must be an invalid constructor that has a return type.
5702 // (The parser checks for a return type and makes the declarator a
5703 // constructor if it has no return type).
5704 if (Name.getAsIdentifierInfo() &&
5705 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5706 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5707 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5708 << SourceRange(D.getIdentifierLoc());
5709 return 0;
5710 }
5711
5712 bool isStatic = SC == SC_Static;
5713
5714 // [class.free]p1:
5715 // Any allocation function for a class T is a static member
5716 // (even if not explicitly declared static).
5717 if (Name.getCXXOverloadedOperator() == OO_New ||
5718 Name.getCXXOverloadedOperator() == OO_Array_New)
5719 isStatic = true;
5720
5721 // [class.free]p6 Any deallocation function for a class X is a static member
5722 // (even if not explicitly declared static).
5723 if (Name.getCXXOverloadedOperator() == OO_Delete ||
5724 Name.getCXXOverloadedOperator() == OO_Array_Delete)
5725 isStatic = true;
5726
5727 IsVirtualOkay = !isStatic;
5728
5729 // This is a C++ method declaration.
5730 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5731 D.getLocStart(), NameInfo, R,
5732 TInfo, isStatic, SCAsWritten, isInline,
5733 isConstexpr, SourceLocation());
5734
5735 } else {
5736 // Determine whether the function was written with a
5737 // prototype. This true when:
5738 // - we're in C++ (where every function has a prototype),
5739 return FunctionDecl::Create(SemaRef.Context, DC,
5740 D.getLocStart(),
5741 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5742 true/*HasPrototype*/, isConstexpr);
5743 }
5744 }
5745
checkVoidParamDecl(ParmVarDecl * Param)5746 void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
5747 // In C++, the empty parameter-type-list must be spelled "void"; a
5748 // typedef of void is not permitted.
5749 if (getLangOpts().CPlusPlus &&
5750 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5751 bool IsTypeAlias = false;
5752 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5753 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5754 else if (const TemplateSpecializationType *TST =
5755 Param->getType()->getAs<TemplateSpecializationType>())
5756 IsTypeAlias = TST->isTypeAlias();
5757 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5758 << IsTypeAlias;
5759 }
5760 }
5761
5762 NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope)5763 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5764 TypeSourceInfo *TInfo, LookupResult &Previous,
5765 MultiTemplateParamsArg TemplateParamLists,
5766 bool &AddToScope) {
5767 QualType R = TInfo->getType();
5768
5769 assert(R.getTypePtr()->isFunctionType());
5770
5771 // TODO: consider using NameInfo for diagnostic.
5772 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5773 DeclarationName Name = NameInfo.getName();
5774 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
5775
5776 if (D.getDeclSpec().isThreadSpecified())
5777 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5778
5779 // Do not allow returning a objc interface by-value.
5780 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
5781 Diag(D.getIdentifierLoc(),
5782 diag::err_object_cannot_be_passed_returned_by_value) << 0
5783 << R->getAs<FunctionType>()->getResultType()
5784 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
5785
5786 QualType T = R->getAs<FunctionType>()->getResultType();
5787 T = Context.getObjCObjectPointerType(T);
5788 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5789 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5790 R = Context.getFunctionType(T,
5791 ArrayRef<QualType>(FPT->arg_type_begin(),
5792 FPT->getNumArgs()),
5793 EPI);
5794 }
5795 else if (isa<FunctionNoProtoType>(R))
5796 R = Context.getFunctionNoProtoType(T);
5797 }
5798
5799 bool isFriend = false;
5800 FunctionTemplateDecl *FunctionTemplate = 0;
5801 bool isExplicitSpecialization = false;
5802 bool isFunctionTemplateSpecialization = false;
5803
5804 bool isDependentClassScopeExplicitSpecialization = false;
5805 bool HasExplicitTemplateArgs = false;
5806 TemplateArgumentListInfo TemplateArgs;
5807
5808 bool isVirtualOkay = false;
5809
5810 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5811 isVirtualOkay);
5812 if (!NewFD) return 0;
5813
5814 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5815 NewFD->setTopLevelDeclInObjCContainer();
5816
5817 if (getLangOpts().CPlusPlus) {
5818 bool isInline = D.getDeclSpec().isInlineSpecified();
5819 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5820 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5821 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5822 isFriend = D.getDeclSpec().isFriendSpecified();
5823 if (isFriend && !isInline && D.isFunctionDefinition()) {
5824 // C++ [class.friend]p5
5825 // A function can be defined in a friend declaration of a
5826 // class . . . . Such a function is implicitly inline.
5827 NewFD->setImplicitlyInline();
5828 }
5829
5830 // If this is a method defined in an __interface, and is not a constructor
5831 // or an overloaded operator, then set the pure flag (isVirtual will already
5832 // return true).
5833 if (const CXXRecordDecl *Parent =
5834 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
5835 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
5836 NewFD->setPure(true);
5837 }
5838
5839 SetNestedNameSpecifier(NewFD, D);
5840 isExplicitSpecialization = false;
5841 isFunctionTemplateSpecialization = false;
5842 if (D.isInvalidType())
5843 NewFD->setInvalidDecl();
5844
5845 // Set the lexical context. If the declarator has a C++
5846 // scope specifier, or is the object of a friend declaration, the
5847 // lexical context will be different from the semantic context.
5848 NewFD->setLexicalDeclContext(CurContext);
5849
5850 // Match up the template parameter lists with the scope specifier, then
5851 // determine whether we have a template or a template specialization.
5852 bool Invalid = false;
5853 if (TemplateParameterList *TemplateParams
5854 = MatchTemplateParametersToScopeSpecifier(
5855 D.getDeclSpec().getLocStart(),
5856 D.getIdentifierLoc(),
5857 D.getCXXScopeSpec(),
5858 TemplateParamLists.data(),
5859 TemplateParamLists.size(),
5860 isFriend,
5861 isExplicitSpecialization,
5862 Invalid)) {
5863 if (TemplateParams->size() > 0) {
5864 // This is a function template
5865
5866 // Check that we can declare a template here.
5867 if (CheckTemplateDeclScope(S, TemplateParams))
5868 return 0;
5869
5870 // A destructor cannot be a template.
5871 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5872 Diag(NewFD->getLocation(), diag::err_destructor_template);
5873 return 0;
5874 }
5875
5876 // If we're adding a template to a dependent context, we may need to
5877 // rebuilding some of the types used within the template parameter list,
5878 // now that we know what the current instantiation is.
5879 if (DC->isDependentContext()) {
5880 ContextRAII SavedContext(*this, DC);
5881 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5882 Invalid = true;
5883 }
5884
5885
5886 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5887 NewFD->getLocation(),
5888 Name, TemplateParams,
5889 NewFD);
5890 FunctionTemplate->setLexicalDeclContext(CurContext);
5891 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5892
5893 // For source fidelity, store the other template param lists.
5894 if (TemplateParamLists.size() > 1) {
5895 NewFD->setTemplateParameterListsInfo(Context,
5896 TemplateParamLists.size() - 1,
5897 TemplateParamLists.data());
5898 }
5899 } else {
5900 // This is a function template specialization.
5901 isFunctionTemplateSpecialization = true;
5902 // For source fidelity, store all the template param lists.
5903 NewFD->setTemplateParameterListsInfo(Context,
5904 TemplateParamLists.size(),
5905 TemplateParamLists.data());
5906
5907 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5908 if (isFriend) {
5909 // We want to remove the "template<>", found here.
5910 SourceRange RemoveRange = TemplateParams->getSourceRange();
5911
5912 // If we remove the template<> and the name is not a
5913 // template-id, we're actually silently creating a problem:
5914 // the friend declaration will refer to an untemplated decl,
5915 // and clearly the user wants a template specialization. So
5916 // we need to insert '<>' after the name.
5917 SourceLocation InsertLoc;
5918 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5919 InsertLoc = D.getName().getSourceRange().getEnd();
5920 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5921 }
5922
5923 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5924 << Name << RemoveRange
5925 << FixItHint::CreateRemoval(RemoveRange)
5926 << FixItHint::CreateInsertion(InsertLoc, "<>");
5927 }
5928 }
5929 }
5930 else {
5931 // All template param lists were matched against the scope specifier:
5932 // this is NOT (an explicit specialization of) a template.
5933 if (TemplateParamLists.size() > 0)
5934 // For source fidelity, store all the template param lists.
5935 NewFD->setTemplateParameterListsInfo(Context,
5936 TemplateParamLists.size(),
5937 TemplateParamLists.data());
5938 }
5939
5940 if (Invalid) {
5941 NewFD->setInvalidDecl();
5942 if (FunctionTemplate)
5943 FunctionTemplate->setInvalidDecl();
5944 }
5945
5946 // C++ [dcl.fct.spec]p5:
5947 // The virtual specifier shall only be used in declarations of
5948 // nonstatic class member functions that appear within a
5949 // member-specification of a class declaration; see 10.3.
5950 //
5951 if (isVirtual && !NewFD->isInvalidDecl()) {
5952 if (!isVirtualOkay) {
5953 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5954 diag::err_virtual_non_function);
5955 } else if (!CurContext->isRecord()) {
5956 // 'virtual' was specified outside of the class.
5957 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5958 diag::err_virtual_out_of_class)
5959 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5960 } else if (NewFD->getDescribedFunctionTemplate()) {
5961 // C++ [temp.mem]p3:
5962 // A member function template shall not be virtual.
5963 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5964 diag::err_virtual_member_function_template)
5965 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5966 } else {
5967 // Okay: Add virtual to the method.
5968 NewFD->setVirtualAsWritten(true);
5969 }
5970 }
5971
5972 // C++ [dcl.fct.spec]p3:
5973 // The inline specifier shall not appear on a block scope function
5974 // declaration.
5975 if (isInline && !NewFD->isInvalidDecl()) {
5976 if (CurContext->isFunctionOrMethod()) {
5977 // 'inline' is not allowed on block scope function declaration.
5978 Diag(D.getDeclSpec().getInlineSpecLoc(),
5979 diag::err_inline_declaration_block_scope) << Name
5980 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5981 }
5982 }
5983
5984 // C++ [dcl.fct.spec]p6:
5985 // The explicit specifier shall be used only in the declaration of a
5986 // constructor or conversion function within its class definition;
5987 // see 12.3.1 and 12.3.2.
5988 if (isExplicit && !NewFD->isInvalidDecl()) {
5989 if (!CurContext->isRecord()) {
5990 // 'explicit' was specified outside of the class.
5991 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5992 diag::err_explicit_out_of_class)
5993 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5994 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5995 !isa<CXXConversionDecl>(NewFD)) {
5996 // 'explicit' was specified on a function that wasn't a constructor
5997 // or conversion function.
5998 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5999 diag::err_explicit_non_ctor_or_conv_function)
6000 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6001 }
6002 }
6003
6004 if (isConstexpr) {
6005 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6006 // are implicitly inline.
6007 NewFD->setImplicitlyInline();
6008
6009 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6010 // be either constructors or to return a literal type. Therefore,
6011 // destructors cannot be declared constexpr.
6012 if (isa<CXXDestructorDecl>(NewFD))
6013 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6014 }
6015
6016 // If __module_private__ was specified, mark the function accordingly.
6017 if (D.getDeclSpec().isModulePrivateSpecified()) {
6018 if (isFunctionTemplateSpecialization) {
6019 SourceLocation ModulePrivateLoc
6020 = D.getDeclSpec().getModulePrivateSpecLoc();
6021 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6022 << 0
6023 << FixItHint::CreateRemoval(ModulePrivateLoc);
6024 } else {
6025 NewFD->setModulePrivate();
6026 if (FunctionTemplate)
6027 FunctionTemplate->setModulePrivate();
6028 }
6029 }
6030
6031 if (isFriend) {
6032 // For now, claim that the objects have no previous declaration.
6033 if (FunctionTemplate) {
6034 FunctionTemplate->setObjectOfFriendDecl(false);
6035 FunctionTemplate->setAccess(AS_public);
6036 }
6037 NewFD->setObjectOfFriendDecl(false);
6038 NewFD->setAccess(AS_public);
6039 }
6040
6041 // If a function is defined as defaulted or deleted, mark it as such now.
6042 switch (D.getFunctionDefinitionKind()) {
6043 case FDK_Declaration:
6044 case FDK_Definition:
6045 break;
6046
6047 case FDK_Defaulted:
6048 NewFD->setDefaulted();
6049 break;
6050
6051 case FDK_Deleted:
6052 NewFD->setDeletedAsWritten();
6053 break;
6054 }
6055
6056 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6057 D.isFunctionDefinition()) {
6058 // C++ [class.mfct]p2:
6059 // A member function may be defined (8.4) in its class definition, in
6060 // which case it is an inline member function (7.1.2)
6061 NewFD->setImplicitlyInline();
6062 }
6063
6064 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6065 !CurContext->isRecord()) {
6066 // C++ [class.static]p1:
6067 // A data or function member of a class may be declared static
6068 // in a class definition, in which case it is a static member of
6069 // the class.
6070
6071 // Complain about the 'static' specifier if it's on an out-of-line
6072 // member function definition.
6073 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6074 diag::err_static_out_of_line)
6075 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6076 }
6077
6078 // C++11 [except.spec]p15:
6079 // A deallocation function with no exception-specification is treated
6080 // as if it were specified with noexcept(true).
6081 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6082 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6083 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6084 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6085 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6086 EPI.ExceptionSpecType = EST_BasicNoexcept;
6087 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
6088 ArrayRef<QualType>(FPT->arg_type_begin(),
6089 FPT->getNumArgs()),
6090 EPI));
6091 }
6092 }
6093
6094 // Filter out previous declarations that don't match the scope.
6095 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewFD),
6096 isExplicitSpecialization ||
6097 isFunctionTemplateSpecialization);
6098
6099 // Handle GNU asm-label extension (encoded as an attribute).
6100 if (Expr *E = (Expr*) D.getAsmLabel()) {
6101 // The parser guarantees this is a string.
6102 StringLiteral *SE = cast<StringLiteral>(E);
6103 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6104 SE->getString()));
6105 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6106 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6107 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6108 if (I != ExtnameUndeclaredIdentifiers.end()) {
6109 NewFD->addAttr(I->second);
6110 ExtnameUndeclaredIdentifiers.erase(I);
6111 }
6112 }
6113
6114 // Copy the parameter declarations from the declarator D to the function
6115 // declaration NewFD, if they are available. First scavenge them into Params.
6116 SmallVector<ParmVarDecl*, 16> Params;
6117 if (D.isFunctionDeclarator()) {
6118 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6119
6120 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6121 // function that takes no arguments, not a function that takes a
6122 // single void argument.
6123 // We let through "const void" here because Sema::GetTypeForDeclarator
6124 // already checks for that case.
6125 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6126 FTI.ArgInfo[0].Param &&
6127 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
6128 // Empty arg list, don't push any params.
6129 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
6130 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
6131 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6132 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
6133 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6134 Param->setDeclContext(NewFD);
6135 Params.push_back(Param);
6136
6137 if (Param->isInvalidDecl())
6138 NewFD->setInvalidDecl();
6139 }
6140 }
6141
6142 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6143 // When we're declaring a function with a typedef, typeof, etc as in the
6144 // following example, we'll need to synthesize (unnamed)
6145 // parameters for use in the declaration.
6146 //
6147 // @code
6148 // typedef void fn(int);
6149 // fn f;
6150 // @endcode
6151
6152 // Synthesize a parameter for each argument type.
6153 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6154 AE = FT->arg_type_end(); AI != AE; ++AI) {
6155 ParmVarDecl *Param =
6156 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6157 Param->setScopeInfo(0, Params.size());
6158 Params.push_back(Param);
6159 }
6160 } else {
6161 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6162 "Should not need args for typedef of non-prototype fn");
6163 }
6164
6165 // Finally, we know we have the right number of parameters, install them.
6166 NewFD->setParams(Params);
6167
6168 // Find all anonymous symbols defined during the declaration of this function
6169 // and add to NewFD. This lets us track decls such 'enum Y' in:
6170 //
6171 // void f(enum Y {AA} x) {}
6172 //
6173 // which would otherwise incorrectly end up in the translation unit scope.
6174 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6175 DeclsInPrototypeScope.clear();
6176
6177 if (D.getDeclSpec().isNoreturnSpecified())
6178 NewFD->addAttr(
6179 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6180 Context));
6181
6182 // Process the non-inheritable attributes on this declaration.
6183 ProcessDeclAttributes(S, NewFD, D,
6184 /*NonInheritable=*/true, /*Inheritable=*/false);
6185
6186 // Functions returning a variably modified type violate C99 6.7.5.2p2
6187 // because all functions have linkage.
6188 if (!NewFD->isInvalidDecl() &&
6189 NewFD->getResultType()->isVariablyModifiedType()) {
6190 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6191 NewFD->setInvalidDecl();
6192 }
6193
6194 // Handle attributes.
6195 ProcessDeclAttributes(S, NewFD, D,
6196 /*NonInheritable=*/false, /*Inheritable=*/true);
6197
6198 QualType RetType = NewFD->getResultType();
6199 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6200 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6201 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6202 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6203 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6204 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
6205 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6206 Context));
6207 }
6208 }
6209
6210 if (!getLangOpts().CPlusPlus) {
6211 // Perform semantic checking on the function declaration.
6212 bool isExplicitSpecialization=false;
6213 if (!NewFD->isInvalidDecl()) {
6214 if (NewFD->isMain())
6215 CheckMain(NewFD, D.getDeclSpec());
6216 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6217 isExplicitSpecialization));
6218 }
6219 // Make graceful recovery from an invalid redeclaration.
6220 else if (!Previous.empty())
6221 D.setRedeclaration(true);
6222 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
6223 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
6224 "previous declaration set still overloaded");
6225 } else {
6226 // If the declarator is a template-id, translate the parser's template
6227 // argument list into our AST format.
6228 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6229 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6230 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6231 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
6232 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6233 TemplateId->NumArgs);
6234 translateTemplateArguments(TemplateArgsPtr,
6235 TemplateArgs);
6236
6237 HasExplicitTemplateArgs = true;
6238
6239 if (NewFD->isInvalidDecl()) {
6240 HasExplicitTemplateArgs = false;
6241 } else if (FunctionTemplate) {
6242 // Function template with explicit template arguments.
6243 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
6244 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
6245
6246 HasExplicitTemplateArgs = false;
6247 } else if (!isFunctionTemplateSpecialization &&
6248 !D.getDeclSpec().isFriendSpecified()) {
6249 // We have encountered something that the user meant to be a
6250 // specialization (because it has explicitly-specified template
6251 // arguments) but that was not introduced with a "template<>" (or had
6252 // too few of them).
6253 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
6254 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
6255 << FixItHint::CreateInsertion(
6256 D.getDeclSpec().getLocStart(),
6257 "template<> ");
6258 isFunctionTemplateSpecialization = true;
6259 } else {
6260 // "friend void foo<>(int);" is an implicit specialization decl.
6261 isFunctionTemplateSpecialization = true;
6262 }
6263 } else if (isFriend && isFunctionTemplateSpecialization) {
6264 // This combination is only possible in a recovery case; the user
6265 // wrote something like:
6266 // template <> friend void foo(int);
6267 // which we're recovering from as if the user had written:
6268 // friend void foo<>(int);
6269 // Go ahead and fake up a template id.
6270 HasExplicitTemplateArgs = true;
6271 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
6272 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
6273 }
6274
6275 // If it's a friend (and only if it's a friend), it's possible
6276 // that either the specialized function type or the specialized
6277 // template is dependent, and therefore matching will fail. In
6278 // this case, don't check the specialization yet.
6279 bool InstantiationDependent = false;
6280 if (isFunctionTemplateSpecialization && isFriend &&
6281 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
6282 TemplateSpecializationType::anyDependentTemplateArguments(
6283 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
6284 InstantiationDependent))) {
6285 assert(HasExplicitTemplateArgs &&
6286 "friend function specialization without template args");
6287 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
6288 Previous))
6289 NewFD->setInvalidDecl();
6290 } else if (isFunctionTemplateSpecialization) {
6291 if (CurContext->isDependentContext() && CurContext->isRecord()
6292 && !isFriend) {
6293 isDependentClassScopeExplicitSpecialization = true;
6294 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
6295 diag::ext_function_specialization_in_class :
6296 diag::err_function_specialization_in_class)
6297 << NewFD->getDeclName();
6298 } else if (CheckFunctionTemplateSpecialization(NewFD,
6299 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
6300 Previous))
6301 NewFD->setInvalidDecl();
6302
6303 // C++ [dcl.stc]p1:
6304 // A storage-class-specifier shall not be specified in an explicit
6305 // specialization (14.7.3)
6306 if (SC != SC_None) {
6307 if (SC != NewFD->getStorageClass())
6308 Diag(NewFD->getLocation(),
6309 diag::err_explicit_specialization_inconsistent_storage_class)
6310 << SC
6311 << FixItHint::CreateRemoval(
6312 D.getDeclSpec().getStorageClassSpecLoc());
6313
6314 else
6315 Diag(NewFD->getLocation(),
6316 diag::ext_explicit_specialization_storage_class)
6317 << FixItHint::CreateRemoval(
6318 D.getDeclSpec().getStorageClassSpecLoc());
6319 }
6320
6321 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
6322 if (CheckMemberSpecialization(NewFD, Previous))
6323 NewFD->setInvalidDecl();
6324 }
6325
6326 // Perform semantic checking on the function declaration.
6327 if (!isDependentClassScopeExplicitSpecialization) {
6328 if (NewFD->isInvalidDecl()) {
6329 // If this is a class member, mark the class invalid immediately.
6330 // This avoids some consistency errors later.
6331 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
6332 methodDecl->getParent()->setInvalidDecl();
6333 } else {
6334 if (NewFD->isMain())
6335 CheckMain(NewFD, D.getDeclSpec());
6336 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6337 isExplicitSpecialization));
6338 }
6339 }
6340
6341 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
6342 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
6343 "previous declaration set still overloaded");
6344
6345 NamedDecl *PrincipalDecl = (FunctionTemplate
6346 ? cast<NamedDecl>(FunctionTemplate)
6347 : NewFD);
6348
6349 if (isFriend && D.isRedeclaration()) {
6350 AccessSpecifier Access = AS_public;
6351 if (!NewFD->isInvalidDecl())
6352 Access = NewFD->getPreviousDecl()->getAccess();
6353
6354 NewFD->setAccess(Access);
6355 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
6356
6357 PrincipalDecl->setObjectOfFriendDecl(true);
6358 }
6359
6360 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
6361 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
6362 PrincipalDecl->setNonMemberOperator();
6363
6364 // If we have a function template, check the template parameter
6365 // list. This will check and merge default template arguments.
6366 if (FunctionTemplate) {
6367 FunctionTemplateDecl *PrevTemplate =
6368 FunctionTemplate->getPreviousDecl();
6369 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
6370 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
6371 D.getDeclSpec().isFriendSpecified()
6372 ? (D.isFunctionDefinition()
6373 ? TPC_FriendFunctionTemplateDefinition
6374 : TPC_FriendFunctionTemplate)
6375 : (D.getCXXScopeSpec().isSet() &&
6376 DC && DC->isRecord() &&
6377 DC->isDependentContext())
6378 ? TPC_ClassTemplateMember
6379 : TPC_FunctionTemplate);
6380 }
6381
6382 if (NewFD->isInvalidDecl()) {
6383 // Ignore all the rest of this.
6384 } else if (!D.isRedeclaration()) {
6385 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
6386 AddToScope };
6387 // Fake up an access specifier if it's supposed to be a class member.
6388 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
6389 NewFD->setAccess(AS_public);
6390
6391 // Qualified decls generally require a previous declaration.
6392 if (D.getCXXScopeSpec().isSet()) {
6393 // ...with the major exception of templated-scope or
6394 // dependent-scope friend declarations.
6395
6396 // TODO: we currently also suppress this check in dependent
6397 // contexts because (1) the parameter depth will be off when
6398 // matching friend templates and (2) we might actually be
6399 // selecting a friend based on a dependent factor. But there
6400 // are situations where these conditions don't apply and we
6401 // can actually do this check immediately.
6402 if (isFriend &&
6403 (TemplateParamLists.size() ||
6404 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
6405 CurContext->isDependentContext())) {
6406 // ignore these
6407 } else {
6408 // The user tried to provide an out-of-line definition for a
6409 // function that is a member of a class or namespace, but there
6410 // was no such member function declared (C++ [class.mfct]p2,
6411 // C++ [namespace.memdef]p2). For example:
6412 //
6413 // class X {
6414 // void f() const;
6415 // };
6416 //
6417 // void X::f() { } // ill-formed
6418 //
6419 // Complain about this problem, and attempt to suggest close
6420 // matches (e.g., those that differ only in cv-qualifiers and
6421 // whether the parameter types are references).
6422
6423 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
6424 NewFD,
6425 ExtraArgs)) {
6426 AddToScope = ExtraArgs.AddToScope;
6427 return Result;
6428 }
6429 }
6430
6431 // Unqualified local friend declarations are required to resolve
6432 // to something.
6433 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
6434 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
6435 NewFD,
6436 ExtraArgs)) {
6437 AddToScope = ExtraArgs.AddToScope;
6438 return Result;
6439 }
6440 }
6441
6442 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
6443 !isFriend && !isFunctionTemplateSpecialization &&
6444 !isExplicitSpecialization) {
6445 // An out-of-line member function declaration must also be a
6446 // definition (C++ [dcl.meaning]p1).
6447 // Note that this is not the case for explicit specializations of
6448 // function templates or member functions of class templates, per
6449 // C++ [temp.expl.spec]p2. We also allow these declarations as an
6450 // extension for compatibility with old SWIG code which likes to
6451 // generate them.
6452 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
6453 << D.getCXXScopeSpec().getRange();
6454 }
6455 }
6456
6457 ProcessPragmaWeak(S, NewFD);
6458 checkAttributesAfterMerging(*this, *NewFD);
6459
6460 AddKnownFunctionAttributes(NewFD);
6461
6462 if (NewFD->hasAttr<OverloadableAttr>() &&
6463 !NewFD->getType()->getAs<FunctionProtoType>()) {
6464 Diag(NewFD->getLocation(),
6465 diag::err_attribute_overloadable_no_prototype)
6466 << NewFD;
6467
6468 // Turn this into a variadic function with no parameters.
6469 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
6470 FunctionProtoType::ExtProtoInfo EPI;
6471 EPI.Variadic = true;
6472 EPI.ExtInfo = FT->getExtInfo();
6473
6474 QualType R = Context.getFunctionType(FT->getResultType(),
6475 ArrayRef<QualType>(),
6476 EPI);
6477 NewFD->setType(R);
6478 }
6479
6480 // If there's a #pragma GCC visibility in scope, and this isn't a class
6481 // member, set the visibility of this function.
6482 if (!DC->isRecord() && NewFD->hasExternalLinkage())
6483 AddPushedVisibilityAttribute(NewFD);
6484
6485 // If there's a #pragma clang arc_cf_code_audited in scope, consider
6486 // marking the function.
6487 AddCFAuditedAttribute(NewFD);
6488
6489 // If this is a locally-scoped extern C function, update the
6490 // map of such names.
6491 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
6492 && !NewFD->isInvalidDecl())
6493 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
6494
6495 // Set this FunctionDecl's range up to the right paren.
6496 NewFD->setRangeEnd(D.getSourceRange().getEnd());
6497
6498 if (getLangOpts().CPlusPlus) {
6499 if (FunctionTemplate) {
6500 if (NewFD->isInvalidDecl())
6501 FunctionTemplate->setInvalidDecl();
6502 return FunctionTemplate;
6503 }
6504 }
6505
6506 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
6507 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
6508 if ((getLangOpts().OpenCLVersion >= 120)
6509 && (SC == SC_Static)) {
6510 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
6511 D.setInvalidType();
6512 }
6513
6514 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
6515 if (!NewFD->getResultType()->isVoidType()) {
6516 Diag(D.getIdentifierLoc(),
6517 diag::err_expected_kernel_void_return_type);
6518 D.setInvalidType();
6519 }
6520
6521 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
6522 PE = NewFD->param_end(); PI != PE; ++PI) {
6523 ParmVarDecl *Param = *PI;
6524 QualType PT = Param->getType();
6525
6526 // OpenCL v1.2 s6.9.a:
6527 // A kernel function argument cannot be declared as a
6528 // pointer to a pointer type.
6529 if (PT->isPointerType() && PT->getPointeeType()->isPointerType()) {
6530 Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_arg);
6531 D.setInvalidType();
6532 }
6533
6534 // OpenCL v1.2 s6.8 n:
6535 // A kernel function argument cannot be declared
6536 // of event_t type.
6537 if (PT->isEventT()) {
6538 Diag(Param->getLocation(), diag::err_event_t_kernel_arg);
6539 D.setInvalidType();
6540 }
6541 }
6542 }
6543
6544 MarkUnusedFileScopedDecl(NewFD);
6545
6546 if (getLangOpts().CUDA)
6547 if (IdentifierInfo *II = NewFD->getIdentifier())
6548 if (!NewFD->isInvalidDecl() &&
6549 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6550 if (II->isStr("cudaConfigureCall")) {
6551 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
6552 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
6553
6554 Context.setcudaConfigureCallDecl(NewFD);
6555 }
6556 }
6557
6558 // Here we have an function template explicit specialization at class scope.
6559 // The actually specialization will be postponed to template instatiation
6560 // time via the ClassScopeFunctionSpecializationDecl node.
6561 if (isDependentClassScopeExplicitSpecialization) {
6562 ClassScopeFunctionSpecializationDecl *NewSpec =
6563 ClassScopeFunctionSpecializationDecl::Create(
6564 Context, CurContext, SourceLocation(),
6565 cast<CXXMethodDecl>(NewFD),
6566 HasExplicitTemplateArgs, TemplateArgs);
6567 CurContext->addDecl(NewSpec);
6568 AddToScope = false;
6569 }
6570
6571 return NewFD;
6572 }
6573
6574 /// \brief Perform semantic checking of a new function declaration.
6575 ///
6576 /// Performs semantic analysis of the new function declaration
6577 /// NewFD. This routine performs all semantic checking that does not
6578 /// require the actual declarator involved in the declaration, and is
6579 /// used both for the declaration of functions as they are parsed
6580 /// (called via ActOnDeclarator) and for the declaration of functions
6581 /// that have been instantiated via C++ template instantiation (called
6582 /// via InstantiateDecl).
6583 ///
6584 /// \param IsExplicitSpecialization whether this new function declaration is
6585 /// an explicit specialization of the previous declaration.
6586 ///
6587 /// This sets NewFD->isInvalidDecl() to true if there was an error.
6588 ///
6589 /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsExplicitSpecialization)6590 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
6591 LookupResult &Previous,
6592 bool IsExplicitSpecialization) {
6593 assert(!NewFD->getResultType()->isVariablyModifiedType()
6594 && "Variably modified return types are not handled here");
6595
6596 // Check for a previous declaration of this name.
6597 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewFD)) {
6598 // Since we did not find anything by this name, look for a non-visible
6599 // extern "C" declaration with the same name.
6600 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6601 = findLocallyScopedExternCDecl(NewFD->getDeclName());
6602 if (Pos != LocallyScopedExternCDecls.end())
6603 Previous.addDecl(Pos->second);
6604 }
6605
6606 // Filter out any non-conflicting previous declarations.
6607 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
6608
6609 bool Redeclaration = false;
6610 NamedDecl *OldDecl = 0;
6611
6612 // Merge or overload the declaration with an existing declaration of
6613 // the same name, if appropriate.
6614 if (!Previous.empty()) {
6615 // Determine whether NewFD is an overload of PrevDecl or
6616 // a declaration that requires merging. If it's an overload,
6617 // there's no more work to do here; we'll just add the new
6618 // function to the scope.
6619 if (!AllowOverloadingOfFunction(Previous, Context)) {
6620 Redeclaration = true;
6621 OldDecl = Previous.getFoundDecl();
6622 } else {
6623 switch (CheckOverload(S, NewFD, Previous, OldDecl,
6624 /*NewIsUsingDecl*/ false)) {
6625 case Ovl_Match:
6626 Redeclaration = true;
6627 break;
6628
6629 case Ovl_NonFunction:
6630 Redeclaration = true;
6631 break;
6632
6633 case Ovl_Overload:
6634 Redeclaration = false;
6635 break;
6636 }
6637
6638 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
6639 // If a function name is overloadable in C, then every function
6640 // with that name must be marked "overloadable".
6641 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
6642 << Redeclaration << NewFD;
6643 NamedDecl *OverloadedDecl = 0;
6644 if (Redeclaration)
6645 OverloadedDecl = OldDecl;
6646 else if (!Previous.empty())
6647 OverloadedDecl = Previous.getRepresentativeDecl();
6648 if (OverloadedDecl)
6649 Diag(OverloadedDecl->getLocation(),
6650 diag::note_attribute_overloadable_prev_overload);
6651 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
6652 Context));
6653 }
6654 }
6655 }
6656
6657 // C++11 [dcl.constexpr]p8:
6658 // A constexpr specifier for a non-static member function that is not
6659 // a constructor declares that member function to be const.
6660 //
6661 // This needs to be delayed until we know whether this is an out-of-line
6662 // definition of a static member function.
6663 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6664 if (MD && MD->isConstexpr() && !MD->isStatic() &&
6665 !isa<CXXConstructorDecl>(MD) &&
6666 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
6667 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
6668 if (FunctionTemplateDecl *OldTD =
6669 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
6670 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
6671 if (!OldMD || !OldMD->isStatic()) {
6672 const FunctionProtoType *FPT =
6673 MD->getType()->castAs<FunctionProtoType>();
6674 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6675 EPI.TypeQuals |= Qualifiers::Const;
6676 MD->setType(Context.getFunctionType(FPT->getResultType(),
6677 ArrayRef<QualType>(FPT->arg_type_begin(),
6678 FPT->getNumArgs()),
6679 EPI));
6680 }
6681 }
6682
6683 if (Redeclaration) {
6684 // NewFD and OldDecl represent declarations that need to be
6685 // merged.
6686 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
6687 NewFD->setInvalidDecl();
6688 return Redeclaration;
6689 }
6690
6691 Previous.clear();
6692 Previous.addDecl(OldDecl);
6693
6694 if (FunctionTemplateDecl *OldTemplateDecl
6695 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
6696 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
6697 FunctionTemplateDecl *NewTemplateDecl
6698 = NewFD->getDescribedFunctionTemplate();
6699 assert(NewTemplateDecl && "Template/non-template mismatch");
6700 if (CXXMethodDecl *Method
6701 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
6702 Method->setAccess(OldTemplateDecl->getAccess());
6703 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
6704 }
6705
6706 // If this is an explicit specialization of a member that is a function
6707 // template, mark it as a member specialization.
6708 if (IsExplicitSpecialization &&
6709 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
6710 NewTemplateDecl->setMemberSpecialization();
6711 assert(OldTemplateDecl->isMemberSpecialization());
6712 }
6713
6714 } else {
6715 // This needs to happen first so that 'inline' propagates.
6716 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
6717
6718 if (isa<CXXMethodDecl>(NewFD)) {
6719 // A valid redeclaration of a C++ method must be out-of-line,
6720 // but (unfortunately) it's not necessarily a definition
6721 // because of templates, which means that the previous
6722 // declaration is not necessarily from the class definition.
6723
6724 // For just setting the access, that doesn't matter.
6725 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
6726 NewFD->setAccess(oldMethod->getAccess());
6727
6728 // Update the key-function state if necessary for this ABI.
6729 if (NewFD->isInlined() &&
6730 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
6731 // setNonKeyFunction needs to work with the original
6732 // declaration from the class definition, and isVirtual() is
6733 // just faster in that case, so map back to that now.
6734 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration());
6735 if (oldMethod->isVirtual()) {
6736 Context.setNonKeyFunction(oldMethod);
6737 }
6738 }
6739 }
6740 }
6741 }
6742
6743 // Semantic checking for this function declaration (in isolation).
6744 if (getLangOpts().CPlusPlus) {
6745 // C++-specific checks.
6746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
6747 CheckConstructor(Constructor);
6748 } else if (CXXDestructorDecl *Destructor =
6749 dyn_cast<CXXDestructorDecl>(NewFD)) {
6750 CXXRecordDecl *Record = Destructor->getParent();
6751 QualType ClassType = Context.getTypeDeclType(Record);
6752
6753 // FIXME: Shouldn't we be able to perform this check even when the class
6754 // type is dependent? Both gcc and edg can handle that.
6755 if (!ClassType->isDependentType()) {
6756 DeclarationName Name
6757 = Context.DeclarationNames.getCXXDestructorName(
6758 Context.getCanonicalType(ClassType));
6759 if (NewFD->getDeclName() != Name) {
6760 Diag(NewFD->getLocation(), diag::err_destructor_name);
6761 NewFD->setInvalidDecl();
6762 return Redeclaration;
6763 }
6764 }
6765 } else if (CXXConversionDecl *Conversion
6766 = dyn_cast<CXXConversionDecl>(NewFD)) {
6767 ActOnConversionDeclarator(Conversion);
6768 }
6769
6770 // Find any virtual functions that this function overrides.
6771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
6772 if (!Method->isFunctionTemplateSpecialization() &&
6773 !Method->getDescribedFunctionTemplate() &&
6774 Method->isCanonicalDecl()) {
6775 if (AddOverriddenMethods(Method->getParent(), Method)) {
6776 // If the function was marked as "static", we have a problem.
6777 if (NewFD->getStorageClass() == SC_Static) {
6778 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
6779 }
6780 }
6781 }
6782
6783 if (Method->isStatic())
6784 checkThisInStaticMemberFunctionType(Method);
6785 }
6786
6787 // Extra checking for C++ overloaded operators (C++ [over.oper]).
6788 if (NewFD->isOverloadedOperator() &&
6789 CheckOverloadedOperatorDeclaration(NewFD)) {
6790 NewFD->setInvalidDecl();
6791 return Redeclaration;
6792 }
6793
6794 // Extra checking for C++0x literal operators (C++0x [over.literal]).
6795 if (NewFD->getLiteralIdentifier() &&
6796 CheckLiteralOperatorDeclaration(NewFD)) {
6797 NewFD->setInvalidDecl();
6798 return Redeclaration;
6799 }
6800
6801 // In C++, check default arguments now that we have merged decls. Unless
6802 // the lexical context is the class, because in this case this is done
6803 // during delayed parsing anyway.
6804 if (!CurContext->isRecord())
6805 CheckCXXDefaultArguments(NewFD);
6806
6807 // If this function declares a builtin function, check the type of this
6808 // declaration against the expected type for the builtin.
6809 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6810 ASTContext::GetBuiltinTypeError Error;
6811 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
6812 QualType T = Context.GetBuiltinType(BuiltinID, Error);
6813 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6814 // The type of this function differs from the type of the builtin,
6815 // so forget about the builtin entirely.
6816 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6817 }
6818 }
6819
6820 // If this function is declared as being extern "C", then check to see if
6821 // the function returns a UDT (class, struct, or union type) that is not C
6822 // compatible, and if it does, warn the user.
6823 // But, issue any diagnostic on the first declaration only.
6824 if (NewFD->isExternC() && Previous.empty()) {
6825 QualType R = NewFD->getResultType();
6826 if (R->isIncompleteType() && !R->isVoidType())
6827 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
6828 << NewFD << R;
6829 else if (!R.isPODType(Context) && !R->isVoidType() &&
6830 !R->isObjCObjectPointerType())
6831 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
6832 }
6833 }
6834 return Redeclaration;
6835 }
6836
getResultSourceRange(const FunctionDecl * FD)6837 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
6838 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6839 if (!TSI)
6840 return SourceRange();
6841
6842 TypeLoc TL = TSI->getTypeLoc();
6843 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
6844 if (!FunctionTL)
6845 return SourceRange();
6846
6847 TypeLoc ResultTL = FunctionTL.getResultLoc();
6848 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
6849 return ResultTL.getSourceRange();
6850
6851 return SourceRange();
6852 }
6853
CheckMain(FunctionDecl * FD,const DeclSpec & DS)6854 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
6855 // C++11 [basic.start.main]p3: A program that declares main to be inline,
6856 // static or constexpr is ill-formed.
6857 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
6858 // appear in a declaration of main.
6859 // static main is not an error under C99, but we should warn about it.
6860 // We accept _Noreturn main as an extension.
6861 if (FD->getStorageClass() == SC_Static)
6862 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
6863 ? diag::err_static_main : diag::warn_static_main)
6864 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6865 if (FD->isInlineSpecified())
6866 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6867 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
6868 if (DS.isNoreturnSpecified()) {
6869 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
6870 SourceRange NoreturnRange(NoreturnLoc,
6871 PP.getLocForEndOfToken(NoreturnLoc));
6872 Diag(NoreturnLoc, diag::ext_noreturn_main);
6873 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
6874 << FixItHint::CreateRemoval(NoreturnRange);
6875 }
6876 if (FD->isConstexpr()) {
6877 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6878 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6879 FD->setConstexpr(false);
6880 }
6881
6882 QualType T = FD->getType();
6883 assert(T->isFunctionType() && "function decl is not of function type");
6884 const FunctionType* FT = T->castAs<FunctionType>();
6885
6886 // All the standards say that main() should should return 'int'.
6887 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6888 // In C and C++, main magically returns 0 if you fall off the end;
6889 // set the flag which tells us that.
6890 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6891 FD->setHasImplicitReturnZero(true);
6892
6893 // In C with GNU extensions we allow main() to have non-integer return
6894 // type, but we should warn about the extension, and we disable the
6895 // implicit-return-zero rule.
6896 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
6897 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6898
6899 SourceRange ResultRange = getResultSourceRange(FD);
6900 if (ResultRange.isValid())
6901 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
6902 << FixItHint::CreateReplacement(ResultRange, "int");
6903
6904 // Otherwise, this is just a flat-out error.
6905 } else {
6906 SourceRange ResultRange = getResultSourceRange(FD);
6907 if (ResultRange.isValid())
6908 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
6909 << FixItHint::CreateReplacement(ResultRange, "int");
6910 else
6911 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
6912
6913 FD->setInvalidDecl(true);
6914 }
6915
6916 // Treat protoless main() as nullary.
6917 if (isa<FunctionNoProtoType>(FT)) return;
6918
6919 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6920 unsigned nparams = FTP->getNumArgs();
6921 assert(FD->getNumParams() == nparams);
6922
6923 bool HasExtraParameters = (nparams > 3);
6924
6925 // Darwin passes an undocumented fourth argument of type char**. If
6926 // other platforms start sprouting these, the logic below will start
6927 // getting shifty.
6928 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
6929 HasExtraParameters = false;
6930
6931 if (HasExtraParameters) {
6932 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6933 FD->setInvalidDecl(true);
6934 nparams = 3;
6935 }
6936
6937 // FIXME: a lot of the following diagnostics would be improved
6938 // if we had some location information about types.
6939
6940 QualType CharPP =
6941 Context.getPointerType(Context.getPointerType(Context.CharTy));
6942 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
6943
6944 for (unsigned i = 0; i < nparams; ++i) {
6945 QualType AT = FTP->getArgType(i);
6946
6947 bool mismatch = true;
6948
6949 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6950 mismatch = false;
6951 else if (Expected[i] == CharPP) {
6952 // As an extension, the following forms are okay:
6953 // char const **
6954 // char const * const *
6955 // char * const *
6956
6957 QualifierCollector qs;
6958 const PointerType* PT;
6959 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6960 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
6961 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
6962 Context.CharTy)) {
6963 qs.removeConst();
6964 mismatch = !qs.empty();
6965 }
6966 }
6967
6968 if (mismatch) {
6969 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6970 // TODO: suggest replacing given type with expected type
6971 FD->setInvalidDecl(true);
6972 }
6973 }
6974
6975 if (nparams == 1 && !FD->isInvalidDecl()) {
6976 Diag(FD->getLocation(), diag::warn_main_one_arg);
6977 }
6978
6979 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6980 Diag(FD->getLocation(), diag::err_main_template_decl);
6981 FD->setInvalidDecl();
6982 }
6983 }
6984
CheckForConstantInitializer(Expr * Init,QualType DclT)6985 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
6986 // FIXME: Need strict checking. In C89, we need to check for
6987 // any assignment, increment, decrement, function-calls, or
6988 // commas outside of a sizeof. In C99, it's the same list,
6989 // except that the aforementioned are allowed in unevaluated
6990 // expressions. Everything else falls under the
6991 // "may accept other forms of constant expressions" exception.
6992 // (We never end up here for C++, so the constant expression
6993 // rules there don't matter.)
6994 if (Init->isConstantInitializer(Context, false))
6995 return false;
6996 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6997 << Init->getSourceRange();
6998 return true;
6999 }
7000
7001 namespace {
7002 // Visits an initialization expression to see if OrigDecl is evaluated in
7003 // its own initialization and throws a warning if it does.
7004 class SelfReferenceChecker
7005 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7006 Sema &S;
7007 Decl *OrigDecl;
7008 bool isRecordType;
7009 bool isPODType;
7010 bool isReferenceType;
7011
7012 public:
7013 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7014
SelfReferenceChecker(Sema & S,Decl * OrigDecl)7015 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7016 S(S), OrigDecl(OrigDecl) {
7017 isPODType = false;
7018 isRecordType = false;
7019 isReferenceType = false;
7020 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7021 isPODType = VD->getType().isPODType(S.Context);
7022 isRecordType = VD->getType()->isRecordType();
7023 isReferenceType = VD->getType()->isReferenceType();
7024 }
7025 }
7026
7027 // For most expressions, the cast is directly above the DeclRefExpr.
7028 // For conditional operators, the cast can be outside the conditional
7029 // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)7030 void HandleValue(Expr *E) {
7031 if (isReferenceType)
7032 return;
7033 E = E->IgnoreParenImpCasts();
7034 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7035 HandleDeclRefExpr(DRE);
7036 return;
7037 }
7038
7039 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7040 HandleValue(CO->getTrueExpr());
7041 HandleValue(CO->getFalseExpr());
7042 return;
7043 }
7044
7045 if (isa<MemberExpr>(E)) {
7046 Expr *Base = E->IgnoreParenImpCasts();
7047 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7048 // Check for static member variables and don't warn on them.
7049 if (!isa<FieldDecl>(ME->getMemberDecl()))
7050 return;
7051 Base = ME->getBase()->IgnoreParenImpCasts();
7052 }
7053 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7054 HandleDeclRefExpr(DRE);
7055 return;
7056 }
7057 }
7058
7059 // Reference types are handled here since all uses of references are
7060 // bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)7061 void VisitDeclRefExpr(DeclRefExpr *E) {
7062 if (isReferenceType)
7063 HandleDeclRefExpr(E);
7064 }
7065
VisitImplicitCastExpr(ImplicitCastExpr * E)7066 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7067 if (E->getCastKind() == CK_LValueToRValue ||
7068 (isRecordType && E->getCastKind() == CK_NoOp))
7069 HandleValue(E->getSubExpr());
7070
7071 Inherited::VisitImplicitCastExpr(E);
7072 }
7073
VisitMemberExpr(MemberExpr * E)7074 void VisitMemberExpr(MemberExpr *E) {
7075 // Don't warn on arrays since they can be treated as pointers.
7076 if (E->getType()->canDecayToPointerType()) return;
7077
7078 // Warn when a non-static method call is followed by non-static member
7079 // field accesses, which is followed by a DeclRefExpr.
7080 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7081 bool Warn = (MD && !MD->isStatic());
7082 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7083 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7084 if (!isa<FieldDecl>(ME->getMemberDecl()))
7085 Warn = false;
7086 Base = ME->getBase()->IgnoreParenImpCasts();
7087 }
7088
7089 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7090 if (Warn)
7091 HandleDeclRefExpr(DRE);
7092 return;
7093 }
7094
7095 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7096 // Visit that expression.
7097 Visit(Base);
7098 }
7099
VisitUnaryOperator(UnaryOperator * E)7100 void VisitUnaryOperator(UnaryOperator *E) {
7101 // For POD record types, addresses of its own members are well-defined.
7102 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7103 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7104 if (!isPODType)
7105 HandleValue(E->getSubExpr());
7106 return;
7107 }
7108 Inherited::VisitUnaryOperator(E);
7109 }
7110
VisitObjCMessageExpr(ObjCMessageExpr * E)7111 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7112
HandleDeclRefExpr(DeclRefExpr * DRE)7113 void HandleDeclRefExpr(DeclRefExpr *DRE) {
7114 Decl* ReferenceDecl = DRE->getDecl();
7115 if (OrigDecl != ReferenceDecl) return;
7116 unsigned diag;
7117 if (isReferenceType) {
7118 diag = diag::warn_uninit_self_reference_in_reference_init;
7119 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7120 diag = diag::warn_static_self_reference_in_init;
7121 } else {
7122 diag = diag::warn_uninit_self_reference_in_init;
7123 }
7124
7125 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7126 S.PDiag(diag)
7127 << DRE->getNameInfo().getName()
7128 << OrigDecl->getLocation()
7129 << DRE->getSourceRange());
7130 }
7131 };
7132
7133 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)7134 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7135 bool DirectInit) {
7136 // Parameters arguments are occassionially constructed with itself,
7137 // for instance, in recursive functions. Skip them.
7138 if (isa<ParmVarDecl>(OrigDecl))
7139 return;
7140
7141 E = E->IgnoreParens();
7142
7143 // Skip checking T a = a where T is not a record or reference type.
7144 // Doing so is a way to silence uninitialized warnings.
7145 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7146 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7147 if (ICE->getCastKind() == CK_LValueToRValue)
7148 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7149 if (DRE->getDecl() == OrigDecl)
7150 return;
7151
7152 SelfReferenceChecker(S, OrigDecl).Visit(E);
7153 }
7154 }
7155
7156 /// AddInitializerToDecl - Adds the initializer Init to the
7157 /// declaration dcl. If DirectInit is true, this is C++ direct
7158 /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit,bool TypeMayContainAuto)7159 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
7160 bool DirectInit, bool TypeMayContainAuto) {
7161 // If there is no declaration, there was an error parsing it. Just ignore
7162 // the initializer.
7163 if (RealDecl == 0 || RealDecl->isInvalidDecl())
7164 return;
7165
7166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
7167 // With declarators parsed the way they are, the parser cannot
7168 // distinguish between a normal initializer and a pure-specifier.
7169 // Thus this grotesque test.
7170 IntegerLiteral *IL;
7171 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
7172 Context.getCanonicalType(IL->getType()) == Context.IntTy)
7173 CheckPureMethod(Method, Init->getSourceRange());
7174 else {
7175 Diag(Method->getLocation(), diag::err_member_function_initialization)
7176 << Method->getDeclName() << Init->getSourceRange();
7177 Method->setInvalidDecl();
7178 }
7179 return;
7180 }
7181
7182 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7183 if (!VDecl) {
7184 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
7185 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7186 RealDecl->setInvalidDecl();
7187 return;
7188 }
7189
7190 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
7191
7192 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7193 AutoType *Auto = 0;
7194 if (TypeMayContainAuto &&
7195 (Auto = VDecl->getType()->getContainedAutoType()) &&
7196 !Auto->isDeduced()) {
7197 Expr *DeduceInit = Init;
7198 // Initializer could be a C++ direct-initializer. Deduction only works if it
7199 // contains exactly one expression.
7200 if (CXXDirectInit) {
7201 if (CXXDirectInit->getNumExprs() == 0) {
7202 // It isn't possible to write this directly, but it is possible to
7203 // end up in this situation with "auto x(some_pack...);"
7204 Diag(CXXDirectInit->getLocStart(),
7205 diag::err_auto_var_init_no_expression)
7206 << VDecl->getDeclName() << VDecl->getType()
7207 << VDecl->getSourceRange();
7208 RealDecl->setInvalidDecl();
7209 return;
7210 } else if (CXXDirectInit->getNumExprs() > 1) {
7211 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
7212 diag::err_auto_var_init_multiple_expressions)
7213 << VDecl->getDeclName() << VDecl->getType()
7214 << VDecl->getSourceRange();
7215 RealDecl->setInvalidDecl();
7216 return;
7217 } else {
7218 DeduceInit = CXXDirectInit->getExpr(0);
7219 }
7220 }
7221
7222 // Expressions default to 'id' when we're in a debugger.
7223 bool DefaultedToAuto = false;
7224 if (getLangOpts().DebuggerCastResultToId &&
7225 Init->getType() == Context.UnknownAnyTy) {
7226 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
7227 if (Result.isInvalid()) {
7228 VDecl->setInvalidDecl();
7229 return;
7230 }
7231 Init = Result.take();
7232 DefaultedToAuto = true;
7233 }
7234
7235 TypeSourceInfo *DeducedType = 0;
7236 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
7237 DAR_Failed)
7238 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
7239 if (!DeducedType) {
7240 RealDecl->setInvalidDecl();
7241 return;
7242 }
7243 VDecl->setTypeSourceInfo(DeducedType);
7244 VDecl->setType(DeducedType->getType());
7245 assert(VDecl->isLinkageValid());
7246
7247 // In ARC, infer lifetime.
7248 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7249 VDecl->setInvalidDecl();
7250
7251 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
7252 // 'id' instead of a specific object type prevents most of our usual checks.
7253 // We only want to warn outside of template instantiations, though:
7254 // inside a template, the 'id' could have come from a parameter.
7255 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
7256 DeducedType->getType()->isObjCIdType()) {
7257 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
7258 Diag(Loc, diag::warn_auto_var_is_id)
7259 << VDecl->getDeclName() << DeduceInit->getSourceRange();
7260 }
7261
7262 // If this is a redeclaration, check that the type we just deduced matches
7263 // the previously declared type.
7264 if (VarDecl *Old = VDecl->getPreviousDecl())
7265 MergeVarDeclTypes(VDecl, Old);
7266 }
7267
7268 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
7269 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
7270 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
7271 VDecl->setInvalidDecl();
7272 return;
7273 }
7274
7275 if (!VDecl->getType()->isDependentType()) {
7276 // A definition must end up with a complete type, which means it must be
7277 // complete with the restriction that an array type might be completed by
7278 // the initializer; note that later code assumes this restriction.
7279 QualType BaseDeclType = VDecl->getType();
7280 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
7281 BaseDeclType = Array->getElementType();
7282 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
7283 diag::err_typecheck_decl_incomplete_type)) {
7284 RealDecl->setInvalidDecl();
7285 return;
7286 }
7287
7288 // The variable can not have an abstract class type.
7289 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7290 diag::err_abstract_type_in_decl,
7291 AbstractVariableType))
7292 VDecl->setInvalidDecl();
7293 }
7294
7295 const VarDecl *Def;
7296 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
7297 Diag(VDecl->getLocation(), diag::err_redefinition)
7298 << VDecl->getDeclName();
7299 Diag(Def->getLocation(), diag::note_previous_definition);
7300 VDecl->setInvalidDecl();
7301 return;
7302 }
7303
7304 const VarDecl* PrevInit = 0;
7305 if (getLangOpts().CPlusPlus) {
7306 // C++ [class.static.data]p4
7307 // If a static data member is of const integral or const
7308 // enumeration type, its declaration in the class definition can
7309 // specify a constant-initializer which shall be an integral
7310 // constant expression (5.19). In that case, the member can appear
7311 // in integral constant expressions. The member shall still be
7312 // defined in a namespace scope if it is used in the program and the
7313 // namespace scope definition shall not contain an initializer.
7314 //
7315 // We already performed a redefinition check above, but for static
7316 // data members we also need to check whether there was an in-class
7317 // declaration with an initializer.
7318 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7319 Diag(VDecl->getLocation(), diag::err_redefinition)
7320 << VDecl->getDeclName();
7321 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7322 return;
7323 }
7324
7325 if (VDecl->hasLocalStorage())
7326 getCurFunction()->setHasBranchProtectedScope();
7327
7328 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
7329 VDecl->setInvalidDecl();
7330 return;
7331 }
7332 }
7333
7334 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
7335 // a kernel function cannot be initialized."
7336 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
7337 Diag(VDecl->getLocation(), diag::err_local_cant_init);
7338 VDecl->setInvalidDecl();
7339 return;
7340 }
7341
7342 // Get the decls type and save a reference for later, since
7343 // CheckInitializerTypes may change it.
7344 QualType DclT = VDecl->getType(), SavT = DclT;
7345
7346 // Expressions default to 'id' when we're in a debugger
7347 // and we are assigning it to a variable of Objective-C pointer type.
7348 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
7349 Init->getType() == Context.UnknownAnyTy) {
7350 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
7351 if (Result.isInvalid()) {
7352 VDecl->setInvalidDecl();
7353 return;
7354 }
7355 Init = Result.take();
7356 }
7357
7358 // Perform the initialization.
7359 if (!VDecl->isInvalidDecl()) {
7360 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7361 InitializationKind Kind
7362 = DirectInit ?
7363 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
7364 Init->getLocStart(),
7365 Init->getLocEnd())
7366 : InitializationKind::CreateDirectList(
7367 VDecl->getLocation())
7368 : InitializationKind::CreateCopy(VDecl->getLocation(),
7369 Init->getLocStart());
7370
7371 Expr **Args = &Init;
7372 unsigned NumArgs = 1;
7373 if (CXXDirectInit) {
7374 Args = CXXDirectInit->getExprs();
7375 NumArgs = CXXDirectInit->getNumExprs();
7376 }
7377 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
7378 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
7379 MultiExprArg(Args, NumArgs), &DclT);
7380 if (Result.isInvalid()) {
7381 VDecl->setInvalidDecl();
7382 return;
7383 }
7384
7385 Init = Result.takeAs<Expr>();
7386 }
7387
7388 // Check for self-references within variable initializers.
7389 // Variables declared within a function/method body (except for references)
7390 // are handled by a dataflow analysis.
7391 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
7392 VDecl->getType()->isReferenceType()) {
7393 CheckSelfReference(*this, RealDecl, Init, DirectInit);
7394 }
7395
7396 // If the type changed, it means we had an incomplete type that was
7397 // completed by the initializer. For example:
7398 // int ary[] = { 1, 3, 5 };
7399 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
7400 if (!VDecl->isInvalidDecl() && (DclT != SavT))
7401 VDecl->setType(DclT);
7402
7403 if (!VDecl->isInvalidDecl()) {
7404 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
7405
7406 if (VDecl->hasAttr<BlocksAttr>())
7407 checkRetainCycles(VDecl, Init);
7408
7409 // It is safe to assign a weak reference into a strong variable.
7410 // Although this code can still have problems:
7411 // id x = self.weakProp;
7412 // id y = self.weakProp;
7413 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7414 // paths through the function. This should be revisited if
7415 // -Wrepeated-use-of-weak is made flow-sensitive.
7416 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
7417 DiagnosticsEngine::Level Level =
7418 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7419 Init->getLocStart());
7420 if (Level != DiagnosticsEngine::Ignored)
7421 getCurFunction()->markSafeWeakUse(Init);
7422 }
7423 }
7424
7425 // The initialization is usually a full-expression.
7426 //
7427 // FIXME: If this is a braced initialization of an aggregate, it is not
7428 // an expression, and each individual field initializer is a separate
7429 // full-expression. For instance, in:
7430 //
7431 // struct Temp { ~Temp(); };
7432 // struct S { S(Temp); };
7433 // struct T { S a, b; } t = { Temp(), Temp() }
7434 //
7435 // we should destroy the first Temp before constructing the second.
7436 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
7437 false,
7438 VDecl->isConstexpr());
7439 if (Result.isInvalid()) {
7440 VDecl->setInvalidDecl();
7441 return;
7442 }
7443 Init = Result.take();
7444
7445 // Attach the initializer to the decl.
7446 VDecl->setInit(Init);
7447
7448 if (VDecl->isLocalVarDecl()) {
7449 // C99 6.7.8p4: All the expressions in an initializer for an object that has
7450 // static storage duration shall be constant expressions or string literals.
7451 // C++ does not have this restriction.
7452 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
7453 VDecl->getStorageClass() == SC_Static)
7454 CheckForConstantInitializer(Init, DclT);
7455 } else if (VDecl->isStaticDataMember() &&
7456 VDecl->getLexicalDeclContext()->isRecord()) {
7457 // This is an in-class initialization for a static data member, e.g.,
7458 //
7459 // struct S {
7460 // static const int value = 17;
7461 // };
7462
7463 // C++ [class.mem]p4:
7464 // A member-declarator can contain a constant-initializer only
7465 // if it declares a static member (9.4) of const integral or
7466 // const enumeration type, see 9.4.2.
7467 //
7468 // C++11 [class.static.data]p3:
7469 // If a non-volatile const static data member is of integral or
7470 // enumeration type, its declaration in the class definition can
7471 // specify a brace-or-equal-initializer in which every initalizer-clause
7472 // that is an assignment-expression is a constant expression. A static
7473 // data member of literal type can be declared in the class definition
7474 // with the constexpr specifier; if so, its declaration shall specify a
7475 // brace-or-equal-initializer in which every initializer-clause that is
7476 // an assignment-expression is a constant expression.
7477
7478 // Do nothing on dependent types.
7479 if (DclT->isDependentType()) {
7480
7481 // Allow any 'static constexpr' members, whether or not they are of literal
7482 // type. We separately check that every constexpr variable is of literal
7483 // type.
7484 } else if (VDecl->isConstexpr()) {
7485
7486 // Require constness.
7487 } else if (!DclT.isConstQualified()) {
7488 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
7489 << Init->getSourceRange();
7490 VDecl->setInvalidDecl();
7491
7492 // We allow integer constant expressions in all cases.
7493 } else if (DclT->isIntegralOrEnumerationType()) {
7494 // Check whether the expression is a constant expression.
7495 SourceLocation Loc;
7496 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
7497 // In C++11, a non-constexpr const static data member with an
7498 // in-class initializer cannot be volatile.
7499 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
7500 else if (Init->isValueDependent())
7501 ; // Nothing to check.
7502 else if (Init->isIntegerConstantExpr(Context, &Loc))
7503 ; // Ok, it's an ICE!
7504 else if (Init->isEvaluatable(Context)) {
7505 // If we can constant fold the initializer through heroics, accept it,
7506 // but report this as a use of an extension for -pedantic.
7507 Diag(Loc, diag::ext_in_class_initializer_non_constant)
7508 << Init->getSourceRange();
7509 } else {
7510 // Otherwise, this is some crazy unknown case. Report the issue at the
7511 // location provided by the isIntegerConstantExpr failed check.
7512 Diag(Loc, diag::err_in_class_initializer_non_constant)
7513 << Init->getSourceRange();
7514 VDecl->setInvalidDecl();
7515 }
7516
7517 // We allow foldable floating-point constants as an extension.
7518 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
7519 // In C++98, this is a GNU extension. In C++11, it is not, but we support
7520 // it anyway and provide a fixit to add the 'constexpr'.
7521 if (getLangOpts().CPlusPlus11) {
7522 Diag(VDecl->getLocation(),
7523 diag::ext_in_class_initializer_float_type_cxx11)
7524 << DclT << Init->getSourceRange();
7525 Diag(VDecl->getLocStart(),
7526 diag::note_in_class_initializer_float_type_cxx11)
7527 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
7528 } else {
7529 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
7530 << DclT << Init->getSourceRange();
7531
7532 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
7533 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
7534 << Init->getSourceRange();
7535 VDecl->setInvalidDecl();
7536 }
7537 }
7538
7539 // Suggest adding 'constexpr' in C++11 for literal types.
7540 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) {
7541 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
7542 << DclT << Init->getSourceRange()
7543 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
7544 VDecl->setConstexpr(true);
7545
7546 } else {
7547 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
7548 << DclT << Init->getSourceRange();
7549 VDecl->setInvalidDecl();
7550 }
7551 } else if (VDecl->isFileVarDecl()) {
7552 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
7553 (!getLangOpts().CPlusPlus ||
7554 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
7555 Diag(VDecl->getLocation(), diag::warn_extern_init);
7556
7557 // C99 6.7.8p4. All file scoped initializers need to be constant.
7558 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
7559 CheckForConstantInitializer(Init, DclT);
7560 }
7561
7562 // We will represent direct-initialization similarly to copy-initialization:
7563 // int x(1); -as-> int x = 1;
7564 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7565 //
7566 // Clients that want to distinguish between the two forms, can check for
7567 // direct initializer using VarDecl::getInitStyle().
7568 // A major benefit is that clients that don't particularly care about which
7569 // exactly form was it (like the CodeGen) can handle both cases without
7570 // special case code.
7571
7572 // C++ 8.5p11:
7573 // The form of initialization (using parentheses or '=') is generally
7574 // insignificant, but does matter when the entity being initialized has a
7575 // class type.
7576 if (CXXDirectInit) {
7577 assert(DirectInit && "Call-style initializer must be direct init.");
7578 VDecl->setInitStyle(VarDecl::CallInit);
7579 } else if (DirectInit) {
7580 // This must be list-initialization. No other way is direct-initialization.
7581 VDecl->setInitStyle(VarDecl::ListInit);
7582 }
7583
7584 CheckCompleteVariableDeclaration(VDecl);
7585 }
7586
7587 /// ActOnInitializerError - Given that there was an error parsing an
7588 /// initializer for the given declaration, try to return to some form
7589 /// of sanity.
ActOnInitializerError(Decl * D)7590 void Sema::ActOnInitializerError(Decl *D) {
7591 // Our main concern here is re-establishing invariants like "a
7592 // variable's type is either dependent or complete".
7593 if (!D || D->isInvalidDecl()) return;
7594
7595 VarDecl *VD = dyn_cast<VarDecl>(D);
7596 if (!VD) return;
7597
7598 // Auto types are meaningless if we can't make sense of the initializer.
7599 if (ParsingInitForAutoVars.count(D)) {
7600 D->setInvalidDecl();
7601 return;
7602 }
7603
7604 QualType Ty = VD->getType();
7605 if (Ty->isDependentType()) return;
7606
7607 // Require a complete type.
7608 if (RequireCompleteType(VD->getLocation(),
7609 Context.getBaseElementType(Ty),
7610 diag::err_typecheck_decl_incomplete_type)) {
7611 VD->setInvalidDecl();
7612 return;
7613 }
7614
7615 // Require an abstract type.
7616 if (RequireNonAbstractType(VD->getLocation(), Ty,
7617 diag::err_abstract_type_in_decl,
7618 AbstractVariableType)) {
7619 VD->setInvalidDecl();
7620 return;
7621 }
7622
7623 // Don't bother complaining about constructors or destructors,
7624 // though.
7625 }
7626
ActOnUninitializedDecl(Decl * RealDecl,bool TypeMayContainAuto)7627 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
7628 bool TypeMayContainAuto) {
7629 // If there is no declaration, there was an error parsing it. Just ignore it.
7630 if (RealDecl == 0)
7631 return;
7632
7633 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
7634 QualType Type = Var->getType();
7635
7636 // C++11 [dcl.spec.auto]p3
7637 if (TypeMayContainAuto && Type->getContainedAutoType()) {
7638 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
7639 << Var->getDeclName() << Type;
7640 Var->setInvalidDecl();
7641 return;
7642 }
7643
7644 // C++11 [class.static.data]p3: A static data member can be declared with
7645 // the constexpr specifier; if so, its declaration shall specify
7646 // a brace-or-equal-initializer.
7647 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
7648 // the definition of a variable [...] or the declaration of a static data
7649 // member.
7650 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
7651 if (Var->isStaticDataMember())
7652 Diag(Var->getLocation(),
7653 diag::err_constexpr_static_mem_var_requires_init)
7654 << Var->getDeclName();
7655 else
7656 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
7657 Var->setInvalidDecl();
7658 return;
7659 }
7660
7661 switch (Var->isThisDeclarationADefinition()) {
7662 case VarDecl::Definition:
7663 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
7664 break;
7665
7666 // We have an out-of-line definition of a static data member
7667 // that has an in-class initializer, so we type-check this like
7668 // a declaration.
7669 //
7670 // Fall through
7671
7672 case VarDecl::DeclarationOnly:
7673 // It's only a declaration.
7674
7675 // Block scope. C99 6.7p7: If an identifier for an object is
7676 // declared with no linkage (C99 6.2.2p6), the type for the
7677 // object shall be complete.
7678 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
7679 !Var->getLinkage() && !Var->isInvalidDecl() &&
7680 RequireCompleteType(Var->getLocation(), Type,
7681 diag::err_typecheck_decl_incomplete_type))
7682 Var->setInvalidDecl();
7683
7684 // Make sure that the type is not abstract.
7685 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7686 RequireNonAbstractType(Var->getLocation(), Type,
7687 diag::err_abstract_type_in_decl,
7688 AbstractVariableType))
7689 Var->setInvalidDecl();
7690 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7691 Var->getStorageClass() == SC_PrivateExtern) {
7692 Diag(Var->getLocation(), diag::warn_private_extern);
7693 Diag(Var->getLocation(), diag::note_private_extern);
7694 }
7695
7696 return;
7697
7698 case VarDecl::TentativeDefinition:
7699 // File scope. C99 6.9.2p2: A declaration of an identifier for an
7700 // object that has file scope without an initializer, and without a
7701 // storage-class specifier or with the storage-class specifier "static",
7702 // constitutes a tentative definition. Note: A tentative definition with
7703 // external linkage is valid (C99 6.2.2p5).
7704 if (!Var->isInvalidDecl()) {
7705 if (const IncompleteArrayType *ArrayT
7706 = Context.getAsIncompleteArrayType(Type)) {
7707 if (RequireCompleteType(Var->getLocation(),
7708 ArrayT->getElementType(),
7709 diag::err_illegal_decl_array_incomplete_type))
7710 Var->setInvalidDecl();
7711 } else if (Var->getStorageClass() == SC_Static) {
7712 // C99 6.9.2p3: If the declaration of an identifier for an object is
7713 // a tentative definition and has internal linkage (C99 6.2.2p3), the
7714 // declared type shall not be an incomplete type.
7715 // NOTE: code such as the following
7716 // static struct s;
7717 // struct s { int a; };
7718 // is accepted by gcc. Hence here we issue a warning instead of
7719 // an error and we do not invalidate the static declaration.
7720 // NOTE: to avoid multiple warnings, only check the first declaration.
7721 if (Var->getPreviousDecl() == 0)
7722 RequireCompleteType(Var->getLocation(), Type,
7723 diag::ext_typecheck_decl_incomplete_type);
7724 }
7725 }
7726
7727 // Record the tentative definition; we're done.
7728 if (!Var->isInvalidDecl())
7729 TentativeDefinitions.push_back(Var);
7730 return;
7731 }
7732
7733 // Provide a specific diagnostic for uninitialized variable
7734 // definitions with incomplete array type.
7735 if (Type->isIncompleteArrayType()) {
7736 Diag(Var->getLocation(),
7737 diag::err_typecheck_incomplete_array_needs_initializer);
7738 Var->setInvalidDecl();
7739 return;
7740 }
7741
7742 // Provide a specific diagnostic for uninitialized variable
7743 // definitions with reference type.
7744 if (Type->isReferenceType()) {
7745 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
7746 << Var->getDeclName()
7747 << SourceRange(Var->getLocation(), Var->getLocation());
7748 Var->setInvalidDecl();
7749 return;
7750 }
7751
7752 // Do not attempt to type-check the default initializer for a
7753 // variable with dependent type.
7754 if (Type->isDependentType())
7755 return;
7756
7757 if (Var->isInvalidDecl())
7758 return;
7759
7760 if (RequireCompleteType(Var->getLocation(),
7761 Context.getBaseElementType(Type),
7762 diag::err_typecheck_decl_incomplete_type)) {
7763 Var->setInvalidDecl();
7764 return;
7765 }
7766
7767 // The variable can not have an abstract class type.
7768 if (RequireNonAbstractType(Var->getLocation(), Type,
7769 diag::err_abstract_type_in_decl,
7770 AbstractVariableType)) {
7771 Var->setInvalidDecl();
7772 return;
7773 }
7774
7775 // Check for jumps past the implicit initializer. C++0x
7776 // clarifies that this applies to a "variable with automatic
7777 // storage duration", not a "local variable".
7778 // C++11 [stmt.dcl]p3
7779 // A program that jumps from a point where a variable with automatic
7780 // storage duration is not in scope to a point where it is in scope is
7781 // ill-formed unless the variable has scalar type, class type with a
7782 // trivial default constructor and a trivial destructor, a cv-qualified
7783 // version of one of these types, or an array of one of the preceding
7784 // types and is declared without an initializer.
7785 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
7786 if (const RecordType *Record
7787 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
7788 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
7789 // Mark the function for further checking even if the looser rules of
7790 // C++11 do not require such checks, so that we can diagnose
7791 // incompatibilities with C++98.
7792 if (!CXXRecord->isPOD())
7793 getCurFunction()->setHasBranchProtectedScope();
7794 }
7795 }
7796
7797 // C++03 [dcl.init]p9:
7798 // If no initializer is specified for an object, and the
7799 // object is of (possibly cv-qualified) non-POD class type (or
7800 // array thereof), the object shall be default-initialized; if
7801 // the object is of const-qualified type, the underlying class
7802 // type shall have a user-declared default
7803 // constructor. Otherwise, if no initializer is specified for
7804 // a non- static object, the object and its subobjects, if
7805 // any, have an indeterminate initial value); if the object
7806 // or any of its subobjects are of const-qualified type, the
7807 // program is ill-formed.
7808 // C++0x [dcl.init]p11:
7809 // If no initializer is specified for an object, the object is
7810 // default-initialized; [...].
7811 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
7812 InitializationKind Kind
7813 = InitializationKind::CreateDefault(Var->getLocation());
7814
7815 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
7816 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
7817 if (Init.isInvalid())
7818 Var->setInvalidDecl();
7819 else if (Init.get()) {
7820 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
7821 // This is important for template substitution.
7822 Var->setInitStyle(VarDecl::CallInit);
7823 }
7824
7825 CheckCompleteVariableDeclaration(Var);
7826 }
7827 }
7828
ActOnCXXForRangeDecl(Decl * D)7829 void Sema::ActOnCXXForRangeDecl(Decl *D) {
7830 VarDecl *VD = dyn_cast<VarDecl>(D);
7831 if (!VD) {
7832 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
7833 D->setInvalidDecl();
7834 return;
7835 }
7836
7837 VD->setCXXForRangeDecl(true);
7838
7839 // for-range-declaration cannot be given a storage class specifier.
7840 int Error = -1;
7841 switch (VD->getStorageClassAsWritten()) {
7842 case SC_None:
7843 break;
7844 case SC_Extern:
7845 Error = 0;
7846 break;
7847 case SC_Static:
7848 Error = 1;
7849 break;
7850 case SC_PrivateExtern:
7851 Error = 2;
7852 break;
7853 case SC_Auto:
7854 Error = 3;
7855 break;
7856 case SC_Register:
7857 Error = 4;
7858 break;
7859 case SC_OpenCLWorkGroupLocal:
7860 llvm_unreachable("Unexpected storage class");
7861 }
7862 if (VD->isConstexpr())
7863 Error = 5;
7864 if (Error != -1) {
7865 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
7866 << VD->getDeclName() << Error;
7867 D->setInvalidDecl();
7868 }
7869 }
7870
CheckCompleteVariableDeclaration(VarDecl * var)7871 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
7872 if (var->isInvalidDecl()) return;
7873
7874 // In ARC, don't allow jumps past the implicit initialization of a
7875 // local retaining variable.
7876 if (getLangOpts().ObjCAutoRefCount &&
7877 var->hasLocalStorage()) {
7878 switch (var->getType().getObjCLifetime()) {
7879 case Qualifiers::OCL_None:
7880 case Qualifiers::OCL_ExplicitNone:
7881 case Qualifiers::OCL_Autoreleasing:
7882 break;
7883
7884 case Qualifiers::OCL_Weak:
7885 case Qualifiers::OCL_Strong:
7886 getCurFunction()->setHasBranchProtectedScope();
7887 break;
7888 }
7889 }
7890
7891 if (var->isThisDeclarationADefinition() &&
7892 var->hasExternalLinkage() &&
7893 getDiagnostics().getDiagnosticLevel(
7894 diag::warn_missing_variable_declarations,
7895 var->getLocation())) {
7896 // Find a previous declaration that's not a definition.
7897 VarDecl *prev = var->getPreviousDecl();
7898 while (prev && prev->isThisDeclarationADefinition())
7899 prev = prev->getPreviousDecl();
7900
7901 if (!prev)
7902 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
7903 }
7904
7905 // All the following checks are C++ only.
7906 if (!getLangOpts().CPlusPlus) return;
7907
7908 QualType type = var->getType();
7909 if (type->isDependentType()) return;
7910
7911 // __block variables might require us to capture a copy-initializer.
7912 if (var->hasAttr<BlocksAttr>()) {
7913 // It's currently invalid to ever have a __block variable with an
7914 // array type; should we diagnose that here?
7915
7916 // Regardless, we don't want to ignore array nesting when
7917 // constructing this copy.
7918 if (type->isStructureOrClassType()) {
7919 SourceLocation poi = var->getLocation();
7920 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
7921 ExprResult result
7922 = PerformMoveOrCopyInitialization(
7923 InitializedEntity::InitializeBlock(poi, type, false),
7924 var, var->getType(), varRef, /*AllowNRVO=*/true);
7925 if (!result.isInvalid()) {
7926 result = MaybeCreateExprWithCleanups(result);
7927 Expr *init = result.takeAs<Expr>();
7928 Context.setBlockVarCopyInits(var, init);
7929 }
7930 }
7931 }
7932
7933 Expr *Init = var->getInit();
7934 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
7935 QualType baseType = Context.getBaseElementType(type);
7936
7937 if (!var->getDeclContext()->isDependentContext() &&
7938 Init && !Init->isValueDependent()) {
7939 if (IsGlobal && !var->isConstexpr() &&
7940 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7941 var->getLocation())
7942 != DiagnosticsEngine::Ignored &&
7943 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
7944 Diag(var->getLocation(), diag::warn_global_constructor)
7945 << Init->getSourceRange();
7946
7947 if (var->isConstexpr()) {
7948 SmallVector<PartialDiagnosticAt, 8> Notes;
7949 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7950 SourceLocation DiagLoc = var->getLocation();
7951 // If the note doesn't add any useful information other than a source
7952 // location, fold it into the primary diagnostic.
7953 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7954 diag::note_invalid_subexpr_in_const_expr) {
7955 DiagLoc = Notes[0].first;
7956 Notes.clear();
7957 }
7958 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7959 << var << Init->getSourceRange();
7960 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7961 Diag(Notes[I].first, Notes[I].second);
7962 }
7963 } else if (var->isUsableInConstantExpressions(Context)) {
7964 // Check whether the initializer of a const variable of integral or
7965 // enumeration type is an ICE now, since we can't tell whether it was
7966 // initialized by a constant expression if we check later.
7967 var->checkInitIsICE();
7968 }
7969 }
7970
7971 // Require the destructor.
7972 if (const RecordType *recordType = baseType->getAs<RecordType>())
7973 FinalizeVarWithDestructor(var, recordType);
7974 }
7975
7976 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7977 /// any semantic actions necessary after any initializer has been attached.
7978 void
FinalizeDeclaration(Decl * ThisDecl)7979 Sema::FinalizeDeclaration(Decl *ThisDecl) {
7980 // Note that we are no longer parsing the initializer for this declaration.
7981 ParsingInitForAutoVars.erase(ThisDecl);
7982
7983 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
7984 if (!VD)
7985 return;
7986
7987 const DeclContext *DC = VD->getDeclContext();
7988 // If there's a #pragma GCC visibility in scope, and this isn't a class
7989 // member, set the visibility of this variable.
7990 if (!DC->isRecord() && VD->hasExternalLinkage())
7991 AddPushedVisibilityAttribute(VD);
7992
7993 if (VD->isFileVarDecl())
7994 MarkUnusedFileScopedDecl(VD);
7995
7996 // Now we have parsed the initializer and can update the table of magic
7997 // tag values.
7998 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
7999 !VD->getType()->isIntegralOrEnumerationType())
8000 return;
8001
8002 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8003 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8004 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8005 I != E; ++I) {
8006 const Expr *MagicValueExpr = VD->getInit();
8007 if (!MagicValueExpr) {
8008 continue;
8009 }
8010 llvm::APSInt MagicValueInt;
8011 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8012 Diag(I->getRange().getBegin(),
8013 diag::err_type_tag_for_datatype_not_ice)
8014 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8015 continue;
8016 }
8017 if (MagicValueInt.getActiveBits() > 64) {
8018 Diag(I->getRange().getBegin(),
8019 diag::err_type_tag_for_datatype_too_large)
8020 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8021 continue;
8022 }
8023 uint64_t MagicValue = MagicValueInt.getZExtValue();
8024 RegisterTypeTagForDatatype(I->getArgumentKind(),
8025 MagicValue,
8026 I->getMatchingCType(),
8027 I->getLayoutCompatible(),
8028 I->getMustBeNull());
8029 }
8030 }
8031
8032 Sema::DeclGroupPtrTy
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,Decl ** Group,unsigned NumDecls)8033 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8034 Decl **Group, unsigned NumDecls) {
8035 SmallVector<Decl*, 8> Decls;
8036
8037 if (DS.isTypeSpecOwned())
8038 Decls.push_back(DS.getRepAsDecl());
8039
8040 for (unsigned i = 0; i != NumDecls; ++i)
8041 if (Decl *D = Group[i])
8042 Decls.push_back(D);
8043
8044 if (DeclSpec::isDeclRep(DS.getTypeSpecType()))
8045 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()))
8046 getASTContext().addUnnamedTag(Tag);
8047
8048 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
8049 DS.getTypeSpecType() == DeclSpec::TST_auto);
8050 }
8051
8052 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
8053 /// group, performing any necessary semantic checking.
8054 Sema::DeclGroupPtrTy
BuildDeclaratorGroup(Decl ** Group,unsigned NumDecls,bool TypeMayContainAuto)8055 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
8056 bool TypeMayContainAuto) {
8057 // C++0x [dcl.spec.auto]p7:
8058 // If the type deduced for the template parameter U is not the same in each
8059 // deduction, the program is ill-formed.
8060 // FIXME: When initializer-list support is added, a distinction is needed
8061 // between the deduced type U and the deduced type which 'auto' stands for.
8062 // auto a = 0, b = { 1, 2, 3 };
8063 // is legal because the deduced type U is 'int' in both cases.
8064 if (TypeMayContainAuto && NumDecls > 1) {
8065 QualType Deduced;
8066 CanQualType DeducedCanon;
8067 VarDecl *DeducedDecl = 0;
8068 for (unsigned i = 0; i != NumDecls; ++i) {
8069 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8070 AutoType *AT = D->getType()->getContainedAutoType();
8071 // Don't reissue diagnostics when instantiating a template.
8072 if (AT && D->isInvalidDecl())
8073 break;
8074 if (AT && AT->isDeduced()) {
8075 QualType U = AT->getDeducedType();
8076 CanQualType UCanon = Context.getCanonicalType(U);
8077 if (Deduced.isNull()) {
8078 Deduced = U;
8079 DeducedCanon = UCanon;
8080 DeducedDecl = D;
8081 } else if (DeducedCanon != UCanon) {
8082 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
8083 diag::err_auto_different_deductions)
8084 << Deduced << DeducedDecl->getDeclName()
8085 << U << D->getDeclName()
8086 << DeducedDecl->getInit()->getSourceRange()
8087 << D->getInit()->getSourceRange();
8088 D->setInvalidDecl();
8089 break;
8090 }
8091 }
8092 }
8093 }
8094 }
8095
8096 ActOnDocumentableDecls(Group, NumDecls);
8097
8098 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
8099 }
8100
ActOnDocumentableDecl(Decl * D)8101 void Sema::ActOnDocumentableDecl(Decl *D) {
8102 ActOnDocumentableDecls(&D, 1);
8103 }
8104
ActOnDocumentableDecls(Decl ** Group,unsigned NumDecls)8105 void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
8106 // Don't parse the comment if Doxygen diagnostics are ignored.
8107 if (NumDecls == 0 || !Group[0])
8108 return;
8109
8110 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
8111 Group[0]->getLocation())
8112 == DiagnosticsEngine::Ignored)
8113 return;
8114
8115 if (NumDecls >= 2) {
8116 // This is a decl group. Normally it will contain only declarations
8117 // procuded from declarator list. But in case we have any definitions or
8118 // additional declaration references:
8119 // 'typedef struct S {} S;'
8120 // 'typedef struct S *S;'
8121 // 'struct S *pS;'
8122 // FinalizeDeclaratorGroup adds these as separate declarations.
8123 Decl *MaybeTagDecl = Group[0];
8124 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
8125 Group++;
8126 NumDecls--;
8127 }
8128 }
8129
8130 // See if there are any new comments that are not attached to a decl.
8131 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
8132 if (!Comments.empty() &&
8133 !Comments.back()->isAttached()) {
8134 // There is at least one comment that not attached to a decl.
8135 // Maybe it should be attached to one of these decls?
8136 //
8137 // Note that this way we pick up not only comments that precede the
8138 // declaration, but also comments that *follow* the declaration -- thanks to
8139 // the lookahead in the lexer: we've consumed the semicolon and looked
8140 // ahead through comments.
8141 for (unsigned i = 0; i != NumDecls; ++i)
8142 Context.getCommentForDecl(Group[i], &PP);
8143 }
8144 }
8145
8146 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
8147 /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)8148 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
8149 const DeclSpec &DS = D.getDeclSpec();
8150
8151 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
8152 // C++03 [dcl.stc]p2 also permits 'auto'.
8153 VarDecl::StorageClass StorageClass = SC_None;
8154 VarDecl::StorageClass StorageClassAsWritten = SC_None;
8155 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
8156 StorageClass = SC_Register;
8157 StorageClassAsWritten = SC_Register;
8158 } else if (getLangOpts().CPlusPlus &&
8159 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
8160 StorageClass = SC_Auto;
8161 StorageClassAsWritten = SC_Auto;
8162 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
8163 Diag(DS.getStorageClassSpecLoc(),
8164 diag::err_invalid_storage_class_in_func_decl);
8165 D.getMutableDeclSpec().ClearStorageClassSpecs();
8166 }
8167
8168 if (D.getDeclSpec().isThreadSpecified())
8169 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8170 if (D.getDeclSpec().isConstexprSpecified())
8171 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8172 << 0;
8173
8174 DiagnoseFunctionSpecifiers(D.getDeclSpec());
8175
8176 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8177 QualType parmDeclType = TInfo->getType();
8178
8179 if (getLangOpts().CPlusPlus) {
8180 // Check that there are no default arguments inside the type of this
8181 // parameter.
8182 CheckExtraCXXDefaultArguments(D);
8183
8184 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
8185 if (D.getCXXScopeSpec().isSet()) {
8186 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
8187 << D.getCXXScopeSpec().getRange();
8188 D.getCXXScopeSpec().clear();
8189 }
8190 }
8191
8192 // Ensure we have a valid name
8193 IdentifierInfo *II = 0;
8194 if (D.hasName()) {
8195 II = D.getIdentifier();
8196 if (!II) {
8197 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
8198 << GetNameForDeclarator(D).getName().getAsString();
8199 D.setInvalidType(true);
8200 }
8201 }
8202
8203 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
8204 if (II) {
8205 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
8206 ForRedeclaration);
8207 LookupName(R, S);
8208 if (R.isSingleResult()) {
8209 NamedDecl *PrevDecl = R.getFoundDecl();
8210 if (PrevDecl->isTemplateParameter()) {
8211 // Maybe we will complain about the shadowed template parameter.
8212 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8213 // Just pretend that we didn't see the previous declaration.
8214 PrevDecl = 0;
8215 } else if (S->isDeclScope(PrevDecl)) {
8216 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
8217 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8218
8219 // Recover by removing the name
8220 II = 0;
8221 D.SetIdentifier(0, D.getIdentifierLoc());
8222 D.setInvalidType(true);
8223 }
8224 }
8225 }
8226
8227 // Temporarily put parameter variables in the translation unit, not
8228 // the enclosing context. This prevents them from accidentally
8229 // looking like class members in C++.
8230 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
8231 D.getLocStart(),
8232 D.getIdentifierLoc(), II,
8233 parmDeclType, TInfo,
8234 StorageClass, StorageClassAsWritten);
8235
8236 if (D.isInvalidType())
8237 New->setInvalidDecl();
8238
8239 assert(S->isFunctionPrototypeScope());
8240 assert(S->getFunctionPrototypeDepth() >= 1);
8241 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
8242 S->getNextFunctionPrototypeIndex());
8243
8244 // Add the parameter declaration into this scope.
8245 S->AddDecl(New);
8246 if (II)
8247 IdResolver.AddDecl(New);
8248
8249 ProcessDeclAttributes(S, New, D);
8250
8251 if (D.getDeclSpec().isModulePrivateSpecified())
8252 Diag(New->getLocation(), diag::err_module_private_local)
8253 << 1 << New->getDeclName()
8254 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8255 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8256
8257 if (New->hasAttr<BlocksAttr>()) {
8258 Diag(New->getLocation(), diag::err_block_on_nonlocal);
8259 }
8260 return New;
8261 }
8262
8263 /// \brief Synthesizes a variable for a parameter arising from a
8264 /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)8265 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
8266 SourceLocation Loc,
8267 QualType T) {
8268 /* FIXME: setting StartLoc == Loc.
8269 Would it be worth to modify callers so as to provide proper source
8270 location for the unnamed parameters, embedding the parameter's type? */
8271 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
8272 T, Context.getTrivialTypeSourceInfo(T, Loc),
8273 SC_None, SC_None, 0);
8274 Param->setImplicit();
8275 return Param;
8276 }
8277
DiagnoseUnusedParameters(ParmVarDecl * const * Param,ParmVarDecl * const * ParamEnd)8278 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
8279 ParmVarDecl * const *ParamEnd) {
8280 // Don't diagnose unused-parameter errors in template instantiations; we
8281 // will already have done so in the template itself.
8282 if (!ActiveTemplateInstantiations.empty())
8283 return;
8284
8285 for (; Param != ParamEnd; ++Param) {
8286 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
8287 !(*Param)->hasAttr<UnusedAttr>()) {
8288 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
8289 << (*Param)->getDeclName();
8290 }
8291 }
8292 }
8293
DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const * Param,ParmVarDecl * const * ParamEnd,QualType ReturnTy,NamedDecl * D)8294 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
8295 ParmVarDecl * const *ParamEnd,
8296 QualType ReturnTy,
8297 NamedDecl *D) {
8298 if (LangOpts.NumLargeByValueCopy == 0) // No check.
8299 return;
8300
8301 // Warn if the return value is pass-by-value and larger than the specified
8302 // threshold.
8303 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
8304 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
8305 if (Size > LangOpts.NumLargeByValueCopy)
8306 Diag(D->getLocation(), diag::warn_return_value_size)
8307 << D->getDeclName() << Size;
8308 }
8309
8310 // Warn if any parameter is pass-by-value and larger than the specified
8311 // threshold.
8312 for (; Param != ParamEnd; ++Param) {
8313 QualType T = (*Param)->getType();
8314 if (T->isDependentType() || !T.isPODType(Context))
8315 continue;
8316 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
8317 if (Size > LangOpts.NumLargeByValueCopy)
8318 Diag((*Param)->getLocation(), diag::warn_parameter_size)
8319 << (*Param)->getDeclName() << Size;
8320 }
8321 }
8322
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,VarDecl::StorageClass StorageClass,VarDecl::StorageClass StorageClassAsWritten)8323 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
8324 SourceLocation NameLoc, IdentifierInfo *Name,
8325 QualType T, TypeSourceInfo *TSInfo,
8326 VarDecl::StorageClass StorageClass,
8327 VarDecl::StorageClass StorageClassAsWritten) {
8328 // In ARC, infer a lifetime qualifier for appropriate parameter types.
8329 if (getLangOpts().ObjCAutoRefCount &&
8330 T.getObjCLifetime() == Qualifiers::OCL_None &&
8331 T->isObjCLifetimeType()) {
8332
8333 Qualifiers::ObjCLifetime lifetime;
8334
8335 // Special cases for arrays:
8336 // - if it's const, use __unsafe_unretained
8337 // - otherwise, it's an error
8338 if (T->isArrayType()) {
8339 if (!T.isConstQualified()) {
8340 DelayedDiagnostics.add(
8341 sema::DelayedDiagnostic::makeForbiddenType(
8342 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
8343 }
8344 lifetime = Qualifiers::OCL_ExplicitNone;
8345 } else {
8346 lifetime = T->getObjCARCImplicitLifetime();
8347 }
8348 T = Context.getLifetimeQualifiedType(T, lifetime);
8349 }
8350
8351 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
8352 Context.getAdjustedParameterType(T),
8353 TSInfo,
8354 StorageClass, StorageClassAsWritten,
8355 0);
8356
8357 // Parameters can not be abstract class types.
8358 // For record types, this is done by the AbstractClassUsageDiagnoser once
8359 // the class has been completely parsed.
8360 if (!CurContext->isRecord() &&
8361 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
8362 AbstractParamType))
8363 New->setInvalidDecl();
8364
8365 // Parameter declarators cannot be interface types. All ObjC objects are
8366 // passed by reference.
8367 if (T->isObjCObjectType()) {
8368 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
8369 Diag(NameLoc,
8370 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
8371 << FixItHint::CreateInsertion(TypeEndLoc, "*");
8372 T = Context.getObjCObjectPointerType(T);
8373 New->setType(T);
8374 }
8375
8376 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
8377 // duration shall not be qualified by an address-space qualifier."
8378 // Since all parameters have automatic store duration, they can not have
8379 // an address space.
8380 if (T.getAddressSpace() != 0) {
8381 Diag(NameLoc, diag::err_arg_with_address_space);
8382 New->setInvalidDecl();
8383 }
8384
8385 return New;
8386 }
8387
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)8388 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
8389 SourceLocation LocAfterDecls) {
8390 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8391
8392 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
8393 // for a K&R function.
8394 if (!FTI.hasPrototype) {
8395 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
8396 --i;
8397 if (FTI.ArgInfo[i].Param == 0) {
8398 SmallString<256> Code;
8399 llvm::raw_svector_ostream(Code) << " int "
8400 << FTI.ArgInfo[i].Ident->getName()
8401 << ";\n";
8402 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
8403 << FTI.ArgInfo[i].Ident
8404 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
8405
8406 // Implicitly declare the argument as type 'int' for lack of a better
8407 // type.
8408 AttributeFactory attrs;
8409 DeclSpec DS(attrs);
8410 const char* PrevSpec; // unused
8411 unsigned DiagID; // unused
8412 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
8413 PrevSpec, DiagID);
8414 // Use the identifier location for the type source range.
8415 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
8416 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
8417 Declarator ParamD(DS, Declarator::KNRTypeListContext);
8418 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
8419 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
8420 }
8421 }
8422 }
8423 }
8424
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D)8425 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
8426 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
8427 assert(D.isFunctionDeclarator() && "Not a function declarator!");
8428 Scope *ParentScope = FnBodyScope->getParent();
8429
8430 D.setFunctionDefinitionKind(FDK_Definition);
8431 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
8432 return ActOnStartOfFunctionDef(FnBodyScope, DP);
8433 }
8434
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossibleZeroParamPrototype)8435 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
8436 const FunctionDecl*& PossibleZeroParamPrototype) {
8437 // Don't warn about invalid declarations.
8438 if (FD->isInvalidDecl())
8439 return false;
8440
8441 // Or declarations that aren't global.
8442 if (!FD->isGlobal())
8443 return false;
8444
8445 // Don't warn about C++ member functions.
8446 if (isa<CXXMethodDecl>(FD))
8447 return false;
8448
8449 // Don't warn about 'main'.
8450 if (FD->isMain())
8451 return false;
8452
8453 // Don't warn about inline functions.
8454 if (FD->isInlined())
8455 return false;
8456
8457 // Don't warn about function templates.
8458 if (FD->getDescribedFunctionTemplate())
8459 return false;
8460
8461 // Don't warn about function template specializations.
8462 if (FD->isFunctionTemplateSpecialization())
8463 return false;
8464
8465 // Don't warn for OpenCL kernels.
8466 if (FD->hasAttr<OpenCLKernelAttr>())
8467 return false;
8468
8469 bool MissingPrototype = true;
8470 for (const FunctionDecl *Prev = FD->getPreviousDecl();
8471 Prev; Prev = Prev->getPreviousDecl()) {
8472 // Ignore any declarations that occur in function or method
8473 // scope, because they aren't visible from the header.
8474 if (Prev->getDeclContext()->isFunctionOrMethod())
8475 continue;
8476
8477 MissingPrototype = !Prev->getType()->isFunctionProtoType();
8478 if (FD->getNumParams() == 0)
8479 PossibleZeroParamPrototype = Prev;
8480 break;
8481 }
8482
8483 return MissingPrototype;
8484 }
8485
CheckForFunctionRedefinition(FunctionDecl * FD)8486 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
8487 // Don't complain if we're in GNU89 mode and the previous definition
8488 // was an extern inline function.
8489 const FunctionDecl *Definition;
8490 if (FD->isDefined(Definition) &&
8491 !canRedefineFunction(Definition, getLangOpts())) {
8492 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
8493 Definition->getStorageClass() == SC_Extern)
8494 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
8495 << FD->getDeclName() << getLangOpts().CPlusPlus;
8496 else
8497 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
8498 Diag(Definition->getLocation(), diag::note_previous_definition);
8499 FD->setInvalidDecl();
8500 }
8501 }
8502
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D)8503 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
8504 // Clear the last template instantiation error context.
8505 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
8506
8507 if (!D)
8508 return D;
8509 FunctionDecl *FD = 0;
8510
8511 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
8512 FD = FunTmpl->getTemplatedDecl();
8513 else
8514 FD = cast<FunctionDecl>(D);
8515
8516 // Enter a new function scope
8517 PushFunctionScope();
8518
8519 // See if this is a redefinition.
8520 if (!FD->isLateTemplateParsed())
8521 CheckForFunctionRedefinition(FD);
8522
8523 // Builtin functions cannot be defined.
8524 if (unsigned BuiltinID = FD->getBuiltinID()) {
8525 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
8526 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
8527 FD->setInvalidDecl();
8528 }
8529 }
8530
8531 // The return type of a function definition must be complete
8532 // (C99 6.9.1p3, C++ [dcl.fct]p6).
8533 QualType ResultType = FD->getResultType();
8534 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
8535 !FD->isInvalidDecl() &&
8536 RequireCompleteType(FD->getLocation(), ResultType,
8537 diag::err_func_def_incomplete_result))
8538 FD->setInvalidDecl();
8539
8540 // GNU warning -Wmissing-prototypes:
8541 // Warn if a global function is defined without a previous
8542 // prototype declaration. This warning is issued even if the
8543 // definition itself provides a prototype. The aim is to detect
8544 // global functions that fail to be declared in header files.
8545 const FunctionDecl *PossibleZeroParamPrototype = 0;
8546 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
8547 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
8548
8549 if (PossibleZeroParamPrototype) {
8550 // We found a declaration that is not a prototype,
8551 // but that could be a zero-parameter prototype
8552 TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo();
8553 TypeLoc TL = TI->getTypeLoc();
8554 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
8555 Diag(PossibleZeroParamPrototype->getLocation(),
8556 diag::note_declaration_not_a_prototype)
8557 << PossibleZeroParamPrototype
8558 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
8559 }
8560 }
8561
8562 if (FnBodyScope)
8563 PushDeclContext(FnBodyScope, FD);
8564
8565 // Check the validity of our function parameters
8566 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
8567 /*CheckParameterNames=*/true);
8568
8569 // Introduce our parameters into the function scope
8570 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
8571 ParmVarDecl *Param = FD->getParamDecl(p);
8572 Param->setOwningFunction(FD);
8573
8574 // If this has an identifier, add it to the scope stack.
8575 if (Param->getIdentifier() && FnBodyScope) {
8576 CheckShadow(FnBodyScope, Param);
8577
8578 PushOnScopeChains(Param, FnBodyScope);
8579 }
8580 }
8581
8582 // If we had any tags defined in the function prototype,
8583 // introduce them into the function scope.
8584 if (FnBodyScope) {
8585 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
8586 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
8587 NamedDecl *D = *I;
8588
8589 // Some of these decls (like enums) may have been pinned to the translation unit
8590 // for lack of a real context earlier. If so, remove from the translation unit
8591 // and reattach to the current context.
8592 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
8593 // Is the decl actually in the context?
8594 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
8595 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
8596 if (*DI == D) {
8597 Context.getTranslationUnitDecl()->removeDecl(D);
8598 break;
8599 }
8600 }
8601 // Either way, reassign the lexical decl context to our FunctionDecl.
8602 D->setLexicalDeclContext(CurContext);
8603 }
8604
8605 // If the decl has a non-null name, make accessible in the current scope.
8606 if (!D->getName().empty())
8607 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
8608
8609 // Similarly, dive into enums and fish their constants out, making them
8610 // accessible in this scope.
8611 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
8612 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
8613 EE = ED->enumerator_end(); EI != EE; ++EI)
8614 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
8615 }
8616 }
8617 }
8618
8619 // Ensure that the function's exception specification is instantiated.
8620 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
8621 ResolveExceptionSpec(D->getLocation(), FPT);
8622
8623 // Checking attributes of current function definition
8624 // dllimport attribute.
8625 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
8626 if (DA && (!FD->getAttr<DLLExportAttr>())) {
8627 // dllimport attribute cannot be directly applied to definition.
8628 // Microsoft accepts dllimport for functions defined within class scope.
8629 if (!DA->isInherited() &&
8630 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
8631 Diag(FD->getLocation(),
8632 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
8633 << "dllimport";
8634 FD->setInvalidDecl();
8635 return D;
8636 }
8637
8638 // Visual C++ appears to not think this is an issue, so only issue
8639 // a warning when Microsoft extensions are disabled.
8640 if (!LangOpts.MicrosoftExt) {
8641 // If a symbol previously declared dllimport is later defined, the
8642 // attribute is ignored in subsequent references, and a warning is
8643 // emitted.
8644 Diag(FD->getLocation(),
8645 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
8646 << FD->getName() << "dllimport";
8647 }
8648 }
8649 // We want to attach documentation to original Decl (which might be
8650 // a function template).
8651 ActOnDocumentableDecl(D);
8652 return D;
8653 }
8654
8655 /// \brief Given the set of return statements within a function body,
8656 /// compute the variables that are subject to the named return value
8657 /// optimization.
8658 ///
8659 /// Each of the variables that is subject to the named return value
8660 /// optimization will be marked as NRVO variables in the AST, and any
8661 /// return statement that has a marked NRVO variable as its NRVO candidate can
8662 /// use the named return value optimization.
8663 ///
8664 /// This function applies a very simplistic algorithm for NRVO: if every return
8665 /// statement in the function has the same NRVO candidate, that candidate is
8666 /// the NRVO variable.
8667 ///
8668 /// FIXME: Employ a smarter algorithm that accounts for multiple return
8669 /// statements and the lifetimes of the NRVO candidates. We should be able to
8670 /// find a maximal set of NRVO variables.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)8671 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
8672 ReturnStmt **Returns = Scope->Returns.data();
8673
8674 const VarDecl *NRVOCandidate = 0;
8675 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
8676 if (!Returns[I]->getNRVOCandidate())
8677 return;
8678
8679 if (!NRVOCandidate)
8680 NRVOCandidate = Returns[I]->getNRVOCandidate();
8681 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
8682 return;
8683 }
8684
8685 if (NRVOCandidate)
8686 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
8687 }
8688
canSkipFunctionBody(Decl * D)8689 bool Sema::canSkipFunctionBody(Decl *D) {
8690 if (!Consumer.shouldSkipFunctionBody(D))
8691 return false;
8692
8693 if (isa<ObjCMethodDecl>(D))
8694 return true;
8695
8696 FunctionDecl *FD = 0;
8697 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
8698 FD = FTD->getTemplatedDecl();
8699 else
8700 FD = cast<FunctionDecl>(D);
8701
8702 // We cannot skip the body of a function (or function template) which is
8703 // constexpr, since we may need to evaluate its body in order to parse the
8704 // rest of the file.
8705 return !FD->isConstexpr();
8706 }
8707
ActOnSkippedFunctionBody(Decl * Decl)8708 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
8709 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
8710 FD->setHasSkippedBody();
8711 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
8712 MD->setHasSkippedBody();
8713 return ActOnFinishFunctionBody(Decl, 0);
8714 }
8715
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)8716 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
8717 return ActOnFinishFunctionBody(D, BodyArg, false);
8718 }
8719
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)8720 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
8721 bool IsInstantiation) {
8722 FunctionDecl *FD = 0;
8723 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
8724 if (FunTmpl)
8725 FD = FunTmpl->getTemplatedDecl();
8726 else
8727 FD = dyn_cast_or_null<FunctionDecl>(dcl);
8728
8729 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
8730 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
8731
8732 if (FD) {
8733 FD->setBody(Body);
8734
8735 // The only way to be included in UndefinedButUsed is if there is an
8736 // ODR use before the definition. Avoid the expensive map lookup if this
8737 // is the first declaration.
8738 if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) {
8739 if (FD->getLinkage() != ExternalLinkage)
8740 UndefinedButUsed.erase(FD);
8741 else if (FD->isInlined() &&
8742 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
8743 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
8744 UndefinedButUsed.erase(FD);
8745 }
8746
8747 // If the function implicitly returns zero (like 'main') or is naked,
8748 // don't complain about missing return statements.
8749 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
8750 WP.disableCheckFallThrough();
8751
8752 // MSVC permits the use of pure specifier (=0) on function definition,
8753 // defined at class scope, warn about this non standard construct.
8754 if (getLangOpts().MicrosoftExt && FD->isPure())
8755 Diag(FD->getLocation(), diag::warn_pure_function_definition);
8756
8757 if (!FD->isInvalidDecl()) {
8758 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
8759 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
8760 FD->getResultType(), FD);
8761
8762 // If this is a constructor, we need a vtable.
8763 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
8764 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
8765
8766 // Try to apply the named return value optimization. We have to check
8767 // if we can do this here because lambdas keep return statements around
8768 // to deduce an implicit return type.
8769 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
8770 !FD->isDependentContext())
8771 computeNRVO(Body, getCurFunction());
8772 }
8773
8774 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
8775 "Function parsing confused");
8776 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
8777 assert(MD == getCurMethodDecl() && "Method parsing confused");
8778 MD->setBody(Body);
8779 if (!MD->isInvalidDecl()) {
8780 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
8781 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
8782 MD->getResultType(), MD);
8783
8784 if (Body)
8785 computeNRVO(Body, getCurFunction());
8786 }
8787 if (getCurFunction()->ObjCShouldCallSuper) {
8788 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
8789 << MD->getSelector().getAsString();
8790 getCurFunction()->ObjCShouldCallSuper = false;
8791 }
8792 } else {
8793 return 0;
8794 }
8795
8796 assert(!getCurFunction()->ObjCShouldCallSuper &&
8797 "This should only be set for ObjC methods, which should have been "
8798 "handled in the block above.");
8799
8800 // Verify and clean out per-function state.
8801 if (Body) {
8802 // C++ constructors that have function-try-blocks can't have return
8803 // statements in the handlers of that block. (C++ [except.handle]p14)
8804 // Verify this.
8805 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
8806 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
8807
8808 // Verify that gotos and switch cases don't jump into scopes illegally.
8809 if (getCurFunction()->NeedsScopeChecking() &&
8810 !dcl->isInvalidDecl() &&
8811 !hasAnyUnrecoverableErrorsInThisFunction() &&
8812 !PP.isCodeCompletionEnabled())
8813 DiagnoseInvalidJumps(Body);
8814
8815 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
8816 if (!Destructor->getParent()->isDependentType())
8817 CheckDestructor(Destructor);
8818
8819 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8820 Destructor->getParent());
8821 }
8822
8823 // If any errors have occurred, clear out any temporaries that may have
8824 // been leftover. This ensures that these temporaries won't be picked up for
8825 // deletion in some later function.
8826 if (PP.getDiagnostics().hasErrorOccurred() ||
8827 PP.getDiagnostics().getSuppressAllDiagnostics()) {
8828 DiscardCleanupsInEvaluationContext();
8829 }
8830 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
8831 !isa<FunctionTemplateDecl>(dcl)) {
8832 // Since the body is valid, issue any analysis-based warnings that are
8833 // enabled.
8834 ActivePolicy = &WP;
8835 }
8836
8837 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
8838 (!CheckConstexprFunctionDecl(FD) ||
8839 !CheckConstexprFunctionBody(FD, Body)))
8840 FD->setInvalidDecl();
8841
8842 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
8843 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
8844 assert(MaybeODRUseExprs.empty() &&
8845 "Leftover expressions for odr-use checking");
8846 }
8847
8848 if (!IsInstantiation)
8849 PopDeclContext();
8850
8851 PopFunctionScopeInfo(ActivePolicy, dcl);
8852
8853 // If any errors have occurred, clear out any temporaries that may have
8854 // been leftover. This ensures that these temporaries won't be picked up for
8855 // deletion in some later function.
8856 if (getDiagnostics().hasErrorOccurred()) {
8857 DiscardCleanupsInEvaluationContext();
8858 }
8859
8860 return dcl;
8861 }
8862
8863
8864 /// When we finish delayed parsing of an attribute, we must attach it to the
8865 /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)8866 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
8867 ParsedAttributes &Attrs) {
8868 // Always attach attributes to the underlying decl.
8869 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8870 D = TD->getTemplatedDecl();
8871 ProcessDeclAttributeList(S, D, Attrs.getList());
8872
8873 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
8874 if (Method->isStatic())
8875 checkThisInStaticMemberFunctionAttributes(Method);
8876 }
8877
8878
8879 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
8880 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)8881 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
8882 IdentifierInfo &II, Scope *S) {
8883 // Before we produce a declaration for an implicitly defined
8884 // function, see whether there was a locally-scoped declaration of
8885 // this name as a function or variable. If so, use that
8886 // (non-visible) declaration, and complain about it.
8887 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
8888 = findLocallyScopedExternCDecl(&II);
8889 if (Pos != LocallyScopedExternCDecls.end()) {
8890 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
8891 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
8892 return Pos->second;
8893 }
8894
8895 // Extension in C99. Legal in C90, but warn about it.
8896 unsigned diag_id;
8897 if (II.getName().startswith("__builtin_"))
8898 diag_id = diag::warn_builtin_unknown;
8899 else if (getLangOpts().C99)
8900 diag_id = diag::ext_implicit_function_decl;
8901 else
8902 diag_id = diag::warn_implicit_function_decl;
8903 Diag(Loc, diag_id) << &II;
8904
8905 // Because typo correction is expensive, only do it if the implicit
8906 // function declaration is going to be treated as an error.
8907 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
8908 TypoCorrection Corrected;
8909 DeclFilterCCC<FunctionDecl> Validator;
8910 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
8911 LookupOrdinaryName, S, 0, Validator))) {
8912 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
8913 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
8914 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
8915
8916 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
8917 << FixItHint::CreateReplacement(Loc, CorrectedStr);
8918
8919 if (Func->getLocation().isValid()
8920 && !II.getName().startswith("__builtin_"))
8921 Diag(Func->getLocation(), diag::note_previous_decl)
8922 << CorrectedQuotedStr;
8923 }
8924 }
8925
8926 // Set a Declarator for the implicit definition: int foo();
8927 const char *Dummy;
8928 AttributeFactory attrFactory;
8929 DeclSpec DS(attrFactory);
8930 unsigned DiagID;
8931 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
8932 (void)Error; // Silence warning.
8933 assert(!Error && "Error setting up implicit decl!");
8934 SourceLocation NoLoc;
8935 Declarator D(DS, Declarator::BlockContext);
8936 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
8937 /*IsAmbiguous=*/false,
8938 /*RParenLoc=*/NoLoc,
8939 /*ArgInfo=*/0,
8940 /*NumArgs=*/0,
8941 /*EllipsisLoc=*/NoLoc,
8942 /*RParenLoc=*/NoLoc,
8943 /*TypeQuals=*/0,
8944 /*RefQualifierIsLvalueRef=*/true,
8945 /*RefQualifierLoc=*/NoLoc,
8946 /*ConstQualifierLoc=*/NoLoc,
8947 /*VolatileQualifierLoc=*/NoLoc,
8948 /*MutableLoc=*/NoLoc,
8949 EST_None,
8950 /*ESpecLoc=*/NoLoc,
8951 /*Exceptions=*/0,
8952 /*ExceptionRanges=*/0,
8953 /*NumExceptions=*/0,
8954 /*NoexceptExpr=*/0,
8955 Loc, Loc, D),
8956 DS.getAttributes(),
8957 SourceLocation());
8958 D.SetIdentifier(&II, Loc);
8959
8960 // Insert this function into translation-unit scope.
8961
8962 DeclContext *PrevDC = CurContext;
8963 CurContext = Context.getTranslationUnitDecl();
8964
8965 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
8966 FD->setImplicit();
8967
8968 CurContext = PrevDC;
8969
8970 AddKnownFunctionAttributes(FD);
8971
8972 return FD;
8973 }
8974
8975 /// \brief Adds any function attributes that we know a priori based on
8976 /// the declaration of this function.
8977 ///
8978 /// These attributes can apply both to implicitly-declared builtins
8979 /// (like __builtin___printf_chk) or to library-declared functions
8980 /// like NSLog or printf.
8981 ///
8982 /// We need to check for duplicate attributes both here and where user-written
8983 /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)8984 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
8985 if (FD->isInvalidDecl())
8986 return;
8987
8988 // If this is a built-in function, map its builtin attributes to
8989 // actual attributes.
8990 if (unsigned BuiltinID = FD->getBuiltinID()) {
8991 // Handle printf-formatting attributes.
8992 unsigned FormatIdx;
8993 bool HasVAListArg;
8994 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
8995 if (!FD->getAttr<FormatAttr>()) {
8996 const char *fmt = "printf";
8997 unsigned int NumParams = FD->getNumParams();
8998 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
8999 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9000 fmt = "NSString";
9001 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9002 fmt, FormatIdx+1,
9003 HasVAListArg ? 0 : FormatIdx+2));
9004 }
9005 }
9006 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9007 HasVAListArg)) {
9008 if (!FD->getAttr<FormatAttr>())
9009 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9010 "scanf", FormatIdx+1,
9011 HasVAListArg ? 0 : FormatIdx+2));
9012 }
9013
9014 // Mark const if we don't care about errno and that is the only
9015 // thing preventing the function from being const. This allows
9016 // IRgen to use LLVM intrinsics for such functions.
9017 if (!getLangOpts().MathErrno &&
9018 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
9019 if (!FD->getAttr<ConstAttr>())
9020 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
9021 }
9022
9023 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
9024 !FD->getAttr<ReturnsTwiceAttr>())
9025 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
9026 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
9027 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
9028 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
9029 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
9030 }
9031
9032 IdentifierInfo *Name = FD->getIdentifier();
9033 if (!Name)
9034 return;
9035 if ((!getLangOpts().CPlusPlus &&
9036 FD->getDeclContext()->isTranslationUnit()) ||
9037 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
9038 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
9039 LinkageSpecDecl::lang_c)) {
9040 // Okay: this could be a libc/libm/Objective-C function we know
9041 // about.
9042 } else
9043 return;
9044
9045 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
9046 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
9047 // target-specific builtins, perhaps?
9048 if (!FD->getAttr<FormatAttr>())
9049 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9050 "printf", 2,
9051 Name->isStr("vasprintf") ? 0 : 3));
9052 }
9053
9054 if (Name->isStr("__CFStringMakeConstantString")) {
9055 // We already have a __builtin___CFStringMakeConstantString,
9056 // but builds that use -fno-constant-cfstrings don't go through that.
9057 if (!FD->getAttr<FormatArgAttr>())
9058 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
9059 }
9060 }
9061
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)9062 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
9063 TypeSourceInfo *TInfo) {
9064 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
9065 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
9066
9067 if (!TInfo) {
9068 assert(D.isInvalidType() && "no declarator info for valid type");
9069 TInfo = Context.getTrivialTypeSourceInfo(T);
9070 }
9071
9072 // Scope manipulation handled by caller.
9073 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
9074 D.getLocStart(),
9075 D.getIdentifierLoc(),
9076 D.getIdentifier(),
9077 TInfo);
9078
9079 // Bail out immediately if we have an invalid declaration.
9080 if (D.isInvalidType()) {
9081 NewTD->setInvalidDecl();
9082 return NewTD;
9083 }
9084
9085 if (D.getDeclSpec().isModulePrivateSpecified()) {
9086 if (CurContext->isFunctionOrMethod())
9087 Diag(NewTD->getLocation(), diag::err_module_private_local)
9088 << 2 << NewTD->getDeclName()
9089 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9090 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9091 else
9092 NewTD->setModulePrivate();
9093 }
9094
9095 // C++ [dcl.typedef]p8:
9096 // If the typedef declaration defines an unnamed class (or
9097 // enum), the first typedef-name declared by the declaration
9098 // to be that class type (or enum type) is used to denote the
9099 // class type (or enum type) for linkage purposes only.
9100 // We need to check whether the type was declared in the declaration.
9101 switch (D.getDeclSpec().getTypeSpecType()) {
9102 case TST_enum:
9103 case TST_struct:
9104 case TST_interface:
9105 case TST_union:
9106 case TST_class: {
9107 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
9108
9109 // Do nothing if the tag is not anonymous or already has an
9110 // associated typedef (from an earlier typedef in this decl group).
9111 if (tagFromDeclSpec->getIdentifier()) break;
9112 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
9113
9114 // A well-formed anonymous tag must always be a TUK_Definition.
9115 assert(tagFromDeclSpec->isThisDeclarationADefinition());
9116
9117 // The type must match the tag exactly; no qualifiers allowed.
9118 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
9119 break;
9120
9121 // Otherwise, set this is the anon-decl typedef for the tag.
9122 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
9123 break;
9124 }
9125
9126 default:
9127 break;
9128 }
9129
9130 return NewTD;
9131 }
9132
9133
9134 /// \brief Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)9135 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
9136 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
9137 QualType T = TI->getType();
9138
9139 if (T->isDependentType())
9140 return false;
9141
9142 if (const BuiltinType *BT = T->getAs<BuiltinType>())
9143 if (BT->isInteger())
9144 return false;
9145
9146 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
9147 return true;
9148 }
9149
9150 /// Check whether this is a valid redeclaration of a previous enumeration.
9151 /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,const EnumDecl * Prev)9152 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
9153 QualType EnumUnderlyingTy,
9154 const EnumDecl *Prev) {
9155 bool IsFixed = !EnumUnderlyingTy.isNull();
9156
9157 if (IsScoped != Prev->isScoped()) {
9158 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
9159 << Prev->isScoped();
9160 Diag(Prev->getLocation(), diag::note_previous_use);
9161 return true;
9162 }
9163
9164 if (IsFixed && Prev->isFixed()) {
9165 if (!EnumUnderlyingTy->isDependentType() &&
9166 !Prev->getIntegerType()->isDependentType() &&
9167 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
9168 Prev->getIntegerType())) {
9169 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
9170 << EnumUnderlyingTy << Prev->getIntegerType();
9171 Diag(Prev->getLocation(), diag::note_previous_use);
9172 return true;
9173 }
9174 } else if (IsFixed != Prev->isFixed()) {
9175 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
9176 << Prev->isFixed();
9177 Diag(Prev->getLocation(), diag::note_previous_use);
9178 return true;
9179 }
9180
9181 return false;
9182 }
9183
9184 /// \brief Get diagnostic %select index for tag kind for
9185 /// redeclaration diagnostic message.
9186 /// WARNING: Indexes apply to particular diagnostics only!
9187 ///
9188 /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)9189 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
9190 switch (Tag) {
9191 case TTK_Struct: return 0;
9192 case TTK_Interface: return 1;
9193 case TTK_Class: return 2;
9194 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
9195 }
9196 }
9197
9198 /// \brief Determine if tag kind is a class-key compatible with
9199 /// class for redeclaration (class, struct, or __interface).
9200 ///
9201 /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)9202 static bool isClassCompatTagKind(TagTypeKind Tag)
9203 {
9204 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
9205 }
9206
9207 /// \brief Determine whether a tag with a given kind is acceptable
9208 /// as a redeclaration of the given tag declaration.
9209 ///
9210 /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo & Name)9211 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
9212 TagTypeKind NewTag, bool isDefinition,
9213 SourceLocation NewTagLoc,
9214 const IdentifierInfo &Name) {
9215 // C++ [dcl.type.elab]p3:
9216 // The class-key or enum keyword present in the
9217 // elaborated-type-specifier shall agree in kind with the
9218 // declaration to which the name in the elaborated-type-specifier
9219 // refers. This rule also applies to the form of
9220 // elaborated-type-specifier that declares a class-name or
9221 // friend class since it can be construed as referring to the
9222 // definition of the class. Thus, in any
9223 // elaborated-type-specifier, the enum keyword shall be used to
9224 // refer to an enumeration (7.2), the union class-key shall be
9225 // used to refer to a union (clause 9), and either the class or
9226 // struct class-key shall be used to refer to a class (clause 9)
9227 // declared using the class or struct class-key.
9228 TagTypeKind OldTag = Previous->getTagKind();
9229 if (!isDefinition || !isClassCompatTagKind(NewTag))
9230 if (OldTag == NewTag)
9231 return true;
9232
9233 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
9234 // Warn about the struct/class tag mismatch.
9235 bool isTemplate = false;
9236 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
9237 isTemplate = Record->getDescribedClassTemplate();
9238
9239 if (!ActiveTemplateInstantiations.empty()) {
9240 // In a template instantiation, do not offer fix-its for tag mismatches
9241 // since they usually mess up the template instead of fixing the problem.
9242 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
9243 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
9244 << getRedeclDiagFromTagKind(OldTag);
9245 return true;
9246 }
9247
9248 if (isDefinition) {
9249 // On definitions, check previous tags and issue a fix-it for each
9250 // one that doesn't match the current tag.
9251 if (Previous->getDefinition()) {
9252 // Don't suggest fix-its for redefinitions.
9253 return true;
9254 }
9255
9256 bool previousMismatch = false;
9257 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
9258 E(Previous->redecls_end()); I != E; ++I) {
9259 if (I->getTagKind() != NewTag) {
9260 if (!previousMismatch) {
9261 previousMismatch = true;
9262 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
9263 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
9264 << getRedeclDiagFromTagKind(I->getTagKind());
9265 }
9266 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
9267 << getRedeclDiagFromTagKind(NewTag)
9268 << FixItHint::CreateReplacement(I->getInnerLocStart(),
9269 TypeWithKeyword::getTagTypeKindName(NewTag));
9270 }
9271 }
9272 return true;
9273 }
9274
9275 // Check for a previous definition. If current tag and definition
9276 // are same type, do nothing. If no definition, but disagree with
9277 // with previous tag type, give a warning, but no fix-it.
9278 const TagDecl *Redecl = Previous->getDefinition() ?
9279 Previous->getDefinition() : Previous;
9280 if (Redecl->getTagKind() == NewTag) {
9281 return true;
9282 }
9283
9284 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
9285 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
9286 << getRedeclDiagFromTagKind(OldTag);
9287 Diag(Redecl->getLocation(), diag::note_previous_use);
9288
9289 // If there is a previous defintion, suggest a fix-it.
9290 if (Previous->getDefinition()) {
9291 Diag(NewTagLoc, diag::note_struct_class_suggestion)
9292 << getRedeclDiagFromTagKind(Redecl->getTagKind())
9293 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
9294 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
9295 }
9296
9297 return true;
9298 }
9299 return false;
9300 }
9301
9302 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
9303 /// former case, Name will be non-null. In the later case, Name will be null.
9304 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
9305 /// reference/declaration/definition of a tag.
ActOnTag(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,AccessSpecifier AS,SourceLocation ModulePrivateLoc,MultiTemplateParamsArg TemplateParameterLists,bool & OwnedDecl,bool & IsDependent,SourceLocation ScopedEnumKWLoc,bool ScopedEnumUsesClassTag,TypeResult UnderlyingType)9306 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9307 SourceLocation KWLoc, CXXScopeSpec &SS,
9308 IdentifierInfo *Name, SourceLocation NameLoc,
9309 AttributeList *Attr, AccessSpecifier AS,
9310 SourceLocation ModulePrivateLoc,
9311 MultiTemplateParamsArg TemplateParameterLists,
9312 bool &OwnedDecl, bool &IsDependent,
9313 SourceLocation ScopedEnumKWLoc,
9314 bool ScopedEnumUsesClassTag,
9315 TypeResult UnderlyingType) {
9316 // If this is not a definition, it must have a name.
9317 IdentifierInfo *OrigName = Name;
9318 assert((Name != 0 || TUK == TUK_Definition) &&
9319 "Nameless record must be a definition!");
9320 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
9321
9322 OwnedDecl = false;
9323 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9324 bool ScopedEnum = ScopedEnumKWLoc.isValid();
9325
9326 // FIXME: Check explicit specializations more carefully.
9327 bool isExplicitSpecialization = false;
9328 bool Invalid = false;
9329
9330 // We only need to do this matching if we have template parameters
9331 // or a scope specifier, which also conveniently avoids this work
9332 // for non-C++ cases.
9333 if (TemplateParameterLists.size() > 0 ||
9334 (SS.isNotEmpty() && TUK != TUK_Reference)) {
9335 if (TemplateParameterList *TemplateParams
9336 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
9337 TemplateParameterLists.data(),
9338 TemplateParameterLists.size(),
9339 TUK == TUK_Friend,
9340 isExplicitSpecialization,
9341 Invalid)) {
9342 if (TemplateParams->size() > 0) {
9343 // This is a declaration or definition of a class template (which may
9344 // be a member of another template).
9345
9346 if (Invalid)
9347 return 0;
9348
9349 OwnedDecl = false;
9350 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
9351 SS, Name, NameLoc, Attr,
9352 TemplateParams, AS,
9353 ModulePrivateLoc,
9354 TemplateParameterLists.size()-1,
9355 TemplateParameterLists.data());
9356 return Result.get();
9357 } else {
9358 // The "template<>" header is extraneous.
9359 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9360 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9361 isExplicitSpecialization = true;
9362 }
9363 }
9364 }
9365
9366 // Figure out the underlying type if this a enum declaration. We need to do
9367 // this early, because it's needed to detect if this is an incompatible
9368 // redeclaration.
9369 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
9370
9371 if (Kind == TTK_Enum) {
9372 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
9373 // No underlying type explicitly specified, or we failed to parse the
9374 // type, default to int.
9375 EnumUnderlying = Context.IntTy.getTypePtr();
9376 else if (UnderlyingType.get()) {
9377 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
9378 // integral type; any cv-qualification is ignored.
9379 TypeSourceInfo *TI = 0;
9380 GetTypeFromParser(UnderlyingType.get(), &TI);
9381 EnumUnderlying = TI;
9382
9383 if (CheckEnumUnderlyingType(TI))
9384 // Recover by falling back to int.
9385 EnumUnderlying = Context.IntTy.getTypePtr();
9386
9387 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
9388 UPPC_FixedUnderlyingType))
9389 EnumUnderlying = Context.IntTy.getTypePtr();
9390
9391 } else if (getLangOpts().MicrosoftMode)
9392 // Microsoft enums are always of int type.
9393 EnumUnderlying = Context.IntTy.getTypePtr();
9394 }
9395
9396 DeclContext *SearchDC = CurContext;
9397 DeclContext *DC = CurContext;
9398 bool isStdBadAlloc = false;
9399
9400 RedeclarationKind Redecl = ForRedeclaration;
9401 if (TUK == TUK_Friend || TUK == TUK_Reference)
9402 Redecl = NotForRedeclaration;
9403
9404 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
9405
9406 if (Name && SS.isNotEmpty()) {
9407 // We have a nested-name tag ('struct foo::bar').
9408
9409 // Check for invalid 'foo::'.
9410 if (SS.isInvalid()) {
9411 Name = 0;
9412 goto CreateNewDecl;
9413 }
9414
9415 // If this is a friend or a reference to a class in a dependent
9416 // context, don't try to make a decl for it.
9417 if (TUK == TUK_Friend || TUK == TUK_Reference) {
9418 DC = computeDeclContext(SS, false);
9419 if (!DC) {
9420 IsDependent = true;
9421 return 0;
9422 }
9423 } else {
9424 DC = computeDeclContext(SS, true);
9425 if (!DC) {
9426 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
9427 << SS.getRange();
9428 return 0;
9429 }
9430 }
9431
9432 if (RequireCompleteDeclContext(SS, DC))
9433 return 0;
9434
9435 SearchDC = DC;
9436 // Look-up name inside 'foo::'.
9437 LookupQualifiedName(Previous, DC);
9438
9439 if (Previous.isAmbiguous())
9440 return 0;
9441
9442 if (Previous.empty()) {
9443 // Name lookup did not find anything. However, if the
9444 // nested-name-specifier refers to the current instantiation,
9445 // and that current instantiation has any dependent base
9446 // classes, we might find something at instantiation time: treat
9447 // this as a dependent elaborated-type-specifier.
9448 // But this only makes any sense for reference-like lookups.
9449 if (Previous.wasNotFoundInCurrentInstantiation() &&
9450 (TUK == TUK_Reference || TUK == TUK_Friend)) {
9451 IsDependent = true;
9452 return 0;
9453 }
9454
9455 // A tag 'foo::bar' must already exist.
9456 Diag(NameLoc, diag::err_not_tag_in_scope)
9457 << Kind << Name << DC << SS.getRange();
9458 Name = 0;
9459 Invalid = true;
9460 goto CreateNewDecl;
9461 }
9462 } else if (Name) {
9463 // If this is a named struct, check to see if there was a previous forward
9464 // declaration or definition.
9465 // FIXME: We're looking into outer scopes here, even when we
9466 // shouldn't be. Doing so can result in ambiguities that we
9467 // shouldn't be diagnosing.
9468 LookupName(Previous, S);
9469
9470 if (Previous.isAmbiguous() &&
9471 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
9472 LookupResult::Filter F = Previous.makeFilter();
9473 while (F.hasNext()) {
9474 NamedDecl *ND = F.next();
9475 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
9476 F.erase();
9477 }
9478 F.done();
9479 }
9480
9481 // Note: there used to be some attempt at recovery here.
9482 if (Previous.isAmbiguous())
9483 return 0;
9484
9485 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
9486 // FIXME: This makes sure that we ignore the contexts associated
9487 // with C structs, unions, and enums when looking for a matching
9488 // tag declaration or definition. See the similar lookup tweak
9489 // in Sema::LookupName; is there a better way to deal with this?
9490 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
9491 SearchDC = SearchDC->getParent();
9492 }
9493 } else if (S->isFunctionPrototypeScope()) {
9494 // If this is an enum declaration in function prototype scope, set its
9495 // initial context to the translation unit.
9496 // FIXME: [citation needed]
9497 SearchDC = Context.getTranslationUnitDecl();
9498 }
9499
9500 if (Previous.isSingleResult() &&
9501 Previous.getFoundDecl()->isTemplateParameter()) {
9502 // Maybe we will complain about the shadowed template parameter.
9503 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
9504 // Just pretend that we didn't see the previous declaration.
9505 Previous.clear();
9506 }
9507
9508 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
9509 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
9510 // This is a declaration of or a reference to "std::bad_alloc".
9511 isStdBadAlloc = true;
9512
9513 if (Previous.empty() && StdBadAlloc) {
9514 // std::bad_alloc has been implicitly declared (but made invisible to
9515 // name lookup). Fill in this implicit declaration as the previous
9516 // declaration, so that the declarations get chained appropriately.
9517 Previous.addDecl(getStdBadAlloc());
9518 }
9519 }
9520
9521 // If we didn't find a previous declaration, and this is a reference
9522 // (or friend reference), move to the correct scope. In C++, we
9523 // also need to do a redeclaration lookup there, just in case
9524 // there's a shadow friend decl.
9525 if (Name && Previous.empty() &&
9526 (TUK == TUK_Reference || TUK == TUK_Friend)) {
9527 if (Invalid) goto CreateNewDecl;
9528 assert(SS.isEmpty());
9529
9530 if (TUK == TUK_Reference) {
9531 // C++ [basic.scope.pdecl]p5:
9532 // -- for an elaborated-type-specifier of the form
9533 //
9534 // class-key identifier
9535 //
9536 // if the elaborated-type-specifier is used in the
9537 // decl-specifier-seq or parameter-declaration-clause of a
9538 // function defined in namespace scope, the identifier is
9539 // declared as a class-name in the namespace that contains
9540 // the declaration; otherwise, except as a friend
9541 // declaration, the identifier is declared in the smallest
9542 // non-class, non-function-prototype scope that contains the
9543 // declaration.
9544 //
9545 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
9546 // C structs and unions.
9547 //
9548 // It is an error in C++ to declare (rather than define) an enum
9549 // type, including via an elaborated type specifier. We'll
9550 // diagnose that later; for now, declare the enum in the same
9551 // scope as we would have picked for any other tag type.
9552 //
9553 // GNU C also supports this behavior as part of its incomplete
9554 // enum types extension, while GNU C++ does not.
9555 //
9556 // Find the context where we'll be declaring the tag.
9557 // FIXME: We would like to maintain the current DeclContext as the
9558 // lexical context,
9559 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
9560 SearchDC = SearchDC->getParent();
9561
9562 // Find the scope where we'll be declaring the tag.
9563 while (S->isClassScope() ||
9564 (getLangOpts().CPlusPlus &&
9565 S->isFunctionPrototypeScope()) ||
9566 ((S->getFlags() & Scope::DeclScope) == 0) ||
9567 (S->getEntity() &&
9568 ((DeclContext *)S->getEntity())->isTransparentContext()))
9569 S = S->getParent();
9570 } else {
9571 assert(TUK == TUK_Friend);
9572 // C++ [namespace.memdef]p3:
9573 // If a friend declaration in a non-local class first declares a
9574 // class or function, the friend class or function is a member of
9575 // the innermost enclosing namespace.
9576 SearchDC = SearchDC->getEnclosingNamespaceContext();
9577 }
9578
9579 // In C++, we need to do a redeclaration lookup to properly
9580 // diagnose some problems.
9581 if (getLangOpts().CPlusPlus) {
9582 Previous.setRedeclarationKind(ForRedeclaration);
9583 LookupQualifiedName(Previous, SearchDC);
9584 }
9585 }
9586
9587 if (!Previous.empty()) {
9588 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
9589
9590 // It's okay to have a tag decl in the same scope as a typedef
9591 // which hides a tag decl in the same scope. Finding this
9592 // insanity with a redeclaration lookup can only actually happen
9593 // in C++.
9594 //
9595 // This is also okay for elaborated-type-specifiers, which is
9596 // technically forbidden by the current standard but which is
9597 // okay according to the likely resolution of an open issue;
9598 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
9599 if (getLangOpts().CPlusPlus) {
9600 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9601 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
9602 TagDecl *Tag = TT->getDecl();
9603 if (Tag->getDeclName() == Name &&
9604 Tag->getDeclContext()->getRedeclContext()
9605 ->Equals(TD->getDeclContext()->getRedeclContext())) {
9606 PrevDecl = Tag;
9607 Previous.clear();
9608 Previous.addDecl(Tag);
9609 Previous.resolveKind();
9610 }
9611 }
9612 }
9613 }
9614
9615 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
9616 // If this is a use of a previous tag, or if the tag is already declared
9617 // in the same scope (so that the definition/declaration completes or
9618 // rementions the tag), reuse the decl.
9619 if (TUK == TUK_Reference || TUK == TUK_Friend ||
9620 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
9621 // Make sure that this wasn't declared as an enum and now used as a
9622 // struct or something similar.
9623 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
9624 TUK == TUK_Definition, KWLoc,
9625 *Name)) {
9626 bool SafeToContinue
9627 = (PrevTagDecl->getTagKind() != TTK_Enum &&
9628 Kind != TTK_Enum);
9629 if (SafeToContinue)
9630 Diag(KWLoc, diag::err_use_with_wrong_tag)
9631 << Name
9632 << FixItHint::CreateReplacement(SourceRange(KWLoc),
9633 PrevTagDecl->getKindName());
9634 else
9635 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
9636 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
9637
9638 if (SafeToContinue)
9639 Kind = PrevTagDecl->getTagKind();
9640 else {
9641 // Recover by making this an anonymous redefinition.
9642 Name = 0;
9643 Previous.clear();
9644 Invalid = true;
9645 }
9646 }
9647
9648 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
9649 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
9650
9651 // If this is an elaborated-type-specifier for a scoped enumeration,
9652 // the 'class' keyword is not necessary and not permitted.
9653 if (TUK == TUK_Reference || TUK == TUK_Friend) {
9654 if (ScopedEnum)
9655 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
9656 << PrevEnum->isScoped()
9657 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
9658 return PrevTagDecl;
9659 }
9660
9661 QualType EnumUnderlyingTy;
9662 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9663 EnumUnderlyingTy = TI->getType();
9664 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
9665 EnumUnderlyingTy = QualType(T, 0);
9666
9667 // All conflicts with previous declarations are recovered by
9668 // returning the previous declaration, unless this is a definition,
9669 // in which case we want the caller to bail out.
9670 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
9671 ScopedEnum, EnumUnderlyingTy, PrevEnum))
9672 return TUK == TUK_Declaration ? PrevTagDecl : 0;
9673 }
9674
9675 if (!Invalid) {
9676 // If this is a use, just return the declaration we found.
9677
9678 // FIXME: In the future, return a variant or some other clue
9679 // for the consumer of this Decl to know it doesn't own it.
9680 // For our current ASTs this shouldn't be a problem, but will
9681 // need to be changed with DeclGroups.
9682 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
9683 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
9684 return PrevTagDecl;
9685
9686 // Diagnose attempts to redefine a tag.
9687 if (TUK == TUK_Definition) {
9688 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
9689 // If we're defining a specialization and the previous definition
9690 // is from an implicit instantiation, don't emit an error
9691 // here; we'll catch this in the general case below.
9692 bool IsExplicitSpecializationAfterInstantiation = false;
9693 if (isExplicitSpecialization) {
9694 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
9695 IsExplicitSpecializationAfterInstantiation =
9696 RD->getTemplateSpecializationKind() !=
9697 TSK_ExplicitSpecialization;
9698 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
9699 IsExplicitSpecializationAfterInstantiation =
9700 ED->getTemplateSpecializationKind() !=
9701 TSK_ExplicitSpecialization;
9702 }
9703
9704 if (!IsExplicitSpecializationAfterInstantiation) {
9705 // A redeclaration in function prototype scope in C isn't
9706 // visible elsewhere, so merely issue a warning.
9707 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
9708 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
9709 else
9710 Diag(NameLoc, diag::err_redefinition) << Name;
9711 Diag(Def->getLocation(), diag::note_previous_definition);
9712 // If this is a redefinition, recover by making this
9713 // struct be anonymous, which will make any later
9714 // references get the previous definition.
9715 Name = 0;
9716 Previous.clear();
9717 Invalid = true;
9718 }
9719 } else {
9720 // If the type is currently being defined, complain
9721 // about a nested redefinition.
9722 const TagType *Tag
9723 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
9724 if (Tag->isBeingDefined()) {
9725 Diag(NameLoc, diag::err_nested_redefinition) << Name;
9726 Diag(PrevTagDecl->getLocation(),
9727 diag::note_previous_definition);
9728 Name = 0;
9729 Previous.clear();
9730 Invalid = true;
9731 }
9732 }
9733
9734 // Okay, this is definition of a previously declared or referenced
9735 // tag PrevDecl. We're going to create a new Decl for it.
9736 }
9737 }
9738 // If we get here we have (another) forward declaration or we
9739 // have a definition. Just create a new decl.
9740
9741 } else {
9742 // If we get here, this is a definition of a new tag type in a nested
9743 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
9744 // new decl/type. We set PrevDecl to NULL so that the entities
9745 // have distinct types.
9746 Previous.clear();
9747 }
9748 // If we get here, we're going to create a new Decl. If PrevDecl
9749 // is non-NULL, it's a definition of the tag declared by
9750 // PrevDecl. If it's NULL, we have a new definition.
9751
9752
9753 // Otherwise, PrevDecl is not a tag, but was found with tag
9754 // lookup. This is only actually possible in C++, where a few
9755 // things like templates still live in the tag namespace.
9756 } else {
9757 // Use a better diagnostic if an elaborated-type-specifier
9758 // found the wrong kind of type on the first
9759 // (non-redeclaration) lookup.
9760 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
9761 !Previous.isForRedeclaration()) {
9762 unsigned Kind = 0;
9763 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9764 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9765 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9766 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
9767 Diag(PrevDecl->getLocation(), diag::note_declared_at);
9768 Invalid = true;
9769
9770 // Otherwise, only diagnose if the declaration is in scope.
9771 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
9772 isExplicitSpecialization)) {
9773 // do nothing
9774
9775 // Diagnose implicit declarations introduced by elaborated types.
9776 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
9777 unsigned Kind = 0;
9778 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9779 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9780 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9781 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
9782 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9783 Invalid = true;
9784
9785 // Otherwise it's a declaration. Call out a particularly common
9786 // case here.
9787 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9788 unsigned Kind = 0;
9789 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
9790 Diag(NameLoc, diag::err_tag_definition_of_typedef)
9791 << Name << Kind << TND->getUnderlyingType();
9792 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9793 Invalid = true;
9794
9795 // Otherwise, diagnose.
9796 } else {
9797 // The tag name clashes with something else in the target scope,
9798 // issue an error and recover by making this tag be anonymous.
9799 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
9800 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9801 Name = 0;
9802 Invalid = true;
9803 }
9804
9805 // The existing declaration isn't relevant to us; we're in a
9806 // new scope, so clear out the previous declaration.
9807 Previous.clear();
9808 }
9809 }
9810
9811 CreateNewDecl:
9812
9813 TagDecl *PrevDecl = 0;
9814 if (Previous.isSingleResult())
9815 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
9816
9817 // If there is an identifier, use the location of the identifier as the
9818 // location of the decl, otherwise use the location of the struct/union
9819 // keyword.
9820 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
9821
9822 // Otherwise, create a new declaration. If there is a previous
9823 // declaration of the same entity, the two will be linked via
9824 // PrevDecl.
9825 TagDecl *New;
9826
9827 bool IsForwardReference = false;
9828 if (Kind == TTK_Enum) {
9829 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9830 // enum X { A, B, C } D; D should chain to X.
9831 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
9832 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
9833 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
9834 // If this is an undefined enum, warn.
9835 if (TUK != TUK_Definition && !Invalid) {
9836 TagDecl *Def;
9837 if (getLangOpts().CPlusPlus11 && cast<EnumDecl>(New)->isFixed()) {
9838 // C++0x: 7.2p2: opaque-enum-declaration.
9839 // Conflicts are diagnosed above. Do nothing.
9840 }
9841 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
9842 Diag(Loc, diag::ext_forward_ref_enum_def)
9843 << New;
9844 Diag(Def->getLocation(), diag::note_previous_definition);
9845 } else {
9846 unsigned DiagID = diag::ext_forward_ref_enum;
9847 if (getLangOpts().MicrosoftMode)
9848 DiagID = diag::ext_ms_forward_ref_enum;
9849 else if (getLangOpts().CPlusPlus)
9850 DiagID = diag::err_forward_ref_enum;
9851 Diag(Loc, DiagID);
9852
9853 // If this is a forward-declared reference to an enumeration, make a
9854 // note of it; we won't actually be introducing the declaration into
9855 // the declaration context.
9856 if (TUK == TUK_Reference)
9857 IsForwardReference = true;
9858 }
9859 }
9860
9861 if (EnumUnderlying) {
9862 EnumDecl *ED = cast<EnumDecl>(New);
9863 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9864 ED->setIntegerTypeSourceInfo(TI);
9865 else
9866 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
9867 ED->setPromotionType(ED->getIntegerType());
9868 }
9869
9870 } else {
9871 // struct/union/class
9872
9873 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9874 // struct X { int A; } D; D should chain to X.
9875 if (getLangOpts().CPlusPlus) {
9876 // FIXME: Look for a way to use RecordDecl for simple structs.
9877 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9878 cast_or_null<CXXRecordDecl>(PrevDecl));
9879
9880 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
9881 StdBadAlloc = cast<CXXRecordDecl>(New);
9882 } else
9883 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9884 cast_or_null<RecordDecl>(PrevDecl));
9885 }
9886
9887 // Maybe add qualifier info.
9888 if (SS.isNotEmpty()) {
9889 if (SS.isSet()) {
9890 // If this is either a declaration or a definition, check the
9891 // nested-name-specifier against the current context. We don't do this
9892 // for explicit specializations, because they have similar checking
9893 // (with more specific diagnostics) in the call to
9894 // CheckMemberSpecialization, below.
9895 if (!isExplicitSpecialization &&
9896 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
9897 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
9898 Invalid = true;
9899
9900 New->setQualifierInfo(SS.getWithLocInContext(Context));
9901 if (TemplateParameterLists.size() > 0) {
9902 New->setTemplateParameterListsInfo(Context,
9903 TemplateParameterLists.size(),
9904 TemplateParameterLists.data());
9905 }
9906 }
9907 else
9908 Invalid = true;
9909 }
9910
9911 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
9912 // Add alignment attributes if necessary; these attributes are checked when
9913 // the ASTContext lays out the structure.
9914 //
9915 // It is important for implementing the correct semantics that this
9916 // happen here (in act on tag decl). The #pragma pack stack is
9917 // maintained as a result of parser callbacks which can occur at
9918 // many points during the parsing of a struct declaration (because
9919 // the #pragma tokens are effectively skipped over during the
9920 // parsing of the struct).
9921 if (TUK == TUK_Definition) {
9922 AddAlignmentAttributesForRecord(RD);
9923 AddMsStructLayoutForRecord(RD);
9924 }
9925 }
9926
9927 if (ModulePrivateLoc.isValid()) {
9928 if (isExplicitSpecialization)
9929 Diag(New->getLocation(), diag::err_module_private_specialization)
9930 << 2
9931 << FixItHint::CreateRemoval(ModulePrivateLoc);
9932 // __module_private__ does not apply to local classes. However, we only
9933 // diagnose this as an error when the declaration specifiers are
9934 // freestanding. Here, we just ignore the __module_private__.
9935 else if (!SearchDC->isFunctionOrMethod())
9936 New->setModulePrivate();
9937 }
9938
9939 // If this is a specialization of a member class (of a class template),
9940 // check the specialization.
9941 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
9942 Invalid = true;
9943
9944 if (Invalid)
9945 New->setInvalidDecl();
9946
9947 if (Attr)
9948 ProcessDeclAttributeList(S, New, Attr);
9949
9950 // If we're declaring or defining a tag in function prototype scope
9951 // in C, note that this type can only be used within the function.
9952 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
9953 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
9954
9955 // Set the lexical context. If the tag has a C++ scope specifier, the
9956 // lexical context will be different from the semantic context.
9957 New->setLexicalDeclContext(CurContext);
9958
9959 // Mark this as a friend decl if applicable.
9960 // In Microsoft mode, a friend declaration also acts as a forward
9961 // declaration so we always pass true to setObjectOfFriendDecl to make
9962 // the tag name visible.
9963 if (TUK == TUK_Friend)
9964 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
9965 getLangOpts().MicrosoftExt);
9966
9967 // Set the access specifier.
9968 if (!Invalid && SearchDC->isRecord())
9969 SetMemberAccessSpecifier(New, PrevDecl, AS);
9970
9971 if (TUK == TUK_Definition)
9972 New->startDefinition();
9973
9974 // If this has an identifier, add it to the scope stack.
9975 if (TUK == TUK_Friend) {
9976 // We might be replacing an existing declaration in the lookup tables;
9977 // if so, borrow its access specifier.
9978 if (PrevDecl)
9979 New->setAccess(PrevDecl->getAccess());
9980
9981 DeclContext *DC = New->getDeclContext()->getRedeclContext();
9982 DC->makeDeclVisibleInContext(New);
9983 if (Name) // can be null along some error paths
9984 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9985 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
9986 } else if (Name) {
9987 S = getNonFieldDeclScope(S);
9988 PushOnScopeChains(New, S, !IsForwardReference);
9989 if (IsForwardReference)
9990 SearchDC->makeDeclVisibleInContext(New);
9991
9992 } else {
9993 CurContext->addDecl(New);
9994 }
9995
9996 // If this is the C FILE type, notify the AST context.
9997 if (IdentifierInfo *II = New->getIdentifier())
9998 if (!New->isInvalidDecl() &&
9999 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
10000 II->isStr("FILE"))
10001 Context.setFILEDecl(New);
10002
10003 // If we were in function prototype scope (and not in C++ mode), add this
10004 // tag to the list of decls to inject into the function definition scope.
10005 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
10006 InFunctionDeclarator && Name)
10007 DeclsInPrototypeScope.push_back(New);
10008
10009 if (PrevDecl)
10010 mergeDeclAttributes(New, PrevDecl);
10011
10012 // If there's a #pragma GCC visibility in scope, set the visibility of this
10013 // record.
10014 AddPushedVisibilityAttribute(New);
10015
10016 OwnedDecl = true;
10017 // In C++, don't return an invalid declaration. We can't recover well from
10018 // the cases where we make the type anonymous.
10019 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
10020 }
10021
ActOnTagStartDefinition(Scope * S,Decl * TagD)10022 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
10023 AdjustDeclIfTemplate(TagD);
10024 TagDecl *Tag = cast<TagDecl>(TagD);
10025
10026 // Enter the tag context.
10027 PushDeclContext(S, Tag);
10028
10029 ActOnDocumentableDecl(TagD);
10030
10031 // If there's a #pragma GCC visibility in scope, set the visibility of this
10032 // record.
10033 AddPushedVisibilityAttribute(Tag);
10034 }
10035
ActOnObjCContainerStartDefinition(Decl * IDecl)10036 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
10037 assert(isa<ObjCContainerDecl>(IDecl) &&
10038 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
10039 DeclContext *OCD = cast<DeclContext>(IDecl);
10040 assert(getContainingDC(OCD) == CurContext &&
10041 "The next DeclContext should be lexically contained in the current one.");
10042 CurContext = OCD;
10043 return IDecl;
10044 }
10045
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,SourceLocation LBraceLoc)10046 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
10047 SourceLocation FinalLoc,
10048 SourceLocation LBraceLoc) {
10049 AdjustDeclIfTemplate(TagD);
10050 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
10051
10052 FieldCollector->StartClass();
10053
10054 if (!Record->getIdentifier())
10055 return;
10056
10057 if (FinalLoc.isValid())
10058 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
10059
10060 // C++ [class]p2:
10061 // [...] The class-name is also inserted into the scope of the
10062 // class itself; this is known as the injected-class-name. For
10063 // purposes of access checking, the injected-class-name is treated
10064 // as if it were a public member name.
10065 CXXRecordDecl *InjectedClassName
10066 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
10067 Record->getLocStart(), Record->getLocation(),
10068 Record->getIdentifier(),
10069 /*PrevDecl=*/0,
10070 /*DelayTypeCreation=*/true);
10071 Context.getTypeDeclType(InjectedClassName, Record);
10072 InjectedClassName->setImplicit();
10073 InjectedClassName->setAccess(AS_public);
10074 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
10075 InjectedClassName->setDescribedClassTemplate(Template);
10076 PushOnScopeChains(InjectedClassName, S);
10077 assert(InjectedClassName->isInjectedClassName() &&
10078 "Broken injected-class-name");
10079 }
10080
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceLocation RBraceLoc)10081 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
10082 SourceLocation RBraceLoc) {
10083 AdjustDeclIfTemplate(TagD);
10084 TagDecl *Tag = cast<TagDecl>(TagD);
10085 Tag->setRBraceLoc(RBraceLoc);
10086
10087 // Make sure we "complete" the definition even it is invalid.
10088 if (Tag->isBeingDefined()) {
10089 assert(Tag->isInvalidDecl() && "We should already have completed it");
10090 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
10091 RD->completeDefinition();
10092 }
10093
10094 if (isa<CXXRecordDecl>(Tag))
10095 FieldCollector->FinishClass();
10096
10097 // Exit this scope of this tag's definition.
10098 PopDeclContext();
10099
10100 if (getCurLexicalContext()->isObjCContainer() &&
10101 Tag->getDeclContext()->isFileContext())
10102 Tag->setTopLevelDeclInObjCContainer();
10103
10104 // Notify the consumer that we've defined a tag.
10105 Consumer.HandleTagDeclDefinition(Tag);
10106 }
10107
ActOnObjCContainerFinishDefinition()10108 void Sema::ActOnObjCContainerFinishDefinition() {
10109 // Exit this scope of this interface definition.
10110 PopDeclContext();
10111 }
10112
ActOnObjCTemporaryExitContainerContext(DeclContext * DC)10113 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
10114 assert(DC == CurContext && "Mismatch of container contexts");
10115 OriginalLexicalContext = DC;
10116 ActOnObjCContainerFinishDefinition();
10117 }
10118
ActOnObjCReenterContainerContext(DeclContext * DC)10119 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
10120 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
10121 OriginalLexicalContext = 0;
10122 }
10123
ActOnTagDefinitionError(Scope * S,Decl * TagD)10124 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
10125 AdjustDeclIfTemplate(TagD);
10126 TagDecl *Tag = cast<TagDecl>(TagD);
10127 Tag->setInvalidDecl();
10128
10129 // Make sure we "complete" the definition even it is invalid.
10130 if (Tag->isBeingDefined()) {
10131 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
10132 RD->completeDefinition();
10133 }
10134
10135 // We're undoing ActOnTagStartDefinition here, not
10136 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
10137 // the FieldCollector.
10138
10139 PopDeclContext();
10140 }
10141
10142 // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,Expr * BitWidth,bool * ZeroWidth)10143 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
10144 IdentifierInfo *FieldName,
10145 QualType FieldTy, Expr *BitWidth,
10146 bool *ZeroWidth) {
10147 // Default to true; that shouldn't confuse checks for emptiness
10148 if (ZeroWidth)
10149 *ZeroWidth = true;
10150
10151 // C99 6.7.2.1p4 - verify the field type.
10152 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
10153 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
10154 // Handle incomplete types with specific error.
10155 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
10156 return ExprError();
10157 if (FieldName)
10158 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
10159 << FieldName << FieldTy << BitWidth->getSourceRange();
10160 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
10161 << FieldTy << BitWidth->getSourceRange();
10162 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
10163 UPPC_BitFieldWidth))
10164 return ExprError();
10165
10166 // If the bit-width is type- or value-dependent, don't try to check
10167 // it now.
10168 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
10169 return Owned(BitWidth);
10170
10171 llvm::APSInt Value;
10172 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
10173 if (ICE.isInvalid())
10174 return ICE;
10175 BitWidth = ICE.take();
10176
10177 if (Value != 0 && ZeroWidth)
10178 *ZeroWidth = false;
10179
10180 // Zero-width bitfield is ok for anonymous field.
10181 if (Value == 0 && FieldName)
10182 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
10183
10184 if (Value.isSigned() && Value.isNegative()) {
10185 if (FieldName)
10186 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
10187 << FieldName << Value.toString(10);
10188 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
10189 << Value.toString(10);
10190 }
10191
10192 if (!FieldTy->isDependentType()) {
10193 uint64_t TypeSize = Context.getTypeSize(FieldTy);
10194 if (Value.getZExtValue() > TypeSize) {
10195 if (!getLangOpts().CPlusPlus) {
10196 if (FieldName)
10197 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
10198 << FieldName << (unsigned)Value.getZExtValue()
10199 << (unsigned)TypeSize;
10200
10201 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
10202 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
10203 }
10204
10205 if (FieldName)
10206 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
10207 << FieldName << (unsigned)Value.getZExtValue()
10208 << (unsigned)TypeSize;
10209 else
10210 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
10211 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
10212 }
10213 }
10214
10215 return Owned(BitWidth);
10216 }
10217
10218 /// ActOnField - Each field of a C struct/union is passed into this in order
10219 /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)10220 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
10221 Declarator &D, Expr *BitfieldWidth) {
10222 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
10223 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
10224 /*InitStyle=*/ICIS_NoInit, AS_public);
10225 return Res;
10226 }
10227
10228 /// HandleField - Analyze a field of a C struct or a C++ data member.
10229 ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)10230 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
10231 SourceLocation DeclStart,
10232 Declarator &D, Expr *BitWidth,
10233 InClassInitStyle InitStyle,
10234 AccessSpecifier AS) {
10235 IdentifierInfo *II = D.getIdentifier();
10236 SourceLocation Loc = DeclStart;
10237 if (II) Loc = D.getIdentifierLoc();
10238
10239 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10240 QualType T = TInfo->getType();
10241 if (getLangOpts().CPlusPlus) {
10242 CheckExtraCXXDefaultArguments(D);
10243
10244 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10245 UPPC_DataMemberType)) {
10246 D.setInvalidType();
10247 T = Context.IntTy;
10248 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
10249 }
10250 }
10251
10252 // TR 18037 does not allow fields to be declared with address spaces.
10253 if (T.getQualifiers().hasAddressSpace()) {
10254 Diag(Loc, diag::err_field_with_address_space);
10255 D.setInvalidType();
10256 }
10257
10258 // OpenCL 1.2 spec, s6.9 r:
10259 // The event type cannot be used to declare a structure or union field.
10260 if (LangOpts.OpenCL && T->isEventT()) {
10261 Diag(Loc, diag::err_event_t_struct_field);
10262 D.setInvalidType();
10263 }
10264
10265 DiagnoseFunctionSpecifiers(D.getDeclSpec());
10266
10267 if (D.getDeclSpec().isThreadSpecified())
10268 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
10269
10270 // Check to see if this name was declared as a member previously
10271 NamedDecl *PrevDecl = 0;
10272 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
10273 LookupName(Previous, S);
10274 switch (Previous.getResultKind()) {
10275 case LookupResult::Found:
10276 case LookupResult::FoundUnresolvedValue:
10277 PrevDecl = Previous.getAsSingle<NamedDecl>();
10278 break;
10279
10280 case LookupResult::FoundOverloaded:
10281 PrevDecl = Previous.getRepresentativeDecl();
10282 break;
10283
10284 case LookupResult::NotFound:
10285 case LookupResult::NotFoundInCurrentInstantiation:
10286 case LookupResult::Ambiguous:
10287 break;
10288 }
10289 Previous.suppressDiagnostics();
10290
10291 if (PrevDecl && PrevDecl->isTemplateParameter()) {
10292 // Maybe we will complain about the shadowed template parameter.
10293 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10294 // Just pretend that we didn't see the previous declaration.
10295 PrevDecl = 0;
10296 }
10297
10298 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
10299 PrevDecl = 0;
10300
10301 bool Mutable
10302 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
10303 SourceLocation TSSL = D.getLocStart();
10304 FieldDecl *NewFD
10305 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
10306 TSSL, AS, PrevDecl, &D);
10307
10308 if (NewFD->isInvalidDecl())
10309 Record->setInvalidDecl();
10310
10311 if (D.getDeclSpec().isModulePrivateSpecified())
10312 NewFD->setModulePrivate();
10313
10314 if (NewFD->isInvalidDecl() && PrevDecl) {
10315 // Don't introduce NewFD into scope; there's already something
10316 // with the same name in the same scope.
10317 } else if (II) {
10318 PushOnScopeChains(NewFD, S);
10319 } else
10320 Record->addDecl(NewFD);
10321
10322 return NewFD;
10323 }
10324
10325 /// \brief Build a new FieldDecl and check its well-formedness.
10326 ///
10327 /// This routine builds a new FieldDecl given the fields name, type,
10328 /// record, etc. \p PrevDecl should refer to any previous declaration
10329 /// with the same name and in the same scope as the field to be
10330 /// created.
10331 ///
10332 /// \returns a new FieldDecl.
10333 ///
10334 /// \todo The Declarator argument is a hack. It will be removed once
CheckFieldDecl(DeclarationName Name,QualType T,TypeSourceInfo * TInfo,RecordDecl * Record,SourceLocation Loc,bool Mutable,Expr * BitWidth,InClassInitStyle InitStyle,SourceLocation TSSL,AccessSpecifier AS,NamedDecl * PrevDecl,Declarator * D)10335 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
10336 TypeSourceInfo *TInfo,
10337 RecordDecl *Record, SourceLocation Loc,
10338 bool Mutable, Expr *BitWidth,
10339 InClassInitStyle InitStyle,
10340 SourceLocation TSSL,
10341 AccessSpecifier AS, NamedDecl *PrevDecl,
10342 Declarator *D) {
10343 IdentifierInfo *II = Name.getAsIdentifierInfo();
10344 bool InvalidDecl = false;
10345 if (D) InvalidDecl = D->isInvalidType();
10346
10347 // If we receive a broken type, recover by assuming 'int' and
10348 // marking this declaration as invalid.
10349 if (T.isNull()) {
10350 InvalidDecl = true;
10351 T = Context.IntTy;
10352 }
10353
10354 QualType EltTy = Context.getBaseElementType(T);
10355 if (!EltTy->isDependentType()) {
10356 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
10357 // Fields of incomplete type force their record to be invalid.
10358 Record->setInvalidDecl();
10359 InvalidDecl = true;
10360 } else {
10361 NamedDecl *Def;
10362 EltTy->isIncompleteType(&Def);
10363 if (Def && Def->isInvalidDecl()) {
10364 Record->setInvalidDecl();
10365 InvalidDecl = true;
10366 }
10367 }
10368 }
10369
10370 // OpenCL v1.2 s6.9.c: bitfields are not supported.
10371 if (BitWidth && getLangOpts().OpenCL) {
10372 Diag(Loc, diag::err_opencl_bitfields);
10373 InvalidDecl = true;
10374 }
10375
10376 // C99 6.7.2.1p8: A member of a structure or union may have any type other
10377 // than a variably modified type.
10378 if (!InvalidDecl && T->isVariablyModifiedType()) {
10379 bool SizeIsNegative;
10380 llvm::APSInt Oversized;
10381
10382 TypeSourceInfo *FixedTInfo =
10383 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
10384 SizeIsNegative,
10385 Oversized);
10386 if (FixedTInfo) {
10387 Diag(Loc, diag::warn_illegal_constant_array_size);
10388 TInfo = FixedTInfo;
10389 T = FixedTInfo->getType();
10390 } else {
10391 if (SizeIsNegative)
10392 Diag(Loc, diag::err_typecheck_negative_array_size);
10393 else if (Oversized.getBoolValue())
10394 Diag(Loc, diag::err_array_too_large)
10395 << Oversized.toString(10);
10396 else
10397 Diag(Loc, diag::err_typecheck_field_variable_size);
10398 InvalidDecl = true;
10399 }
10400 }
10401
10402 // Fields can not have abstract class types
10403 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
10404 diag::err_abstract_type_in_decl,
10405 AbstractFieldType))
10406 InvalidDecl = true;
10407
10408 bool ZeroWidth = false;
10409 // If this is declared as a bit-field, check the bit-field.
10410 if (!InvalidDecl && BitWidth) {
10411 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
10412 if (!BitWidth) {
10413 InvalidDecl = true;
10414 BitWidth = 0;
10415 ZeroWidth = false;
10416 }
10417 }
10418
10419 // Check that 'mutable' is consistent with the type of the declaration.
10420 if (!InvalidDecl && Mutable) {
10421 unsigned DiagID = 0;
10422 if (T->isReferenceType())
10423 DiagID = diag::err_mutable_reference;
10424 else if (T.isConstQualified())
10425 DiagID = diag::err_mutable_const;
10426
10427 if (DiagID) {
10428 SourceLocation ErrLoc = Loc;
10429 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
10430 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
10431 Diag(ErrLoc, DiagID);
10432 Mutable = false;
10433 InvalidDecl = true;
10434 }
10435 }
10436
10437 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
10438 BitWidth, Mutable, InitStyle);
10439 if (InvalidDecl)
10440 NewFD->setInvalidDecl();
10441
10442 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
10443 Diag(Loc, diag::err_duplicate_member) << II;
10444 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10445 NewFD->setInvalidDecl();
10446 }
10447
10448 if (!InvalidDecl && getLangOpts().CPlusPlus) {
10449 if (Record->isUnion()) {
10450 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
10451 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
10452 if (RDecl->getDefinition()) {
10453 // C++ [class.union]p1: An object of a class with a non-trivial
10454 // constructor, a non-trivial copy constructor, a non-trivial
10455 // destructor, or a non-trivial copy assignment operator
10456 // cannot be a member of a union, nor can an array of such
10457 // objects.
10458 if (CheckNontrivialField(NewFD))
10459 NewFD->setInvalidDecl();
10460 }
10461 }
10462
10463 // C++ [class.union]p1: If a union contains a member of reference type,
10464 // the program is ill-formed.
10465 if (EltTy->isReferenceType()) {
10466 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
10467 << NewFD->getDeclName() << EltTy;
10468 NewFD->setInvalidDecl();
10469 }
10470 }
10471 }
10472
10473 // FIXME: We need to pass in the attributes given an AST
10474 // representation, not a parser representation.
10475 if (D) {
10476 // FIXME: What to pass instead of TUScope?
10477 ProcessDeclAttributes(TUScope, NewFD, *D);
10478
10479 if (NewFD->hasAttrs())
10480 CheckAlignasUnderalignment(NewFD);
10481 }
10482
10483 // In auto-retain/release, infer strong retension for fields of
10484 // retainable type.
10485 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
10486 NewFD->setInvalidDecl();
10487
10488 if (T.isObjCGCWeak())
10489 Diag(Loc, diag::warn_attribute_weak_on_field);
10490
10491 NewFD->setAccess(AS);
10492 return NewFD;
10493 }
10494
CheckNontrivialField(FieldDecl * FD)10495 bool Sema::CheckNontrivialField(FieldDecl *FD) {
10496 assert(FD);
10497 assert(getLangOpts().CPlusPlus && "valid check only for C++");
10498
10499 if (FD->isInvalidDecl())
10500 return true;
10501
10502 QualType EltTy = Context.getBaseElementType(FD->getType());
10503 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
10504 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
10505 if (RDecl->getDefinition()) {
10506 // We check for copy constructors before constructors
10507 // because otherwise we'll never get complaints about
10508 // copy constructors.
10509
10510 CXXSpecialMember member = CXXInvalid;
10511 // We're required to check for any non-trivial constructors. Since the
10512 // implicit default constructor is suppressed if there are any
10513 // user-declared constructors, we just need to check that there is a
10514 // trivial default constructor and a trivial copy constructor. (We don't
10515 // worry about move constructors here, since this is a C++98 check.)
10516 if (RDecl->hasNonTrivialCopyConstructor())
10517 member = CXXCopyConstructor;
10518 else if (!RDecl->hasTrivialDefaultConstructor())
10519 member = CXXDefaultConstructor;
10520 else if (RDecl->hasNonTrivialCopyAssignment())
10521 member = CXXCopyAssignment;
10522 else if (RDecl->hasNonTrivialDestructor())
10523 member = CXXDestructor;
10524
10525 if (member != CXXInvalid) {
10526 if (!getLangOpts().CPlusPlus11 &&
10527 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
10528 // Objective-C++ ARC: it is an error to have a non-trivial field of
10529 // a union. However, system headers in Objective-C programs
10530 // occasionally have Objective-C lifetime objects within unions,
10531 // and rather than cause the program to fail, we make those
10532 // members unavailable.
10533 SourceLocation Loc = FD->getLocation();
10534 if (getSourceManager().isInSystemHeader(Loc)) {
10535 if (!FD->hasAttr<UnavailableAttr>())
10536 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
10537 "this system field has retaining ownership"));
10538 return false;
10539 }
10540 }
10541
10542 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
10543 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
10544 diag::err_illegal_union_or_anon_struct_member)
10545 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
10546 DiagnoseNontrivial(RDecl, member);
10547 return !getLangOpts().CPlusPlus11;
10548 }
10549 }
10550 }
10551
10552 return false;
10553 }
10554
10555 /// TranslateIvarVisibility - Translate visibility from a token ID to an
10556 /// AST enum value.
10557 static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)10558 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
10559 switch (ivarVisibility) {
10560 default: llvm_unreachable("Unknown visitibility kind");
10561 case tok::objc_private: return ObjCIvarDecl::Private;
10562 case tok::objc_public: return ObjCIvarDecl::Public;
10563 case tok::objc_protected: return ObjCIvarDecl::Protected;
10564 case tok::objc_package: return ObjCIvarDecl::Package;
10565 }
10566 }
10567
10568 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
10569 /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)10570 Decl *Sema::ActOnIvar(Scope *S,
10571 SourceLocation DeclStart,
10572 Declarator &D, Expr *BitfieldWidth,
10573 tok::ObjCKeywordKind Visibility) {
10574
10575 IdentifierInfo *II = D.getIdentifier();
10576 Expr *BitWidth = (Expr*)BitfieldWidth;
10577 SourceLocation Loc = DeclStart;
10578 if (II) Loc = D.getIdentifierLoc();
10579
10580 // FIXME: Unnamed fields can be handled in various different ways, for
10581 // example, unnamed unions inject all members into the struct namespace!
10582
10583 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10584 QualType T = TInfo->getType();
10585
10586 if (BitWidth) {
10587 // 6.7.2.1p3, 6.7.2.1p4
10588 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
10589 if (!BitWidth)
10590 D.setInvalidType();
10591 } else {
10592 // Not a bitfield.
10593
10594 // validate II.
10595
10596 }
10597 if (T->isReferenceType()) {
10598 Diag(Loc, diag::err_ivar_reference_type);
10599 D.setInvalidType();
10600 }
10601 // C99 6.7.2.1p8: A member of a structure or union may have any type other
10602 // than a variably modified type.
10603 else if (T->isVariablyModifiedType()) {
10604 Diag(Loc, diag::err_typecheck_ivar_variable_size);
10605 D.setInvalidType();
10606 }
10607
10608 // Get the visibility (access control) for this ivar.
10609 ObjCIvarDecl::AccessControl ac =
10610 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
10611 : ObjCIvarDecl::None;
10612 // Must set ivar's DeclContext to its enclosing interface.
10613 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
10614 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
10615 return 0;
10616 ObjCContainerDecl *EnclosingContext;
10617 if (ObjCImplementationDecl *IMPDecl =
10618 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10619 if (LangOpts.ObjCRuntime.isFragile()) {
10620 // Case of ivar declared in an implementation. Context is that of its class.
10621 EnclosingContext = IMPDecl->getClassInterface();
10622 assert(EnclosingContext && "Implementation has no class interface!");
10623 }
10624 else
10625 EnclosingContext = EnclosingDecl;
10626 } else {
10627 if (ObjCCategoryDecl *CDecl =
10628 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10629 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
10630 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
10631 return 0;
10632 }
10633 }
10634 EnclosingContext = EnclosingDecl;
10635 }
10636
10637 // Construct the decl.
10638 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
10639 DeclStart, Loc, II, T,
10640 TInfo, ac, (Expr *)BitfieldWidth);
10641
10642 if (II) {
10643 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
10644 ForRedeclaration);
10645 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
10646 && !isa<TagDecl>(PrevDecl)) {
10647 Diag(Loc, diag::err_duplicate_member) << II;
10648 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10649 NewID->setInvalidDecl();
10650 }
10651 }
10652
10653 // Process attributes attached to the ivar.
10654 ProcessDeclAttributes(S, NewID, D);
10655
10656 if (D.isInvalidType())
10657 NewID->setInvalidDecl();
10658
10659 // In ARC, infer 'retaining' for ivars of retainable type.
10660 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
10661 NewID->setInvalidDecl();
10662
10663 if (D.getDeclSpec().isModulePrivateSpecified())
10664 NewID->setModulePrivate();
10665
10666 if (II) {
10667 // FIXME: When interfaces are DeclContexts, we'll need to add
10668 // these to the interface.
10669 S->AddDecl(NewID);
10670 IdResolver.AddDecl(NewID);
10671 }
10672
10673 if (LangOpts.ObjCRuntime.isNonFragile() &&
10674 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
10675 Diag(Loc, diag::warn_ivars_in_interface);
10676
10677 return NewID;
10678 }
10679
10680 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
10681 /// class and class extensions. For every class @interface and class
10682 /// extension @interface, if the last ivar is a bitfield of any type,
10683 /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)10684 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
10685 SmallVectorImpl<Decl *> &AllIvarDecls) {
10686 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
10687 return;
10688
10689 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
10690 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
10691
10692 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
10693 return;
10694 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
10695 if (!ID) {
10696 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
10697 if (!CD->IsClassExtension())
10698 return;
10699 }
10700 // No need to add this to end of @implementation.
10701 else
10702 return;
10703 }
10704 // All conditions are met. Add a new bitfield to the tail end of ivars.
10705 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
10706 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
10707
10708 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
10709 DeclLoc, DeclLoc, 0,
10710 Context.CharTy,
10711 Context.getTrivialTypeSourceInfo(Context.CharTy,
10712 DeclLoc),
10713 ObjCIvarDecl::Private, BW,
10714 true);
10715 AllIvarDecls.push_back(Ivar);
10716 }
10717
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,llvm::ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,AttributeList * Attr)10718 void Sema::ActOnFields(Scope* S,
10719 SourceLocation RecLoc, Decl *EnclosingDecl,
10720 llvm::ArrayRef<Decl *> Fields,
10721 SourceLocation LBrac, SourceLocation RBrac,
10722 AttributeList *Attr) {
10723 assert(EnclosingDecl && "missing record or interface decl");
10724
10725 // If this is an Objective-C @implementation or category and we have
10726 // new fields here we should reset the layout of the interface since
10727 // it will now change.
10728 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
10729 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
10730 switch (DC->getKind()) {
10731 default: break;
10732 case Decl::ObjCCategory:
10733 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
10734 break;
10735 case Decl::ObjCImplementation:
10736 Context.
10737 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
10738 break;
10739 }
10740 }
10741
10742 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
10743
10744 // Start counting up the number of named members; make sure to include
10745 // members of anonymous structs and unions in the total.
10746 unsigned NumNamedMembers = 0;
10747 if (Record) {
10748 for (RecordDecl::decl_iterator i = Record->decls_begin(),
10749 e = Record->decls_end(); i != e; i++) {
10750 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
10751 if (IFD->getDeclName())
10752 ++NumNamedMembers;
10753 }
10754 }
10755
10756 // Verify that all the fields are okay.
10757 SmallVector<FieldDecl*, 32> RecFields;
10758
10759 bool ARCErrReported = false;
10760 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
10761 i != end; ++i) {
10762 FieldDecl *FD = cast<FieldDecl>(*i);
10763
10764 // Get the type for the field.
10765 const Type *FDTy = FD->getType().getTypePtr();
10766
10767 if (!FD->isAnonymousStructOrUnion()) {
10768 // Remember all fields written by the user.
10769 RecFields.push_back(FD);
10770 }
10771
10772 // If the field is already invalid for some reason, don't emit more
10773 // diagnostics about it.
10774 if (FD->isInvalidDecl()) {
10775 EnclosingDecl->setInvalidDecl();
10776 continue;
10777 }
10778
10779 // C99 6.7.2.1p2:
10780 // A structure or union shall not contain a member with
10781 // incomplete or function type (hence, a structure shall not
10782 // contain an instance of itself, but may contain a pointer to
10783 // an instance of itself), except that the last member of a
10784 // structure with more than one named member may have incomplete
10785 // array type; such a structure (and any union containing,
10786 // possibly recursively, a member that is such a structure)
10787 // shall not be a member of a structure or an element of an
10788 // array.
10789 if (FDTy->isFunctionType()) {
10790 // Field declared as a function.
10791 Diag(FD->getLocation(), diag::err_field_declared_as_function)
10792 << FD->getDeclName();
10793 FD->setInvalidDecl();
10794 EnclosingDecl->setInvalidDecl();
10795 continue;
10796 } else if (FDTy->isIncompleteArrayType() && Record &&
10797 ((i + 1 == Fields.end() && !Record->isUnion()) ||
10798 ((getLangOpts().MicrosoftExt ||
10799 getLangOpts().CPlusPlus) &&
10800 (i + 1 == Fields.end() || Record->isUnion())))) {
10801 // Flexible array member.
10802 // Microsoft and g++ is more permissive regarding flexible array.
10803 // It will accept flexible array in union and also
10804 // as the sole element of a struct/class.
10805 if (getLangOpts().MicrosoftExt) {
10806 if (Record->isUnion())
10807 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
10808 << FD->getDeclName();
10809 else if (Fields.size() == 1)
10810 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
10811 << FD->getDeclName() << Record->getTagKind();
10812 } else if (getLangOpts().CPlusPlus) {
10813 if (Record->isUnion())
10814 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10815 << FD->getDeclName();
10816 else if (Fields.size() == 1)
10817 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
10818 << FD->getDeclName() << Record->getTagKind();
10819 } else if (!getLangOpts().C99) {
10820 if (Record->isUnion())
10821 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10822 << FD->getDeclName();
10823 else
10824 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
10825 << FD->getDeclName() << Record->getTagKind();
10826 } else if (NumNamedMembers < 1) {
10827 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
10828 << FD->getDeclName();
10829 FD->setInvalidDecl();
10830 EnclosingDecl->setInvalidDecl();
10831 continue;
10832 }
10833 if (!FD->getType()->isDependentType() &&
10834 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
10835 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
10836 << FD->getDeclName() << FD->getType();
10837 FD->setInvalidDecl();
10838 EnclosingDecl->setInvalidDecl();
10839 continue;
10840 }
10841 // Okay, we have a legal flexible array member at the end of the struct.
10842 if (Record)
10843 Record->setHasFlexibleArrayMember(true);
10844 } else if (!FDTy->isDependentType() &&
10845 RequireCompleteType(FD->getLocation(), FD->getType(),
10846 diag::err_field_incomplete)) {
10847 // Incomplete type
10848 FD->setInvalidDecl();
10849 EnclosingDecl->setInvalidDecl();
10850 continue;
10851 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
10852 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
10853 // If this is a member of a union, then entire union becomes "flexible".
10854 if (Record && Record->isUnion()) {
10855 Record->setHasFlexibleArrayMember(true);
10856 } else {
10857 // If this is a struct/class and this is not the last element, reject
10858 // it. Note that GCC supports variable sized arrays in the middle of
10859 // structures.
10860 if (i + 1 != Fields.end())
10861 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
10862 << FD->getDeclName() << FD->getType();
10863 else {
10864 // We support flexible arrays at the end of structs in
10865 // other structs as an extension.
10866 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
10867 << FD->getDeclName();
10868 if (Record)
10869 Record->setHasFlexibleArrayMember(true);
10870 }
10871 }
10872 }
10873 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
10874 RequireNonAbstractType(FD->getLocation(), FD->getType(),
10875 diag::err_abstract_type_in_decl,
10876 AbstractIvarType)) {
10877 // Ivars can not have abstract class types
10878 FD->setInvalidDecl();
10879 }
10880 if (Record && FDTTy->getDecl()->hasObjectMember())
10881 Record->setHasObjectMember(true);
10882 if (Record && FDTTy->getDecl()->hasVolatileMember())
10883 Record->setHasVolatileMember(true);
10884 } else if (FDTy->isObjCObjectType()) {
10885 /// A field cannot be an Objective-c object
10886 Diag(FD->getLocation(), diag::err_statically_allocated_object)
10887 << FixItHint::CreateInsertion(FD->getLocation(), "*");
10888 QualType T = Context.getObjCObjectPointerType(FD->getType());
10889 FD->setType(T);
10890 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
10891 (!getLangOpts().CPlusPlus || Record->isUnion())) {
10892 // It's an error in ARC if a field has lifetime.
10893 // We don't want to report this in a system header, though,
10894 // so we just make the field unavailable.
10895 // FIXME: that's really not sufficient; we need to make the type
10896 // itself invalid to, say, initialize or copy.
10897 QualType T = FD->getType();
10898 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
10899 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
10900 SourceLocation loc = FD->getLocation();
10901 if (getSourceManager().isInSystemHeader(loc)) {
10902 if (!FD->hasAttr<UnavailableAttr>()) {
10903 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
10904 "this system field has retaining ownership"));
10905 }
10906 } else {
10907 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
10908 << T->isBlockPointerType() << Record->getTagKind();
10909 }
10910 ARCErrReported = true;
10911 }
10912 } else if (getLangOpts().ObjC1 &&
10913 getLangOpts().getGC() != LangOptions::NonGC &&
10914 Record && !Record->hasObjectMember()) {
10915 if (FD->getType()->isObjCObjectPointerType() ||
10916 FD->getType().isObjCGCStrong())
10917 Record->setHasObjectMember(true);
10918 else if (Context.getAsArrayType(FD->getType())) {
10919 QualType BaseType = Context.getBaseElementType(FD->getType());
10920 if (BaseType->isRecordType() &&
10921 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
10922 Record->setHasObjectMember(true);
10923 else if (BaseType->isObjCObjectPointerType() ||
10924 BaseType.isObjCGCStrong())
10925 Record->setHasObjectMember(true);
10926 }
10927 }
10928 if (Record && FD->getType().isVolatileQualified())
10929 Record->setHasVolatileMember(true);
10930 // Keep track of the number of named members.
10931 if (FD->getIdentifier())
10932 ++NumNamedMembers;
10933 }
10934
10935 // Okay, we successfully defined 'Record'.
10936 if (Record) {
10937 bool Completed = false;
10938 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
10939 if (!CXXRecord->isInvalidDecl()) {
10940 // Set access bits correctly on the directly-declared conversions.
10941 for (CXXRecordDecl::conversion_iterator
10942 I = CXXRecord->conversion_begin(),
10943 E = CXXRecord->conversion_end(); I != E; ++I)
10944 I.setAccess((*I)->getAccess());
10945
10946 if (!CXXRecord->isDependentType()) {
10947 // Adjust user-defined destructor exception spec.
10948 if (getLangOpts().CPlusPlus11 &&
10949 CXXRecord->hasUserDeclaredDestructor())
10950 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10951
10952 // Add any implicitly-declared members to this class.
10953 AddImplicitlyDeclaredMembersToClass(CXXRecord);
10954
10955 // If we have virtual base classes, we may end up finding multiple
10956 // final overriders for a given virtual function. Check for this
10957 // problem now.
10958 if (CXXRecord->getNumVBases()) {
10959 CXXFinalOverriderMap FinalOverriders;
10960 CXXRecord->getFinalOverriders(FinalOverriders);
10961
10962 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10963 MEnd = FinalOverriders.end();
10964 M != MEnd; ++M) {
10965 for (OverridingMethods::iterator SO = M->second.begin(),
10966 SOEnd = M->second.end();
10967 SO != SOEnd; ++SO) {
10968 assert(SO->second.size() > 0 &&
10969 "Virtual function without overridding functions?");
10970 if (SO->second.size() == 1)
10971 continue;
10972
10973 // C++ [class.virtual]p2:
10974 // In a derived class, if a virtual member function of a base
10975 // class subobject has more than one final overrider the
10976 // program is ill-formed.
10977 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
10978 << (const NamedDecl *)M->first << Record;
10979 Diag(M->first->getLocation(),
10980 diag::note_overridden_virtual_function);
10981 for (OverridingMethods::overriding_iterator
10982 OM = SO->second.begin(),
10983 OMEnd = SO->second.end();
10984 OM != OMEnd; ++OM)
10985 Diag(OM->Method->getLocation(), diag::note_final_overrider)
10986 << (const NamedDecl *)M->first << OM->Method->getParent();
10987
10988 Record->setInvalidDecl();
10989 }
10990 }
10991 CXXRecord->completeDefinition(&FinalOverriders);
10992 Completed = true;
10993 }
10994 }
10995 }
10996 }
10997
10998 if (!Completed)
10999 Record->completeDefinition();
11000
11001 if (Record->hasAttrs())
11002 CheckAlignasUnderalignment(Record);
11003 } else {
11004 ObjCIvarDecl **ClsFields =
11005 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
11006 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
11007 ID->setEndOfDefinitionLoc(RBrac);
11008 // Add ivar's to class's DeclContext.
11009 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
11010 ClsFields[i]->setLexicalDeclContext(ID);
11011 ID->addDecl(ClsFields[i]);
11012 }
11013 // Must enforce the rule that ivars in the base classes may not be
11014 // duplicates.
11015 if (ID->getSuperClass())
11016 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
11017 } else if (ObjCImplementationDecl *IMPDecl =
11018 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11019 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
11020 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
11021 // Ivar declared in @implementation never belongs to the implementation.
11022 // Only it is in implementation's lexical context.
11023 ClsFields[I]->setLexicalDeclContext(IMPDecl);
11024 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
11025 IMPDecl->setIvarLBraceLoc(LBrac);
11026 IMPDecl->setIvarRBraceLoc(RBrac);
11027 } else if (ObjCCategoryDecl *CDecl =
11028 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11029 // case of ivars in class extension; all other cases have been
11030 // reported as errors elsewhere.
11031 // FIXME. Class extension does not have a LocEnd field.
11032 // CDecl->setLocEnd(RBrac);
11033 // Add ivar's to class extension's DeclContext.
11034 // Diagnose redeclaration of private ivars.
11035 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
11036 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
11037 if (IDecl) {
11038 if (const ObjCIvarDecl *ClsIvar =
11039 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
11040 Diag(ClsFields[i]->getLocation(),
11041 diag::err_duplicate_ivar_declaration);
11042 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
11043 continue;
11044 }
11045 for (ObjCInterfaceDecl::known_extensions_iterator
11046 Ext = IDecl->known_extensions_begin(),
11047 ExtEnd = IDecl->known_extensions_end();
11048 Ext != ExtEnd; ++Ext) {
11049 if (const ObjCIvarDecl *ClsExtIvar
11050 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
11051 Diag(ClsFields[i]->getLocation(),
11052 diag::err_duplicate_ivar_declaration);
11053 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
11054 continue;
11055 }
11056 }
11057 }
11058 ClsFields[i]->setLexicalDeclContext(CDecl);
11059 CDecl->addDecl(ClsFields[i]);
11060 }
11061 CDecl->setIvarLBraceLoc(LBrac);
11062 CDecl->setIvarRBraceLoc(RBrac);
11063 }
11064 }
11065
11066 if (Attr)
11067 ProcessDeclAttributeList(S, Record, Attr);
11068 }
11069
11070 /// \brief Determine whether the given integral value is representable within
11071 /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)11072 static bool isRepresentableIntegerValue(ASTContext &Context,
11073 llvm::APSInt &Value,
11074 QualType T) {
11075 assert(T->isIntegralType(Context) && "Integral type required!");
11076 unsigned BitWidth = Context.getIntWidth(T);
11077
11078 if (Value.isUnsigned() || Value.isNonNegative()) {
11079 if (T->isSignedIntegerOrEnumerationType())
11080 --BitWidth;
11081 return Value.getActiveBits() <= BitWidth;
11082 }
11083 return Value.getMinSignedBits() <= BitWidth;
11084 }
11085
11086 // \brief Given an integral type, return the next larger integral type
11087 // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)11088 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
11089 // FIXME: Int128/UInt128 support, which also needs to be introduced into
11090 // enum checking below.
11091 assert(T->isIntegralType(Context) && "Integral type required!");
11092 const unsigned NumTypes = 4;
11093 QualType SignedIntegralTypes[NumTypes] = {
11094 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
11095 };
11096 QualType UnsignedIntegralTypes[NumTypes] = {
11097 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
11098 Context.UnsignedLongLongTy
11099 };
11100
11101 unsigned BitWidth = Context.getTypeSize(T);
11102 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
11103 : UnsignedIntegralTypes;
11104 for (unsigned I = 0; I != NumTypes; ++I)
11105 if (Context.getTypeSize(Types[I]) > BitWidth)
11106 return Types[I];
11107
11108 return QualType();
11109 }
11110
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)11111 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
11112 EnumConstantDecl *LastEnumConst,
11113 SourceLocation IdLoc,
11114 IdentifierInfo *Id,
11115 Expr *Val) {
11116 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
11117 llvm::APSInt EnumVal(IntWidth);
11118 QualType EltTy;
11119
11120 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
11121 Val = 0;
11122
11123 if (Val)
11124 Val = DefaultLvalueConversion(Val).take();
11125
11126 if (Val) {
11127 if (Enum->isDependentType() || Val->isTypeDependent())
11128 EltTy = Context.DependentTy;
11129 else {
11130 SourceLocation ExpLoc;
11131 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
11132 !getLangOpts().MicrosoftMode) {
11133 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
11134 // constant-expression in the enumerator-definition shall be a converted
11135 // constant expression of the underlying type.
11136 EltTy = Enum->getIntegerType();
11137 ExprResult Converted =
11138 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
11139 CCEK_Enumerator);
11140 if (Converted.isInvalid())
11141 Val = 0;
11142 else
11143 Val = Converted.take();
11144 } else if (!Val->isValueDependent() &&
11145 !(Val = VerifyIntegerConstantExpression(Val,
11146 &EnumVal).take())) {
11147 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
11148 } else {
11149 if (Enum->isFixed()) {
11150 EltTy = Enum->getIntegerType();
11151
11152 // In Obj-C and Microsoft mode, require the enumeration value to be
11153 // representable in the underlying type of the enumeration. In C++11,
11154 // we perform a non-narrowing conversion as part of converted constant
11155 // expression checking.
11156 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
11157 if (getLangOpts().MicrosoftMode) {
11158 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
11159 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
11160 } else
11161 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
11162 } else
11163 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
11164 } else if (getLangOpts().CPlusPlus) {
11165 // C++11 [dcl.enum]p5:
11166 // If the underlying type is not fixed, the type of each enumerator
11167 // is the type of its initializing value:
11168 // - If an initializer is specified for an enumerator, the
11169 // initializing value has the same type as the expression.
11170 EltTy = Val->getType();
11171 } else {
11172 // C99 6.7.2.2p2:
11173 // The expression that defines the value of an enumeration constant
11174 // shall be an integer constant expression that has a value
11175 // representable as an int.
11176
11177 // Complain if the value is not representable in an int.
11178 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
11179 Diag(IdLoc, diag::ext_enum_value_not_int)
11180 << EnumVal.toString(10) << Val->getSourceRange()
11181 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
11182 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
11183 // Force the type of the expression to 'int'.
11184 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
11185 }
11186 EltTy = Val->getType();
11187 }
11188 }
11189 }
11190 }
11191
11192 if (!Val) {
11193 if (Enum->isDependentType())
11194 EltTy = Context.DependentTy;
11195 else if (!LastEnumConst) {
11196 // C++0x [dcl.enum]p5:
11197 // If the underlying type is not fixed, the type of each enumerator
11198 // is the type of its initializing value:
11199 // - If no initializer is specified for the first enumerator, the
11200 // initializing value has an unspecified integral type.
11201 //
11202 // GCC uses 'int' for its unspecified integral type, as does
11203 // C99 6.7.2.2p3.
11204 if (Enum->isFixed()) {
11205 EltTy = Enum->getIntegerType();
11206 }
11207 else {
11208 EltTy = Context.IntTy;
11209 }
11210 } else {
11211 // Assign the last value + 1.
11212 EnumVal = LastEnumConst->getInitVal();
11213 ++EnumVal;
11214 EltTy = LastEnumConst->getType();
11215
11216 // Check for overflow on increment.
11217 if (EnumVal < LastEnumConst->getInitVal()) {
11218 // C++0x [dcl.enum]p5:
11219 // If the underlying type is not fixed, the type of each enumerator
11220 // is the type of its initializing value:
11221 //
11222 // - Otherwise the type of the initializing value is the same as
11223 // the type of the initializing value of the preceding enumerator
11224 // unless the incremented value is not representable in that type,
11225 // in which case the type is an unspecified integral type
11226 // sufficient to contain the incremented value. If no such type
11227 // exists, the program is ill-formed.
11228 QualType T = getNextLargerIntegralType(Context, EltTy);
11229 if (T.isNull() || Enum->isFixed()) {
11230 // There is no integral type larger enough to represent this
11231 // value. Complain, then allow the value to wrap around.
11232 EnumVal = LastEnumConst->getInitVal();
11233 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
11234 ++EnumVal;
11235 if (Enum->isFixed())
11236 // When the underlying type is fixed, this is ill-formed.
11237 Diag(IdLoc, diag::err_enumerator_wrapped)
11238 << EnumVal.toString(10)
11239 << EltTy;
11240 else
11241 Diag(IdLoc, diag::warn_enumerator_too_large)
11242 << EnumVal.toString(10);
11243 } else {
11244 EltTy = T;
11245 }
11246
11247 // Retrieve the last enumerator's value, extent that type to the
11248 // type that is supposed to be large enough to represent the incremented
11249 // value, then increment.
11250 EnumVal = LastEnumConst->getInitVal();
11251 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
11252 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
11253 ++EnumVal;
11254
11255 // If we're not in C++, diagnose the overflow of enumerator values,
11256 // which in C99 means that the enumerator value is not representable in
11257 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
11258 // permits enumerator values that are representable in some larger
11259 // integral type.
11260 if (!getLangOpts().CPlusPlus && !T.isNull())
11261 Diag(IdLoc, diag::warn_enum_value_overflow);
11262 } else if (!getLangOpts().CPlusPlus &&
11263 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
11264 // Enforce C99 6.7.2.2p2 even when we compute the next value.
11265 Diag(IdLoc, diag::ext_enum_value_not_int)
11266 << EnumVal.toString(10) << 1;
11267 }
11268 }
11269 }
11270
11271 if (!EltTy->isDependentType()) {
11272 // Make the enumerator value match the signedness and size of the
11273 // enumerator's type.
11274 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
11275 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
11276 }
11277
11278 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
11279 Val, EnumVal);
11280 }
11281
11282
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,AttributeList * Attr,SourceLocation EqualLoc,Expr * Val)11283 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
11284 SourceLocation IdLoc, IdentifierInfo *Id,
11285 AttributeList *Attr,
11286 SourceLocation EqualLoc, Expr *Val) {
11287 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
11288 EnumConstantDecl *LastEnumConst =
11289 cast_or_null<EnumConstantDecl>(lastEnumConst);
11290
11291 // The scope passed in may not be a decl scope. Zip up the scope tree until
11292 // we find one that is.
11293 S = getNonFieldDeclScope(S);
11294
11295 // Verify that there isn't already something declared with this name in this
11296 // scope.
11297 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
11298 ForRedeclaration);
11299 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11300 // Maybe we will complain about the shadowed template parameter.
11301 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
11302 // Just pretend that we didn't see the previous declaration.
11303 PrevDecl = 0;
11304 }
11305
11306 if (PrevDecl) {
11307 // When in C++, we may get a TagDecl with the same name; in this case the
11308 // enum constant will 'hide' the tag.
11309 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
11310 "Received TagDecl when not in C++!");
11311 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
11312 if (isa<EnumConstantDecl>(PrevDecl))
11313 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
11314 else
11315 Diag(IdLoc, diag::err_redefinition) << Id;
11316 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11317 return 0;
11318 }
11319 }
11320
11321 // C++ [class.mem]p15:
11322 // If T is the name of a class, then each of the following shall have a name
11323 // different from T:
11324 // - every enumerator of every member of class T that is an unscoped
11325 // enumerated type
11326 if (CXXRecordDecl *Record
11327 = dyn_cast<CXXRecordDecl>(
11328 TheEnumDecl->getDeclContext()->getRedeclContext()))
11329 if (!TheEnumDecl->isScoped() &&
11330 Record->getIdentifier() && Record->getIdentifier() == Id)
11331 Diag(IdLoc, diag::err_member_name_of_class) << Id;
11332
11333 EnumConstantDecl *New =
11334 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
11335
11336 if (New) {
11337 // Process attributes.
11338 if (Attr) ProcessDeclAttributeList(S, New, Attr);
11339
11340 // Register this decl in the current scope stack.
11341 New->setAccess(TheEnumDecl->getAccess());
11342 PushOnScopeChains(New, S);
11343 }
11344
11345 ActOnDocumentableDecl(New);
11346
11347 return New;
11348 }
11349
11350 // Returns true when the enum initial expression does not trigger the
11351 // duplicate enum warning. A few common cases are exempted as follows:
11352 // Element2 = Element1
11353 // Element2 = Element1 + 1
11354 // Element2 = Element1 - 1
11355 // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)11356 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
11357 Expr *InitExpr = ECD->getInitExpr();
11358 if (!InitExpr)
11359 return true;
11360 InitExpr = InitExpr->IgnoreImpCasts();
11361
11362 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
11363 if (!BO->isAdditiveOp())
11364 return true;
11365 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
11366 if (!IL)
11367 return true;
11368 if (IL->getValue() != 1)
11369 return true;
11370
11371 InitExpr = BO->getLHS();
11372 }
11373
11374 // This checks if the elements are from the same enum.
11375 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
11376 if (!DRE)
11377 return true;
11378
11379 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
11380 if (!EnumConstant)
11381 return true;
11382
11383 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
11384 Enum)
11385 return true;
11386
11387 return false;
11388 }
11389
11390 struct DupKey {
11391 int64_t val;
11392 bool isTombstoneOrEmptyKey;
DupKeyDupKey11393 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
11394 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
11395 };
11396
GetDupKey(const llvm::APSInt & Val)11397 static DupKey GetDupKey(const llvm::APSInt& Val) {
11398 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
11399 false);
11400 }
11401
11402 struct DenseMapInfoDupKey {
getEmptyKeyDenseMapInfoDupKey11403 static DupKey getEmptyKey() { return DupKey(0, true); }
getTombstoneKeyDenseMapInfoDupKey11404 static DupKey getTombstoneKey() { return DupKey(1, true); }
getHashValueDenseMapInfoDupKey11405 static unsigned getHashValue(const DupKey Key) {
11406 return (unsigned)(Key.val * 37);
11407 }
isEqualDenseMapInfoDupKey11408 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
11409 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
11410 LHS.val == RHS.val;
11411 }
11412 };
11413
11414 // Emits a warning when an element is implicitly set a value that
11415 // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,Decl ** Elements,unsigned NumElements,EnumDecl * Enum,QualType EnumType)11416 static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements,
11417 unsigned NumElements, EnumDecl *Enum,
11418 QualType EnumType) {
11419 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
11420 Enum->getLocation()) ==
11421 DiagnosticsEngine::Ignored)
11422 return;
11423 // Avoid anonymous enums
11424 if (!Enum->getIdentifier())
11425 return;
11426
11427 // Only check for small enums.
11428 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
11429 return;
11430
11431 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
11432 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
11433
11434 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
11435 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
11436 ValueToVectorMap;
11437
11438 DuplicatesVector DupVector;
11439 ValueToVectorMap EnumMap;
11440
11441 // Populate the EnumMap with all values represented by enum constants without
11442 // an initialier.
11443 for (unsigned i = 0; i < NumElements; ++i) {
11444 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
11445
11446 // Null EnumConstantDecl means a previous diagnostic has been emitted for
11447 // this constant. Skip this enum since it may be ill-formed.
11448 if (!ECD) {
11449 return;
11450 }
11451
11452 if (ECD->getInitExpr())
11453 continue;
11454
11455 DupKey Key = GetDupKey(ECD->getInitVal());
11456 DeclOrVector &Entry = EnumMap[Key];
11457
11458 // First time encountering this value.
11459 if (Entry.isNull())
11460 Entry = ECD;
11461 }
11462
11463 // Create vectors for any values that has duplicates.
11464 for (unsigned i = 0; i < NumElements; ++i) {
11465 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
11466 if (!ValidDuplicateEnum(ECD, Enum))
11467 continue;
11468
11469 DupKey Key = GetDupKey(ECD->getInitVal());
11470
11471 DeclOrVector& Entry = EnumMap[Key];
11472 if (Entry.isNull())
11473 continue;
11474
11475 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
11476 // Ensure constants are different.
11477 if (D == ECD)
11478 continue;
11479
11480 // Create new vector and push values onto it.
11481 ECDVector *Vec = new ECDVector();
11482 Vec->push_back(D);
11483 Vec->push_back(ECD);
11484
11485 // Update entry to point to the duplicates vector.
11486 Entry = Vec;
11487
11488 // Store the vector somewhere we can consult later for quick emission of
11489 // diagnostics.
11490 DupVector.push_back(Vec);
11491 continue;
11492 }
11493
11494 ECDVector *Vec = Entry.get<ECDVector*>();
11495 // Make sure constants are not added more than once.
11496 if (*Vec->begin() == ECD)
11497 continue;
11498
11499 Vec->push_back(ECD);
11500 }
11501
11502 // Emit diagnostics.
11503 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
11504 DupVectorEnd = DupVector.end();
11505 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
11506 ECDVector *Vec = *DupVectorIter;
11507 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
11508
11509 // Emit warning for one enum constant.
11510 ECDVector::iterator I = Vec->begin();
11511 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
11512 << (*I)->getName() << (*I)->getInitVal().toString(10)
11513 << (*I)->getSourceRange();
11514 ++I;
11515
11516 // Emit one note for each of the remaining enum constants with
11517 // the same value.
11518 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
11519 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
11520 << (*I)->getName() << (*I)->getInitVal().toString(10)
11521 << (*I)->getSourceRange();
11522 delete Vec;
11523 }
11524 }
11525
ActOnEnumBody(SourceLocation EnumLoc,SourceLocation LBraceLoc,SourceLocation RBraceLoc,Decl * EnumDeclX,Decl ** Elements,unsigned NumElements,Scope * S,AttributeList * Attr)11526 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
11527 SourceLocation RBraceLoc, Decl *EnumDeclX,
11528 Decl **Elements, unsigned NumElements,
11529 Scope *S, AttributeList *Attr) {
11530 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
11531 QualType EnumType = Context.getTypeDeclType(Enum);
11532
11533 if (Attr)
11534 ProcessDeclAttributeList(S, Enum, Attr);
11535
11536 if (Enum->isDependentType()) {
11537 for (unsigned i = 0; i != NumElements; ++i) {
11538 EnumConstantDecl *ECD =
11539 cast_or_null<EnumConstantDecl>(Elements[i]);
11540 if (!ECD) continue;
11541
11542 ECD->setType(EnumType);
11543 }
11544
11545 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
11546 return;
11547 }
11548
11549 // TODO: If the result value doesn't fit in an int, it must be a long or long
11550 // long value. ISO C does not support this, but GCC does as an extension,
11551 // emit a warning.
11552 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
11553 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
11554 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
11555
11556 // Verify that all the values are okay, compute the size of the values, and
11557 // reverse the list.
11558 unsigned NumNegativeBits = 0;
11559 unsigned NumPositiveBits = 0;
11560
11561 // Keep track of whether all elements have type int.
11562 bool AllElementsInt = true;
11563
11564 for (unsigned i = 0; i != NumElements; ++i) {
11565 EnumConstantDecl *ECD =
11566 cast_or_null<EnumConstantDecl>(Elements[i]);
11567 if (!ECD) continue; // Already issued a diagnostic.
11568
11569 const llvm::APSInt &InitVal = ECD->getInitVal();
11570
11571 // Keep track of the size of positive and negative values.
11572 if (InitVal.isUnsigned() || InitVal.isNonNegative())
11573 NumPositiveBits = std::max(NumPositiveBits,
11574 (unsigned)InitVal.getActiveBits());
11575 else
11576 NumNegativeBits = std::max(NumNegativeBits,
11577 (unsigned)InitVal.getMinSignedBits());
11578
11579 // Keep track of whether every enum element has type int (very commmon).
11580 if (AllElementsInt)
11581 AllElementsInt = ECD->getType() == Context.IntTy;
11582 }
11583
11584 // Figure out the type that should be used for this enum.
11585 QualType BestType;
11586 unsigned BestWidth;
11587
11588 // C++0x N3000 [conv.prom]p3:
11589 // An rvalue of an unscoped enumeration type whose underlying
11590 // type is not fixed can be converted to an rvalue of the first
11591 // of the following types that can represent all the values of
11592 // the enumeration: int, unsigned int, long int, unsigned long
11593 // int, long long int, or unsigned long long int.
11594 // C99 6.4.4.3p2:
11595 // An identifier declared as an enumeration constant has type int.
11596 // The C99 rule is modified by a gcc extension
11597 QualType BestPromotionType;
11598
11599 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
11600 // -fshort-enums is the equivalent to specifying the packed attribute on all
11601 // enum definitions.
11602 if (LangOpts.ShortEnums)
11603 Packed = true;
11604
11605 if (Enum->isFixed()) {
11606 BestType = Enum->getIntegerType();
11607 if (BestType->isPromotableIntegerType())
11608 BestPromotionType = Context.getPromotedIntegerType(BestType);
11609 else
11610 BestPromotionType = BestType;
11611 // We don't need to set BestWidth, because BestType is going to be the type
11612 // of the enumerators, but we do anyway because otherwise some compilers
11613 // warn that it might be used uninitialized.
11614 BestWidth = CharWidth;
11615 }
11616 else if (NumNegativeBits) {
11617 // If there is a negative value, figure out the smallest integer type (of
11618 // int/long/longlong) that fits.
11619 // If it's packed, check also if it fits a char or a short.
11620 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
11621 BestType = Context.SignedCharTy;
11622 BestWidth = CharWidth;
11623 } else if (Packed && NumNegativeBits <= ShortWidth &&
11624 NumPositiveBits < ShortWidth) {
11625 BestType = Context.ShortTy;
11626 BestWidth = ShortWidth;
11627 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
11628 BestType = Context.IntTy;
11629 BestWidth = IntWidth;
11630 } else {
11631 BestWidth = Context.getTargetInfo().getLongWidth();
11632
11633 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
11634 BestType = Context.LongTy;
11635 } else {
11636 BestWidth = Context.getTargetInfo().getLongLongWidth();
11637
11638 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
11639 Diag(Enum->getLocation(), diag::warn_enum_too_large);
11640 BestType = Context.LongLongTy;
11641 }
11642 }
11643 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
11644 } else {
11645 // If there is no negative value, figure out the smallest type that fits
11646 // all of the enumerator values.
11647 // If it's packed, check also if it fits a char or a short.
11648 if (Packed && NumPositiveBits <= CharWidth) {
11649 BestType = Context.UnsignedCharTy;
11650 BestPromotionType = Context.IntTy;
11651 BestWidth = CharWidth;
11652 } else if (Packed && NumPositiveBits <= ShortWidth) {
11653 BestType = Context.UnsignedShortTy;
11654 BestPromotionType = Context.IntTy;
11655 BestWidth = ShortWidth;
11656 } else if (NumPositiveBits <= IntWidth) {
11657 BestType = Context.UnsignedIntTy;
11658 BestWidth = IntWidth;
11659 BestPromotionType
11660 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
11661 ? Context.UnsignedIntTy : Context.IntTy;
11662 } else if (NumPositiveBits <=
11663 (BestWidth = Context.getTargetInfo().getLongWidth())) {
11664 BestType = Context.UnsignedLongTy;
11665 BestPromotionType
11666 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
11667 ? Context.UnsignedLongTy : Context.LongTy;
11668 } else {
11669 BestWidth = Context.getTargetInfo().getLongLongWidth();
11670 assert(NumPositiveBits <= BestWidth &&
11671 "How could an initializer get larger than ULL?");
11672 BestType = Context.UnsignedLongLongTy;
11673 BestPromotionType
11674 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
11675 ? Context.UnsignedLongLongTy : Context.LongLongTy;
11676 }
11677 }
11678
11679 // Loop over all of the enumerator constants, changing their types to match
11680 // the type of the enum if needed.
11681 for (unsigned i = 0; i != NumElements; ++i) {
11682 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
11683 if (!ECD) continue; // Already issued a diagnostic.
11684
11685 // Standard C says the enumerators have int type, but we allow, as an
11686 // extension, the enumerators to be larger than int size. If each
11687 // enumerator value fits in an int, type it as an int, otherwise type it the
11688 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
11689 // that X has type 'int', not 'unsigned'.
11690
11691 // Determine whether the value fits into an int.
11692 llvm::APSInt InitVal = ECD->getInitVal();
11693
11694 // If it fits into an integer type, force it. Otherwise force it to match
11695 // the enum decl type.
11696 QualType NewTy;
11697 unsigned NewWidth;
11698 bool NewSign;
11699 if (!getLangOpts().CPlusPlus &&
11700 !Enum->isFixed() &&
11701 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
11702 NewTy = Context.IntTy;
11703 NewWidth = IntWidth;
11704 NewSign = true;
11705 } else if (ECD->getType() == BestType) {
11706 // Already the right type!
11707 if (getLangOpts().CPlusPlus)
11708 // C++ [dcl.enum]p4: Following the closing brace of an
11709 // enum-specifier, each enumerator has the type of its
11710 // enumeration.
11711 ECD->setType(EnumType);
11712 continue;
11713 } else {
11714 NewTy = BestType;
11715 NewWidth = BestWidth;
11716 NewSign = BestType->isSignedIntegerOrEnumerationType();
11717 }
11718
11719 // Adjust the APSInt value.
11720 InitVal = InitVal.extOrTrunc(NewWidth);
11721 InitVal.setIsSigned(NewSign);
11722 ECD->setInitVal(InitVal);
11723
11724 // Adjust the Expr initializer and type.
11725 if (ECD->getInitExpr() &&
11726 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
11727 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
11728 CK_IntegralCast,
11729 ECD->getInitExpr(),
11730 /*base paths*/ 0,
11731 VK_RValue));
11732 if (getLangOpts().CPlusPlus)
11733 // C++ [dcl.enum]p4: Following the closing brace of an
11734 // enum-specifier, each enumerator has the type of its
11735 // enumeration.
11736 ECD->setType(EnumType);
11737 else
11738 ECD->setType(NewTy);
11739 }
11740
11741 Enum->completeDefinition(BestType, BestPromotionType,
11742 NumPositiveBits, NumNegativeBits);
11743
11744 // If we're declaring a function, ensure this decl isn't forgotten about -
11745 // it needs to go into the function scope.
11746 if (InFunctionDeclarator)
11747 DeclsInPrototypeScope.push_back(Enum);
11748
11749 CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType);
11750
11751 // Now that the enum type is defined, ensure it's not been underaligned.
11752 if (Enum->hasAttrs())
11753 CheckAlignasUnderalignment(Enum);
11754 }
11755
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)11756 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
11757 SourceLocation StartLoc,
11758 SourceLocation EndLoc) {
11759 StringLiteral *AsmString = cast<StringLiteral>(expr);
11760
11761 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
11762 AsmString, StartLoc,
11763 EndLoc);
11764 CurContext->addDecl(New);
11765 return New;
11766 }
11767
ActOnModuleImport(SourceLocation AtLoc,SourceLocation ImportLoc,ModuleIdPath Path)11768 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
11769 SourceLocation ImportLoc,
11770 ModuleIdPath Path) {
11771 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
11772 Module::AllVisible,
11773 /*IsIncludeDirective=*/false);
11774 if (!Mod)
11775 return true;
11776
11777 SmallVector<SourceLocation, 2> IdentifierLocs;
11778 Module *ModCheck = Mod;
11779 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
11780 // If we've run out of module parents, just drop the remaining identifiers.
11781 // We need the length to be consistent.
11782 if (!ModCheck)
11783 break;
11784 ModCheck = ModCheck->Parent;
11785
11786 IdentifierLocs.push_back(Path[I].second);
11787 }
11788
11789 ImportDecl *Import = ImportDecl::Create(Context,
11790 Context.getTranslationUnitDecl(),
11791 AtLoc.isValid()? AtLoc : ImportLoc,
11792 Mod, IdentifierLocs);
11793 Context.getTranslationUnitDecl()->addDecl(Import);
11794 return Import;
11795 }
11796
createImplicitModuleImport(SourceLocation Loc,Module * Mod)11797 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
11798 // Create the implicit import declaration.
11799 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
11800 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
11801 Loc, Mod, Loc);
11802 TU->addDecl(ImportD);
11803 Consumer.HandleImplicitImportDecl(ImportD);
11804
11805 // Make the module visible.
11806 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
11807 }
11808
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)11809 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
11810 IdentifierInfo* AliasName,
11811 SourceLocation PragmaLoc,
11812 SourceLocation NameLoc,
11813 SourceLocation AliasNameLoc) {
11814 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
11815 LookupOrdinaryName);
11816 AsmLabelAttr *Attr =
11817 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
11818
11819 if (PrevDecl)
11820 PrevDecl->addAttr(Attr);
11821 else
11822 (void)ExtnameUndeclaredIdentifiers.insert(
11823 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
11824 }
11825
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)11826 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
11827 SourceLocation PragmaLoc,
11828 SourceLocation NameLoc) {
11829 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
11830
11831 if (PrevDecl) {
11832 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
11833 } else {
11834 (void)WeakUndeclaredIdentifiers.insert(
11835 std::pair<IdentifierInfo*,WeakInfo>
11836 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
11837 }
11838 }
11839
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)11840 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
11841 IdentifierInfo* AliasName,
11842 SourceLocation PragmaLoc,
11843 SourceLocation NameLoc,
11844 SourceLocation AliasNameLoc) {
11845 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
11846 LookupOrdinaryName);
11847 WeakInfo W = WeakInfo(Name, NameLoc);
11848
11849 if (PrevDecl) {
11850 if (!PrevDecl->hasAttr<AliasAttr>())
11851 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
11852 DeclApplyPragmaWeak(TUScope, ND, W);
11853 } else {
11854 (void)WeakUndeclaredIdentifiers.insert(
11855 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
11856 }
11857 }
11858
getObjCDeclContext() const11859 Decl *Sema::getObjCDeclContext() const {
11860 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
11861 }
11862
getCurContextAvailability() const11863 AvailabilityResult Sema::getCurContextAvailability() const {
11864 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
11865 return D->getAvailability();
11866 }
11867