blob: 2edebaba343987ba9dd936ce91c78751b628b855 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregor9e876872011-03-01 18:12:44 +000015#include "TypeLocBuilder.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Faisal Valifad9e132013-09-26 19:54:12 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000021#include "clang/AST/CommentDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Chandler Carrutha7689ef2011-03-27 09:46:56 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000026#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000027#include "clang/AST/StmtCXX.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34#include "clang/Parse/ParseDiagnostic.h"
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000043#include "llvm/ADT/SmallString.h"
John McCall66755862009-12-24 09:58:38 +000044#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000045#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000046#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000047#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000048using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000049using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000050
Richard Smithc89edf52011-07-01 19:46:12 +000051Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
52 if (OwnedType) {
53 Decl *Group[2] = { OwnedType, Ptr };
54 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
55 }
56
John McCalld226f652010-08-21 09:40:31 +000057 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner682bf922009-03-29 16:50:03 +000058}
59
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000060namespace {
61
62class TypeNameValidatorCCC : public CorrectionCandidateCallback {
63 public:
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000064 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
65 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000066 WantExpressionKeywords = false;
67 WantCXXNamedCasts = false;
68 WantRemainingKeywords = false;
69 }
70
71 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
72 if (NamedDecl *ND = candidate.getCorrectionDecl())
73 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
74 (AllowInvalidDecl || !ND->isInvalidDecl());
75 else
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000076 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000077 }
78
79 private:
80 bool AllowInvalidDecl;
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000081 bool WantClassName;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000082};
83
84}
85
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +000086/// \brief Determine whether the token kind starts a simple-type-specifier.
87bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
88 switch (Kind) {
89 // FIXME: Take into account the current language when deciding whether a
90 // token kind is a valid type specifier
91 case tok::kw_short:
92 case tok::kw_long:
93 case tok::kw___int64:
94 case tok::kw___int128:
95 case tok::kw_signed:
96 case tok::kw_unsigned:
97 case tok::kw_void:
98 case tok::kw_char:
99 case tok::kw_int:
100 case tok::kw_half:
101 case tok::kw_float:
102 case tok::kw_double:
103 case tok::kw_wchar_t:
104 case tok::kw_bool:
105 case tok::kw___underlying_type:
106 return true;
107
108 case tok::annot_typename:
109 case tok::kw_char16_t:
110 case tok::kw_char32_t:
111 case tok::kw_typeof:
David Majnemerff989a82013-09-22 01:24:26 +0000112 case tok::annot_decltype:
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +0000113 case tok::kw_decltype:
114 return getLangOpts().CPlusPlus;
115
116 default:
117 break;
118 }
119
120 return false;
121}
122
Douglas Gregord6efafa2009-02-04 19:16:12 +0000123/// \brief If the identifier refers to a type name within this scope,
124/// return the declaration of that type.
125///
126/// This routine performs ordinary name lookup of the identifier II
127/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000128/// determine whether the name refers to a type. If so, returns an
129/// opaque pointer (actually a QualType) corresponding to that
130/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +0000131///
132/// If name lookup results in an ambiguity, this routine will complain
133/// and then return NULL.
Dmitri Gribenko8eead162013-05-03 13:12:11 +0000134ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallb3d87482010-08-24 05:47:05 +0000135 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000136 bool isClassName, bool HasTrailingDot,
Douglas Gregor9e876872011-03-01 18:12:44 +0000137 ParsedType ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000138 bool IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000139 bool WantNontrivialTypeSourceInfo,
140 IdentifierInfo **CorrectedII) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000141 // Determine where we will perform name lookup.
142 DeclContext *LookupCtx = 0;
143 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +0000144 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000145 if (ObjectType->isRecordType())
146 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +0000147 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000148 LookupCtx = computeDeclContext(*SS, false);
149
150 if (!LookupCtx) {
151 if (isDependentScopeSpecifier(*SS)) {
152 // C++ [temp.res]p3:
153 // A qualified-id that refers to a type and in which the
154 // nested-name-specifier depends on a template-parameter (14.6.2)
155 // shall be prefixed by the keyword typename to indicate that the
156 // qualified-id denotes a type, forming an
157 // elaborated-type-specifier (7.1.5.3).
158 //
159 // We therefore do not perform any name lookup if the result would
160 // refer to a member of an unknown specialization.
Richard Smithc5a89a12012-04-02 01:30:27 +0000161 if (!isClassName && !IsCtorOrDtorName)
John McCallb3d87482010-08-24 05:47:05 +0000162 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000163
John McCall33500952010-06-11 00:33:02 +0000164 // We know from the grammar that this name refers to a type,
165 // so build a dependent node to describe the type.
Douglas Gregor9e876872011-03-01 18:12:44 +0000166 if (WantNontrivialTypeSourceInfo)
167 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
168
169 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallb3d87482010-08-24 05:47:05 +0000170 QualType T =
Douglas Gregor9e876872011-03-01 18:12:44 +0000171 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +0000172 II, NameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +0000173
174 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000175 }
176
John McCallb3d87482010-08-24 05:47:05 +0000177 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000178 }
179
John McCall77bb1aa2010-05-01 00:40:08 +0000180 if (!LookupCtx->isDependentContext() &&
181 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000182 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000183 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000184
185 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
186 // lookup for class-names.
187 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
188 LookupOrdinaryName;
189 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000190 if (LookupCtx) {
191 // Perform "qualified" name lookup into the declaration context we
192 // computed, which is either the type of the base of a member access
193 // expression or the declaration context associated with a prior
194 // nested-name-specifier.
195 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000196
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000197 if (ObjectTypePtr && Result.empty()) {
198 // C++ [basic.lookup.classref]p3:
199 // If the unqualified-id is ~type-name, the type-name is looked up
200 // in the context of the entire postfix-expression. If the type T of
201 // the object expression is of a class type C, the type-name is also
202 // looked up in the scope of class C. At least one of the lookups shall
203 // find a name that refers to (possibly cv-qualified) T.
204 LookupName(Result, S);
205 }
206 } else {
207 // Perform unqualified name lookup.
208 LookupName(Result, S);
209 }
210
Chris Lattner22bd9052009-02-16 22:07:16 +0000211 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000212 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000213 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000214 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000215 if (CorrectedII) {
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +0000216 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000217 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000218 Kind, S, SS, Validator);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000219 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
220 TemplateTy Template;
221 bool MemberOfUnknownSpecialization;
222 UnqualifiedId TemplateName;
223 TemplateName.setIdentifier(NewII, NameLoc);
224 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
225 CXXScopeSpec NewSS, *NewSSPtr = SS;
226 if (SS && NNS) {
227 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
228 NewSSPtr = &NewSS;
229 }
230 if (Correction && (NNS || NewII != &II) &&
231 // Ignore a correction to a template type as the to-be-corrected
232 // identifier is not a template (typo correction for template names
233 // is handled elsewhere).
David Blaikie4e4d0842012-03-11 07:00:24 +0000234 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000235 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
236 false, Template, MemberOfUnknownSpecialization))) {
237 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
238 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000239 IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000240 WantNontrivialTypeSourceInfo);
241 if (Ty) {
Richard Smith2d670972013-08-17 00:46:16 +0000242 diagnoseTypo(Correction,
243 PDiag(diag::err_unknown_type_or_class_name_suggest)
244 << Result.getLookupName() << isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000245 if (SS && NNS)
246 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
247 *CorrectedII = NewII;
248 return Ty;
249 }
250 }
251 }
252 // If typo correction failed or was not performed, fall through
Chris Lattner22bd9052009-02-16 22:07:16 +0000253 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000254 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000255 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000256 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000257
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000258 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000259 // Recover from type-hiding ambiguities by hiding the type. We'll
260 // do the lookup again when looking for an object, and we can
261 // diagnose the error then. If we don't do this, then the error
262 // about hiding the type will be immediately followed by an error
263 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000264 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
265 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000266 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000267 }
John McCall6e247262009-10-10 05:48:19 +0000268
Douglas Gregor31a19b62009-04-01 21:51:26 +0000269 // Look to see if we have a type anywhere in the list of results.
270 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
271 Res != ResEnd; ++Res) {
272 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000273 if (!IIDecl ||
274 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000275 IIDecl->getLocation().getRawEncoding())
276 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000277 }
278 }
279
280 if (!IIDecl) {
281 // None of the entities we found is a type, so there is no way
282 // to even assume that the result is a type. In this case, don't
283 // complain about the ambiguity. The parser will either try to
284 // perform this lookup again (e.g., as an object name), which
285 // will produce the ambiguity, or will complain that it expected
286 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000287 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000288 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000289 }
290
291 // We found a type within the ambiguous lookup; diagnose the
292 // ambiguity and then return that type. This might be the right
293 // answer, or it might not be, but it suppresses any attempt to
294 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000295 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000296
Chris Lattner22bd9052009-02-16 22:07:16 +0000297 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000298 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000299 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000300 }
301
Chris Lattner10ca3372009-10-25 17:16:46 +0000302 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000303
Chris Lattner10ca3372009-10-25 17:16:46 +0000304 QualType T;
305 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000306 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000307
Chris Lattner10ca3372009-10-25 17:16:46 +0000308 if (T.isNull())
309 T = Context.getTypeDeclType(TD);
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000310
311 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
312 // constructor or destructor name (in such a case, the scope specifier
313 // will be attached to the enclosing Expr or Decl node).
314 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor9e876872011-03-01 18:12:44 +0000315 if (WantNontrivialTypeSourceInfo) {
316 // Construct a type with type-source information.
317 TypeLocBuilder Builder;
318 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
319
320 T = getElaboratedType(ETK_None, *SS, T);
321 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +0000322 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor9e876872011-03-01 18:12:44 +0000323 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
324 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
325 } else {
326 T = getElaboratedType(ETK_None, *SS, T);
327 }
328 }
Chris Lattner10ca3372009-10-25 17:16:46 +0000329 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000330 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000331 if (!HasTrailingDot)
332 T = Context.getObjCInterfaceType(IDecl);
333 }
334
335 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000336 // If it's not plausibly a type, suppress diagnostics.
337 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000338 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000339 }
John McCallb3d87482010-08-24 05:47:05 +0000340 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000341}
342
Chris Lattner4c97d762009-04-12 21:49:30 +0000343/// isTagName() - This method is called *for error recovery purposes only*
344/// to determine if the specified name is a valid tag name ("struct foo"). If
345/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matos6666ed42012-08-31 18:45:21 +0000346/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
347/// cases in C where the user forgot to specify the tag.
Chris Lattner4c97d762009-04-12 21:49:30 +0000348DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
349 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000350 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
351 LookupName(R, S, false);
352 R.suppressDiagnostics();
353 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000354 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000355 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000356 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matos6666ed42012-08-31 18:45:21 +0000357 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000358 case TTK_Union: return DeclSpec::TST_union;
359 case TTK_Class: return DeclSpec::TST_class;
360 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000361 }
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chris Lattner4c97d762009-04-12 21:49:30 +0000364 return DeclSpec::TST_unspecified;
365}
366
Francois Pichet6943e9b2011-04-13 02:38:49 +0000367/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
368/// if a CXXScopeSpec's type is equal to the type of one of the base classes
369/// then downgrade the missing typename error to a warning.
370/// This is needed for MSVC compatibility; Example:
371/// @code
372/// template<class T> class A {
373/// public:
374/// typedef int TYPE;
375/// };
376/// template<class T> class B : public A<T> {
377/// public:
378/// A<T>::TYPE a; // no typename required because A<T> is a base class.
379/// };
380/// @endcode
Francois Pichetf11dbe92011-10-11 01:50:09 +0000381bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000382 if (CurContext->isRecord()) {
Francois Pichet3441a522011-04-13 02:44:57 +0000383 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000384
385 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
386 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
387 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
388 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
389 return true;
Francois Pichetf11dbe92011-10-11 01:50:09 +0000390 return S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000391 }
Francois Pichetf11dbe92011-10-11 01:50:09 +0000392 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000393}
394
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000395bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000396 SourceLocation IILoc,
397 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000398 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000399 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000400 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000401 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000402
Douglas Gregor546be3c2009-12-30 17:04:44 +0000403 // There may have been a typo in the name of the type. Look up typo
404 // results, in case we have something that we can suggest.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000405 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000406 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000407 LookupOrdinaryName, S, SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000408 Validator)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000409 if (Corrected.isKeyword()) {
410 // We corrected to a keyword.
Richard Smith2d670972013-08-17 00:46:16 +0000411 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
412 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000413 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000414 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000415 if (!SS || !SS->isSet()) {
Richard Smith2d670972013-08-17 00:46:16 +0000416 diagnoseTypo(Corrected,
417 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000418 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +0000419 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
420 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000421 II->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000422 diagnoseTypo(Corrected,
423 PDiag(diag::err_unknown_nested_typename_suggest)
424 << II << DC << DroppedSpecifier << SS->getRange());
425 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000426 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000427 }
Douglas Gregor546be3c2009-12-30 17:04:44 +0000428
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000429 CXXScopeSpec tmpSS;
430 if (Corrected.getCorrectionSpecifier())
431 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
432 SourceRange(IILoc));
Richard Smith2d670972013-08-17 00:46:16 +0000433 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000434 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
435 false, ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000436 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000437 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor546be3c2009-12-30 17:04:44 +0000438 }
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000439 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000440 }
441
David Blaikie4e4d0842012-03-11 07:00:24 +0000442 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000443 // See if II is a class template that the user forgot to pass arguments to.
444 UnqualifiedId Name;
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000445 Name.setIdentifier(II, IILoc);
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000446 CXXScopeSpec EmptySS;
447 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000448 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000449 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000450 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000451 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov18062392013-08-27 13:15:56 +0000452 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000453 Diag(IILoc, diag::err_template_missing_args) << TplName;
454 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
455 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
456 << TplDecl->getTemplateParameters()->getSourceRange();
457 }
458 return true;
459 }
460 }
461
Douglas Gregora786fdb2009-10-13 23:27:22 +0000462 // FIXME: Should we move the logic that tries to recover from a missing tag
463 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
464
Douglas Gregor546be3c2009-12-30 17:04:44 +0000465 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000466 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregora786fdb2009-10-13 23:27:22 +0000467 else if (DeclContext *DC = computeDeclContext(*SS, false))
468 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000469 << II << DC << SS->getRange();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000470 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000471 unsigned DiagID = diag::err_typename_missing;
David Blaikie4e4d0842012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichetcf320c62011-04-22 08:25:24 +0000473 DiagID = diag::warn_typename_missing;
Francois Pichet6943e9b2011-04-13 02:38:49 +0000474
475 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000476 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000477 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000478 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000479 SuggestedType = ActOnTypenameType(S, SourceLocation(),
480 *SS, *II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000481 } else {
482 assert(SS && SS->isInvalid() &&
483 "Invalid scope specifier has already been diagnosed");
484 }
485
486 return true;
487}
Chris Lattner4c97d762009-04-12 21:49:30 +0000488
Douglas Gregor312eadb2011-04-24 05:37:28 +0000489/// \brief Determine whether the given result set contains either a type name
490/// or
491static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000492 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000493 NextToken.is(tok::less);
494
495 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
496 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
497 return true;
498
499 if (CheckTemplate && isa<TemplateDecl>(*I))
500 return true;
501 }
502
503 return false;
504}
505
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000506static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
507 Scope *S, CXXScopeSpec &SS,
508 IdentifierInfo *&Name,
509 SourceLocation NameLoc) {
Richard Smith69e48262012-09-06 01:37:56 +0000510 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
511 SemaRef.LookupParsedName(R, S, &SS);
512 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000513 const char *TagName = 0;
514 const char *FixItTagName = 0;
515 switch (Tag->getTagKind()) {
516 case TTK_Class:
517 TagName = "class";
518 FixItTagName = "class ";
519 break;
520
521 case TTK_Enum:
522 TagName = "enum";
523 FixItTagName = "enum ";
524 break;
525
526 case TTK_Struct:
527 TagName = "struct";
528 FixItTagName = "struct ";
529 break;
530
Joao Matos6666ed42012-08-31 18:45:21 +0000531 case TTK_Interface:
532 TagName = "__interface";
533 FixItTagName = "__interface ";
534 break;
535
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000536 case TTK_Union:
537 TagName = "union";
538 FixItTagName = "union ";
539 break;
540 }
541
542 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
543 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
544 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
545
Richard Smith69e48262012-09-06 01:37:56 +0000546 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
547 I != IEnd; ++I)
548 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
549 << Name << TagName;
550
551 // Replace lookup results with just the tag decl.
552 Result.clear(Sema::LookupTagName);
553 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000554 return true;
555 }
556
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000557 return false;
558}
559
Richard Smith05766812012-08-18 00:55:03 +0000560/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
561static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
562 QualType T, SourceLocation NameLoc) {
563 ASTContext &Context = S.Context;
564
565 TypeLocBuilder Builder;
566 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
567
568 T = S.getElaboratedType(ETK_None, SS, T);
569 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
570 ElabTL.setElaboratedKeywordLoc(SourceLocation());
571 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
572 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
573}
574
Douglas Gregor312eadb2011-04-24 05:37:28 +0000575Sema::NameClassification Sema::ClassifyName(Scope *S,
576 CXXScopeSpec &SS,
577 IdentifierInfo *&Name,
578 SourceLocation NameLoc,
Richard Smith05766812012-08-18 00:55:03 +0000579 const Token &NextToken,
580 bool IsAddressOfOperand,
581 CorrectionCandidateCallback *CCC) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000582 DeclarationNameInfo NameInfo(Name, NameLoc);
583 ObjCMethodDecl *CurMethod = getCurMethodDecl();
584
585 if (NextToken.is(tok::coloncolon)) {
586 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
587 QualType(), false, SS, 0, false);
588
589 }
590
591 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
592 LookupParsedName(Result, S, &SS, !CurMethod);
593
594 // Perform lookup for Objective-C instance variables (including automatically
595 // synthesized instance variables), if we're in an Objective-C method.
596 // FIXME: This lookup really, really needs to be folded in to the normal
597 // unqualified lookup mechanism.
598 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
599 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorec385cf2011-04-25 15:05:41 +0000600 if (E.get() || E.isInvalid())
Douglas Gregor312eadb2011-04-24 05:37:28 +0000601 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000602 }
603
604 bool SecondTry = false;
605 bool IsFilteredTemplateName = false;
606
607Corrected:
608 switch (Result.getResultKind()) {
609 case LookupResult::NotFound:
610 // If an unqualified-id is followed by a '(', then we have a function
611 // call.
612 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
613 // In C++, this is an ADL-only call.
614 // FIXME: Reference?
David Blaikie4e4d0842012-03-11 07:00:24 +0000615 if (getLangOpts().CPlusPlus)
Douglas Gregor312eadb2011-04-24 05:37:28 +0000616 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
617
618 // C90 6.3.2.2:
619 // If the expression that precedes the parenthesized argument list in a
620 // function call consists solely of an identifier, and if no
621 // declaration is visible for this identifier, the identifier is
622 // implicitly declared exactly as if, in the innermost block containing
623 // the function call, the declaration
624 //
625 // extern int identifier ();
626 //
627 // appeared.
628 //
629 // We also allow this in C99 as an extension.
630 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
631 Result.addDecl(D);
632 Result.resolveKind();
633 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
634 }
635 }
636
637 // In C, we first see whether there is a tag type by the same name, in
638 // which case it's likely that the user just forget to write "enum",
639 // "struct", or "union".
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000640 if (!getLangOpts().CPlusPlus && !SecondTry &&
641 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
642 break;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000643 }
644
645 // Perform typo correction to determine if there is another name that is
646 // close to this name.
Richard Smith05766812012-08-18 00:55:03 +0000647 if (!SecondTry && CCC) {
Douglas Gregor3a348c82011-07-14 04:54:23 +0000648 SecondTry = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000649 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikied662a792011-10-19 22:56:21 +0000650 Result.getLookupKind(), S,
Richard Smith05766812012-08-18 00:55:03 +0000651 &SS, *CCC)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000652 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
653 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smith2d670972013-08-17 00:46:16 +0000654
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000655 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor3b887352011-04-27 04:48:22 +0000656 NamedDecl *UnderlyingFirstDecl
657 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikie4e4d0842012-03-11 07:00:24 +0000658 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000659 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000660 UnqualifiedDiag = diag::err_no_template_suggest;
661 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor3b887352011-04-27 04:48:22 +0000662 } else if (UnderlyingFirstDecl &&
663 (isa<TypeDecl>(UnderlyingFirstDecl) ||
664 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
665 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie30262b72013-03-21 21:35:15 +0000666 UnqualifiedDiag = diag::err_unknown_typename_suggest;
667 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
668 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000669
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000670 if (SS.isEmpty()) {
Richard Smith2d670972013-08-17 00:46:16 +0000671 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000672 } else {// FIXME: is this even reachable? Test it.
Richard Smith2d670972013-08-17 00:46:16 +0000673 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
674 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000675 Name->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000676 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
677 << Name << computeDeclContext(SS, false)
678 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000679 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000680
681 // Update the name, so that the caller has the new name.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000682 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smith2d670972013-08-17 00:46:16 +0000683
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000684 // Typo correction corrected to a keyword.
685 if (Corrected.isKeyword())
Richard Smith2d670972013-08-17 00:46:16 +0000686 return Name;
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000687
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000688 // Also update the LookupResult...
689 // FIXME: This should probably go away at some point
690 Result.clear();
691 Result.setLookupName(Corrected.getCorrection());
Richard Smith2d670972013-08-17 00:46:16 +0000692 if (FirstDecl)
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000693 Result.addDecl(FirstDecl);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000694
695 // If we found an Objective-C instance variable, let
696 // LookupInObjCMethod build the appropriate expression to
697 // reference the ivar.
698 // FIXME: This is a gross hack.
699 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
700 Result.clear();
701 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000702 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000703 }
704
705 goto Corrected;
706 }
707 }
708
709 // We failed to correct; just fall through and let the parser deal with it.
710 Result.suppressDiagnostics();
711 return NameClassification::Unknown();
712
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000713 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000714 // We performed name lookup into the current instantiation, and there were
715 // dependent bases, so we treat this result the same way as any other
716 // dependent nested-name-specifier.
717
718 // C++ [temp.res]p2:
719 // A name used in a template declaration or definition and that is
720 // dependent on a template-parameter is assumed not to name a type
721 // unless the applicable name lookup finds a type name or the name is
722 // qualified by the keyword typename.
723 //
724 // FIXME: If the next token is '<', we might want to ask the parser to
725 // perform some heroics to see if we actually have a
726 // template-argument-list, which would indicate a missing 'template'
727 // keyword here.
Richard Smith05766812012-08-18 00:55:03 +0000728 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
729 NameInfo, IsAddressOfOperand,
730 /*TemplateArgs=*/0);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000731 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000732
733 case LookupResult::Found:
734 case LookupResult::FoundOverloaded:
735 case LookupResult::FoundUnresolvedValue:
736 break;
737
738 case LookupResult::Ambiguous:
David Blaikie4e4d0842012-03-11 07:00:24 +0000739 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000740 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000741 // C++ [temp.local]p3:
742 // A lookup that finds an injected-class-name (10.2) can result in an
743 // ambiguity in certain cases (for example, if it is found in more than
744 // one base class). If all of the injected-class-names that are found
745 // refer to specializations of the same class template, and if the name
746 // is followed by a template-argument-list, the reference refers to the
747 // class template itself and not a specialization thereof, and is not
748 // ambiguous.
749 //
750 // This filtering can make an ambiguous result into an unambiguous one,
751 // so try again after filtering out template names.
752 FilterAcceptableTemplateNames(Result);
753 if (!Result.isAmbiguous()) {
754 IsFilteredTemplateName = true;
755 break;
756 }
757 }
758
759 // Diagnose the ambiguity and return an error.
760 return NameClassification::Error();
761 }
762
David Blaikie4e4d0842012-03-11 07:00:24 +0000763 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000764 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
765 // C++ [temp.names]p3:
766 // After name lookup (3.4) finds that a name is a template-name or that
767 // an operator-function-id or a literal- operator-id refers to a set of
768 // overloaded functions any member of which is a function template if
769 // this is followed by a <, the < is always taken as the delimiter of a
770 // template-argument-list and never as the less-than operator.
771 if (!IsFilteredTemplateName)
772 FilterAcceptableTemplateNames(Result);
773
Douglas Gregor3b887352011-04-27 04:48:22 +0000774 if (!Result.empty()) {
775 bool IsFunctionTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000776 bool IsVarTemplate;
Douglas Gregor3b887352011-04-27 04:48:22 +0000777 TemplateName Template;
778 if (Result.end() - Result.begin() > 1) {
779 IsFunctionTemplate = true;
780 Template = Context.getOverloadedTemplateName(Result.begin(),
781 Result.end());
782 } else {
783 TemplateDecl *TD
784 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
785 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000786 IsVarTemplate = isa<VarTemplateDecl>(TD);
787
Douglas Gregor3b887352011-04-27 04:48:22 +0000788 if (SS.isSet() && !SS.isInvalid())
789 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000790 /*TemplateKeyword=*/false,
Douglas Gregor3b887352011-04-27 04:48:22 +0000791 TD);
792 else
793 Template = TemplateName(TD);
794 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000795
Douglas Gregor3b887352011-04-27 04:48:22 +0000796 if (IsFunctionTemplate) {
797 // Function templates always go through overload resolution, at which
798 // point we'll perform the various checks (e.g., accessibility) we need
799 // to based on which function we selected.
800 Result.suppressDiagnostics();
801
802 return NameClassification::FunctionTemplate(Template);
803 }
Larisse Voufoef4579c2013-08-06 01:03:05 +0000804
805 return IsVarTemplate ? NameClassification::VarTemplate(Template)
806 : NameClassification::TypeTemplate(Template);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000807 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000808 }
Richard Smith05766812012-08-18 00:55:03 +0000809
Douglas Gregor3b887352011-04-27 04:48:22 +0000810 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000811 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
812 DiagnoseUseOfDecl(Type, NameLoc);
813 QualType T = Context.getTypeDeclType(Type);
Richard Smith05766812012-08-18 00:55:03 +0000814 if (SS.isNotEmpty())
815 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000816 return ParsedType::make(T);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000817 }
Richard Smith05766812012-08-18 00:55:03 +0000818
Douglas Gregor312eadb2011-04-24 05:37:28 +0000819 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
820 if (!Class) {
821 // FIXME: It's unfortunate that we don't have a Type node for handling this.
822 if (ObjCCompatibleAliasDecl *Alias
823 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
824 Class = Alias->getClassInterface();
825 }
826
827 if (Class) {
828 DiagnoseUseOfDecl(Class, NameLoc);
829
830 if (NextToken.is(tok::period)) {
831 // Interface. <something> is parsed as a property reference expression.
832 // Just return "unknown" as a fall-through for now.
833 Result.suppressDiagnostics();
834 return NameClassification::Unknown();
835 }
836
837 QualType T = Context.getObjCInterfaceType(Class);
838 return ParsedType::make(T);
839 }
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000840
Richard Smith05766812012-08-18 00:55:03 +0000841 // We can have a type template here if we're classifying a template argument.
842 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
843 return NameClassification::TypeTemplate(
844 TemplateName(cast<TemplateDecl>(FirstDecl)));
845
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000846 // Check for a tag type hidden by a non-type decl in a few cases where it
847 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidis99e9fe02013-05-07 19:54:28 +0000848 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
849 if ((NextToken.is(tok::identifier) ||
850 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
851 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
852 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
853 DiagnoseUseOfDecl(Type, NameLoc);
854 QualType T = Context.getTypeDeclType(Type);
855 if (SS.isNotEmpty())
856 return buildNestedType(*this, SS, T, NameLoc);
857 return ParsedType::make(T);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000858 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000859
Richard Smith05766812012-08-18 00:55:03 +0000860 if (FirstDecl->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000861 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor3b887352011-04-27 04:48:22 +0000862
Douglas Gregor312eadb2011-04-24 05:37:28 +0000863 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
864 return BuildDeclarationNameExpr(SS, Result, ADL);
865}
866
John McCall88232aa2009-08-18 00:00:49 +0000867// Determines the context to return to after temporarily entering a
868// context. This depends in an unnecessarily complicated way on the
869// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000870DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000871
John McCall88232aa2009-08-18 00:00:49 +0000872 // Functions defined inline within classes aren't parsed until we've
873 // finished parsing the top-level class, so the top-level class is
874 // the context we'll need to return to.
875 if (isa<FunctionDecl>(DC)) {
876 DC = DC->getLexicalParent();
877
878 // A function not defined within a class will always return to its
879 // lexical context.
880 if (!isa<CXXRecordDecl>(DC))
881 return DC;
882
883 // A C++ inline method/friend is parsed *after* the topmost class
884 // it was declared in is fully parsed ("complete"); the topmost
885 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000886 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000887 DC = RD;
888
889 // Return the declaration context of the topmost class the inline method is
890 // declared in.
891 return DC;
892 }
893
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000894 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000895}
896
Douglas Gregor44b43212008-12-11 16:49:14 +0000897void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000898 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000899 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000900 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000901 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000902}
903
Chris Lattnerb048c982008-04-06 04:47:34 +0000904void Sema::PopDeclContext() {
905 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000906
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000907 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000908 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000909}
910
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000911/// EnterDeclaratorContext - Used when we must lookup names in the context
912/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000913///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000914void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000915 // C++0x [basic.lookup.unqual]p13:
916 // A name used in the definition of a static data member of class
917 // X (after the qualified-id of the static member) is looked up as
918 // if the name was used in a member function of X.
919 // C++0x [basic.lookup.unqual]p14:
920 // If a variable member of a namespace is defined outside of the
921 // scope of its namespace then any name used in the definition of
922 // the variable member (after the declarator-id) is looked up as
923 // if the definition of the variable member occurred in its
924 // namespace.
925 // Both of these imply that we should push a scope whose context
926 // is the semantic context of the declaration. We can't use
927 // PushDeclContext here because that context is not necessarily
928 // lexically contained in the current context. Fortunately,
929 // the containing scope should have the appropriate information.
930
931 assert(!S->getEntity() && "scope already has entity");
932
933#ifndef NDEBUG
934 Scope *Ancestor = S->getParent();
935 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
936 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
937#endif
938
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000939 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000940 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000941}
942
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000943void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000944 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000945
John McCall7a1dc562009-12-19 10:49:29 +0000946 // Switch back to the lexical context. The safety of this is
947 // enforced by an assert in EnterDeclaratorContext.
948 Scope *Ancestor = S->getParent();
949 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekf0d58612013-10-08 17:08:03 +0000950 CurContext = Ancestor->getEntity();
John McCall7a1dc562009-12-19 10:49:29 +0000951
952 // We don't need to do anything with the scope, which is going to
953 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000954}
955
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000956
957void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
958 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
959 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
960 // We assume that the caller has already called
961 // ActOnReenterTemplateScope
962 FD = TFD->getTemplatedDecl();
963 }
964 if (!FD)
965 return;
966
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000967 // Same implementation as PushDeclContext, but enters the context
968 // from the lexical parent, rather than the top-level class.
969 assert(CurContext == FD->getLexicalParent() &&
970 "The next DeclContext should be lexically contained in the current one.");
971 CurContext = FD;
972 S->setEntity(CurContext);
973
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000974 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
975 ParmVarDecl *Param = FD->getParamDecl(P);
976 // If the parameter has an identifier, then add it to the scope
977 if (Param->getIdentifier()) {
978 S->AddDecl(Param);
979 IdResolver.AddDecl(Param);
980 }
981 }
982}
983
984
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000985void Sema::ActOnExitFunctionContext() {
986 // Same implementation as PopDeclContext, but returns to the lexical parent,
987 // rather than the top-level class.
988 assert(CurContext && "DeclContext imbalance!");
989 CurContext = CurContext->getLexicalParent();
990 assert(CurContext && "Popped translation unit!");
991}
992
993
Douglas Gregorf9201e02009-02-11 23:02:49 +0000994/// \brief Determine whether we allow overloading of the function
995/// PrevDecl with another declaration.
996///
997/// This routine determines whether overloading is possible, not
998/// whether some new function is actually an overload. It will return
999/// true in C++ (where we can always provide overloads) or, as an
1000/// extension, in C when the previous function is already an
1001/// overloaded function declaration or has the "overloadable"
1002/// attribute.
John McCall68263142009-11-18 22:49:29 +00001003static bool AllowOverloadingOfFunction(LookupResult &Previous,
1004 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001005 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001006 return true;
1007
John McCall68263142009-11-18 22:49:29 +00001008 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001009 return true;
1010
John McCall68263142009-11-18 22:49:29 +00001011 return (Previous.getResultKind() == LookupResult::Found
1012 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +00001013}
1014
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001015/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +00001016void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +00001017 // Move up the scope chain until we find the nearest enclosing
1018 // non-transparent context. The declaration will be introduced into this
1019 // scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00001020 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor074149e2009-01-05 19:45:36 +00001021 S = S->getParent();
1022
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001023 // Add scoped declarations into their context, so that they can be
1024 // found later. Declarations without a context won't be inserted
1025 // into any context.
John McCallab88d972009-08-31 22:39:49 +00001026 if (AddToContext)
1027 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001028
Richard Smitha41c97a2013-09-20 01:15:31 +00001029 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1030 // are function-local declarations.
1031 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +00001032 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smitha41c97a2013-09-20 01:15:31 +00001033 D->getLexicalDeclContext()->getRedeclContext()) &&
1034 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruth8761d682010-02-21 07:08:09 +00001035 return;
1036
1037 // Template instantiations should also not be pushed into scope.
1038 if (isa<FunctionDecl>(D) &&
1039 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +00001040 return;
1041
John McCallf36e02d2009-10-09 21:13:30 +00001042 // If this replaces anything in the current scope,
1043 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1044 IEnd = IdResolver.end();
1045 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001046 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1047 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +00001048 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001049
John McCallf36e02d2009-10-09 21:13:30 +00001050 // Should only need to replace one decl.
1051 break;
Douglas Gregor516ff432009-04-24 02:57:34 +00001052 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001053 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001054
John McCalld226f652010-08-21 09:40:31 +00001055 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001056
1057 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1058 // Implicitly-generated labels may end up getting generated in an order that
1059 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1060 // the label at the appropriate place in the identifier chain.
1061 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +00001062 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +00001063 if (IDC == CurContext) {
1064 if (!S->isDeclScope(*I))
1065 continue;
1066 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001067 break;
1068 }
1069
Douglas Gregor250e7a72011-03-16 16:39:03 +00001070 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001071 } else {
1072 IdResolver.AddDecl(D);
1073 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001074}
1075
Douglas Gregoreee242f2011-10-27 09:33:13 +00001076void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1077 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1078 TUScope->AddDecl(D);
1079}
1080
Richard Smithdd9459f2013-08-13 18:18:50 +00001081bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001082 bool ExplicitInstantiationOrSpecialization) {
Nico Weber355a1662012-12-17 03:51:09 +00001083 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001084 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001085}
1086
John McCall5f1e0942010-08-24 08:50:51 +00001087Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1088 DeclContext *TargetDC = DC->getPrimaryContext();
1089 do {
Ted Kremenekf0d58612013-10-08 17:08:03 +00001090 if (DeclContext *ScopeDC = S->getEntity())
John McCall5f1e0942010-08-24 08:50:51 +00001091 if (ScopeDC->getPrimaryContext() == TargetDC)
1092 return S;
1093 } while ((S = S->getParent()));
1094
1095 return 0;
1096}
1097
John McCall68263142009-11-18 22:49:29 +00001098static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1099 DeclContext*,
1100 ASTContext&);
1101
1102/// Filters out lookup results that don't fall within the given scope
1103/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001104void Sema::FilterLookupForScope(LookupResult &R,
1105 DeclContext *Ctx, Scope *S,
1106 bool ConsiderLinkage,
1107 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001108 LookupResult::Filter F = R.makeFilter();
1109 while (F.hasNext()) {
1110 NamedDecl *D = F.next();
1111
Richard Smith3e4c6c42011-05-05 21:57:07 +00001112 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001113 continue;
1114
1115 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001116 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001117 continue;
1118
1119 F.erase();
1120 }
1121
1122 F.done();
1123}
1124
1125static bool isUsingDecl(NamedDecl *D) {
1126 return isa<UsingShadowDecl>(D) ||
1127 isa<UnresolvedUsingTypenameDecl>(D) ||
1128 isa<UnresolvedUsingValueDecl>(D);
1129}
1130
1131/// Removes using shadow declarations from the lookup results.
1132static void RemoveUsingDecls(LookupResult &R) {
1133 LookupResult::Filter F = R.makeFilter();
1134 while (F.hasNext())
1135 if (isUsingDecl(F.next()))
1136 F.erase();
1137
1138 F.done();
1139}
1140
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001141/// \brief Check for this common pattern:
1142/// @code
1143/// class S {
1144/// S(const S&); // DO NOT IMPLEMENT
1145/// void operator=(const S&); // DO NOT IMPLEMENT
1146/// };
1147/// @endcode
1148static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1149 // FIXME: Should check for private access too but access is set after we get
1150 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001151 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001152 return false;
1153
1154 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1155 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001156 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1157 return Method->isCopyAssignmentOperator();
1158 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001159}
1160
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001161// We need this to handle
1162//
1163// typedef struct {
1164// void *foo() { return 0; }
1165// } A;
1166//
1167// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1168// for example. If 'A', foo will have external linkage. If we have '*A',
1169// foo will have no linkage. Since we can't know untill we get to the end
1170// of the typedef, this function finds out if D might have non external linkage.
1171// Callers should verify at the end of the TU if it D has external linkage or
1172// not.
1173bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1174 const DeclContext *DC = D->getDeclContext();
1175 while (!DC->isTranslationUnit()) {
1176 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1177 if (!RD->hasNameForLinkage())
1178 return true;
1179 }
1180 DC = DC->getParent();
1181 }
1182
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001183 return !D->isExternallyVisible();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001184}
1185
Eli Friedman39bd3712013-09-10 03:05:56 +00001186// FIXME: This needs to be refactored; some other isInMainFile users want
1187// these semantics.
1188static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1189 if (S.TUKind != TU_Complete)
1190 return false;
1191 return S.SourceMgr.isInMainFile(Loc);
1192}
1193
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001194bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1195 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001196
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001197 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1198 return false;
1199
1200 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001201 if (D->getDeclContext()->isDependentContext() ||
1202 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001203 return false;
1204
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001205 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001206 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1207 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001208
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001209 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1210 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1211 return false;
1212 } else {
Eli Friedman39bd3712013-09-10 03:05:56 +00001213 // 'static inline' functions are defined in headers; don't warn.
1214 if (FD->isInlineSpecified() &&
1215 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001216 return false;
1217 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001218
Sean Hunt10620eb2011-05-06 20:44:56 +00001219 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001220 Context.DeclMustBeEmitted(FD))
1221 return false;
John McCall82b96592010-10-27 01:41:35 +00001222 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman39bd3712013-09-10 03:05:56 +00001223 // Constants and utility variables are defined in headers with internal
1224 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1225 // like "inline".)
1226 if (!isMainFileLoc(*this, VD->getLocation()))
1227 return false;
1228
Eli Friedman39bd3712013-09-10 03:05:56 +00001229 if (Context.DeclMustBeEmitted(VD))
John McCall82b96592010-10-27 01:41:35 +00001230 return false;
1231
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001232 if (VD->isStaticDataMember() &&
1233 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1234 return false;
John McCall82b96592010-10-27 01:41:35 +00001235 } else {
1236 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001237 }
1238
John McCall82b96592010-10-27 01:41:35 +00001239 // Only warn for unused decls internal to the translation unit.
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001240 return mightHaveNonExternalLinkage(D);
John McCall82b96592010-10-27 01:41:35 +00001241}
1242
1243void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001244 if (!D)
1245 return;
1246
1247 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001248 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001249 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1250 return; // First should already be in the vector.
1251 }
1252
1253 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001254 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001255 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1256 return; // First should already be in the vector.
1257 }
1258
David Blaikie7f7c42b2012-05-26 05:35:39 +00001259 if (ShouldWarnIfUnusedFileScopedDecl(D))
1260 UnusedFileScopedDecls.push_back(D);
1261}
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001262
Anders Carlsson99a000e2009-11-07 07:18:14 +00001263static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001264 if (D->isInvalidDecl())
1265 return false;
1266
Eli Friedmandd9d6452012-01-13 23:41:25 +00001267 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001268 return false;
John McCall86ff3082010-02-04 22:26:26 +00001269
Chris Lattner57ad3782011-02-17 20:34:02 +00001270 if (isa<LabelDecl>(D))
1271 return true;
1272
John McCall86ff3082010-02-04 22:26:26 +00001273 // White-list anything that isn't a local variable.
1274 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1275 !D->getDeclContext()->isFunctionOrMethod())
1276 return false;
1277
1278 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001279 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001280
1281 // White-list anything with an __attribute__((unused)) type.
1282 QualType Ty = VD->getType();
1283
1284 // Only look at the outermost level of typedef.
Douglas Gregor2c8e81e2012-09-14 05:10:40 +00001285 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallaec58602010-03-31 02:47:45 +00001286 if (TT->getDecl()->hasAttr<UnusedAttr>())
1287 return false;
1288 }
1289
Douglas Gregor5764f612010-05-08 23:05:03 +00001290 // If we failed to complete the type for some reason, or if the type is
1291 // dependent, don't diagnose the variable.
1292 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001293 return false;
1294
John McCallaec58602010-03-31 02:47:45 +00001295 if (const TagType *TT = Ty->getAs<TagType>()) {
1296 const TagDecl *Tag = TT->getDecl();
1297 if (Tag->hasAttr<UnusedAttr>())
1298 return false;
1299
1300 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001301 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001302 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001303
1304 if (const Expr *Init = VD->getInit()) {
David Blaikie39e17762012-10-24 21:29:06 +00001305 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1306 Init = Cleanups->getSubExpr();
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001307 const CXXConstructExpr *Construct =
1308 dyn_cast<CXXConstructExpr>(Init);
1309 if (Construct && !Construct->isElidable()) {
1310 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001311 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001312 return false;
1313 }
1314 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001315 }
1316 }
John McCallaec58602010-03-31 02:47:45 +00001317
1318 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001319 }
1320
John McCall86ff3082010-02-04 22:26:26 +00001321 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001322}
1323
Anna Zaksd5612a22011-07-28 20:52:06 +00001324static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1325 FixItHint &Hint) {
1326 if (isa<LabelDecl>(D)) {
1327 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001328 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001329 if (AfterColon.isInvalid())
1330 return;
1331 Hint = FixItHint::CreateRemoval(CharSourceRange::
1332 getCharRange(D->getLocStart(), AfterColon));
1333 }
1334 return;
1335}
1336
Chris Lattner337e5502011-02-18 01:27:55 +00001337/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1338/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001339void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001340 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001341 if (!ShouldDiagnoseUnusedDecl(D))
1342 return;
1343
Anna Zaksd5612a22011-07-28 20:52:06 +00001344 GenerateFixForUnusedDecl(D, Context, Hint);
1345
Chris Lattner57ad3782011-02-17 20:34:02 +00001346 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001347 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001348 DiagID = diag::warn_unused_exception_param;
1349 else if (isa<LabelDecl>(D))
1350 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001351 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001352 DiagID = diag::warn_unused_variable;
1353
Anna Zaksd5612a22011-07-28 20:52:06 +00001354 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001355}
1356
Chris Lattner337e5502011-02-18 01:27:55 +00001357static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1358 // Verify that we have no forward references left. If so, there was a goto
1359 // or address of a label taken, but no definition of it. Label fwd
1360 // definitions are indicated with a null substmt.
1361 if (L->getStmt() == 0)
1362 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1363}
1364
Steve Naroffb216c882007-10-09 22:01:59 +00001365void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001366 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001367 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001368 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1371 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001372 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001373 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001374
Douglas Gregor44b43212008-12-11 16:49:14 +00001375 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1376 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001377
Douglas Gregor44b43212008-12-11 16:49:14 +00001378 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001379
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001380 // Diagnose unused variables in this scope.
Matt Beaumont-Gay59d8ccb2013-03-28 21:46:45 +00001381 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001382 DiagnoseUnusedDecl(D);
1383
Chris Lattner337e5502011-02-18 01:27:55 +00001384 // If this was a forward reference to a label, verify it was defined.
1385 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1386 CheckPoppedLabel(LD, *this);
1387
Douglas Gregor44b43212008-12-11 16:49:14 +00001388 // Remove this name from our lexical scope.
1389 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 }
1391}
1392
James Molloy16f1f712012-02-29 10:24:19 +00001393void Sema::ActOnStartFunctionDeclarator() {
1394 ++InFunctionDeclarator;
1395}
1396
1397void Sema::ActOnEndFunctionDeclarator() {
1398 assert(InFunctionDeclarator);
1399 --InFunctionDeclarator;
1400}
1401
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001402/// \brief Look for an Objective-C class in the translation unit.
1403///
1404/// \param Id The name of the Objective-C class we're looking for. If
1405/// typo-correction fixes this name, the Id will be updated
1406/// to the fixed name.
1407///
1408/// \param IdLoc The location of the name in the translation unit.
1409///
James Dennett16ae9de2012-06-22 10:16:05 +00001410/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001411/// if there is no class with the given name.
1412///
1413/// \returns The declaration of the named Objective-C class, or NULL if the
1414/// class could not be found.
1415ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1416 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001417 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001418 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1419 // creation from this context.
1420 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1421
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001422 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001423 // Perform typo correction at the given location, but only if we
1424 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001425 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1426 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1427 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001428 Validator)) {
Richard Smith2d670972013-08-17 00:46:16 +00001429 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001430 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001431 Id = IDecl->getIdentifier();
1432 }
1433 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001434 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1435 // This routine must always return a class definition, if any.
1436 if (Def && Def->getDefinition())
1437 Def = Def->getDefinition();
1438 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001439}
1440
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001441/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1442/// from S, where a non-field would be declared. This routine copes
1443/// with the difference between C and C++ scoping rules in structs and
1444/// unions. For example, the following code is well-formed in C but
1445/// ill-formed in C++:
1446/// @code
1447/// struct S6 {
1448/// enum { BAR } e;
1449/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001450///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001451/// void test_S6() {
1452/// struct S6 a;
1453/// a.e = BAR;
1454/// }
1455/// @endcode
1456/// For the declaration of BAR, this routine will return a different
1457/// scope. The scope S will be the scope of the unnamed enumeration
1458/// within S6. In C++, this routine will return the scope associated
1459/// with S6, because the enumeration's scope is a transparent
1460/// context but structures can contain non-field names. In C, this
1461/// routine will return the translation unit scope, since the
1462/// enumeration's scope is a transparent context and structures cannot
1463/// contain non-field names.
1464Scope *Sema::getNonFieldDeclScope(Scope *S) {
1465 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001466 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001467 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001468 S = S->getParent();
1469 return S;
1470}
1471
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001472/// \brief Looks up the declaration of "struct objc_super" and
1473/// saves it for later use in building builtin declaration of
1474/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1475/// pre-existing declaration exists no action takes place.
1476static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1477 IdentifierInfo *II) {
1478 if (!II->isStr("objc_msgSendSuper"))
1479 return;
1480 ASTContext &Context = ThisSema.Context;
1481
1482 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1483 SourceLocation(), Sema::LookupTagName);
1484 ThisSema.LookupName(Result, S);
1485 if (Result.getResultKind() == LookupResult::Found)
1486 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1487 Context.setObjCSuperType(Context.getTagDeclType(TD));
1488}
1489
Douglas Gregor3e41d602009-02-13 23:20:09 +00001490/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1491/// file scope. lazily create a decl for it. ForRedeclaration is true
1492/// if we're creating this built-in in anticipation of redeclaring the
1493/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001494NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001495 Scope *S, bool ForRedeclaration,
1496 SourceLocation Loc) {
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001497 LookupPredefedObjCSuperType(*this, S, II);
1498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 Builtin::ID BID = (Builtin::ID)bid;
1500
Chris Lattner86df27b2009-06-14 00:45:47 +00001501 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001502 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001503 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001504 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001505 // Okay
1506 break;
1507
Mike Stumpf711c412009-07-28 23:57:15 +00001508 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001509 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001510 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001511 << Context.BuiltinInfo.GetName(BID);
1512 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001513
Mike Stumpf711c412009-07-28 23:57:15 +00001514 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001515 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001516 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001517 << Context.BuiltinInfo.GetName(BID);
1518 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001519
1520 case ASTContext::GE_Missing_ucontext:
1521 if (ForRedeclaration)
1522 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1523 << Context.BuiltinInfo.GetName(BID);
1524 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001525 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001526
1527 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1528 Diag(Loc, diag::ext_implicit_lib_function_decl)
1529 << Context.BuiltinInfo.GetName(BID)
1530 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001531 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001532 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001533 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001534 Diag(Loc, diag::note_please_include_header)
1535 << Context.BuiltinInfo.getHeaderName(BID)
1536 << Context.BuiltinInfo.GetName(BID);
1537 }
1538
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001539 FunctionDecl *New = FunctionDecl::Create(Context,
1540 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001541 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001542 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001543 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001544 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001545 New->setImplicit();
1546
Chris Lattner95e2c712008-05-05 22:18:14 +00001547 // Create Decl objects for each parameter, adding them to the
1548 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001549 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001550 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001551 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1552 ParmVarDecl *parm =
1553 ParmVarDecl::Create(Context, New, SourceLocation(),
1554 SourceLocation(), 0,
1555 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001556 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001557 parm->setScopeInfo(0, i);
1558 Params.push_back(parm);
1559 }
David Blaikie4278c652011-09-21 18:16:56 +00001560 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
1563 AddKnownFunctionAttributes(New);
1564
Chris Lattner7f925cc2008-04-11 07:00:53 +00001565 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001566 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1567 // relate Scopes to DeclContexts, and probably eliminate CurContext
1568 // entirely, but we're not there yet.
1569 DeclContext *SavedContext = CurContext;
1570 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001571 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001572 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 return New;
1574}
1575
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001576/// \brief Filter out any previous declarations that the given declaration
1577/// should not consider because they are not permitted to conflict, e.g.,
1578/// because they come from hidden sub-modules and do not refer to the same
1579/// entity.
1580static void filterNonConflictingPreviousDecls(ASTContext &context,
1581 NamedDecl *decl,
1582 LookupResult &previous){
1583 // This is only interesting when modules are enabled.
1584 if (!context.getLangOpts().Modules)
1585 return;
1586
1587 // Empty sets are uninteresting.
1588 if (previous.empty())
1589 return;
1590
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001591 LookupResult::Filter filter = previous.makeFilter();
1592 while (filter.hasNext()) {
1593 NamedDecl *old = filter.next();
1594
1595 // Non-hidden declarations are never ignored.
1596 if (!old->isHidden())
1597 continue;
1598
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001599 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001600 filter.erase();
1601 }
1602
1603 filter.done();
1604}
1605
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001606bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1607 QualType OldType;
1608 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1609 OldType = OldTypedef->getUnderlyingType();
1610 else
1611 OldType = Context.getTypeDeclType(Old);
1612 QualType NewType = New->getUnderlyingType();
1613
Douglas Gregorec3bd722012-01-11 22:33:48 +00001614 if (NewType->isVariablyModifiedType()) {
1615 // Must not redefine a typedef with a variably-modified type.
1616 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1617 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1618 << Kind << NewType;
1619 if (Old->getLocation().isValid())
1620 Diag(Old->getLocation(), diag::note_previous_definition);
1621 New->setInvalidDecl();
1622 return true;
1623 }
1624
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001625 if (OldType != NewType &&
1626 !OldType->isDependentType() &&
1627 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001628 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001629 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1630 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1631 << Kind << NewType << OldType;
1632 if (Old->getLocation().isValid())
1633 Diag(Old->getLocation(), diag::note_previous_definition);
1634 New->setInvalidDecl();
1635 return true;
1636 }
1637 return false;
1638}
1639
Richard Smith162e1c12011-04-15 14:24:37 +00001640/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001641/// same name and scope as a previous declaration 'Old'. Figure out
1642/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001643/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001644///
Richard Smith162e1c12011-04-15 14:24:37 +00001645void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001646 // If the new decl is known invalid already, don't bother doing any
1647 // merging checks.
1648 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Steve Naroff2b255c42008-09-09 14:32:20 +00001650 // Allow multiple definitions for ObjC built-in typedefs.
1651 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001652 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001653 const IdentifierInfo *TypeID = New->getIdentifier();
1654 switch (TypeID->getLength()) {
1655 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001656 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001657 {
1658 if (!TypeID->isStr("id"))
1659 break;
1660 QualType T = New->getUnderlyingType();
1661 if (!T->isPointerType())
1662 break;
1663 if (!T->isVoidPointerType()) {
1664 QualType PT = T->getAs<PointerType>()->getPointeeType();
1665 if (!PT->isStructureType())
1666 break;
1667 }
1668 Context.setObjCIdRedefinitionType(T);
1669 // Install the built-in type for 'id', ignoring the current definition.
1670 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1671 return;
1672 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001673 case 5:
1674 if (!TypeID->isStr("Class"))
1675 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001676 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001677 // Install the built-in type for 'Class', ignoring the current definition.
1678 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001679 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001680 case 3:
1681 if (!TypeID->isStr("SEL"))
1682 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001683 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001684 // Install the built-in type for 'SEL', ignoring the current definition.
1685 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001686 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001687 }
1688 // Fall through - the typedef name was not a builtin type.
1689 }
John McCall68263142009-11-18 22:49:29 +00001690
Douglas Gregor66973122009-01-28 17:15:10 +00001691 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001692 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1693 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001694 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001695 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001696
1697 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001698 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001699 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001700
Chris Lattnereaaebc72009-04-25 08:06:05 +00001701 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 }
Douglas Gregor66973122009-01-28 17:15:10 +00001703
John McCall68263142009-11-18 22:49:29 +00001704 // If the old declaration is invalid, just give up here.
1705 if (Old->isInvalidDecl())
1706 return New->setInvalidDecl();
1707
Chris Lattner99cb9972008-07-25 18:44:27 +00001708 // If the typedef types are not identical, reject them in all languages and
1709 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001710 if (isIncompatibleTypedef(Old, New))
1711 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Justin Bogner2dd68de2013-10-08 00:19:09 +00001713 // The types match. Link up the redeclaration chain and merge attributes if
1714 // the old declaration was a typedef.
1715 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001716 New->setPreviousDecl(Typedef);
Justin Bogner2dd68de2013-10-08 00:19:09 +00001717 mergeDeclAttributes(New, Old);
1718 }
Eli Friedman9ec40992013-07-16 02:07:49 +00001719
David Blaikie4e4d0842012-03-11 07:00:24 +00001720 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001721 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001722
David Blaikie4e4d0842012-03-11 07:00:24 +00001723 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001724 // C++ [dcl.typedef]p2:
1725 // In a given non-class scope, a typedef specifier can be used to
1726 // redefine the name of any type declared in that scope to refer
1727 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001728 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001729 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001730
1731 // C++0x [dcl.typedef]p4:
1732 // In a given class scope, a typedef specifier can be used to redefine
1733 // any class-name declared in that scope that is not also a typedef-name
1734 // to refer to the type to which it already refers.
1735 //
1736 // This wording came in via DR424, which was a correction to the
1737 // wording in DR56, which accidentally banned code like:
1738 //
1739 // struct S {
1740 // typedef struct A { } A;
1741 // };
1742 //
1743 // in the C++03 standard. We implement the C++0x semantics, which
1744 // allow the above but disallow
1745 //
1746 // struct S {
1747 // typedef int I;
1748 // typedef int I;
1749 // };
1750 //
1751 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001752 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001753 return;
1754
Chris Lattner32b06752009-04-17 22:04:20 +00001755 Diag(New->getLocation(), diag::err_redefinition)
1756 << New->getDeclName();
1757 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001758 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001759 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001760
Douglas Gregorc0004df2012-01-11 04:25:01 +00001761 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001762 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001763 return;
1764
Chris Lattner32b06752009-04-17 22:04:20 +00001765 // If we have a redefinition of a typedef in C, emit a warning. This warning
1766 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001767 // -Wtypedef-redefinition. If either the original or the redefinition is
1768 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001769 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001770 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1771 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001772 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Chris Lattner32b06752009-04-17 22:04:20 +00001774 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1775 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001776 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001777 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001778}
1779
Chris Lattner6b6b5372008-06-26 18:38:35 +00001780/// DeclhasAttr - returns true if decl Declaration already has the target
1781/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001782static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001783DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001784 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1785 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1786 // responsible for making sure they are consistent.
1787 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1788 if (AA)
1789 return false;
1790
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001791 // The following thread safety attributes can also be duplicated.
1792 switch (A->getKind()) {
1793 case attr::ExclusiveLocksRequired:
1794 case attr::SharedLocksRequired:
1795 case attr::LocksExcluded:
1796 case attr::ExclusiveLockFunction:
1797 case attr::SharedLockFunction:
1798 case attr::UnlockFunction:
1799 case attr::ExclusiveTrylockFunction:
1800 case attr::SharedTrylockFunction:
1801 case attr::GuardedBy:
1802 case attr::PtGuardedBy:
1803 case attr::AcquiredBefore:
1804 case attr::AcquiredAfter:
1805 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001806 default:
1807 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001808 }
1809
Sean Huntcf807c42010-08-18 23:23:40 +00001810 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001811 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001812 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1813 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001814 if (Ann) {
1815 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1816 return true;
1817 continue;
1818 }
Sean Huntcf807c42010-08-18 23:23:40 +00001819 // FIXME: Don't hardcode this check
1820 if (OA && isa<OwnershipAttr>(*i))
1821 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001822 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001823 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001824
1825 return false;
1826}
1827
Richard Smith671b3212013-02-22 04:55:39 +00001828static bool isAttributeTargetADefinition(Decl *D) {
1829 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1830 return VD->isThisDeclarationADefinition();
1831 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1832 return TD->isCompleteDefinition() || TD->isBeingDefined();
1833 return true;
1834}
1835
1836/// Merge alignment attributes from \p Old to \p New, taking into account the
1837/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1838///
1839/// \return \c true if any attributes were added to \p New.
1840static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1841 // Look for alignas attributes on Old, and pick out whichever attribute
1842 // specifies the strictest alignment requirement.
1843 AlignedAttr *OldAlignasAttr = 0;
1844 AlignedAttr *OldStrictestAlignAttr = 0;
1845 unsigned OldAlign = 0;
1846 for (specific_attr_iterator<AlignedAttr>
1847 I = Old->specific_attr_begin<AlignedAttr>(),
1848 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1849 // FIXME: We have no way of representing inherited dependent alignments
1850 // in a case like:
1851 // template<int A, int B> struct alignas(A) X;
1852 // template<int A, int B> struct alignas(B) X {};
1853 // For now, we just ignore any alignas attributes which are not on the
1854 // definition in such a case.
1855 if (I->isAlignmentDependent())
1856 return false;
1857
1858 if (I->isAlignas())
1859 OldAlignasAttr = *I;
1860
1861 unsigned Align = I->getAlignment(S.Context);
1862 if (Align > OldAlign) {
1863 OldAlign = Align;
1864 OldStrictestAlignAttr = *I;
1865 }
1866 }
1867
1868 // Look for alignas attributes on New.
1869 AlignedAttr *NewAlignasAttr = 0;
1870 unsigned NewAlign = 0;
1871 for (specific_attr_iterator<AlignedAttr>
1872 I = New->specific_attr_begin<AlignedAttr>(),
1873 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1874 if (I->isAlignmentDependent())
1875 return false;
1876
1877 if (I->isAlignas())
1878 NewAlignasAttr = *I;
1879
1880 unsigned Align = I->getAlignment(S.Context);
1881 if (Align > NewAlign)
1882 NewAlign = Align;
1883 }
1884
1885 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1886 // Both declarations have 'alignas' attributes. We require them to match.
1887 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1888 // fall short. (If two declarations both have alignas, they must both match
1889 // every definition, and so must match each other if there is a definition.)
1890
1891 // If either declaration only contains 'alignas(0)' specifiers, then it
1892 // specifies the natural alignment for the type.
1893 if (OldAlign == 0 || NewAlign == 0) {
1894 QualType Ty;
1895 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1896 Ty = VD->getType();
1897 else
1898 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1899
1900 if (OldAlign == 0)
1901 OldAlign = S.Context.getTypeAlign(Ty);
1902 if (NewAlign == 0)
1903 NewAlign = S.Context.getTypeAlign(Ty);
1904 }
1905
1906 if (OldAlign != NewAlign) {
1907 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1908 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1909 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1910 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1911 }
1912 }
1913
1914 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1915 // C++11 [dcl.align]p6:
1916 // if any declaration of an entity has an alignment-specifier,
1917 // every defining declaration of that entity shall specify an
1918 // equivalent alignment.
1919 // C11 6.7.5/7:
1920 // If the definition of an object does not have an alignment
1921 // specifier, any other declaration of that object shall also
1922 // have no alignment specifier.
1923 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1924 << OldAlignasAttr->isC11();
1925 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1926 << OldAlignasAttr->isC11();
1927 }
1928
1929 bool AnyAdded = false;
1930
1931 // Ensure we have an attribute representing the strictest alignment.
1932 if (OldAlign > NewAlign) {
1933 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1934 Clone->setInherited(true);
1935 New->addAttr(Clone);
1936 AnyAdded = true;
1937 }
1938
1939 // Ensure we have an alignas attribute if the old declaration had one.
1940 if (OldAlignasAttr && !NewAlignasAttr &&
1941 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1942 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1943 Clone->setInherited(true);
1944 New->addAttr(Clone);
1945 AnyAdded = true;
1946 }
1947
1948 return AnyAdded;
1949}
1950
1951static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1952 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001953 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001954 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001955 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001956 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1957 AA->getIntroduced(), AA->getDeprecated(),
1958 AA->getObsoleted(), AA->getUnavailable(),
1959 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001960 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001961 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1962 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1963 AttrSpellingListIndex);
1964 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1965 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1966 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001967 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001968 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1969 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001970 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001971 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1972 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001973 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001974 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1975 FA->getFormatIdx(), FA->getFirstArg(),
1976 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001977 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001978 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1979 AttrSpellingListIndex);
1980 else if (isa<AlignedAttr>(Attr))
1981 // AlignedAttrs are handled separately, because we need to handle all
1982 // such attributes on a declaration at the same time.
1983 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00001984 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001985 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00001986
Rafael Espindola599f1b72012-05-13 03:25:18 +00001987 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00001988 NewAttr->setInherited(true);
1989 D->addAttr(NewAttr);
1990 return true;
1991 }
1992
1993 return false;
1994}
1995
Rafael Espindola4b044c62012-07-15 01:05:36 +00001996static const Decl *getDefinition(const Decl *D) {
1997 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00001998 return TD->getDefinition();
Rafael Espindolab1c0e202013-10-22 21:39:03 +00001999 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2000 const VarDecl *Def = VD->getDefinition();
2001 if (Def)
2002 return Def;
2003 return VD->getActingDefinition();
2004 }
Rafael Espindola4b044c62012-07-15 01:05:36 +00002005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00002006 const FunctionDecl* Def;
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002007 if (FD->isDefined(Def))
Rafael Espindola3f664062012-05-18 01:47:00 +00002008 return Def;
2009 }
2010 return NULL;
2011}
2012
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002013static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2014 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2015 I != E; ++I) {
2016 Attr *Attribute = *I;
2017 if (Attribute->getKind() == Kind)
2018 return true;
2019 }
2020 return false;
2021}
2022
2023/// checkNewAttributesAfterDef - If we already have a definition, check that
2024/// there are no new attributes in this declaration.
2025static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2026 if (!New->hasAttrs())
2027 return;
2028
2029 const Decl *Def = getDefinition(Old);
2030 if (!Def || Def == New)
2031 return;
2032
2033 AttrVec &NewAttributes = New->getAttrs();
2034 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2035 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002036
2037 if (isa<AliasAttr>(NewAttribute)) {
2038 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2039 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2040 else {
2041 VarDecl *VD = cast<VarDecl>(New);
2042 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2043 VarDecl::TentativeDefinition
2044 ? diag::err_alias_after_tentative
2045 : diag::err_redefinition;
2046 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2047 S.Diag(Def->getLocation(), diag::note_previous_definition);
2048 VD->setInvalidDecl();
2049 }
2050 ++I;
2051 continue;
2052 }
2053
2054 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2055 // Tentative definitions are only interesting for the alias check above.
2056 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2057 ++I;
2058 continue;
2059 }
2060 }
2061
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002062 if (hasAttribute(Def, NewAttribute->getKind())) {
2063 ++I;
2064 continue; // regular attr merging will take care of validating this.
2065 }
Richard Smith671b3212013-02-22 04:55:39 +00002066
Richard Smith7586a6e2013-01-30 05:45:05 +00002067 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002068 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002069 ++I;
2070 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002071 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2072 if (AA->isAlignas()) {
2073 // C++11 [dcl.align]p6:
2074 // if any declaration of an entity has an alignment-specifier,
2075 // every defining declaration of that entity shall specify an
2076 // equivalent alignment.
2077 // C11 6.7.5/7:
2078 // If the definition of an object does not have an alignment
2079 // specifier, any other declaration of that object shall also
2080 // have no alignment specifier.
2081 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2082 << AA->isC11();
2083 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2084 << AA->isC11();
2085 NewAttributes.erase(NewAttributes.begin() + I);
2086 --E;
2087 continue;
2088 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002089 }
Richard Smith671b3212013-02-22 04:55:39 +00002090
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002091 S.Diag(NewAttribute->getLocation(),
2092 diag::warn_attribute_precede_definition);
2093 S.Diag(Def->getLocation(), diag::note_previous_definition);
2094 NewAttributes.erase(NewAttributes.begin() + I);
2095 --E;
2096 }
2097}
2098
John McCalleca5d222011-03-02 04:00:57 +00002099/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002100void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002101 AvailabilityMergeKind AMK) {
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002102 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2103 UsedAttr *NewAttr = OldAttr->clone(Context);
2104 NewAttr->setInherited(true);
2105 New->addAttr(NewAttr);
2106 }
2107
Richard Smith3a2b7a12013-01-28 22:42:45 +00002108 if (!Old->hasAttrs() && !New->hasAttrs())
2109 return;
2110
Rafael Espindola3f664062012-05-18 01:47:00 +00002111 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002112 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002113
Douglas Gregor27c6da22012-01-01 20:30:41 +00002114 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002115 return;
John McCalleca5d222011-03-02 04:00:57 +00002116
Douglas Gregor27c6da22012-01-01 20:30:41 +00002117 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002118
Sean Huntcf807c42010-08-18 23:23:40 +00002119 // Ensure that any moving of objects within the allocated map is done before
2120 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002121 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002122
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002123 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002124 i = Old->specific_attr_begin<InheritableAttr>(),
2125 e = Old->specific_attr_end<InheritableAttr>();
2126 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002127 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002128 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002129 if (isa<DeprecatedAttr>(*i) ||
2130 isa<UnavailableAttr>(*i) ||
2131 isa<AvailabilityAttr>(*i)) {
2132 switch (AMK) {
2133 case AMK_None:
2134 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002135
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002136 case AMK_Redeclaration:
2137 break;
2138
2139 case AMK_Override:
2140 Override = true;
2141 break;
2142 }
2143 }
2144
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002145 // Already handled.
2146 if (isa<UsedAttr>(*i))
2147 continue;
2148
Richard Smith671b3212013-02-22 04:55:39 +00002149 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002150 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002151 }
John McCalleca5d222011-03-02 04:00:57 +00002152
Richard Smith671b3212013-02-22 04:55:39 +00002153 if (mergeAlignedAttrs(*this, New, Old))
2154 foundAny = true;
2155
Douglas Gregor27c6da22012-01-01 20:30:41 +00002156 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002157}
2158
2159/// mergeParamDeclAttributes - Copy attributes from the old parameter
2160/// to the new one.
2161static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2162 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002163 Sema &S) {
2164 // C++11 [dcl.attr.depend]p2:
2165 // The first declaration of a function shall specify the
2166 // carries_dependency attribute for its declarator-id if any declaration
2167 // of the function specifies the carries_dependency attribute.
2168 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2169 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2170 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2171 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2172 // Find the first declaration of the parameter.
2173 // FIXME: Should we build redeclaration chains for function parameters?
2174 const FunctionDecl *FirstFD =
Rafael Espindolabc650912013-10-17 15:37:26 +00002175 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smith3a2b7a12013-01-28 22:42:45 +00002176 const ParmVarDecl *FirstVD =
2177 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2178 S.Diag(FirstVD->getLocation(),
2179 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2180 }
2181
John McCalleca5d222011-03-02 04:00:57 +00002182 if (!oldDecl->hasAttrs())
2183 return;
2184
2185 bool foundAny = newDecl->hasAttrs();
2186
2187 // Ensure that any moving of objects within the allocated map is
2188 // done before we process them.
2189 if (!foundAny) newDecl->setAttrs(AttrVec());
2190
2191 for (specific_attr_iterator<InheritableParamAttr>
2192 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2193 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2194 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002195 InheritableAttr *newAttr =
2196 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002197 newAttr->setInherited(true);
2198 newDecl->addAttr(newAttr);
2199 foundAny = true;
2200 }
2201 }
2202
2203 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002204}
2205
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002206namespace {
2207
Douglas Gregorc8376562009-03-06 22:43:54 +00002208/// Used in MergeFunctionDecl to keep track of function parameters in
2209/// C.
2210struct GNUCompatibleParamWarning {
2211 ParmVarDecl *OldParm;
2212 ParmVarDecl *NewParm;
2213 QualType PromotedType;
2214};
2215
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002216}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002217
2218/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002219Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002220 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002221 if (Ctor->isDefaultConstructor())
2222 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002223
2224 if (Ctor->isCopyConstructor())
2225 return Sema::CXXCopyConstructor;
2226
2227 if (Ctor->isMoveConstructor())
2228 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002229 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002230 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002231 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002232 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002233 } else if (MD->isMoveAssignmentOperator()) {
2234 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002235 }
Sean Huntf961ea52011-05-10 19:08:14 +00002236
Sean Huntf961ea52011-05-10 19:08:14 +00002237 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002238}
2239
Sebastian Redl515ddd82010-06-09 21:17:41 +00002240/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002241/// only extern inline functions can be redefined, and even then only in
2242/// GNU89 mode.
2243static bool canRedefineFunction(const FunctionDecl *FD,
2244 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002245 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2246 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002247 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002248 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002249}
2250
Reid Kleckneref072032013-08-27 23:08:25 +00002251const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2252 const AttributedType *AT = T->getAs<AttributedType>();
2253 while (AT && !AT->isCallingConv())
2254 AT = AT->getModifiedType()->getAs<AttributedType>();
2255 return AT;
John McCallfb609142012-08-25 02:00:03 +00002256}
2257
Benjamin Kramera574c892013-02-15 12:30:38 +00002258template <typename T>
2259static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002260 const DeclContext *DC = Old->getDeclContext();
2261 if (DC->isRecord())
2262 return false;
2263
2264 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002265 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002266 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002267 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002268 return true;
2269 return false;
2270}
2271
Chris Lattner04421082008-04-08 04:40:51 +00002272/// MergeFunctionDecl - We just parsed a function 'New' from
2273/// declarator D which has the same name and scope as a previous
2274/// declaration 'Old'. Figure out how to resolve this situation,
2275/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002276///
2277/// In C++, New and Old must be declarations that are not
2278/// overloaded. Use IsOverload to determine whether New and Old are
2279/// overloaded, and to select the Old declaration that New should be
2280/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002281///
2282/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002283bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2284 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002286 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002287 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002288 = dyn_cast<FunctionTemplateDecl>(OldD))
2289 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002290 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002291 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002293 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002294 if (New->getFriendObjectKind()) {
2295 Diag(New->getLocation(), diag::err_using_decl_friend);
2296 Diag(Shadow->getTargetDecl()->getLocation(),
2297 diag::note_using_decl_target);
2298 Diag(Shadow->getUsingDecl()->getLocation(),
2299 diag::note_using_decl) << 0;
2300 return true;
2301 }
2302
John McCall41ce66f2009-12-10 19:51:03 +00002303 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2304 Diag(Shadow->getTargetDecl()->getLocation(),
2305 diag::note_using_decl_target);
2306 Diag(Shadow->getUsingDecl()->getLocation(),
2307 diag::note_using_decl) << 0;
2308 return true;
2309 }
2310
Chris Lattner5dc266a2008-11-20 06:13:02 +00002311 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002312 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002313 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002314 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002316
David Majnemerbcd06502013-07-07 23:49:50 +00002317 // If the old declaration is invalid, just give up here.
2318 if (Old->isInvalidDecl())
2319 return true;
2320
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002321 // Determine whether the previous declaration was a definition,
2322 // implicit declaration, or a declaration.
2323 diag::kind PrevDiag;
2324 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002325 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002326 else if (Old->isImplicit())
2327 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002328 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002329 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002331 // Don't complain about this if we're in GNU89 mode and the old function
2332 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002333 // Don't complain about specializations. They are not supposed to have
2334 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002335 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002336 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002337 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002338 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002339 !canRedefineFunction(Old, getLangOpts())) {
2340 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002341 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2342 Diag(Old->getLocation(), PrevDiag);
2343 } else {
2344 Diag(New->getLocation(), diag::err_static_non_static) << New;
2345 Diag(Old->getLocation(), PrevDiag);
2346 return true;
2347 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002348 }
2349
Reid Kleckneref072032013-08-27 23:08:25 +00002350
2351 // If a function is first declared with a calling convention, but is later
2352 // declared or defined without one, all following decls assume the calling
2353 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002354 //
John McCallfb609142012-08-25 02:00:03 +00002355 // It's OK if a function is first declared without a calling convention,
2356 // but is later declared or defined with the default calling convention.
2357 //
Reid Kleckneref072032013-08-27 23:08:25 +00002358 // To test if either decl has an explicit calling convention, we look for
2359 // AttributedType sugar nodes on the type as written. If they are missing or
2360 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002361 //
2362 // Note also that we DO NOT return at this point, because we still have
2363 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002364 QualType OldQType = Context.getCanonicalType(Old->getType());
2365 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002366 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002367 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002368 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2369 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2370 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002371
Reid Kleckneref072032013-08-27 23:08:25 +00002372 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002373 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckneref072032013-08-27 23:08:25 +00002374 const FunctionType *FT =
2375 First->getType().getCanonicalType()->castAs<FunctionType>();
2376 FunctionType::ExtInfo FI = FT->getExtInfo();
2377 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2378 if (!NewCCExplicit) {
2379 // Inherit the CC from the previous declaration if it was specified
2380 // there but not here.
2381 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2382 RequiresAdjustment = true;
2383 } else {
2384 // Calling conventions aren't compatible, so complain.
2385 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2386 Diag(New->getLocation(), diag::err_cconv_change)
2387 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2388 << !FirstCCExplicit
2389 << (!FirstCCExplicit ? "" :
2390 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002391
Reid Kleckneref072032013-08-27 23:08:25 +00002392 // Put the note on the first decl, since it is the one that matters.
2393 Diag(First->getLocation(), diag::note_previous_declaration);
2394 return true;
2395 }
John McCallf82b4e82010-02-04 05:44:44 +00002396 }
2397
John McCall04a67a62010-02-05 21:31:56 +00002398 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002399 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2400 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2401 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002402 }
2403
Douglas Gregord2c64902010-06-18 21:30:25 +00002404 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002405 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2406 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2407 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002408 Diag(New->getLocation(), diag::err_regparm_mismatch)
2409 << NewType->getRegParmType()
2410 << OldType->getRegParmType();
2411 Diag(Old->getLocation(), diag::note_previous_declaration);
2412 return true;
2413 }
John McCalle6a365d2010-12-19 02:44:49 +00002414
2415 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2416 RequiresAdjustment = true;
2417 }
2418
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002419 // Merge ns_returns_retained attribute.
2420 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2421 if (NewTypeInfo.getProducesResult()) {
2422 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2423 Diag(Old->getLocation(), diag::note_previous_declaration);
2424 return true;
2425 }
2426
2427 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2428 RequiresAdjustment = true;
2429 }
2430
John McCalle6a365d2010-12-19 02:44:49 +00002431 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002432 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2433 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2434 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002435 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002436 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002437 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002438
2439 // If this redeclaration makes the function inline, we may need to add it to
2440 // UndefinedButUsed.
2441 if (!Old->isInlined() && New->isInlined() &&
2442 !New->hasAttr<GNUInlineAttr>() &&
2443 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2444 Old->isUsed(false) &&
2445 !Old->isDefined() && !New->isThisDeclarationADefinition())
2446 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2447 SourceLocation()));
2448
2449 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2450 // about it.
2451 if (New->hasAttr<GNUInlineAttr>() &&
2452 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2453 UndefinedButUsed.erase(Old->getCanonicalDecl());
2454 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002455
David Blaikie4e4d0842012-03-11 07:00:24 +00002456 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002457 // (C++98 13.1p2):
2458 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002459 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002460 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002461
2462 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002463 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002464 // Redeclarations or specializations of a function or function template
2465 // with a declared return type that uses a placeholder type shall also
2466 // use that placeholder, not a deduced type.
2467 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2468 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2469 : OldType)->getResultType();
2470 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2471 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2472 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002473 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002474 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2475 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2476 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002477 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2478 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002479 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2480 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002481 if (New->isCXXClassMember() && New->isOutOfLine())
2482 Diag(New->getLocation(),
2483 diag::err_member_def_does_not_match_ret_type) << New;
2484 else
2485 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002486 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2487 return true;
2488 }
2489 else
2490 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002491 }
2492
Richard Smith60e141e2013-05-04 07:00:32 +00002493 QualType OldReturnType = OldType->getResultType();
2494 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2495 if (OldReturnType != NewReturnType) {
2496 // If this function has a deduced return type and has already been
2497 // defined, copy the deduced value from the old declaration.
2498 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2499 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002500 New->setType(
2501 SubstAutoType(New->getType(),
2502 OldAT->isDependentType() ? Context.DependentTy
2503 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002504 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002505 SubstAutoType(NewQType,
2506 OldAT->isDependentType() ? Context.DependentTy
2507 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002508 }
2509 }
2510
2511 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2512 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002513 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002514 // Preserve triviality.
2515 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002516
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002517 // MSVC allows explicit template specialization at class scope:
2518 // 2 CXMethodDecls referring to the same function will be injected.
2519 // We don't want a redeclartion error.
2520 bool IsClassScopeExplicitSpecialization =
2521 OldMethod->isFunctionTemplateSpecialization() &&
2522 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002523 bool isFriend = NewMethod->getFriendObjectKind();
2524
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002525 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2526 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002527 // -- Member function declarations with the same name and the
2528 // same parameter types cannot be overloaded if any of them
2529 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002530 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002531 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2532 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2533 return true;
2534 }
Richard Smith838925d2012-07-13 04:12:04 +00002535
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002536 // C++ [class.mem]p1:
2537 // [...] A member shall not be declared twice in the
2538 // member-specification, except that a nested class or member
2539 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002540 if (ActiveTemplateInstantiations.empty()) {
2541 unsigned NewDiag;
2542 if (isa<CXXConstructorDecl>(OldMethod))
2543 NewDiag = diag::err_constructor_redeclared;
2544 else if (isa<CXXDestructorDecl>(NewMethod))
2545 NewDiag = diag::err_destructor_redeclared;
2546 else if (isa<CXXConversionDecl>(NewMethod))
2547 NewDiag = diag::err_conv_function_redeclared;
2548 else
2549 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002550
Richard Smith838925d2012-07-13 04:12:04 +00002551 Diag(New->getLocation(), NewDiag);
2552 } else {
2553 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2554 << New << New->getType();
2555 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002556 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002557
2558 // Complain if this is an explicit declaration of a special
2559 // member that was initially declared implicitly.
2560 //
2561 // As an exception, it's okay to befriend such methods in order
2562 // to permit the implicit constructor/destructor/operator calls.
2563 } else if (OldMethod->isImplicit()) {
2564 if (isFriend) {
2565 NewMethod->setImplicit();
2566 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002567 Diag(NewMethod->getLocation(),
2568 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002569 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002570 return true;
2571 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002572 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002573 Diag(NewMethod->getLocation(),
2574 diag::err_definition_of_explicitly_defaulted_member)
2575 << getSpecialMember(OldMethod);
2576 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002577 }
2578 }
2579
Richard Smithcd8ab512013-01-17 01:30:42 +00002580 // C++11 [dcl.attr.noreturn]p1:
2581 // The first declaration of a function shall specify the noreturn
2582 // attribute if any declaration of that function specifies the noreturn
2583 // attribute.
2584 if (New->hasAttr<CXX11NoReturnAttr>() &&
2585 !Old->hasAttr<CXX11NoReturnAttr>()) {
2586 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2587 diag::err_noreturn_missing_on_first_decl);
Rafael Espindolabc650912013-10-17 15:37:26 +00002588 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithcd8ab512013-01-17 01:30:42 +00002589 diag::note_noreturn_missing_first_decl);
2590 }
2591
Richard Smith3a2b7a12013-01-28 22:42:45 +00002592 // C++11 [dcl.attr.depend]p2:
2593 // The first declaration of a function shall specify the
2594 // carries_dependency attribute for its declarator-id if any declaration
2595 // of the function specifies the carries_dependency attribute.
2596 if (New->hasAttr<CarriesDependencyAttr>() &&
2597 !Old->hasAttr<CarriesDependencyAttr>()) {
2598 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2599 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindolabc650912013-10-17 15:37:26 +00002600 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002601 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2602 }
2603
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002604 // (C++98 8.3.5p3):
2605 // All declarations for a function shall agree exactly in both the
2606 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002607 // We also want to respect all the extended bits except noreturn.
2608
2609 // noreturn should now match unless the old type info didn't have it.
2610 QualType OldQTypeForComparison = OldQType;
2611 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2612 assert(OldQType == QualType(OldType, 0));
2613 const FunctionType *OldTypeForComparison
2614 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2615 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2616 assert(OldQTypeForComparison.isCanonical());
2617 }
2618
Rafael Espindola950fee22013-02-14 01:18:37 +00002619 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokera8a2ebe2013-10-22 22:53:01 +00002620 // As a special case, retain the language linkage from previous
2621 // declarations of a friend function as an extension.
2622 //
2623 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2624 // and is useful because there's otherwise no way to specify language
2625 // linkage within class scope.
2626 //
2627 // Check cautiously as the friend object kind isn't yet complete.
2628 if (New->getFriendObjectKind() != Decl::FOK_None) {
2629 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2630 Diag(Old->getLocation(), PrevDiag);
2631 } else {
2632 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2633 Diag(Old->getLocation(), PrevDiag);
2634 return true;
2635 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002636 }
2637
John McCalle6a365d2010-12-19 02:44:49 +00002638 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002639 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002640
Richard Smitha41c97a2013-09-20 01:15:31 +00002641 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2642 New->isLocalExternDecl()) {
2643 // It's OK if we couldn't merge types for a local function declaraton
2644 // if either the old or new type is dependent. We'll merge the types
2645 // when we instantiate the function.
2646 return false;
2647 }
2648
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002649 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002650 }
Chris Lattner04421082008-04-08 04:40:51 +00002651
2652 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002653 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002654 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002655 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002656 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2657 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002658 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002659 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002660 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002661 // The old declaration provided a function prototype, but the
2662 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002663 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002664 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002665 OldProto->arg_type_end());
2666 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002667 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002668 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002669 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002670 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002671
2672 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002674 for (FunctionProtoType::arg_type_iterator
2675 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002676 ParamEnd = OldProto->arg_type_end();
2677 ParamType != ParamEnd; ++ParamType) {
2678 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002679 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002680 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002681 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002682 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002683 0);
John McCallfb44de92011-05-01 22:35:37 +00002684 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002685 Param->setImplicit();
2686 Params.push_back(Param);
2687 }
2688
David Blaikie4278c652011-09-21 18:16:56 +00002689 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002690 }
Douglas Gregor68719812009-02-16 18:20:44 +00002691
Richard Smithdd9459f2013-08-13 18:18:50 +00002692 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002693 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002694
Douglas Gregorc8376562009-03-06 22:43:54 +00002695 // GNU C permits a K&R definition to follow a prototype declaration
2696 // if the declared types of the parameters in the K&R definition
2697 // match the types in the prototype declaration, even when the
2698 // promoted types of the parameters from the K&R definition differ
2699 // from the types in the prototype. GCC then keeps the types from
2700 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002701 //
2702 // If a variadic prototype is followed by a non-variadic K&R definition,
2703 // the K&R definition becomes variadic. This is sort of an edge case, but
2704 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2705 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002706 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002707 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002708 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002709 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002710 SmallVector<QualType, 16> ArgTypes;
2711 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002712 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002713 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002714 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002715 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Douglas Gregorc8376562009-03-06 22:43:54 +00002717 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002718 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2719 NewProto->getResultType());
2720 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002721 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002722 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002723 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2724 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002725 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002726 NewProto->getArgType(Idx))) {
2727 ArgTypes.push_back(NewParm->getType());
2728 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002729 NewParm->getType(),
2730 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002731 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002732 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2733 Warnings.push_back(Warn);
2734 ArgTypes.push_back(NewParm->getType());
2735 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002736 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002737 }
2738
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002739 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002740 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2741 Diag(Warnings[Warn].NewParm->getLocation(),
2742 diag::ext_param_promoted_not_compatible_with_prototype)
2743 << Warnings[Warn].PromotedType
2744 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002745 if (Warnings[Warn].OldParm->getLocation().isValid())
2746 Diag(Warnings[Warn].OldParm->getLocation(),
2747 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002748 }
2749
Richard Smithdd9459f2013-08-13 18:18:50 +00002750 if (MergeTypeWithOld)
2751 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2752 OldProto->getExtProtoInfo()));
2753 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002754 }
2755
2756 // Fall through to diagnose conflicting types.
2757 }
2758
John McCall088831d2013-04-14 08:50:55 +00002759 // A function that has already been declared has been redeclared or
2760 // defined with a different type; show an appropriate diagnostic.
2761
2762 // If the previous declaration was an implicitly-generated builtin
2763 // declaration, then at the very least we should use a specialized note.
2764 unsigned BuiltinID;
2765 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2766 // If it's actually a library-defined builtin function like 'malloc'
2767 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002768 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002769 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2770 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2771 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002772
2773 // If this is a global redeclaration, just forget hereafter
2774 // about the "builtin-ness" of the function.
2775 //
2776 // Doing this for local extern declarations is problematic. If
2777 // the builtin declaration remains visible, a second invalid
2778 // local declaration will produce a hard error; if it doesn't
2779 // remain visible, a single bogus local redeclaration (which is
2780 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002781 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002782 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2783
Douglas Gregor374e1562009-03-23 17:47:24 +00002784 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002785 }
Steve Naroff837618c2008-01-16 15:01:34 +00002786
Douglas Gregorcda9c672009-02-16 17:45:42 +00002787 PrevDiag = diag::note_previous_builtin_declaration;
2788 }
2789
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002790 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002791 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002792 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002793}
2794
Douglas Gregor04495c82009-02-24 01:23:02 +00002795/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002796/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002797///
2798/// This routine handles the merging of attributes and other
Alp Toker89673e02013-10-22 09:00:49 +00002799/// properties of function declarations from the old declaration to
Douglas Gregor04495c82009-02-24 01:23:02 +00002800/// the new declaration, once we know that New is in fact a
2801/// redeclaration of Old.
2802///
2803/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002804bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002805 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002806 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002807 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002808
Douglas Gregor04495c82009-02-24 01:23:02 +00002809 // Merge "pure" flag.
2810 if (Old->isPure())
2811 New->setPure();
2812
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002813 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00002814 if (Old->getMostRecentDecl()->isUsed(false))
2815 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002816
John McCalleca5d222011-03-02 04:00:57 +00002817 // Merge attributes from the parameters. These can mismatch with K&R
2818 // declarations.
2819 if (New->getNumParams() == Old->getNumParams())
2820 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2821 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002822 *this);
John McCalleca5d222011-03-02 04:00:57 +00002823
David Blaikie4e4d0842012-03-11 07:00:24 +00002824 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002825 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002826
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002827 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002828 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2829 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002830 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002831 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002832 New->setType(Merged);
2833
Douglas Gregor04495c82009-02-24 01:23:02 +00002834 return false;
2835}
2836
John McCallf85e1932011-06-15 23:02:42 +00002837
John McCalleca5d222011-03-02 04:00:57 +00002838void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002839 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002840
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002841 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002842 AvailabilityMergeKind MergeKind =
2843 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2844 : AMK_Override;
2845 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002846
2847 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002848 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2849 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002850 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002851 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002852 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002853 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002854
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002855 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002856}
2857
Sebastian Redl60618fa2011-03-12 11:50:43 +00002858/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2859/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002860/// emitting diagnostics as appropriate.
2861///
2862/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002863/// to here in AddInitializerToDecl. We can't check them before the initializer
2864/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002865void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2866 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002867 if (New->isInvalidDecl() || Old->isInvalidDecl())
2868 return;
2869
2870 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002871 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002872 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002873 // We don't know what the new type is until the initializer is attached.
2874 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002875 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2876 // These could still be something that needs exception specs checked.
2877 return MergeVarDeclExceptionSpecs(New, Old);
2878 }
Richard Smith34b41d92011-02-20 03:19:35 +00002879 // C++ [basic.link]p10:
2880 // [...] the types specified by all declarations referring to a given
2881 // object or function shall be identical, except that declarations for an
2882 // array object can specify array types that differ by the presence or
2883 // absence of a major array bound (8.3.4).
2884 else if (Old->getType()->isIncompleteArrayType() &&
2885 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002886 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2887 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2888 if (Context.hasSameType(OldArray->getElementType(),
2889 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002890 MergedT = New->getType();
2891 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002892 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002893 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2894 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2895 if (Context.hasSameType(OldArray->getElementType(),
2896 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002897 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002898 } else if (New->getType()->isObjCObjectPointerType() &&
2899 Old->getType()->isObjCObjectPointerType()) {
2900 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2901 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002902 }
2903 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002904 // C 6.2.7p2:
2905 // All declarations that refer to the same object or function shall have
2906 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002907 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2908 }
2909 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002910 // It's OK if we couldn't merge types if either type is dependent, for a
2911 // block-scope variable. In other cases (static data members of class
2912 // templates, variable templates, ...), we require the types to be
2913 // equivalent.
2914 // FIXME: The C++ standard doesn't say anything about this.
2915 if ((New->getType()->isDependentType() ||
2916 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2917 // If the old type was dependent, we can't merge with it, so the new type
2918 // becomes dependent for now. We'll reproduce the original type when we
2919 // instantiate the TypeSourceInfo for the variable.
2920 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2921 New->setType(Context.DependentTy);
2922 return;
2923 }
2924
2925 // FIXME: Even if this merging succeeds, some other non-visible declaration
2926 // of this variable might have an incompatible type. For instance:
2927 //
2928 // extern int arr[];
2929 // void f() { extern int arr[2]; }
2930 // void g() { extern int arr[3]; }
2931 //
2932 // Neither C nor C++ requires a diagnostic for this, but we should still try
2933 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002934 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002935 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002936 Diag(Old->getLocation(), diag::note_previous_definition);
2937 return New->setInvalidDecl();
2938 }
John McCall5b8740f2013-04-01 18:34:28 +00002939
2940 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002941 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002942 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002943 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002944}
2945
Richard Smith99a72382013-09-03 21:00:58 +00002946static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2947 LookupResult &Previous) {
2948 // C11 6.2.7p4:
2949 // For an identifier with internal or external linkage declared
2950 // in a scope in which a prior declaration of that identifier is
2951 // visible, if the prior declaration specifies internal or
2952 // external linkage, the type of the identifier at the later
2953 // declaration becomes the composite type.
2954 //
2955 // If the variable isn't visible, we do not merge with its type.
2956 if (Previous.isShadowed())
2957 return false;
2958
2959 if (S.getLangOpts().CPlusPlus) {
2960 // C++11 [dcl.array]p3:
2961 // If there is a preceding declaration of the entity in the same
2962 // scope in which the bound was specified, an omitted array bound
2963 // is taken to be the same as in that earlier declaration.
2964 return NewVD->isPreviousDeclInSameBlockScope() ||
2965 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2966 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2967 } else {
2968 // If the old declaration was function-local, don't merge with its
2969 // type unless we're in the same function.
2970 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2971 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2972 }
2973}
2974
Reid Spencer5f016e22007-07-11 17:01:13 +00002975/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2976/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2977/// situation, merging decls or emitting diagnostics as appropriate.
2978///
Mike Stump1eb44332009-09-09 15:08:12 +00002979/// Tentative definition rules (C99 6.9.2p2) are checked by
2980/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002981/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00002982///
Richard Smith99a72382013-09-03 21:00:58 +00002983void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00002984 // If the new decl is already invalid, don't do any other checking.
2985 if (New->isInvalidDecl())
2986 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Larisse Voufo4a919892013-08-14 03:09:19 +00002988 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00002989 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00002990 if (Previous.isSingleResult() &&
2991 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00002992 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00002993 Old = Old->getDescribedVarTemplate() ? Old : 0;
2994 else
2995 Old = Old->getDescribedVarTemplate() ? 0 : Old;
2996 }
2997 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002998 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002999 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00003000 Diag(Previous.getRepresentativeDecl()->getLocation(),
3001 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003002 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003004
Rafael Espindola90cc3902013-04-15 12:49:13 +00003005 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3006 return;
3007
Douglas Gregor7f6ff022010-08-30 14:32:14 +00003008 // C++ [class.mem]p1:
3009 // A member shall not be declared twice in the member-specification [...]
3010 //
3011 // Here, we need only consider static data members.
3012 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3013 Diag(New->getLocation(), diag::err_duplicate_member)
3014 << New->getIdentifier();
3015 Diag(Old->getLocation(), diag::note_previous_declaration);
3016 New->setInvalidDecl();
3017 }
3018
Douglas Gregor27c6da22012-01-01 20:30:41 +00003019 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00003020 // Warn if an already-declared variable is made a weak_import in a subsequent
3021 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00003022 if (New->getAttr<WeakImportAttr>() &&
3023 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003024 !Old->getAttr<WeakImportAttr>()) {
3025 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3026 Diag(Old->getLocation(), diag::note_previous_definition);
3027 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00003028 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003029 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003030
Richard Smith34b41d92011-02-20 03:19:35 +00003031 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00003032 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3033
Richard Smith34b41d92011-02-20 03:19:35 +00003034 if (New->isInvalidDecl())
3035 return;
Douglas Gregor656de632009-03-11 23:52:16 +00003036
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003037 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00003038 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003039 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00003040 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003041 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003042 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003043 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003044 }
Mike Stump1eb44332009-09-09 15:08:12 +00003045 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003046 // For an identifier declared with the storage-class specifier
3047 // extern in a scope in which a prior declaration of that
3048 // identifier is visible,23) if the prior declaration specifies
3049 // internal or external linkage, the linkage of the identifier at
3050 // the later declaration is the same as the linkage specified at
3051 // the prior declaration. If no prior declaration is visible, or
3052 // if the prior declaration specifies no linkage, then the
3053 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00003054 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003055 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003056 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003057 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003058 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003059 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003060 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003061 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003062 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003063
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003064 // Check if extern is followed by non-extern and vice-versa.
3065 if (New->hasExternalStorage() &&
3066 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3067 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3068 Diag(Old->getLocation(), diag::note_previous_definition);
3069 return New->setInvalidDecl();
3070 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003071 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3072 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003073 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3074 Diag(Old->getLocation(), diag::note_previous_definition);
3075 return New->setInvalidDecl();
3076 }
3077
Steve Naroff094cefb2008-09-17 14:05:40 +00003078 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003080 // FIXME: The test for external storage here seems wrong? We still
3081 // need to check for mismatches.
3082 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003083 // Don't complain about out-of-line definitions of static members.
3084 !(Old->getLexicalDeclContext()->isRecord() &&
3085 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003086 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003087 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003088 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003089 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003090
Richard Smith38afbc72013-04-13 02:43:54 +00003091 if (New->getTLSKind() != Old->getTLSKind()) {
3092 if (!Old->getTLSKind()) {
3093 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3094 Diag(Old->getLocation(), diag::note_previous_declaration);
3095 } else if (!New->getTLSKind()) {
3096 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3097 Diag(Old->getLocation(), diag::note_previous_declaration);
3098 } else {
3099 // Do not allow redeclaration to change the variable between requiring
3100 // static and dynamic initialization.
3101 // FIXME: GCC allows this, but uses the TLS keyword on the first
3102 // declaration to determine the kind. Do we need to be compatible here?
3103 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3104 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3105 Diag(Old->getLocation(), diag::note_previous_declaration);
3106 }
Eli Friedman63054b32009-04-19 20:27:55 +00003107 }
3108
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003109 // C++ doesn't have tentative definitions, so go right ahead and check here.
3110 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003111 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003112 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003113 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003114 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003115 Diag(Def->getLocation(), diag::note_previous_definition);
3116 New->setInvalidDecl();
3117 return;
3118 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003119
Rafael Espindola950fee22013-02-14 01:18:37 +00003120 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003121 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3122 Diag(Old->getLocation(), diag::note_previous_definition);
3123 New->setInvalidDecl();
3124 return;
3125 }
3126
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003127 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00003128 if (Old->getMostRecentDecl()->isUsed(false))
3129 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003130
Douglas Gregor275a3692009-03-10 23:43:53 +00003131 // Keep a chain of previous declarations.
Rafael Espindolabc650912013-10-17 15:37:26 +00003132 New->setPreviousDecl(Old);
John McCall46460a62010-01-20 21:53:11 +00003133
3134 // Inherit access appropriately.
3135 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003136
3137 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3138 if (New->isStaticDataMember() && New->isOutOfLine())
3139 VTD->setAccess(New->getAccess());
3140 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003141}
3142
3143/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3144/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003145Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003146 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003147 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003148}
3149
Eli Friedman5e867c82013-07-10 00:30:46 +00003150static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003151 if (!S.Context.getLangOpts().CPlusPlus)
3152 return;
3153
Eli Friedman5e867c82013-07-10 00:30:46 +00003154 if (isa<CXXRecordDecl>(Tag->getParent())) {
3155 // If this tag is the direct child of a class, number it if
3156 // it is anonymous.
3157 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3158 return;
3159 MangleNumberingContext &MCtx =
3160 S.Context.getManglingNumberContext(Tag->getParent());
3161 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3162 return;
3163 }
3164
3165 // If this tag isn't a direct child of a class, number it if it is local.
3166 Decl *ManglingContextDecl;
3167 if (MangleNumberingContext *MCtx =
3168 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3169 ManglingContextDecl)) {
3170 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3171 }
3172}
3173
Chandler Carruth0f4be742011-05-03 18:35:10 +00003174/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003175/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003176/// parameters to cope with template friend declarations.
3177Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3178 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003179 MultiTemplateParamsArg TemplateParams,
3180 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003181 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003182 TagDecl *Tag = 0;
3183 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3184 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003185 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003186 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003187 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003188 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003189
3190 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003191 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003192
John McCall67d1a672009-08-06 02:15:43 +00003193 // Note that the above type specs guarantee that the
3194 // type rep is a Decl, whereas in many of the others
3195 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003196 if (isa<TagDecl>(TagD))
3197 Tag = cast<TagDecl>(TagD);
3198 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3199 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003200 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003201
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003202 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003203 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003204 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003205 if (Tag->isInvalidDecl())
3206 return Tag;
3207 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003208
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003209 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3210 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3211 // or incomplete types shall not be restrict-qualified."
3212 if (TypeQuals & DeclSpec::TQ_restrict)
3213 Diag(DS.getRestrictSpecLoc(),
3214 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3215 << DS.getSourceRange();
3216 }
3217
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003218 if (DS.isConstexprSpecified()) {
3219 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3220 // and definitions of functions and variables.
3221 if (Tag)
3222 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3223 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3224 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003225 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3226 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003227 else
3228 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3229 // Don't emit warnings after this error.
3230 return TagD;
3231 }
3232
Richard Smithc7f81162013-03-18 22:52:47 +00003233 DiagnoseFunctionSpecifiers(DS);
3234
Douglas Gregord85bea22009-09-26 06:47:28 +00003235 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003236 // If we're dealing with a decl but not a TagDecl, assume that
3237 // whatever routines created it handled the friendship aspect.
3238 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003239 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003240 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003241 }
John McCallac4df242011-03-22 23:00:04 +00003242
Richard Smithc7f81162013-03-18 22:52:47 +00003243 CXXScopeSpec &SS = DS.getTypeSpecScope();
3244 bool IsExplicitSpecialization =
3245 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3246 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3247 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3248 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3249 // nested-name-specifier unless it is an explicit instantiation
3250 // or an explicit specialization.
3251 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3252 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3253 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3254 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3255 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3256 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3257 << SS.getRange();
3258 return 0;
3259 }
3260
3261 // Track whether this decl-specifier declares anything.
3262 bool DeclaresAnything = true;
3263
3264 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003265 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003266 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003267 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003268 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003269 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003270 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003271
Richard Smithc7f81162013-03-18 22:52:47 +00003272 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003273 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003274 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003275
Richard Smithc7f81162013-03-18 22:52:47 +00003276 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003277 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003278 CurContext->isRecord() &&
3279 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3280 // Handle 2 kinds of anonymous struct:
3281 // struct STRUCT;
3282 // and
3283 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3284 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003285 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003286 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3287 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003288 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003289 << DS.getSourceRange();
3290 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3291 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003292 }
Richard Smithc7f81162013-03-18 22:52:47 +00003293
3294 // Skip all the checks below if we have a type error.
3295 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3296 (TagD && TagD->isInvalidDecl()))
3297 return TagD;
3298
3299 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003300 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3301 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3302 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003303 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3304 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003305
John McCallac4df242011-03-22 23:00:04 +00003306 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003307 // Customize diagnostic for a typedef missing a name.
3308 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003309 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003310 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003311 else
3312 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003313 }
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Richard Smithc7f81162013-03-18 22:52:47 +00003315 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003316 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3317 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3318 << Tag->getTagKind()
3319 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3320
Richard Smithc7f81162013-03-18 22:52:47 +00003321 ActOnDocumentableDecl(TagD);
3322
3323 // C 6.7/2:
3324 // A declaration [...] shall declare at least a declarator [...], a tag,
3325 // or the members of an enumeration.
3326 // C++ [dcl.dcl]p3:
3327 // [If there are no declarators], and except for the declaration of an
3328 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3329 // names into the program, or shall redeclare a name introduced by a
3330 // previous declaration.
3331 if (!DeclaresAnything) {
3332 // In C, we allow this as a (popular) extension / bug. Don't bother
3333 // producing further diagnostics for redundant qualifiers after this.
3334 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3335 return TagD;
3336 }
3337
3338 // C++ [dcl.stc]p1:
3339 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3340 // init-declarator-list of the declaration shall not be empty.
3341 // C++ [dcl.fct.spec]p1:
3342 // If a cv-qualifier appears in a decl-specifier-seq, the
3343 // init-declarator-list of the declaration shall not be empty.
3344 //
3345 // Spurious qualifiers here appear to be valid in C.
3346 unsigned DiagID = diag::warn_standalone_specifier;
3347 if (getLangOpts().CPlusPlus)
3348 DiagID = diag::ext_standalone_specifier;
3349
3350 // Note that a linkage-specification sets a storage class, but
3351 // 'extern "C" struct foo;' is actually valid and not theoretically
3352 // useless.
3353 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3354 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3355 Diag(DS.getStorageClassSpecLoc(), DiagID)
3356 << DeclSpec::getSpecifierName(SCS);
3357
Richard Smithec642442013-04-12 22:46:28 +00003358 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3359 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3360 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003361 if (DS.getTypeQualifiers()) {
3362 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3363 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3364 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3365 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3366 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003367 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3368 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003369 }
3370
Eli Friedmanfc038e92011-12-17 00:36:09 +00003371 // Warn about ignored type attributes, for example:
3372 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003373 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003374 if (!DS.getAttributes().empty()) {
3375 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3376 if (TypeSpecType == DeclSpec::TST_class ||
3377 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003378 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003379 TypeSpecType == DeclSpec::TST_union ||
3380 TypeSpecType == DeclSpec::TST_enum) {
3381 AttributeList* attrs = DS.getAttributes().getList();
3382 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003383 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003384 << attrs->getName()
3385 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3386 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003387 TypeSpecType == DeclSpec::TST_union ? 2 :
3388 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003389 attrs = attrs->getNext();
3390 }
3391 }
3392 }
John McCallac4df242011-03-22 23:00:04 +00003393
John McCalld226f652010-08-21 09:40:31 +00003394 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003395}
3396
John McCall1d7c5282009-12-18 10:40:03 +00003397/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003398/// check if there's an existing declaration that can't be overloaded.
3399///
3400/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003401static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3402 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003403 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003404 DeclarationName Name,
3405 SourceLocation NameLoc,
3406 unsigned diagnostic) {
3407 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3408 Sema::ForRedeclaration);
3409 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003410
John McCall1d7c5282009-12-18 10:40:03 +00003411 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003412 return false;
3413
3414 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003415 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003416 assert(PrevDecl && "Expected a non-null Decl");
3417
3418 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3419 return false;
John McCall68263142009-11-18 22:49:29 +00003420
John McCall1d7c5282009-12-18 10:40:03 +00003421 SemaRef.Diag(NameLoc, diagnostic) << Name;
3422 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003423
3424 return true;
3425}
3426
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003427/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3428/// anonymous struct or union AnonRecord into the owning context Owner
3429/// and scope S. This routine will be invoked just after we realize
3430/// that an unnamed union or struct is actually an anonymous union or
3431/// struct, e.g.,
3432///
3433/// @code
3434/// union {
3435/// int i;
3436/// float f;
3437/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3438/// // f into the surrounding scope.x
3439/// @endcode
3440///
3441/// This routine is recursive, injecting the names of nested anonymous
3442/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003443static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003444 DeclContext *Owner,
3445 RecordDecl *AnonRecord,
3446 AccessSpecifier AS,
3447 SmallVectorImpl<NamedDecl *> &Chaining,
3448 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003449 unsigned diagKind
3450 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3451 : diag::err_anonymous_struct_member_redecl;
3452
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003453 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003454
3455 // Look every FieldDecl and IndirectFieldDecl with a name.
3456 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3457 DEnd = AnonRecord->decls_end();
3458 D != DEnd; ++D) {
3459 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3460 cast<NamedDecl>(*D)->getDeclName()) {
3461 ValueDecl *VD = cast<ValueDecl>(*D);
3462 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3463 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003464 // C++ [class.union]p2:
3465 // The names of the members of an anonymous union shall be
3466 // distinct from the names of any other entity in the
3467 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003468 Invalid = true;
3469 } else {
3470 // C++ [class.union]p2:
3471 // For the purpose of name lookup, after the anonymous union
3472 // definition, the members of the anonymous union are
3473 // considered to have been defined in the scope in which the
3474 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003475 unsigned OldChainingSize = Chaining.size();
3476 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3477 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3478 PE = IF->chain_end(); PI != PE; ++PI)
3479 Chaining.push_back(*PI);
3480 else
3481 Chaining.push_back(VD);
3482
Francois Pichet87c2e122010-11-21 06:08:52 +00003483 assert(Chaining.size() >= 2);
3484 NamedDecl **NamedChain =
3485 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3486 for (unsigned i = 0; i < Chaining.size(); i++)
3487 NamedChain[i] = Chaining[i];
3488
3489 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003490 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3491 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003492 NamedChain, Chaining.size());
3493
3494 IndirectField->setAccess(AS);
3495 IndirectField->setImplicit();
3496 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003497
3498 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003499 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003500
Francois Pichet8e161ed2010-11-23 06:07:27 +00003501 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003502 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003503 }
3504 }
3505
3506 return Invalid;
3507}
3508
Douglas Gregor16573fa2010-04-19 22:54:31 +00003509/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3510/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003511/// illegal input values are mapped to SC_None.
3512static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003513StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3514 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3515 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3516 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003517 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003518 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003519 case DeclSpec::SCS_extern:
3520 if (DS.isExternInLinkageSpec())
3521 return SC_None;
3522 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003523 case DeclSpec::SCS_static: return SC_Static;
3524 case DeclSpec::SCS_auto: return SC_Auto;
3525 case DeclSpec::SCS_register: return SC_Register;
3526 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003527 // Illegal SCSs map to None: error reporting is up to the caller.
3528 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003529 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003530 }
3531 llvm_unreachable("unknown storage class specifier");
3532}
3533
Francois Pichet8e161ed2010-11-23 06:07:27 +00003534/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003535/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003536/// (C++ [class.union]) and a C11 feature; anonymous structures
3537/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003538Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3539 AccessSpecifier AS,
3540 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003541 DeclContext *Owner = Record->getDeclContext();
3542
3543 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003544 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003545 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003546 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003547 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003548 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003549 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003550
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003551 // C and C++ require different kinds of checks for anonymous
3552 // structs/unions.
3553 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003554 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003555 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003556 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003557 if (Record->isUnion()) {
3558 // C++ [class.union]p6:
3559 // Anonymous unions declared in a named namespace or in the
3560 // global namespace shall be declared static.
3561 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3562 (isa<TranslationUnitDecl>(Owner) ||
3563 (isa<NamespaceDecl>(Owner) &&
3564 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003565 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3566 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003567
3568 // Recover by adding 'static'.
3569 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3570 PrevSpec, DiagID);
3571 }
3572 // C++ [class.union]p6:
3573 // A storage class is not allowed in a declaration of an
3574 // anonymous union in a class scope.
3575 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3576 isa<RecordDecl>(Owner)) {
3577 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003578 diag::err_anonymous_union_with_storage_spec)
3579 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003580
3581 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003582 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3583 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003584 PrevSpec, DiagID);
3585 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003586 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003587
Douglas Gregor7604f642011-05-09 23:05:33 +00003588 // Ignore const/volatile/restrict qualifiers.
3589 if (DS.getTypeQualifiers()) {
3590 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3591 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003592 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003593 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3594 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003595 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003596 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003597 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003598 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3599 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003600 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003601 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003602 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003603 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003604 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3605 Diag(DS.getAtomicSpecLoc(),
3606 diag::ext_anonymous_struct_union_qualified)
3607 << Record->isUnion() << "_Atomic"
3608 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003609
3610 DS.ClearTypeQualifiers();
3611 }
3612
Mike Stump1eb44332009-09-09 15:08:12 +00003613 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003614 // The member-specification of an anonymous union shall only
3615 // define non-static data members. [Note: nested types and
3616 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003617 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3618 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003619 Mem != MemEnd; ++Mem) {
3620 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3621 // C++ [class.union]p3:
3622 // An anonymous union shall not have private or protected
3623 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003624 assert(FD->getAccess() != AS_none);
3625 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003626 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3627 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3628 Invalid = true;
3629 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003630
Sean Huntcf34e752011-05-16 22:41:40 +00003631 // C++ [class.union]p1
3632 // An object of a class with a non-trivial constructor, a non-trivial
3633 // copy constructor, a non-trivial destructor, or a non-trivial copy
3634 // assignment operator cannot be a member of a union, nor can an
3635 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003636 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003637 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003638 } else if ((*Mem)->isImplicit()) {
3639 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003640 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3641 // This is a type that showed up in an
3642 // elaborated-type-specifier inside the anonymous struct or
3643 // union, but which actually declares a type outside of the
3644 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003645 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3646 if (!MemRecord->isAnonymousStructOrUnion() &&
3647 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003648 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003649 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00003650 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3651 << (int)Record->isUnion();
3652 else {
3653 // This is a nested type declaration.
3654 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3655 << (int)Record->isUnion();
3656 Invalid = true;
3657 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003658 } else {
3659 // This is an anonymous type definition within another anonymous type.
3660 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3661 // not part of standard C++.
3662 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003663 diag::ext_anonymous_record_with_anonymous_type)
3664 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003665 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003666 } else if (isa<AccessSpecDecl>(*Mem)) {
3667 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003668 } else {
3669 // We have something that isn't a non-static data
3670 // member. Complain about it.
3671 unsigned DK = diag::err_anonymous_record_bad_member;
3672 if (isa<TypeDecl>(*Mem))
3673 DK = diag::err_anonymous_record_with_type;
3674 else if (isa<FunctionDecl>(*Mem))
3675 DK = diag::err_anonymous_record_with_function;
3676 else if (isa<VarDecl>(*Mem))
3677 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003678
3679 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003680 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003681 DK == diag::err_anonymous_record_with_type)
3682 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003683 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003684 else {
3685 Diag((*Mem)->getLocation(), DK)
3686 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003687 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003688 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003689 }
3690 }
Mike Stump1eb44332009-09-09 15:08:12 +00003691 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003692
3693 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003694 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003695 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003696 Invalid = true;
3697 }
3698
John McCalleb692e02009-10-22 23:31:08 +00003699 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003700 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003701 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003702 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003703
Mike Stump1eb44332009-09-09 15:08:12 +00003704 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003705 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003706 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003707 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003708 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003709 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003710 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003711 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003712 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003713 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003714 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003715 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003716 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003717 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003718 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003719 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003720 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003721 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003722 // mutable can only appear on non-static class members, so it's always
3723 // an error here
3724 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3725 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003726 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003727 }
3728
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003729 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003730 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003731 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003732 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003733 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003734
3735 // Default-initialize the implicit variable. This initialization will be
3736 // trivial in almost all cases, except if a union member has an in-class
3737 // initializer:
3738 // union { int n = 0; };
3739 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003740 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003741 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003742
3743 // Add the anonymous struct/union object to the current
3744 // context. We'll be referencing this object when we refer to one of
3745 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003746 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003747
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003748 // Inject the members of the anonymous struct/union into the owning
3749 // context and into the identifier resolver chain for name lookup
3750 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003751 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003752 Chain.push_back(Anon);
3753
Francois Pichet8e161ed2010-11-23 06:07:27 +00003754 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3755 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003756 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003757
3758 // Mark this as an anonymous struct/union type. Note that we do not
3759 // do this until after we have already checked and injected the
3760 // members of this anonymous struct/union type, because otherwise
3761 // the members could be injected twice: once by DeclContext when it
3762 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003763 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003764 Record->setAnonymousStructOrUnion(true);
3765
3766 if (Invalid)
3767 Anon->setInvalidDecl();
3768
John McCalld226f652010-08-21 09:40:31 +00003769 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003770}
3771
Francois Pichet8e161ed2010-11-23 06:07:27 +00003772/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3773/// Microsoft C anonymous structure.
3774/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3775/// Example:
3776///
3777/// struct A { int a; };
3778/// struct B { struct A; int b; };
3779///
3780/// void foo() {
3781/// B var;
3782/// var.a = 3;
3783/// }
3784///
3785Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3786 RecordDecl *Record) {
3787
3788 // If there is no Record, get the record via the typedef.
3789 if (!Record)
3790 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3791
3792 // Mock up a declarator.
3793 Declarator Dc(DS, Declarator::TypeNameContext);
3794 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3795 assert(TInfo && "couldn't build declarator info for anonymous struct");
3796
3797 // Create a declaration for this anonymous struct.
3798 NamedDecl* Anon = FieldDecl::Create(Context,
3799 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003800 DS.getLocStart(),
3801 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003802 /*IdentifierInfo=*/0,
3803 Context.getTypeDeclType(Record),
3804 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003805 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003806 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003807 Anon->setImplicit();
3808
3809 // Add the anonymous struct object to the current context.
3810 CurContext->addDecl(Anon);
3811
3812 // Inject the members of the anonymous struct into the current
3813 // context and into the identifier resolver chain for name lookup
3814 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003815 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003816 Chain.push_back(Anon);
3817
Nico Weberee625af2012-02-01 00:41:00 +00003818 RecordDecl *RecordDef = Record->getDefinition();
3819 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3820 RecordDef, AS_none,
3821 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003822 Anon->setInvalidDecl();
3823
3824 return Anon;
3825}
Steve Narofff0090632007-09-02 02:04:30 +00003826
Douglas Gregor10bd3682008-11-17 22:58:34 +00003827/// GetNameForDeclarator - Determine the full declaration name for the
3828/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003829DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003830 return GetNameFromUnqualifiedId(D.getName());
3831}
3832
Abramo Bagnara25777432010-08-11 22:01:17 +00003833/// \brief Retrieves the declaration name from a parsed unqualified-id.
3834DeclarationNameInfo
3835Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3836 DeclarationNameInfo NameInfo;
3837 NameInfo.setLoc(Name.StartLocation);
3838
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003839 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003840
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003841 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003842 case UnqualifiedId::IK_Identifier:
3843 NameInfo.setName(Name.Identifier);
3844 NameInfo.setLoc(Name.StartLocation);
3845 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003846
Abramo Bagnara25777432010-08-11 22:01:17 +00003847 case UnqualifiedId::IK_OperatorFunctionId:
3848 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3849 Name.OperatorFunctionId.Operator));
3850 NameInfo.setLoc(Name.StartLocation);
3851 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3852 = Name.OperatorFunctionId.SymbolLocations[0];
3853 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3854 = Name.EndLocation.getRawEncoding();
3855 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003856
Abramo Bagnara25777432010-08-11 22:01:17 +00003857 case UnqualifiedId::IK_LiteralOperatorId:
3858 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3859 Name.Identifier));
3860 NameInfo.setLoc(Name.StartLocation);
3861 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3862 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003863
Abramo Bagnara25777432010-08-11 22:01:17 +00003864 case UnqualifiedId::IK_ConversionFunctionId: {
3865 TypeSourceInfo *TInfo;
3866 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3867 if (Ty.isNull())
3868 return DeclarationNameInfo();
3869 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3870 Context.getCanonicalType(Ty)));
3871 NameInfo.setLoc(Name.StartLocation);
3872 NameInfo.setNamedTypeInfo(TInfo);
3873 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003874 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003875
3876 case UnqualifiedId::IK_ConstructorName: {
3877 TypeSourceInfo *TInfo;
3878 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3879 if (Ty.isNull())
3880 return DeclarationNameInfo();
3881 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3882 Context.getCanonicalType(Ty)));
3883 NameInfo.setLoc(Name.StartLocation);
3884 NameInfo.setNamedTypeInfo(TInfo);
3885 return NameInfo;
3886 }
3887
3888 case UnqualifiedId::IK_ConstructorTemplateId: {
3889 // In well-formed code, we can only have a constructor
3890 // template-id that refers to the current context, so go there
3891 // to find the actual type being constructed.
3892 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3893 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3894 return DeclarationNameInfo();
3895
3896 // Determine the type of the class being constructed.
3897 QualType CurClassType = Context.getTypeDeclType(CurClass);
3898
3899 // FIXME: Check two things: that the template-id names the same type as
3900 // CurClassType, and that the template-id does not occur when the name
3901 // was qualified.
3902
3903 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3904 Context.getCanonicalType(CurClassType)));
3905 NameInfo.setLoc(Name.StartLocation);
3906 // FIXME: should we retrieve TypeSourceInfo?
3907 NameInfo.setNamedTypeInfo(0);
3908 return NameInfo;
3909 }
3910
3911 case UnqualifiedId::IK_DestructorName: {
3912 TypeSourceInfo *TInfo;
3913 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3914 if (Ty.isNull())
3915 return DeclarationNameInfo();
3916 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3917 Context.getCanonicalType(Ty)));
3918 NameInfo.setLoc(Name.StartLocation);
3919 NameInfo.setNamedTypeInfo(TInfo);
3920 return NameInfo;
3921 }
3922
3923 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003924 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003925 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3926 return Context.getNameForTemplate(TName, TNameLoc);
3927 }
3928
3929 } // switch (Name.getKind())
3930
David Blaikieb219cfc2011-09-23 05:06:16 +00003931 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003932}
3933
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003934static QualType getCoreType(QualType Ty) {
3935 do {
3936 if (Ty->isPointerType() || Ty->isReferenceType())
3937 Ty = Ty->getPointeeType();
3938 else if (Ty->isArrayType())
3939 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3940 else
3941 return Ty.withoutLocalFastQualifiers();
3942 } while (true);
3943}
3944
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003945/// hasSimilarParameters - Determine whether the C++ functions Declaration
3946/// and Definition have "nearly" matching parameters. This heuristic is
3947/// used to improve diagnostics in the case where an out-of-line function
3948/// definition doesn't match any declaration within the class or namespace.
3949/// Also sets Params to the list of indices to the parameters that differ
3950/// between the declaration and the definition. If hasSimilarParameters
3951/// returns true and Params is empty, then all of the parameters match.
3952static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003953 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003954 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003955 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003956 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003957 if (Declaration->param_size() != Definition->param_size())
3958 return false;
3959 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3960 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3961 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3962
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003963 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003964 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003965 continue;
3966
3967 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3968 QualType DefParamBaseTy = getCoreType(DefParamTy);
3969 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3970 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3971
3972 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3973 (DeclTyName && DeclTyName == DefTyName))
3974 Params.push_back(Idx);
3975 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003976 return false;
3977 }
3978
3979 return true;
3980}
3981
John McCall63b43852010-04-29 23:50:39 +00003982/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3983/// declarator needs to be rebuilt in the current instantiation.
3984/// Any bits of declarator which appear before the name are valid for
3985/// consideration here. That's specifically the type in the decl spec
3986/// and the base type in any member-pointer chunks.
3987static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3988 DeclarationName Name) {
3989 // The types we specifically need to rebuild are:
3990 // - typenames, typeofs, and decltypes
3991 // - types which will become injected class names
3992 // Of course, we also need to rebuild any type referencing such a
3993 // type. It's safest to just say "dependent", but we call out a
3994 // few cases here.
3995
3996 DeclSpec &DS = D.getMutableDeclSpec();
3997 switch (DS.getTypeSpecType()) {
3998 case DeclSpec::TST_typename:
3999 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00004000 case DeclSpec::TST_underlyingType:
4001 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00004002 // Grab the type from the parser.
4003 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00004004 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00004005 if (T.isNull() || !T->isDependentType()) break;
4006
4007 // Make sure there's a type source info. This isn't really much
4008 // of a waste; most dependent types should have type source info
4009 // attached already.
4010 if (!TSI)
4011 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4012
4013 // Rebuild the type in the current instantiation.
4014 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4015 if (!TSI) return true;
4016
4017 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00004018 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4019 DS.UpdateTypeRep(LocType);
4020 break;
4021 }
4022
Richard Smithc4a83912012-10-01 20:35:07 +00004023 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00004024 case DeclSpec::TST_typeofExpr: {
4025 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00004026 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00004027 if (Result.isInvalid()) return true;
4028 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00004029 break;
4030 }
4031
4032 default:
4033 // Nothing to do for these decl specs.
4034 break;
4035 }
4036
4037 // It doesn't matter what order we do this in.
4038 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4039 DeclaratorChunk &Chunk = D.getTypeObject(I);
4040
4041 // The only type information in the declarator which can come
4042 // before the declaration name is the base type of a member
4043 // pointer.
4044 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4045 continue;
4046
4047 // Rebuild the scope specifier in-place.
4048 CXXScopeSpec &SS = Chunk.Mem.Scope();
4049 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4050 return true;
4051 }
4052
4053 return false;
4054}
4055
Anders Carlsson3242ee02011-07-04 16:28:17 +00004056Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00004057 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004058 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004059
4060 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004061 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004062 Dcl->setTopLevelDeclInObjCContainer();
4063
4064 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004065}
4066
Richard Smith162e1c12011-04-15 14:24:37 +00004067/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4068/// If T is the name of a class, then each of the following shall have a
4069/// name different from T:
4070/// - every static data member of class T;
4071/// - every member function of class T
4072/// - every member of class T that is itself a type;
4073/// \returns true if the declaration name violates these rules.
4074bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4075 DeclarationNameInfo NameInfo) {
4076 DeclarationName Name = NameInfo.getName();
4077
4078 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4079 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4080 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4081 return true;
4082 }
4083
4084 return false;
4085}
Douglas Gregor42acead2012-03-17 23:06:31 +00004086
Douglas Gregor69605872012-03-28 16:01:27 +00004087/// \brief Diagnose a declaration whose declarator-id has the given
4088/// nested-name-specifier.
4089///
4090/// \param SS The nested-name-specifier of the declarator-id.
4091///
4092/// \param DC The declaration context to which the nested-name-specifier
4093/// resolves.
4094///
4095/// \param Name The name of the entity being declared.
4096///
4097/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004098///
4099/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004100bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004101 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004102 SourceLocation Loc) {
4103 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004104 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004105 Cur = Cur->getParent();
4106
4107 // C++ [dcl.meaning]p1:
4108 // A declarator-id shall not be qualified except for the definition
4109 // of a member function (9.3) or static data member (9.4) outside of
4110 // its class, the definition or explicit instantiation of a function
4111 // or variable member of a namespace outside of its namespace, or the
4112 // definition of an explicit specialization outside of its namespace,
4113 // or the declaration of a friend function that is a member of
4114 // another class or namespace (11.3). [...]
4115
4116 // The user provided a superfluous scope specifier that refers back to the
4117 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004118 //
4119 // class X {
4120 // void X::f();
4121 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004122 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004123 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4124 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004125 << Name << FixItHint::CreateRemoval(SS.getRange());
4126 SS.clear();
4127 return false;
4128 }
Douglas Gregor69605872012-03-28 16:01:27 +00004129
4130 // Check whether the qualifying scope encloses the scope of the original
4131 // declaration.
4132 if (!Cur->Encloses(DC)) {
4133 if (Cur->isRecord())
4134 Diag(Loc, diag::err_member_qualification)
4135 << Name << SS.getRange();
4136 else if (isa<TranslationUnitDecl>(DC))
4137 Diag(Loc, diag::err_invalid_declarator_global_scope)
4138 << Name << SS.getRange();
4139 else if (isa<FunctionDecl>(Cur))
4140 Diag(Loc, diag::err_invalid_declarator_in_function)
4141 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004142 else if (isa<BlockDecl>(Cur))
4143 Diag(Loc, diag::err_invalid_declarator_in_block)
4144 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004145 else
4146 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004147 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004148
Douglas Gregor42acead2012-03-17 23:06:31 +00004149 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004150 }
4151
4152 if (Cur->isRecord()) {
4153 // Cannot qualify members within a class.
4154 Diag(Loc, diag::err_member_qualification)
4155 << Name << SS.getRange();
4156 SS.clear();
4157
4158 // C++ constructors and destructors with incorrect scopes can break
4159 // our AST invariants by having the wrong underlying types. If
4160 // that's the case, then drop this declaration entirely.
4161 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4162 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4163 !Context.hasSameType(Name.getCXXNameType(),
4164 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4165 return true;
4166
4167 return false;
4168 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004169
Douglas Gregor69605872012-03-28 16:01:27 +00004170 // C++11 [dcl.meaning]p1:
4171 // [...] "The nested-name-specifier of the qualified declarator-id shall
4172 // not begin with a decltype-specifer"
4173 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4174 while (SpecLoc.getPrefix())
4175 SpecLoc = SpecLoc.getPrefix();
4176 if (dyn_cast_or_null<DecltypeType>(
4177 SpecLoc.getNestedNameSpecifier()->getAsType()))
4178 Diag(Loc, diag::err_decltype_in_declarator)
4179 << SpecLoc.getTypeLoc().getSourceRange();
4180
Douglas Gregor42acead2012-03-17 23:06:31 +00004181 return false;
4182}
4183
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004184NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4185 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004186 // TODO: consider using NameInfo for diagnostic.
4187 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4188 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004189
Chris Lattnere80a59c2007-07-25 00:24:17 +00004190 // All of these full declarators require an identifier. If it doesn't have
4191 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004192 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004193 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004194 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004195 diag::err_declarator_need_ident)
4196 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004197 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004198 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4199 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004200
Chris Lattner31e05722007-08-26 06:24:45 +00004201 // The scope passed in may not be a decl scope. Zip up the scope tree until
4202 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004203 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004204 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004205 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004206
John McCall63b43852010-04-29 23:50:39 +00004207 DeclContext *DC = CurContext;
4208 if (D.getCXXScopeSpec().isInvalid())
4209 D.setInvalidType();
4210 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004211 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4212 UPPC_DeclarationQualifier))
4213 return 0;
4214
John McCall63b43852010-04-29 23:50:39 +00004215 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4216 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4217 if (!DC) {
4218 // If we could not compute the declaration context, it's because the
4219 // declaration context is dependent but does not refer to a class,
4220 // class template, or class template partial specialization. Complain
4221 // and return early, to avoid the coming semantic disaster.
4222 Diag(D.getIdentifierLoc(),
4223 diag::err_template_qualified_declarator_no_match)
4224 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4225 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004226 return 0;
John McCall63b43852010-04-29 23:50:39 +00004227 }
John McCall63b43852010-04-29 23:50:39 +00004228 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004229
John McCall63b43852010-04-29 23:50:39 +00004230 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004231 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004232 return 0;
John McCall63b43852010-04-29 23:50:39 +00004233
Douglas Gregor69605872012-03-28 16:01:27 +00004234 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4235 Diag(D.getIdentifierLoc(),
4236 diag::err_member_def_undefined_record)
4237 << Name << DC << D.getCXXScopeSpec().getRange();
4238 D.setInvalidType();
4239 } else if (!D.getDeclSpec().isFriendSpecified()) {
4240 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4241 Name, D.getIdentifierLoc())) {
4242 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004243 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004244
4245 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004246 }
John McCall63b43852010-04-29 23:50:39 +00004247 }
4248
4249 // Check whether we need to rebuild the type of the given
4250 // declaration in the current instantiation.
4251 if (EnteringContext && IsDependentContext &&
4252 TemplateParamLists.size() != 0) {
4253 ContextRAII SavedContext(*this, DC);
4254 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4255 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004256 }
4257 }
Richard Smith162e1c12011-04-15 14:24:37 +00004258
4259 if (DiagnoseClassNameShadow(DC, NameInfo))
4260 // If this is a typedef, we'll end up spewing multiple diagnostics.
4261 // Just return early; it's safer.
4262 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4263 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004264
John McCallbf1a0282010-06-04 23:28:52 +00004265 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4266 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004267
Douglas Gregord0937222010-12-13 22:49:22 +00004268 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4269 UPPC_DeclarationType))
4270 D.setInvalidType();
4271
Abramo Bagnara25777432010-08-11 22:01:17 +00004272 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004273 ForRedeclaration);
4274
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004275 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004276 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004277 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004278 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004279
4280 // If the declaration we're planning to build will be a function
4281 // or object with linkage, then look for another declaration with
4282 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004283 //
4284 // If the declaration we're planning to build will be declared with
4285 // external linkage in the translation unit, create any builtin with
4286 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004287 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4288 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004289 else if (CurContext->isFunctionOrMethod() &&
4290 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4291 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004292 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004293 CreateBuiltins =
4294 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4295 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4296 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4297 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004298
4299 if (IsLinkageLookup)
4300 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004301
Richard Smithdd9459f2013-08-13 18:18:50 +00004302 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004303 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004304 LookupQualifiedName(Previous, DC);
4305
Douglas Gregor69605872012-03-28 16:01:27 +00004306 // C++ [dcl.meaning]p1:
4307 // When the declarator-id is qualified, the declaration shall refer to a
4308 // previously declared member of the class or namespace to which the
4309 // qualifier refers (or, in the case of a namespace, of an element of the
4310 // inline namespace set of that namespace (7.3.1)) or to a specialization
4311 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004312 //
Douglas Gregor69605872012-03-28 16:01:27 +00004313 // Note that we already checked the context above, and that we do not have
4314 // enough information to make sure that Previous contains the declaration
4315 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004316 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004317 // class X {
4318 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004319 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004320 // };
4321 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004322 // void X::f(int) { } // ill-formed
4323 //
Douglas Gregor69605872012-03-28 16:01:27 +00004324 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004325 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004326 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004327
4328 // C++ [dcl.meaning]p1:
4329 // [...] the member shall not merely have been introduced by a
4330 // using-declaration in the scope of the class or namespace nominated by
4331 // the nested-name-specifier of the declarator-id.
4332 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004333 }
4334
John McCall68263142009-11-18 22:49:29 +00004335 if (Previous.isSingleResult() &&
4336 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004337 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004338 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004339 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4340 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Douglas Gregor72c3f312008-12-05 18:15:24 +00004342 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004343 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004344 }
4345
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004346 // In C++, the previous declaration we find might be a tag type
4347 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004348 // tag type. Note that this does does not apply if we're declaring a
4349 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004350 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004351 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004352 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004353
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004354 // Check that there are no default arguments other than in the parameters
4355 // of a function declaration (C++ only).
4356 if (getLangOpts().CPlusPlus)
4357 CheckExtraCXXDefaultArguments(D);
4358
Nico Webere6bb76c2012-12-23 00:40:46 +00004359 NamedDecl *New;
4360
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004361 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004362 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004363 if (TemplateParamLists.size()) {
4364 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004365 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004366 }
Mike Stump1eb44332009-09-09 15:08:12 +00004367
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004368 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004369 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004370 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004371 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004372 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004373 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004374 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4375 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004376 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004377
4378 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004379 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004381 // If this has an identifier and is not an invalid redeclaration or
4382 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004383 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004384 !(D.isRedeclaration() && New->isInvalidDecl())) {
4385 // Only make a locally-scoped extern declaration visible if it is the first
4386 // declaration of this entity. Qualified lookup for such an entity should
4387 // only find this declaration if there is no visible declaration of it.
4388 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4389 PushOnScopeChains(New, S, AddToContext);
4390 if (!AddToContext)
4391 CurContext->addHiddenDecl(New);
4392 }
Mike Stump1eb44332009-09-09 15:08:12 +00004393
John McCalld226f652010-08-21 09:40:31 +00004394 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004395}
4396
Abramo Bagnara88adb982012-11-08 16:27:30 +00004397/// Helper method to turn variable array types into constant array
4398/// types in certain situations which would otherwise be errors (for
4399/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004400static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4401 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004402 bool &SizeIsNegative,
4403 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004404 // This method tries to turn a variable array into a constant
4405 // array even when the size isn't an ICE. This is necessary
4406 // for compatibility with code that depends on gcc's buggy
4407 // constant expression folding, like struct {char x[(int)(char*)2];}
4408 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004409 Oversized = 0;
4410
4411 if (T->isDependentType())
4412 return QualType();
4413
John McCall0953e762009-09-24 19:53:00 +00004414 QualifierCollector Qs;
4415 const Type *Ty = Qs.strip(T);
4416
4417 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004418 QualType Pointee = PTy->getPointeeType();
4419 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004420 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4421 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004422 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004423 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004424 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004425 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004426 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4427 QualType Inner = PTy->getInnerType();
4428 QualType FixedType =
4429 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4430 Oversized);
4431 if (FixedType.isNull()) return FixedType;
4432 FixedType = Context.getParenType(FixedType);
4433 return Qs.apply(Context, FixedType);
4434 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004435
4436 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004437 if (!VLATy)
4438 return QualType();
4439 // FIXME: We should probably handle this case
4440 if (VLATy->getElementType()->isVariablyModifiedType())
4441 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Richard Smithaa9c3502011-12-07 00:43:50 +00004443 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004444 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004445 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004446 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004447
Douglas Gregor2767ce22010-08-18 00:39:00 +00004448 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004449 if (Res.isSigned() && Res.isNegative()) {
4450 SizeIsNegative = true;
4451 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004452 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004453
Douglas Gregor2767ce22010-08-18 00:39:00 +00004454 // Check whether the array is too large to be addressed.
4455 unsigned ActiveSizeBits
4456 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4457 Res);
4458 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4459 Oversized = Res;
4460 return QualType();
4461 }
4462
4463 return Context.getConstantArrayType(VLATy->getElementType(),
4464 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004465}
4466
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004467static void
4468FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004469 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4470 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4471 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4472 DstPTL.getPointeeLoc());
4473 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004474 return;
4475 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004476 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4477 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4478 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4479 DstPTL.getInnerLoc());
4480 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4481 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004482 return;
4483 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004484 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4485 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4486 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4487 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004488 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004489 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4490 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4491 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004492}
4493
Abramo Bagnara88adb982012-11-08 16:27:30 +00004494/// Helper method to turn variable array types into constant array
4495/// types in certain situations which would otherwise be errors (for
4496/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004497static TypeSourceInfo*
4498TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4499 ASTContext &Context,
4500 bool &SizeIsNegative,
4501 llvm::APSInt &Oversized) {
4502 QualType FixedTy
4503 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4504 SizeIsNegative, Oversized);
4505 if (FixedTy.isNull())
4506 return 0;
4507 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4508 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4509 FixedTInfo->getTypeLoc());
4510 return FixedTInfo;
4511}
4512
Richard Smith5ea6ef42013-01-10 23:43:47 +00004513/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004514/// that it can be found later for redeclarations. We include any extern "C"
4515/// declaration that is not visible in the translation unit here, not just
4516/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004517void
Richard Smith662f41b2013-06-18 20:15:12 +00004518Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004519 if (!getLangOpts().CPlusPlus &&
4520 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4521 // Don't need to track declarations in the TU in C.
4522 return;
4523
Douglas Gregor63935192009-03-02 00:19:53 +00004524 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004525 // FIXME: There can be multiple such declarations if they are functions marked
4526 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004527 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004528}
4529
Richard Smith662f41b2013-06-18 20:15:12 +00004530NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004531 if (ExternalSource) {
4532 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004533 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004534 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004535 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004536 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4537 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004538 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4539 if (Pos == LocallyScopedExternCDecls.end())
4540 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004541 }
4542 }
Richard Smith662f41b2013-06-18 20:15:12 +00004543
4544 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola87bcee82013-10-19 16:55:03 +00004545 return D ? D->getMostRecentDecl() : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004546}
4547
Eli Friedman85a53192009-04-07 19:37:57 +00004548/// \brief Diagnose function specifiers on a declaration of an identifier that
4549/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004550void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004551 // FIXME: We should probably indicate the identifier in question to avoid
4552 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004553 if (DS.isInlineSpecified())
4554 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004555 diag::err_inline_non_function);
4556
Richard Smithc7f81162013-03-18 22:52:47 +00004557 if (DS.isVirtualSpecified())
4558 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004559 diag::err_virtual_non_function);
4560
Richard Smithc7f81162013-03-18 22:52:47 +00004561 if (DS.isExplicitSpecified())
4562 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004563 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004564
Richard Smithc7f81162013-03-18 22:52:47 +00004565 if (DS.isNoreturnSpecified())
4566 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004567 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004568}
4569
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004570NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004571Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004572 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004573 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4574 if (D.getCXXScopeSpec().isSet()) {
4575 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4576 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004577 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004578 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004579 DC = CurContext;
4580 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004581 }
4582
Richard Smithc7f81162013-03-18 22:52:47 +00004583 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004584
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004585 if (D.getDeclSpec().isConstexprSpecified())
4586 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4587 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004588
Douglas Gregoraef01992010-07-13 06:37:01 +00004589 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4590 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4591 << D.getName().getSourceRange();
4592 return 0;
4593 }
4594
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004595 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004596 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004597
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004598 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004599 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004600
Richard Smith3e4c6c42011-05-05 21:57:07 +00004601 CheckTypedefForVariablyModifiedType(S, NewTD);
4602
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004603 bool Redeclaration = D.isRedeclaration();
4604 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4605 D.setRedeclaration(Redeclaration);
4606 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004607}
4608
Richard Smith3e4c6c42011-05-05 21:57:07 +00004609void
4610Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004611 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4612 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004613 // Note that variably modified types must be fixed before merging the decl so
4614 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004615 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4616 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004617 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004618 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004619
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004620 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004621 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004622 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004623 TypeSourceInfo *FixedTInfo =
4624 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4625 SizeIsNegative,
4626 Oversized);
4627 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004628 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004629 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004630 } else {
4631 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004632 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004633 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004634 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004635 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004636 Diag(NewTD->getLocation(), diag::err_array_too_large)
4637 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004638 else
Richard Smith162e1c12011-04-15 14:24:37 +00004639 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004640 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004641 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004642 }
4643 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004644}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004645
Richard Smith3e4c6c42011-05-05 21:57:07 +00004646
4647/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4648/// declares a typedef-name, either using the 'typedef' type specifier or via
4649/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4650NamedDecl*
4651Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4652 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004653 // Merge the decl with the existing one if appropriate. If the decl is
4654 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004655 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004656 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004657 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004658 if (!Previous.empty()) {
4659 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004660 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004661 }
4662
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004663 // If this is the C FILE type, notify the AST context.
4664 if (IdentifierInfo *II = NewTD->getIdentifier())
4665 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004666 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004667 if (II->isStr("FILE"))
4668 Context.setFILEDecl(NewTD);
4669 else if (II->isStr("jmp_buf"))
4670 Context.setjmp_bufDecl(NewTD);
4671 else if (II->isStr("sigjmp_buf"))
4672 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004673 else if (II->isStr("ucontext_t"))
4674 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004675 }
4676
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004677 return NewTD;
4678}
4679
Douglas Gregor8f301052009-02-24 19:23:27 +00004680/// \brief Determines whether the given declaration is an out-of-scope
4681/// previous declaration.
4682///
4683/// This routine should be invoked when name lookup has found a
4684/// previous declaration (PrevDecl) that is not in the scope where a
4685/// new declaration by the same name is being introduced. If the new
4686/// declaration occurs in a local scope, previous declarations with
4687/// linkage may still be considered previous declarations (C99
4688/// 6.2.2p4-5, C++ [basic.link]p6).
4689///
4690/// \param PrevDecl the previous declaration found by name
4691/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004692///
Douglas Gregor8f301052009-02-24 19:23:27 +00004693/// \param DC the context in which the new declaration is being
4694/// declared.
4695///
4696/// \returns true if PrevDecl is an out-of-scope previous declaration
4697/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004698static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004699isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4700 ASTContext &Context) {
4701 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004702 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004703
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004704 if (!PrevDecl->hasLinkage())
4705 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004706
David Blaikie4e4d0842012-03-11 07:00:24 +00004707 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004708 // C++ [basic.link]p6:
4709 // If there is a visible declaration of an entity with linkage
4710 // having the same name and type, ignoring entities declared
4711 // outside the innermost enclosing namespace scope, the block
4712 // scope declaration declares that same entity and receives the
4713 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004714 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004715 if (!OuterContext->isFunctionOrMethod())
4716 // This rule only applies to block-scope declarations.
4717 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004718
4719 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4720 if (PrevOuterContext->isRecord())
4721 // We found a member function: ignore it.
4722 return false;
4723
4724 // Find the innermost enclosing namespace for the new and
4725 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004726 OuterContext = OuterContext->getEnclosingNamespaceContext();
4727 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004728
Douglas Gregor757c6002010-08-27 22:55:10 +00004729 // The previous declaration is in a different namespace, so it
4730 // isn't the same function.
4731 if (!OuterContext->Equals(PrevOuterContext))
4732 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004733 }
4734
Douglas Gregor8f301052009-02-24 19:23:27 +00004735 return true;
4736}
4737
John McCallb6217662010-03-15 10:12:16 +00004738static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4739 CXXScopeSpec &SS = D.getCXXScopeSpec();
4740 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004741 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004742}
4743
John McCallf85e1932011-06-15 23:02:42 +00004744bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4745 QualType type = decl->getType();
4746 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4747 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4748 // Various kinds of declaration aren't allowed to be __autoreleasing.
4749 unsigned kind = -1U;
4750 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4751 if (var->hasAttr<BlocksAttr>())
4752 kind = 0; // __block
4753 else if (!var->hasLocalStorage())
4754 kind = 1; // global
4755 } else if (isa<ObjCIvarDecl>(decl)) {
4756 kind = 3; // ivar
4757 } else if (isa<FieldDecl>(decl)) {
4758 kind = 2; // field
4759 }
4760
4761 if (kind != -1U) {
4762 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4763 << kind;
4764 }
4765 } else if (lifetime == Qualifiers::OCL_None) {
4766 // Try to infer lifetime.
4767 if (!type->isObjCLifetimeType())
4768 return false;
4769
4770 lifetime = type->getObjCARCImplicitLifetime();
4771 type = Context.getLifetimeQualifiedType(type, lifetime);
4772 decl->setType(type);
4773 }
4774
4775 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4776 // Thread-local variables cannot have lifetime.
4777 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004778 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004779 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004780 << var->getType();
4781 return true;
4782 }
4783 }
4784
4785 return false;
4786}
4787
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004788static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4789 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004790 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004791 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004792 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4793 ND.dropAttr<WeakAttr>();
4794 }
4795 }
4796 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004797 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004798 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4799 ND.dropAttr<WeakRefAttr>();
4800 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004801 }
Reid Klecknera7225342013-05-20 14:02:37 +00004802
4803 // 'selectany' only applies to externally visible varable declarations.
4804 // It does not apply to functions.
4805 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4806 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4807 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4808 ND.dropAttr<SelectAnyAttr>();
4809 }
4810 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004811}
4812
John McCallb421d922013-04-02 02:48:58 +00004813/// Given that we are within the definition of the given function,
4814/// will that definition behave like C99's 'inline', where the
4815/// definition is discarded except for optimization purposes?
4816static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4817 // Try to avoid calling GetGVALinkageForFunction.
4818
4819 // All cases of this require the 'inline' keyword.
4820 if (!FD->isInlined()) return false;
4821
4822 // This is only possible in C++ with the gnu_inline attribute.
4823 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4824 return false;
4825
4826 // Okay, go ahead and call the relatively-more-expensive function.
4827
4828#ifndef NDEBUG
4829 // AST quite reasonably asserts that it's working on a function
4830 // definition. We don't really have a way to tell it that we're
4831 // currently defining the function, so just lie to it in +Asserts
4832 // builds. This is an awful hack.
4833 FD->setLazyBody(1);
4834#endif
4835
4836 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4837
4838#ifndef NDEBUG
4839 FD->setLazyBody(0);
4840#endif
4841
4842 return isC99Inline;
4843}
4844
Richard Smithaa4bc182013-06-30 09:48:50 +00004845/// Determine whether a variable is extern "C" prior to attaching
4846/// an initializer. We can't just call isExternC() here, because that
4847/// will also compute and cache whether the declaration is externally
4848/// visible, which might change when we attach the initializer.
4849///
4850/// This can only be used if the declaration is known to not be a
4851/// redeclaration of an internal linkage declaration.
4852///
4853/// For instance:
4854///
4855/// auto x = []{};
4856///
4857/// Attaching the initializer here makes this declaration not externally
4858/// visible, because its type has internal linkage.
4859///
4860/// FIXME: This is a hack.
4861template<typename T>
4862static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4863 if (S.getLangOpts().CPlusPlus) {
4864 // In C++, the overloadable attribute negates the effects of extern "C".
4865 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4866 return false;
4867 }
4868 return D->isExternC();
4869}
4870
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004871static bool shouldConsiderLinkage(const VarDecl *VD) {
4872 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4873 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004874 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004875 if (DC->isFileContext())
4876 return true;
4877 if (DC->isRecord())
4878 return false;
4879 llvm_unreachable("Unexpected context");
4880}
4881
4882static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4883 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4884 if (DC->isFileContext() || DC->isFunctionOrMethod())
4885 return true;
4886 if (DC->isRecord())
4887 return false;
4888 llvm_unreachable("Unexpected context");
4889}
4890
Richard Smitha41c97a2013-09-20 01:15:31 +00004891/// Adjust the \c DeclContext for a function or variable that might be a
4892/// function-local external declaration.
4893bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4894 if (!DC->isFunctionOrMethod())
4895 return false;
4896
4897 // If this is a local extern function or variable declared within a function
4898 // template, don't add it into the enclosing namespace scope until it is
4899 // instantiated; it might have a dependent type right now.
4900 if (DC->isDependentContext())
4901 return true;
4902
4903 // C++11 [basic.link]p7:
4904 // When a block scope declaration of an entity with linkage is not found to
4905 // refer to some other declaration, then that entity is a member of the
4906 // innermost enclosing namespace.
4907 //
4908 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4909 // semantically-enclosing namespace, not a lexically-enclosing one.
4910 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4911 DC = DC->getParent();
4912 return true;
4913}
4914
Larisse Voufoef4579c2013-08-06 01:03:05 +00004915NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004916Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004917 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004918 MultiTemplateParamsArg TemplateParamLists,
4919 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004920 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004921 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004922
Douglas Gregor16573fa2010-04-19 22:54:31 +00004923 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004924 VarDecl::StorageClass SC =
4925 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004926
Richard Smitha41c97a2013-09-20 01:15:31 +00004927 DeclContext *OriginalDC = DC;
4928 bool IsLocalExternDecl = SC == SC_Extern &&
4929 adjustContextForLocalExternDecl(DC);
4930
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004931 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004932 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4933 // half array type (unless the cl_khr_fp16 extension is enabled).
4934 if (Context.getBaseElementType(R)->isHalfType()) {
4935 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4936 D.setInvalidType();
4937 }
4938 }
4939
Douglas Gregor16573fa2010-04-19 22:54:31 +00004940 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004941 // mutable can only appear on non-static class members, so it's always
4942 // an error here
4943 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004944 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004945 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004946 }
John McCallb421d922013-04-02 02:48:58 +00004947
Richard Smith9109bf12013-06-17 01:34:01 +00004948 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4949 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4950 D.getDeclSpec().getStorageClassSpecLoc())) {
4951 // In C++11, the 'register' storage class specifier is deprecated.
4952 // Suppress the warning in system macros, it's used in macros in some
4953 // popular C system headers, such as in glibc's htonl() macro.
4954 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4955 diag::warn_deprecated_register)
4956 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4957 }
4958
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004959 IdentifierInfo *II = Name.getAsIdentifierInfo();
4960 if (!II) {
4961 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004962 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004963 return 0;
4964 }
4965
Richard Smithc7f81162013-03-18 22:52:47 +00004966 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004967
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004968 if (!DC->isRecord() && S->getFnParent() == 0) {
4969 // C99 6.9p2: The storage-class specifiers auto and register shall not
4970 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00004971 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004972 // If this is a register variable with an asm label specified, then this
4973 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00004974 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004975 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4976 else
4977 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004978 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004979 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004980 }
Richard Smith9109bf12013-06-17 01:34:01 +00004981
David Blaikie4e4d0842012-03-11 07:00:24 +00004982 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004983 // Set up the special work-group-local storage class for variables in the
4984 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00004985 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004986 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00004987 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00004988
Guy Benyei21f18c42013-02-07 10:55:47 +00004989 // OpenCL v1.2 s6.9.b p4:
4990 // The sampler type cannot be used with the __local and __global address
4991 // space qualifiers.
4992 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
4993 R.getAddressSpace() == LangAS::opencl_global)) {
4994 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
4995 }
4996
Guy Benyeie6b9d802013-01-20 12:31:11 +00004997 // OpenCL 1.2 spec, p6.9 r:
4998 // The event type cannot be used to declare a program scope variable.
4999 // The event type cannot be used with the __local, __constant and __global
5000 // address space qualifiers.
5001 if (R->isEventT()) {
5002 if (S->getParent() == 0) {
5003 Diag(D.getLocStart(), diag::err_event_t_global_var);
5004 D.setInvalidType();
5005 }
5006
5007 if (R.getAddressSpace()) {
5008 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5009 D.setInvalidType();
5010 }
5011 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005012 }
5013
Larisse Voufoef4579c2013-08-06 01:03:05 +00005014 bool IsExplicitSpecialization = false;
5015 bool IsVariableTemplateSpecialization = false;
5016 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00005017 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005018 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00005019 VarDecl *NewVD = 0;
5020 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00005021 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005022 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005023 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005024 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005025
5026 if (D.isInvalidType())
5027 NewVD->setInvalidDecl();
5028 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00005029 bool Invalid = false;
5030
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005031 if (DC->isRecord() && !CurContext->isRecord()) {
5032 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00005033 switch (SC) {
5034 case SC_None:
5035 break;
5036 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005037 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5038 diag::err_static_out_of_line)
5039 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00005040 break;
5041 case SC_Auto:
5042 case SC_Register:
5043 case SC_Extern:
5044 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5045 // to names of variables declared in a block or to function parameters.
5046 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5047 // of class members
5048
5049 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5050 diag::err_storage_class_for_static_member)
5051 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5052 break;
5053 case SC_PrivateExtern:
5054 llvm_unreachable("C storage class in c++!");
5055 case SC_OpenCLWorkGroupLocal:
5056 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00005057 }
Larisse Voufo06935f32013-08-06 03:43:07 +00005058 }
5059
Richard Smithb9c64d82012-02-16 20:41:22 +00005060 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005061 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5062 if (RD->isLocalClass())
5063 Diag(D.getIdentifierLoc(),
5064 diag::err_static_data_member_not_allowed_in_local_class)
5065 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005066
Richard Smithb9c64d82012-02-16 20:41:22 +00005067 // C++98 [class.union]p1: If a union contains a static data member,
5068 // the program is ill-formed. C++11 drops this restriction.
5069 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005070 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005071 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005072 ? diag::warn_cxx98_compat_static_data_member_in_union
5073 : diag::ext_static_data_member_in_union) << Name;
5074 // We conservatively disallow static data members in anonymous structs.
5075 else if (!RD->getDeclName())
5076 Diag(D.getIdentifierLoc(),
5077 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005078 << Name << RD->isUnion();
5079 }
5080 }
5081
Larisse Voufoef4579c2013-08-06 01:03:05 +00005082 NamedDecl *PrevDecl = 0;
5083 if (Previous.begin() != Previous.end())
5084 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5085 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5086
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005087 // Match up the template parameter lists with the scope specifier, then
5088 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005089 TemplateParameterList *TemplateParams =
5090 MatchTemplateParametersToScopeSpecifier(
5091 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5092 D.getCXXScopeSpec(), TemplateParamLists,
5093 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005094 if (TemplateParams) {
5095 if (!TemplateParams->size() &&
5096 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005097 // There is an extraneous 'template<>' for this variable. Complain
5098 // about it, but allow the declaration of the variable.
5099 Diag(TemplateParams->getTemplateLoc(),
5100 diag::err_template_variable_noparams)
5101 << II
5102 << SourceRange(TemplateParams->getTemplateLoc(),
5103 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005104 } else {
5105 // Only C++1y supports variable templates (N3651).
5106 Diag(D.getIdentifierLoc(),
5107 getLangOpts().CPlusPlus1y
5108 ? diag::warn_cxx11_compat_variable_template
5109 : diag::ext_variable_template);
5110
5111 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5112 // This is an explicit specialization or a partial specialization.
5113 // Check that we can declare a specialization here
5114
5115 IsVariableTemplateSpecialization = true;
5116 IsPartialSpecialization = TemplateParams->size() > 0;
5117
5118 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005119 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005120 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005121
5122 // Check that we can declare a template here.
5123 if (CheckTemplateDeclScope(S, TemplateParams))
5124 return 0;
5125
5126 // If there is a previous declaration with the same name, check
5127 // whether this is a valid redeclaration.
5128 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5129 PrevDecl = PrevVarTemplate = 0;
5130
5131 if (PrevVarTemplate) {
5132 // Ensure that the template parameter lists are compatible.
5133 if (!TemplateParameterListsAreEqual(
5134 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5135 /*Complain=*/true, TPL_TemplateMatch))
5136 return 0;
5137 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5138 // Maybe we will complain about the shadowed template parameter.
5139 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5140
5141 // Just pretend that we didn't see the previous declaration.
5142 PrevDecl = 0;
5143 } else if (PrevDecl) {
5144 // C++ [temp]p5:
5145 // ... a template name declared in namespace scope or in class
5146 // scope shall be unique in that scope.
5147 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5148 << Name;
5149 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5150 return 0;
5151 }
5152
5153 // Check the template parameter list of this declaration, possibly
5154 // merging in the template parameter list from the previous variable
5155 // template declaration.
5156 if (CheckTemplateParameterList(
5157 TemplateParams,
5158 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5159 : 0,
5160 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5161 DC->isDependentContext())
5162 ? TPC_ClassTemplateMember
5163 : TPC_VarTemplate))
5164 Invalid = true;
5165
5166 if (D.getCXXScopeSpec().isSet()) {
5167 // If the name of the template was qualified, we must be defining
5168 // the template out-of-line.
5169 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5170 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005171 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5172 << Name << DC << /*IsDefinition*/true
5173 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005174 Invalid = true;
5175 }
5176 }
5177 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005178 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005179 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5180 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5181
5182 // We have encountered something that the user meant to be a
5183 // specialization (because it has explicitly-specified template
5184 // arguments) but that was not introduced with a "template<>" (or had
5185 // too few of them).
5186 // FIXME: Differentiate between attempts for explicit instantiations
5187 // (starting with "template") and the rest.
5188 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5189 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5190 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5191 "template<> ");
5192 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005193 }
Mike Stump1eb44332009-09-09 15:08:12 +00005194
Larisse Voufoef4579c2013-08-06 01:03:05 +00005195 if (IsVariableTemplateSpecialization) {
5196 if (!PrevVarTemplate) {
5197 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5198 << IsPartialSpecialization;
5199 return 0;
5200 }
5201
5202 SourceLocation TemplateKWLoc =
5203 TemplateParamLists.size() > 0
5204 ? TemplateParamLists[0]->getTemplateLoc()
5205 : SourceLocation();
5206 DeclResult Res = ActOnVarTemplateSpecialization(
5207 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5208 IsPartialSpecialization);
5209 if (Res.isInvalid())
5210 return 0;
5211 NewVD = cast<VarDecl>(Res.get());
5212 AddToScope = false;
5213 } else
5214 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5215 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005216
Larisse Voufo567f9172013-08-22 00:59:14 +00005217 // If this is supposed to be a variable template, create it as such.
5218 if (IsVariableTemplate) {
5219 NewTemplate =
5220 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5221 TemplateParams, NewVD, PrevVarTemplate);
5222 NewVD->setDescribedVarTemplate(NewTemplate);
5223 }
5224
Richard Smith483b9f32011-02-21 20:05:19 +00005225 // If this decl has an auto type in need of deduction, make a note of the
5226 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005227 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005228 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005229
Larisse Voufo567f9172013-08-22 00:59:14 +00005230 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005231 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005232 if (NewTemplate)
5233 NewTemplate->setInvalidDecl();
5234 }
Mike Stump1eb44332009-09-09 15:08:12 +00005235
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005236 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005237
Larisse Voufoef4579c2013-08-06 01:03:05 +00005238 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5239 if (TemplateParams && TemplateParamLists.size() > 1 &&
5240 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5241 NewVD->setTemplateParameterListsInfo(
5242 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5243 } else if (IsVariableTemplateSpecialization ||
5244 (!TemplateParams && TemplateParamLists.size() > 0 &&
5245 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005246 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005247 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005248 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005249 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005250
Richard Smith7ca48502012-02-13 22:16:19 +00005251 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005252 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005253 }
5254
Douglas Gregore3895852011-09-12 18:37:38 +00005255 // Set the lexical context. If the declarator has a C++ scope specifier, the
5256 // lexical context will be different from the semantic context.
5257 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005258 if (NewTemplate)
5259 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005260
Richard Smitha41c97a2013-09-20 01:15:31 +00005261 if (IsLocalExternDecl)
5262 NewVD->setLocalExternDecl();
5263
Richard Smithec642442013-04-12 22:46:28 +00005264 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005265 if (NewVD->hasLocalStorage()) {
5266 // C++11 [dcl.stc]p4:
5267 // When thread_local is applied to a variable of block scope the
5268 // storage-class-specifier static is implied if it does not appear
5269 // explicitly.
5270 // Core issue: 'static' is not implied if the variable is declared
5271 // 'extern'.
5272 if (SCSpec == DeclSpec::SCS_unspecified &&
5273 TSCS == DeclSpec::TSCS_thread_local &&
5274 DC->isFunctionOrMethod())
5275 NewVD->setTSCSpec(TSCS);
5276 else
5277 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5278 diag::err_thread_non_global)
5279 << DeclSpec::getSpecifierName(TSCS);
5280 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005281 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5282 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005283 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005284 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005285 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005286
John McCallb421d922013-04-02 02:48:58 +00005287 // C99 6.7.4p3
5288 // An inline definition of a function with external linkage shall
5289 // not contain a definition of a modifiable object with static or
5290 // thread storage duration...
5291 // We only apply this when the function is required to be defined
5292 // elsewhere, i.e. when the function is not 'extern inline'. Note
5293 // that a local variable with thread storage duration still has to
5294 // be marked 'static'. Also note that it's possible to get these
5295 // semantics in C++ using __attribute__((gnu_inline)).
5296 if (SC == SC_Static && S->getFnParent() != 0 &&
5297 !NewVD->getType().isConstQualified()) {
5298 FunctionDecl *CurFD = getCurFunctionDecl();
5299 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5300 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5301 diag::warn_static_local_in_extern_inline);
5302 MaybeSuggestAddingStaticToDecl(CurFD);
5303 }
5304 }
5305
Douglas Gregord023aec2011-09-09 20:53:38 +00005306 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005307 if (IsVariableTemplateSpecialization)
5308 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5309 << (IsPartialSpecialization ? 1 : 0)
5310 << FixItHint::CreateRemoval(
5311 D.getDeclSpec().getModulePrivateSpecLoc());
5312 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005313 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5314 << 2
5315 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005316 else if (NewVD->hasLocalStorage())
5317 Diag(NewVD->getLocation(), diag::err_module_private_local)
5318 << 0 << NewVD->getDeclName()
5319 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5320 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005321 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005322 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005323 if (NewTemplate)
5324 NewTemplate->setModulePrivate();
5325 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005326 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005327
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005328 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005329 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005330
Richard Smithbe507b62013-02-01 08:12:08 +00005331 if (NewVD->hasAttrs())
5332 CheckAlignasUnderalignment(NewVD);
5333
Peter Collingbournec0c00662012-08-28 20:37:50 +00005334 if (getLangOpts().CUDA) {
5335 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5336 // storage [duration]."
5337 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005338 (NewVD->hasAttr<CUDASharedAttr>() ||
5339 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005340 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005341 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005342 }
5343
John McCallf85e1932011-06-15 23:02:42 +00005344 // In auto-retain/release, infer strong retension for variables of
5345 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005346 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005347 NewVD->setInvalidDecl();
5348
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005349 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005350 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005351 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005352 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005353 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005354 if (S->getFnParent() != 0) {
5355 switch (SC) {
5356 case SC_None:
5357 case SC_Auto:
5358 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5359 break;
5360 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005361 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005362 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5363 break;
5364 case SC_Static:
5365 case SC_Extern:
5366 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005367 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005368 break;
5369 }
5370 }
5371
5372 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005373 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005374 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5375 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5376 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5377 if (I != ExtnameUndeclaredIdentifiers.end()) {
5378 NewVD->addAttr(I->second);
5379 ExtnameUndeclaredIdentifiers.erase(I);
5380 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005381 }
5382
John McCall8472af42010-03-16 21:48:18 +00005383 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005384 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005385 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005386
John McCall68263142009-11-18 22:49:29 +00005387 // Don't consider existing declarations that are in a different
5388 // scope and are out-of-semantic-context declarations (if the new
5389 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005390 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005391 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005392 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5393
Richard Smithdd9459f2013-08-13 18:18:50 +00005394 // Check whether the previous declaration is in the same block scope. This
5395 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5396 if (getLangOpts().CPlusPlus &&
5397 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5398 NewVD->setPreviousDeclInSameBlockScope(
5399 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005400 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005401
David Blaikie4e4d0842012-03-11 07:00:24 +00005402 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005403 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5404 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005405 // Merge the decl with the existing one if appropriate.
5406 if (!Previous.empty()) {
5407 if (Previous.isSingleResult() &&
5408 isa<FieldDecl>(Previous.getFoundDecl()) &&
5409 D.getCXXScopeSpec().isSet()) {
5410 // The user tried to define a non-static data member
5411 // out-of-line (C++ [dcl.meaning]p1).
5412 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5413 << D.getCXXScopeSpec().getRange();
5414 Previous.clear();
5415 NewVD->setInvalidDecl();
5416 }
5417 } else if (D.getCXXScopeSpec().isSet()) {
5418 // No previous declaration in the qualifying scope.
5419 Diag(D.getIdentifierLoc(), diag::err_no_member)
5420 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005421 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005422 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005423 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005424
Larisse Voufoef4579c2013-08-06 01:03:05 +00005425 if (!IsVariableTemplateSpecialization) {
5426 if (PrevVarTemplate) {
5427 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5428 LookupOrdinaryName, ForRedeclaration);
5429 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005430 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005431 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005432 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005433 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005434
5435 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005436 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005437 CheckMemberSpecialization(NewVD, Previous))
5438 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005439 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005440
Rafael Espindola65611bf2013-03-02 21:41:48 +00005441 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005442 checkAttributesAfterMerging(*this, *NewVD);
5443
Richard Smithaa4bc182013-06-30 09:48:50 +00005444 // If this is the first declaration of an extern C variable, update
5445 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00005446 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00005447 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005448 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005449
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005450 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005451 Decl *ManglingContextDecl;
5452 if (MangleNumberingContext *MCtx =
5453 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5454 ManglingContextDecl)) {
5455 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5456 }
5457 }
5458
Larisse Voufoef4579c2013-08-06 01:03:05 +00005459 // If we are providing an explicit specialization of a static variable
5460 // template, make a note of that.
5461 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005462 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005463
Larisse Voufo567f9172013-08-22 00:59:14 +00005464 if (NewTemplate) {
5465 ActOnDocumentableDecl(NewTemplate);
5466 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005467 }
5468
Larisse Voufo567f9172013-08-22 00:59:14 +00005469 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005470}
5471
John McCall053f4bd2010-03-22 09:20:08 +00005472/// \brief Diagnose variable or built-in function shadowing. Implements
5473/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005474///
John McCall053f4bd2010-03-22 09:20:08 +00005475/// This method is called whenever a VarDecl is added to a "useful"
5476/// scope.
John McCall8472af42010-03-16 21:48:18 +00005477///
John McCalla369a952010-03-20 04:12:52 +00005478/// \param S the scope in which the shadowing name is being declared
5479/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005480///
John McCall053f4bd2010-03-22 09:20:08 +00005481void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005482 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005483 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005484 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005485 return;
5486
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005487 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005488 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005489 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005490
5491 DeclContext *NewDC = D->getDeclContext();
5492
John McCalla369a952010-03-20 04:12:52 +00005493 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005494 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005495 return;
John McCall8472af42010-03-16 21:48:18 +00005496
John McCall8472af42010-03-16 21:48:18 +00005497 NamedDecl* ShadowedDecl = R.getFoundDecl();
5498 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5499 return;
5500
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005501 // Fields are not shadowed by variables in C++ static methods.
5502 if (isa<FieldDecl>(ShadowedDecl))
5503 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5504 if (MD->isStatic())
5505 return;
5506
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005507 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5508 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005509 // For shadowing external vars, make sure that we point to the global
5510 // declaration, not a locally scoped extern declaration.
5511 for (VarDecl::redecl_iterator
5512 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5513 I != E; ++I)
5514 if (I->isFileVarDecl()) {
5515 ShadowedDecl = *I;
5516 break;
5517 }
5518 }
5519
5520 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5521
John McCalla369a952010-03-20 04:12:52 +00005522 // Only warn about certain kinds of shadowing for class members.
5523 if (NewDC && NewDC->isRecord()) {
5524 // In particular, don't warn about shadowing non-class members.
5525 if (!OldDC->isRecord())
5526 return;
5527
5528 // TODO: should we warn about static data members shadowing
5529 // static data members from base classes?
5530
5531 // TODO: don't diagnose for inaccessible shadowed members.
5532 // This is hard to do perfectly because we might friend the
5533 // shadowing context, but that's just a false negative.
5534 }
5535
5536 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005537 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005538 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005539 if (isa<FieldDecl>(ShadowedDecl))
5540 Kind = 3; // field
5541 else
5542 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005543 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005544 Kind = 1; // global
5545 else
5546 Kind = 0; // local
5547
John McCalla369a952010-03-20 04:12:52 +00005548 DeclarationName Name = R.getLookupName();
5549
John McCall8472af42010-03-16 21:48:18 +00005550 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005551 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005552 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5553}
5554
John McCall053f4bd2010-03-22 09:20:08 +00005555/// \brief Check -Wshadow without the advantage of a previous lookup.
5556void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005557 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005558 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005559 return;
5560
John McCall053f4bd2010-03-22 09:20:08 +00005561 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5562 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5563 LookupName(R, S);
5564 CheckShadow(S, D, R);
5565}
5566
Richard Smithaa4bc182013-06-30 09:48:50 +00005567/// Check for conflict between this global or extern "C" declaration and
5568/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005569template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005570static bool checkGlobalOrExternCConflict(
5571 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5572 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5573 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005574
Richard Smithaa4bc182013-06-30 09:48:50 +00005575 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5576 // The common case: this global doesn't conflict with any extern "C"
5577 // declaration.
5578 return false;
5579 }
5580
5581 if (Prev) {
5582 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5583 // Both the old and new declarations have C language linkage. This is a
5584 // redeclaration.
5585 Previous.clear();
5586 Previous.addDecl(Prev);
5587 return true;
5588 }
5589
5590 // This is a global, non-extern "C" declaration, and there is a previous
5591 // non-global extern "C" declaration. Diagnose if this is a variable
5592 // declaration.
5593 if (!isa<VarDecl>(ND))
5594 return false;
5595 } else {
5596 // The declaration is extern "C". Check for any declaration in the
5597 // translation unit which might conflict.
5598 if (IsGlobal) {
5599 // We have already performed the lookup into the translation unit.
5600 IsGlobal = false;
5601 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5602 I != E; ++I) {
5603 if (isa<VarDecl>(*I)) {
5604 Prev = *I;
5605 break;
5606 }
5607 }
5608 } else {
5609 DeclContext::lookup_result R =
5610 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5611 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5612 I != E; ++I) {
5613 if (isa<VarDecl>(*I)) {
5614 Prev = *I;
5615 break;
5616 }
5617 // FIXME: If we have any other entity with this name in global scope,
5618 // the declaration is ill-formed, but that is a defect: it breaks the
5619 // 'stat' hack, for instance. Only variables can have mangled name
5620 // clashes with extern "C" declarations, so only they deserve a
5621 // diagnostic.
5622 }
5623 }
5624
5625 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005626 return false;
5627 }
5628
Richard Smithaa4bc182013-06-30 09:48:50 +00005629 // Use the first declaration's location to ensure we point at something which
5630 // is lexically inside an extern "C" linkage-spec.
5631 assert(Prev && "should have found a previous declaration to diagnose");
5632 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindolabc650912013-10-17 15:37:26 +00005633 Prev = FD->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005634 else
Rafael Espindolabc650912013-10-17 15:37:26 +00005635 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005636
5637 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5638 << IsGlobal << ND;
5639 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5640 << IsGlobal;
5641 return false;
5642}
5643
5644/// Apply special rules for handling extern "C" declarations. Returns \c true
5645/// if we have found that this is a redeclaration of some prior entity.
5646///
5647/// Per C++ [dcl.link]p6:
5648/// Two declarations [for a function or variable] with C language linkage
5649/// with the same name that appear in different scopes refer to the same
5650/// [entity]. An entity with C language linkage shall not be declared with
5651/// the same name as an entity in global scope.
5652template<typename T>
5653static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5654 LookupResult &Previous) {
5655 if (!S.getLangOpts().CPlusPlus) {
5656 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005657 // variable declared in function scope. We don't need this in C++, because
5658 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005659 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5660 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5661 Previous.clear();
5662 Previous.addDecl(Prev);
5663 return true;
5664 }
5665 }
5666 return false;
5667 }
5668
5669 // A declaration in the translation unit can conflict with an extern "C"
5670 // declaration.
5671 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5672 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5673
5674 // An extern "C" declaration can conflict with a declaration in the
5675 // translation unit or can be a redeclaration of an extern "C" declaration
5676 // in another scope.
5677 if (isIncompleteDeclExternC(S,ND))
5678 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5679
5680 // Neither global nor extern "C": nothing to do.
5681 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005682}
5683
Richard Smithdc7a4f52013-04-30 13:56:41 +00005684void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005685 // If the decl is already known invalid, don't check it.
5686 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005687 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005688
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005689 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5690 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005691
Richard Smithdc7a4f52013-04-30 13:56:41 +00005692 // Defer checking an 'auto' type until its initializer is attached.
5693 if (T->isUndeducedType())
5694 return;
5695
John McCallc12c5bb2010-05-15 11:32:37 +00005696 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005697 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5698 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005699 T = Context.getObjCObjectPointerType(T);
5700 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005701 }
Mike Stump1eb44332009-09-09 15:08:12 +00005702
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005703 // Emit an error if an address space was applied to decl with local storage.
5704 // This includes arrays of objects with address space qualifiers, but not
5705 // automatic variables that point to other address spaces.
5706 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005707 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005708 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005709 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005710 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005711 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005712
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005713 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5714 // __constant address space.
5715 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5716 && T.getAddressSpace() != LangAS::opencl_constant
5717 && !T->isSamplerT()){
5718 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5719 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005720 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005721 }
5722
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005723 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5724 // scope.
5725 if ((getLangOpts().OpenCLVersion >= 120)
5726 && NewVD->isStaticLocal()) {
5727 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5728 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005729 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005730 }
5731
Mike Stumpf33651c2009-04-14 00:57:29 +00005732 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005733 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005734 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005735 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005736 else {
5737 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005738 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005739 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005740 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005741
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005742 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005743 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005744 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005745 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005746
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005747 if ((isVM && NewVD->hasLinkage()) ||
5748 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005749 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005750 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005751 TypeSourceInfo *FixedTInfo =
5752 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5753 SizeIsNegative, Oversized);
5754 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005755 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005756 // FIXME: This won't give the correct result for
5757 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005758 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005759
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005760 if (NewVD->isFileVarDecl())
5761 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005762 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005763 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005764 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005765 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005766 else
5767 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005768 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005769 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005770 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005771 }
5772
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005773 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005774 if (NewVD->isFileVarDecl())
5775 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5776 else
5777 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005778 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005779 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005780 }
Mike Stump1eb44332009-09-09 15:08:12 +00005781
Chris Lattnereaaebc72009-04-25 08:06:05 +00005782 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005783 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005784 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005785 }
5786
David Majnemeraa715672013-05-29 00:56:45 +00005787 if (T->isVoidType()) {
5788 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5789 // of objects and functions.
5790 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5791 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5792 << T;
5793 NewVD->setInvalidDecl();
5794 return;
5795 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005796 }
5797
5798 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5799 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5800 NewVD->setInvalidDecl();
5801 return;
5802 }
5803
5804 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5805 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5806 NewVD->setInvalidDecl();
5807 return;
5808 }
5809
5810 if (NewVD->isConstexpr() && !T->isDependentType() &&
5811 RequireLiteralType(NewVD->getLocation(), T,
5812 diag::err_constexpr_var_non_literal)) {
5813 // Can't perform this check until the type is deduced.
5814 NewVD->setInvalidDecl();
5815 return;
5816 }
5817}
5818
5819/// \brief Perform semantic checking on a newly-created variable
5820/// declaration.
5821///
5822/// This routine performs all of the type-checking required for a
5823/// variable declaration once it has been built. It is used both to
5824/// check variables after they have been parsed and their declarators
5825/// have been translated into a declaration, and to check variables
5826/// that have been instantiated from a template.
5827///
5828/// Sets NewVD->isInvalidDecl() if an error was encountered.
5829///
5830/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005831bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005832 CheckVariableDeclarationType(NewVD);
5833
5834 // If the decl is already known invalid, don't check it.
5835 if (NewVD->isInvalidDecl())
5836 return false;
5837
John McCall5b8740f2013-04-01 18:34:28 +00005838 // If we did not find anything by this name, look for a non-visible
5839 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005840 if (Previous.empty() &&
5841 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005842 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005843
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005844 // Filter out any non-conflicting previous declarations.
5845 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5846
John McCall68263142009-11-18 22:49:29 +00005847 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005848 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005849 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005850 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005851 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005852}
5853
Douglas Gregora8f32e02009-10-06 17:59:45 +00005854/// \brief Data used with FindOverriddenMethod
5855struct FindOverriddenMethodData {
5856 Sema *S;
5857 CXXMethodDecl *Method;
5858};
5859
5860/// \brief Member lookup function that determines whether a given C++
5861/// method overrides a method in a base class, to be used with
5862/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005863static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005864 CXXBasePath &Path,
5865 void *UserData) {
5866 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005867
Douglas Gregora8f32e02009-10-06 17:59:45 +00005868 FindOverriddenMethodData *Data
5869 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005870
5871 DeclarationName Name = Data->Method->getDeclName();
5872
5873 // FIXME: Do we care about other names here too?
5874 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005875 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005876 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5877 CanQualType CT = Data->S->Context.getCanonicalType(T);
5878
Anders Carlsson1a689722009-11-27 01:26:58 +00005879 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005880 }
5881
5882 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005883 !Path.Decls.empty();
5884 Path.Decls = Path.Decls.slice(1)) {
5885 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005886 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5887 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005888 return true;
5889 }
5890 }
5891
5892 return false;
5893}
5894
David Blaikie5708c182012-10-17 00:47:58 +00005895namespace {
5896 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5897}
5898/// \brief Report an error regarding overriding, along with any relevant
5899/// overriden methods.
5900///
5901/// \param DiagID the primary error to report.
5902/// \param MD the overriding method.
5903/// \param OEK which overrides to include as notes.
5904static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5905 OverrideErrorKind OEK = OEK_All) {
5906 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5907 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5908 E = MD->end_overridden_methods();
5909 I != E; ++I) {
5910 // This check (& the OEK parameter) could be replaced by a predicate, but
5911 // without lambdas that would be overkill. This is still nicer than writing
5912 // out the diag loop 3 times.
5913 if ((OEK == OEK_All) ||
5914 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5915 (OEK == OEK_Deleted && (*I)->isDeleted()))
5916 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5917 }
5918}
5919
Sebastian Redla165da02009-11-18 21:51:29 +00005920/// AddOverriddenMethods - See if a method overrides any in the base classes,
5921/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005922bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005923 // Look for virtual methods in base classes that this method might override.
5924 CXXBasePaths Paths;
5925 FindOverriddenMethodData Data;
5926 Data.Method = MD;
5927 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005928 bool hasDeletedOverridenMethods = false;
5929 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005930 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005931 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5932 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5933 E = Paths.found_decls_end(); I != E; ++I) {
5934 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005935 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005936 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005937 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005938 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005939 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005940 hasDeletedOverridenMethods |= OldMD->isDeleted();
5941 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005942 AddedAny = true;
5943 }
Sebastian Redla165da02009-11-18 21:51:29 +00005944 }
5945 }
5946 }
David Blaikie5708c182012-10-17 00:47:58 +00005947
5948 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5949 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5950 }
5951 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5952 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5953 }
5954
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005955 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005956}
5957
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005958namespace {
5959 // Struct for holding all of the extra arguments needed by
5960 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5961 struct ActOnFDArgs {
5962 Scope *S;
5963 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005964 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005965 bool AddToScope;
5966 };
5967}
5968
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005969namespace {
5970
5971// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005972// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005973class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5974 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005975 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5976 CXXRecordDecl *Parent)
5977 : Context(Context), OriginalFD(TypoFD),
5978 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005979
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005980 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005981 if (candidate.getEditDistance() == 0)
5982 return false;
5983
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005984 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005985 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5986 CDeclEnd = candidate.end();
5987 CDecl != CDeclEnd; ++CDecl) {
5988 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5989
5990 if (FD && !FD->hasBody() &&
5991 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5992 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5993 CXXRecordDecl *Parent = MD->getParent();
5994 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5995 return true;
5996 } else if (!ExpectedParent) {
5997 return true;
5998 }
5999 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006000 }
6001
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006002 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006003 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006004
6005 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006006 ASTContext &Context;
6007 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006008 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006009};
6010
6011}
6012
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006013/// \brief Generate diagnostics for an invalid function redeclaration.
6014///
6015/// This routine handles generating the diagnostic messages for an invalid
6016/// function redeclaration, including finding possible similar declarations
6017/// or performing typo correction if there are no previous declarations with
6018/// the same name.
6019///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006020/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006021/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00006022static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006023 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00006024 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006025 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006026 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006027 SmallVector<unsigned, 1> MismatchedParams;
6028 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006029 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00006030 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00006031 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6032 : diag::err_member_decl_does_not_match;
6033 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6034 IsLocalFriend ? Sema::LookupLocalFriendName
6035 : Sema::LookupOrdinaryName,
6036 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006037
6038 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00006039 if (IsLocalFriend)
6040 SemaRef.LookupName(Prev, S);
6041 else
6042 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00006043 assert(!Prev.isAmbiguous() &&
6044 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006045 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006046 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6047 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006048 if (!Prev.empty()) {
6049 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6050 Func != FuncEnd; ++Func) {
6051 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006052 if (FD &&
6053 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006054 // Add 1 to the index so that 0 can mean the mismatch didn't
6055 // involve a parameter
6056 unsigned ParamNum =
6057 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6058 NearMatches.push_back(std::make_pair(FD, ParamNum));
6059 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006060 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006061 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006062 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006063 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6064 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6065 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006066 // Set up everything for the call to ActOnFunctionDeclarator
6067 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6068 ExtraArgs.D.getIdentifierLoc());
6069 Previous.clear();
6070 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006071 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6072 CDeclEnd = Correction.end();
6073 CDecl != CDeclEnd; ++CDecl) {
6074 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006075 if (FD && !FD->hasBody() &&
6076 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006077 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006078 }
6079 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006080 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006081
6082 NamedDecl *Result;
6083 // Retry building the function declaration with the new previous
6084 // declarations, and with errors suppressed.
6085 {
6086 // Trap errors.
6087 Sema::SFINAETrap Trap(SemaRef);
6088
6089 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6090 // pieces need to verify the typo-corrected C++ declaration and hopefully
6091 // eliminate the need for the parameter pack ExtraArgs.
6092 Result = SemaRef.ActOnFunctionDeclarator(
6093 ExtraArgs.S, ExtraArgs.D,
6094 Correction.getCorrectionDecl()->getDeclContext(),
6095 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6096 ExtraArgs.AddToScope);
6097
6098 if (Trap.hasErrorOccurred())
6099 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006100 }
Richard Smith2d670972013-08-17 00:46:16 +00006101
6102 if (Result) {
6103 // Determine which correction we picked.
6104 Decl *Canonical = Result->getCanonicalDecl();
6105 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6106 I != E; ++I)
6107 if ((*I)->getCanonicalDecl() == Canonical)
6108 Correction.setCorrectionDecl(*I);
6109
6110 SemaRef.diagnoseTypo(
6111 Correction,
6112 SemaRef.PDiag(IsLocalFriend
6113 ? diag::err_no_matching_local_friend_suggest
6114 : diag::err_member_decl_does_not_match_suggest)
6115 << Name << NewDC << IsDefinition);
6116 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006117 }
Richard Smith2d670972013-08-17 00:46:16 +00006118
6119 // Pretend the typo correction never occurred
6120 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6121 ExtraArgs.D.getIdentifierLoc());
6122 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6123 Previous.clear();
6124 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006125 }
6126
Richard Smith2d670972013-08-17 00:46:16 +00006127 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6128 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006129
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006130 bool NewFDisConst = false;
6131 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006132 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006133
Craig Topper8bc99dd2013-07-04 03:15:42 +00006134 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006135 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6136 NearMatch != NearMatchEnd; ++NearMatch) {
6137 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006138 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6139 bool FDisConst = MD && MD->isConst();
6140 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006141
Richard Smitha41c97a2013-09-20 01:15:31 +00006142 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006143 if (unsigned Idx = NearMatch->second) {
6144 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006145 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6146 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006147 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6148 : diag::note_local_decl_close_param_match)
6149 << Idx << FDParam->getType()
6150 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006151 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006152 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006153 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006154 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006155 SemaRef.Diag(FD->getLocation(),
6156 IsMember ? diag::note_member_def_close_match
6157 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006158 }
Richard Smith2d670972013-08-17 00:46:16 +00006159 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006160}
6161
David Blaikied662a792011-10-19 22:56:21 +00006162static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6163 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006164 switch (D.getDeclSpec().getStorageClassSpec()) {
6165 default: llvm_unreachable("Unknown storage class!");
6166 case DeclSpec::SCS_auto:
6167 case DeclSpec::SCS_register:
6168 case DeclSpec::SCS_mutable:
6169 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6170 diag::err_typecheck_sclass_func);
6171 D.setInvalidType();
6172 break;
6173 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006174 case DeclSpec::SCS_extern:
6175 if (D.getDeclSpec().isExternInLinkageSpec())
6176 return SC_None;
6177 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006178 case DeclSpec::SCS_static: {
6179 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6180 // C99 6.7.1p5:
6181 // The declaration of an identifier for a function that has
6182 // block scope shall have no explicit storage-class specifier
6183 // other than extern
6184 // See also (C++ [dcl.stc]p4).
6185 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6186 diag::err_static_block_func);
6187 break;
6188 } else
6189 return SC_Static;
6190 }
6191 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6192 }
6193
6194 // No explicit storage class has already been returned
6195 return SC_None;
6196}
6197
6198static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6199 DeclContext *DC, QualType &R,
6200 TypeSourceInfo *TInfo,
6201 FunctionDecl::StorageClass SC,
6202 bool &IsVirtualOkay) {
6203 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6204 DeclarationName Name = NameInfo.getName();
6205
6206 FunctionDecl *NewFD = 0;
6207 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006208
David Blaikie4e4d0842012-03-11 07:00:24 +00006209 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006210 // Determine whether the function was written with a
6211 // prototype. This true when:
6212 // - there is a prototype in the declarator, or
6213 // - the type R of the function is some kind of typedef or other reference
6214 // to a type name (which eventually refers to a function type).
6215 bool HasPrototype =
6216 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6217 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6218
David Blaikied662a792011-10-19 22:56:21 +00006219 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006220 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006221 TInfo, SC, isInline,
6222 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006223 if (D.isInvalidType())
6224 NewFD->setInvalidDecl();
6225
6226 // Set the lexical context.
6227 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6228
6229 return NewFD;
6230 }
6231
6232 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6233 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6234
6235 // Check that the return type is not an abstract class type.
6236 // For record types, this is done by the AbstractClassUsageDiagnoser once
6237 // the class has been completely parsed.
6238 if (!DC->isRecord() &&
6239 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6240 R->getAs<FunctionType>()->getResultType(),
6241 diag::err_abstract_type_in_decl,
6242 SemaRef.AbstractReturnType))
6243 D.setInvalidType();
6244
6245 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6246 // This is a C++ constructor declaration.
6247 assert(DC->isRecord() &&
6248 "Constructors can only be declared in a member context");
6249
6250 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6251 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006252 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006253 R, TInfo, isExplicit, isInline,
6254 /*isImplicitlyDeclared=*/false,
6255 isConstexpr);
6256
6257 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6258 // This is a C++ destructor declaration.
6259 if (DC->isRecord()) {
6260 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6261 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6262 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6263 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006264 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006265 NameInfo, R, TInfo, isInline,
6266 /*isImplicitlyDeclared=*/false);
6267
6268 // If the class is complete, then we now create the implicit exception
6269 // specification. If the class is incomplete or dependent, we can't do
6270 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006271 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006272 Record->getDefinition() && !Record->isBeingDefined() &&
6273 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6274 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6275 }
6276
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006277 // The Microsoft ABI requires that we perform the destructor body
6278 // checks (i.e. operator delete() lookup) at every declaration, as
6279 // any translation unit may need to emit a deleting destructor.
6280 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6281 !Record->isDependentType() && Record->getDefinition() &&
6282 !Record->isBeingDefined()) {
6283 SemaRef.CheckDestructor(NewDD);
6284 }
6285
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006286 IsVirtualOkay = true;
6287 return NewDD;
6288
6289 } else {
6290 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6291 D.setInvalidType();
6292
6293 // Create a FunctionDecl to satisfy the function definition parsing
6294 // code path.
6295 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006296 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006297 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006298 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006299 /*hasPrototype=*/true, isConstexpr);
6300 }
6301
6302 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6303 if (!DC->isRecord()) {
6304 SemaRef.Diag(D.getIdentifierLoc(),
6305 diag::err_conv_function_not_member);
6306 return 0;
6307 }
6308
6309 SemaRef.CheckConversionDeclarator(D, R, SC);
6310 IsVirtualOkay = true;
6311 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006312 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006313 R, TInfo, isInline, isExplicit,
6314 isConstexpr, SourceLocation());
6315
6316 } else if (DC->isRecord()) {
6317 // If the name of the function is the same as the name of the record,
6318 // then this must be an invalid constructor that has a return type.
6319 // (The parser checks for a return type and makes the declarator a
6320 // constructor if it has no return type).
6321 if (Name.getAsIdentifierInfo() &&
6322 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6323 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6324 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6325 << SourceRange(D.getIdentifierLoc());
6326 return 0;
6327 }
6328
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006329 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006330 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6331 cast<CXXRecordDecl>(DC),
6332 D.getLocStart(), NameInfo, R,
6333 TInfo, SC, isInline,
6334 isConstexpr, SourceLocation());
6335 IsVirtualOkay = !Ret->isStatic();
6336 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006337 } else {
6338 // Determine whether the function was written with a
6339 // prototype. This true when:
6340 // - we're in C++ (where every function has a prototype),
6341 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006342 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006343 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006344 true/*HasPrototype*/, isConstexpr);
6345 }
6346}
6347
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006348void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6349 // In C++, the empty parameter-type-list must be spelled "void"; a
6350 // typedef of void is not permitted.
6351 if (getLangOpts().CPlusPlus &&
6352 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6353 bool IsTypeAlias = false;
6354 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6355 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6356 else if (const TemplateSpecializationType *TST =
6357 Param->getType()->getAs<TemplateSpecializationType>())
6358 IsTypeAlias = TST->isTypeAlias();
6359 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6360 << IsTypeAlias;
6361 }
6362}
6363
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006364enum OpenCLParamType {
6365 ValidKernelParam,
6366 PtrPtrKernelParam,
6367 PtrKernelParam,
6368 InvalidKernelParam,
6369 RecordKernelParam
6370};
6371
6372static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6373 if (PT->isPointerType()) {
6374 QualType PointeeType = PT->getPointeeType();
6375 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6376 }
6377
6378 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6379 // be used as builtin types.
6380
6381 if (PT->isImageType())
6382 return PtrKernelParam;
6383
6384 if (PT->isBooleanType())
6385 return InvalidKernelParam;
6386
6387 if (PT->isEventT())
6388 return InvalidKernelParam;
6389
6390 if (PT->isHalfType())
6391 return InvalidKernelParam;
6392
6393 if (PT->isRecordType())
6394 return RecordKernelParam;
6395
6396 return ValidKernelParam;
6397}
6398
6399static void checkIsValidOpenCLKernelParameter(
6400 Sema &S,
6401 Declarator &D,
6402 ParmVarDecl *Param,
6403 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6404 QualType PT = Param->getType();
6405
6406 // Cache the valid types we encounter to avoid rechecking structs that are
6407 // used again
6408 if (ValidTypes.count(PT.getTypePtr()))
6409 return;
6410
6411 switch (getOpenCLKernelParameterType(PT)) {
6412 case PtrPtrKernelParam:
6413 // OpenCL v1.2 s6.9.a:
6414 // A kernel function argument cannot be declared as a
6415 // pointer to a pointer type.
6416 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6417 D.setInvalidType();
6418 return;
6419
6420 // OpenCL v1.2 s6.9.k:
6421 // Arguments to kernel functions in a program cannot be declared with the
6422 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6423 // uintptr_t or a struct and/or union that contain fields declared to be
6424 // one of these built-in scalar types.
6425
6426 case InvalidKernelParam:
6427 // OpenCL v1.2 s6.8 n:
6428 // A kernel function argument cannot be declared
6429 // of event_t type.
6430 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6431 D.setInvalidType();
6432 return;
6433
6434 case PtrKernelParam:
6435 case ValidKernelParam:
6436 ValidTypes.insert(PT.getTypePtr());
6437 return;
6438
6439 case RecordKernelParam:
6440 break;
6441 }
6442
6443 // Track nested structs we will inspect
6444 SmallVector<const Decl *, 4> VisitStack;
6445
6446 // Track where we are in the nested structs. Items will migrate from
6447 // VisitStack to HistoryStack as we do the DFS for bad field.
6448 SmallVector<const FieldDecl *, 4> HistoryStack;
6449 HistoryStack.push_back((const FieldDecl *) 0);
6450
6451 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6452 VisitStack.push_back(PD);
6453
6454 assert(VisitStack.back() && "First decl null?");
6455
6456 do {
6457 const Decl *Next = VisitStack.pop_back_val();
6458 if (!Next) {
6459 assert(!HistoryStack.empty());
6460 // Found a marker, we have gone up a level
6461 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6462 ValidTypes.insert(Hist->getType().getTypePtr());
6463
6464 continue;
6465 }
6466
6467 // Adds everything except the original parameter declaration (which is not a
6468 // field itself) to the history stack.
6469 const RecordDecl *RD;
6470 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6471 HistoryStack.push_back(Field);
6472 RD = Field->getType()->castAs<RecordType>()->getDecl();
6473 } else {
6474 RD = cast<RecordDecl>(Next);
6475 }
6476
6477 // Add a null marker so we know when we've gone back up a level
6478 VisitStack.push_back((const Decl *) 0);
6479
6480 for (RecordDecl::field_iterator I = RD->field_begin(),
6481 E = RD->field_end(); I != E; ++I) {
6482 const FieldDecl *FD = *I;
6483 QualType QT = FD->getType();
6484
6485 if (ValidTypes.count(QT.getTypePtr()))
6486 continue;
6487
6488 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6489 if (ParamType == ValidKernelParam)
6490 continue;
6491
6492 if (ParamType == RecordKernelParam) {
6493 VisitStack.push_back(FD);
6494 continue;
6495 }
6496
6497 // OpenCL v1.2 s6.9.p:
6498 // Arguments to kernel functions that are declared to be a struct or union
6499 // do not allow OpenCL objects to be passed as elements of the struct or
6500 // union.
6501 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6502 S.Diag(Param->getLocation(),
6503 diag::err_record_with_pointers_kernel_param)
6504 << PT->isUnionType()
6505 << PT;
6506 } else {
6507 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6508 }
6509
6510 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6511 << PD->getDeclName();
6512
6513 // We have an error, now let's go back up through history and show where
6514 // the offending field came from
6515 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6516 E = HistoryStack.end(); I != E; ++I) {
6517 const FieldDecl *OuterField = *I;
6518 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6519 << OuterField->getType();
6520 }
6521
6522 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6523 << QT->isPointerType()
6524 << QT;
6525 D.setInvalidType();
6526 return;
6527 }
6528 } while (!VisitStack.empty());
6529}
6530
Mike Stump1eb44332009-09-09 15:08:12 +00006531NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006532Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006533 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006534 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006535 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006536 QualType R = TInfo->getType();
6537
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006538 assert(R.getTypePtr()->isFunctionType());
6539
Abramo Bagnara25777432010-08-11 22:01:17 +00006540 // TODO: consider using NameInfo for diagnostic.
6541 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6542 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006543 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006544
Richard Smithec642442013-04-12 22:46:28 +00006545 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6546 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6547 diag::err_invalid_thread)
6548 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006549
Reid Klecknerd1a32c32013-10-08 00:58:57 +00006550 if (D.isFirstDeclarationOfMember())
6551 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckneref072032013-08-27 23:08:25 +00006552
Douglas Gregor3922ed02010-12-10 19:28:19 +00006553 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006554 FunctionTemplateDecl *FunctionTemplate = 0;
6555 bool isExplicitSpecialization = false;
6556 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006557
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006558 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006559 bool HasExplicitTemplateArgs = false;
6560 TemplateArgumentListInfo TemplateArgs;
6561
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006562 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006563
Richard Smitha41c97a2013-09-20 01:15:31 +00006564 DeclContext *OriginalDC = DC;
6565 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6566
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006567 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6568 isVirtualOkay);
6569 if (!NewFD) return 0;
6570
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006571 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6572 NewFD->setTopLevelDeclInObjCContainer();
6573
Richard Smitha41c97a2013-09-20 01:15:31 +00006574 // Set the lexical context. If this is a function-scope declaration, or has a
6575 // C++ scope specifier, or is the object of a friend declaration, the lexical
6576 // context will be different from the semantic context.
6577 NewFD->setLexicalDeclContext(CurContext);
6578
6579 if (IsLocalExternDecl)
6580 NewFD->setLocalExternDecl();
6581
David Blaikie4e4d0842012-03-11 07:00:24 +00006582 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006583 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006584 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6585 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006586 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006587 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006588 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006589 // C++ [class.friend]p5
6590 // A function can be defined in a friend declaration of a
6591 // class . . . . Such a function is implicitly inline.
6592 NewFD->setImplicitlyInline();
6593 }
6594
John McCalle402e722012-09-25 07:32:39 +00006595 // If this is a method defined in an __interface, and is not a constructor
6596 // or an overloaded operator, then set the pure flag (isVirtual will already
6597 // return true).
6598 if (const CXXRecordDecl *Parent =
6599 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6600 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006601 NewFD->setPure(true);
6602 }
6603
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006604 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006605 isExplicitSpecialization = false;
6606 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006607 if (D.isInvalidType())
6608 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006609
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006610 // Match up the template parameter lists with the scope specifier, then
6611 // determine whether we have a template or a template specialization.
6612 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006613 if (TemplateParameterList *TemplateParams =
6614 MatchTemplateParametersToScopeSpecifier(
6615 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6616 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6617 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006618 if (TemplateParams->size() > 0) {
6619 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006620
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006621 // Check that we can declare a template here.
6622 if (CheckTemplateDeclScope(S, TemplateParams))
6623 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006624
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006625 // A destructor cannot be a template.
6626 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6627 Diag(NewFD->getLocation(), diag::err_destructor_template);
6628 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006629 }
Douglas Gregor20606502011-10-14 15:31:12 +00006630
6631 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006632 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006633 // now that we know what the current instantiation is.
6634 if (DC->isDependentContext()) {
6635 ContextRAII SavedContext(*this, DC);
6636 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6637 Invalid = true;
6638 }
6639
John McCall5fd378b2010-03-24 08:27:58 +00006640
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006641 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6642 NewFD->getLocation(),
6643 Name, TemplateParams,
6644 NewFD);
6645 FunctionTemplate->setLexicalDeclContext(CurContext);
6646 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6647
6648 // For source fidelity, store the other template param lists.
6649 if (TemplateParamLists.size() > 1) {
6650 NewFD->setTemplateParameterListsInfo(Context,
6651 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006652 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006653 }
6654 } else {
6655 // This is a function template specialization.
6656 isFunctionTemplateSpecialization = true;
6657 // For source fidelity, store all the template param lists.
6658 NewFD->setTemplateParameterListsInfo(Context,
6659 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006660 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006661
6662 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6663 if (isFriend) {
6664 // We want to remove the "template<>", found here.
6665 SourceRange RemoveRange = TemplateParams->getSourceRange();
6666
6667 // If we remove the template<> and the name is not a
6668 // template-id, we're actually silently creating a problem:
6669 // the friend declaration will refer to an untemplated decl,
6670 // and clearly the user wants a template specialization. So
6671 // we need to insert '<>' after the name.
6672 SourceLocation InsertLoc;
6673 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6674 InsertLoc = D.getName().getSourceRange().getEnd();
6675 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6676 }
6677
6678 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6679 << Name << RemoveRange
6680 << FixItHint::CreateRemoval(RemoveRange)
6681 << FixItHint::CreateInsertion(InsertLoc, "<>");
6682 }
6683 }
6684 }
6685 else {
6686 // All template param lists were matched against the scope specifier:
6687 // this is NOT (an explicit specialization of) a template.
6688 if (TemplateParamLists.size() > 0)
6689 // For source fidelity, store all the template param lists.
6690 NewFD->setTemplateParameterListsInfo(Context,
6691 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006692 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006693 }
6694
6695 if (Invalid) {
6696 NewFD->setInvalidDecl();
6697 if (FunctionTemplate)
6698 FunctionTemplate->setInvalidDecl();
6699 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006700
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006701 // C++ [dcl.fct.spec]p5:
6702 // The virtual specifier shall only be used in declarations of
6703 // nonstatic class member functions that appear within a
6704 // member-specification of a class declaration; see 10.3.
6705 //
6706 if (isVirtual && !NewFD->isInvalidDecl()) {
6707 if (!isVirtualOkay) {
6708 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6709 diag::err_virtual_non_function);
6710 } else if (!CurContext->isRecord()) {
6711 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006712 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6713 diag::err_virtual_out_of_class)
6714 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6715 } else if (NewFD->getDescribedFunctionTemplate()) {
6716 // C++ [temp.mem]p3:
6717 // A member function template shall not be virtual.
6718 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6719 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006720 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6721 } else {
6722 // Okay: Add virtual to the method.
6723 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006724 }
Richard Smith60e141e2013-05-04 07:00:32 +00006725
6726 if (getLangOpts().CPlusPlus1y &&
6727 NewFD->getResultType()->isUndeducedType())
6728 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006729 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006730
Richard Smith37e849a2013-08-14 20:16:31 +00006731 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6732 NewFD->getResultType()->isUndeducedType()) {
6733 // If the function template is referenced directly (for instance, as a
6734 // member of the current instantiation), pretend it has a dependent type.
6735 // This is not really justified by the standard, but is the only sane
6736 // thing to do.
6737 const FunctionProtoType *FPT =
6738 NewFD->getType()->castAs<FunctionProtoType>();
6739 QualType Result = SubstAutoType(FPT->getResultType(),
6740 Context.DependentTy);
6741 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6742 FPT->getExtProtoInfo()));
6743 }
6744
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006745 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006746 // The inline specifier shall not appear on a block scope function
6747 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006748 if (isInline && !NewFD->isInvalidDecl()) {
6749 if (CurContext->isFunctionOrMethod()) {
6750 // 'inline' is not allowed on block scope function declaration.
6751 Diag(D.getDeclSpec().getInlineSpecLoc(),
6752 diag::err_inline_declaration_block_scope) << Name
6753 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6754 }
6755 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006756
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006757 // C++ [dcl.fct.spec]p6:
6758 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006759 // constructor or conversion function within its class definition;
6760 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006761 if (isExplicit && !NewFD->isInvalidDecl()) {
6762 if (!CurContext->isRecord()) {
6763 // 'explicit' was specified outside of the class.
6764 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6765 diag::err_explicit_out_of_class)
6766 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6767 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6768 !isa<CXXConversionDecl>(NewFD)) {
6769 // 'explicit' was specified on a function that wasn't a constructor
6770 // or conversion function.
6771 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6772 diag::err_explicit_non_ctor_or_conv_function)
6773 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6774 }
6775 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006776
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006777 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006778 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006779 // are implicitly inline.
6780 NewFD->setImplicitlyInline();
6781
Richard Smith21c8fa82013-01-14 05:37:29 +00006782 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006783 // be either constructors or to return a literal type. Therefore,
6784 // destructors cannot be declared constexpr.
6785 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006786 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006787 }
6788
Douglas Gregor8d267c52011-09-09 02:06:17 +00006789 // If __module_private__ was specified, mark the function accordingly.
6790 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006791 if (isFunctionTemplateSpecialization) {
6792 SourceLocation ModulePrivateLoc
6793 = D.getDeclSpec().getModulePrivateSpecLoc();
6794 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6795 << 0
6796 << FixItHint::CreateRemoval(ModulePrivateLoc);
6797 } else {
6798 NewFD->setModulePrivate();
6799 if (FunctionTemplate)
6800 FunctionTemplate->setModulePrivate();
6801 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006802 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006803
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006804 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006805 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006806 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006807 FunctionTemplate->setAccess(AS_public);
6808 }
Richard Smith22050f22013-07-17 23:53:16 +00006809 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006810 NewFD->setAccess(AS_public);
6811 }
6812
Douglas Gregor45fa5602011-11-07 20:56:01 +00006813 // If a function is defined as defaulted or deleted, mark it as such now.
6814 switch (D.getFunctionDefinitionKind()) {
6815 case FDK_Declaration:
6816 case FDK_Definition:
6817 break;
6818
6819 case FDK_Defaulted:
6820 NewFD->setDefaulted();
6821 break;
6822
6823 case FDK_Deleted:
6824 NewFD->setDeletedAsWritten();
6825 break;
6826 }
6827
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006828 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6829 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006830 // C++ [class.mfct]p2:
6831 // A member function may be defined (8.4) in its class definition, in
6832 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006833 NewFD->setImplicitlyInline();
6834 }
6835
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006836 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6837 !CurContext->isRecord()) {
6838 // C++ [class.static]p1:
6839 // A data or function member of a class may be declared static
6840 // in a class definition, in which case it is a static member of
6841 // the class.
6842
6843 // Complain about the 'static' specifier if it's on an out-of-line
6844 // member function definition.
6845 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6846 diag::err_static_out_of_line)
6847 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6848 }
Richard Smith444d3842012-10-20 08:26:51 +00006849
6850 // C++11 [except.spec]p15:
6851 // A deallocation function with no exception-specification is treated
6852 // as if it were specified with noexcept(true).
6853 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6854 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6855 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006856 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006857 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6858 EPI.ExceptionSpecType = EST_BasicNoexcept;
6859 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006860 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006861 }
David Majnemerd2b0cf32013-10-20 05:40:29 +00006862
6863 // C++11 [replacement.functions]p3:
6864 // The program's definitions shall not be specified as inline.
David Majnemer3abf5f62013-10-21 00:25:32 +00006865 //
6866 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
David Majnemerd2b0cf32013-10-20 05:40:29 +00006867 if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6868 Diag(D.getDeclSpec().getInlineSpecLoc(),
6869 diag::err_operator_new_delete_declared_inline)
6870 << NewFD->getDeclName();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006871 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006872
6873 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006874 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006875 isExplicitSpecialization ||
6876 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006877
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006878 // Handle GNU asm-label extension (encoded as an attribute).
6879 if (Expr *E = (Expr*) D.getAsmLabel()) {
6880 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006881 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006882 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6883 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006884 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6885 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6886 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6887 if (I != ExtnameUndeclaredIdentifiers.end()) {
6888 NewFD->addAttr(I->second);
6889 ExtnameUndeclaredIdentifiers.erase(I);
6890 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006891 }
6892
Chris Lattner2dbd2852009-04-25 06:12:16 +00006893 // Copy the parameter declarations from the declarator D to the function
6894 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006895 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006896 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006897 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006898
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006899 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6900 // function that takes no arguments, not a function that takes a
6901 // single void argument.
6902 // We let through "const void" here because Sema::GetTypeForDeclarator
6903 // already checks for that case.
6904 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6905 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006906 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006907 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006908 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006909 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006910 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006911 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006912 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6913 Param->setDeclContext(NewFD);
6914 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006915
6916 if (Param->isInvalidDecl())
6917 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006918 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006919 }
Mike Stump1eb44332009-09-09 15:08:12 +00006920
John McCall183700f2009-09-21 23:43:11 +00006921 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006922 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006923 // following example, we'll need to synthesize (unnamed)
6924 // parameters for use in the declaration.
6925 //
6926 // @code
6927 // typedef void fn(int);
6928 // fn f;
6929 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006930
Chris Lattner1ad9b282009-04-25 06:03:53 +00006931 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006932 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6933 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006934 ParmVarDecl *Param =
6935 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006936 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006937 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006938 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006939 } else {
6940 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6941 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006942 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006943
Chris Lattner2dbd2852009-04-25 06:12:16 +00006944 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006945 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006946
James Molloy16f1f712012-02-29 10:24:19 +00006947 // Find all anonymous symbols defined during the declaration of this function
6948 // and add to NewFD. This lets us track decls such 'enum Y' in:
6949 //
6950 // void f(enum Y {AA} x) {}
6951 //
6952 // which would otherwise incorrectly end up in the translation unit scope.
6953 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6954 DeclsInPrototypeScope.clear();
6955
Richard Smith7586a6e2013-01-30 05:45:05 +00006956 if (D.getDeclSpec().isNoreturnSpecified())
6957 NewFD->addAttr(
6958 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6959 Context));
6960
Richard Smithb03a9df2012-03-13 05:56:40 +00006961 // Functions returning a variably modified type violate C99 6.7.5.2p2
6962 // because all functions have linkage.
6963 if (!NewFD->isInvalidDecl() &&
6964 NewFD->getResultType()->isVariablyModifiedType()) {
6965 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6966 NewFD->setInvalidDecl();
6967 }
6968
Rafael Espindola98ae8342012-05-10 02:50:16 +00006969 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006970 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006971
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006972 QualType RetType = NewFD->getResultType();
6973 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6974 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6975 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6976 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006977 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006978 // Attach the attribute to the new decl. Don't apply the attribute if it
6979 // returns an instance of the class (e.g. assignment operators).
6980 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006981 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6982 Context));
6983 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006984 }
6985
David Blaikie4e4d0842012-03-11 07:00:24 +00006986 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006987 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00006988 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00006989 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6990 CheckMain(NewFD, D.getDeclSpec());
6991
David Majnemere9f6f332013-09-16 22:44:20 +00006992 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6993 CheckMSVCRTEntryPoint(NewFD);
6994
David Majnemerc371db62013-07-06 02:13:46 +00006995 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00006996 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6997 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00006998 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00006999 // Make graceful recovery from an invalid redeclaration.
7000 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007001 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007002 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7003 "previous declaration set still overloaded");
7004 } else {
7005 // If the declarator is a template-id, translate the parser's template
7006 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007007 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7008 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7009 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7010 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007011 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007012 TemplateId->NumArgs);
7013 translateTemplateArguments(TemplateArgsPtr,
7014 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007015
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007016 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007017
Douglas Gregor89b9f102011-06-06 15:22:55 +00007018 if (NewFD->isInvalidDecl()) {
7019 HasExplicitTemplateArgs = false;
7020 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007021 // Function template with explicit template arguments.
7022 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7023 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7024
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007025 HasExplicitTemplateArgs = false;
7026 } else if (!isFunctionTemplateSpecialization &&
7027 !D.getDeclSpec().isFriendSpecified()) {
7028 // We have encountered something that the user meant to be a
7029 // specialization (because it has explicitly-specified template
7030 // arguments) but that was not introduced with a "template<>" (or had
7031 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007032 // FIXME: Differentiate between attempts for explicit instantiations
7033 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007034 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7035 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7036 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007037 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007038 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007039 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007040 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007041 // "friend void foo<>(int);" is an implicit specialization decl.
7042 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007043 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007044 } else if (isFriend && isFunctionTemplateSpecialization) {
7045 // This combination is only possible in a recovery case; the user
7046 // wrote something like:
7047 // template <> friend void foo(int);
7048 // which we're recovering from as if the user had written:
7049 // friend void foo<>(int);
7050 // Go ahead and fake up a template id.
7051 HasExplicitTemplateArgs = true;
7052 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7053 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007054 }
John McCall29ae6e52010-10-13 05:45:15 +00007055
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007056 // If it's a friend (and only if it's a friend), it's possible
7057 // that either the specialized function type or the specialized
7058 // template is dependent, and therefore matching will fail. In
7059 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007060 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007061 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007062 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7063 TemplateSpecializationType::anyDependentTemplateArguments(
7064 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7065 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007066 assert(HasExplicitTemplateArgs &&
7067 "friend function specialization without template args");
7068 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7069 Previous))
7070 NewFD->setInvalidDecl();
7071 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007072 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007073 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007074 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007075 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007076 diag::ext_function_specialization_in_class :
7077 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007078 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007079 } else if (CheckFunctionTemplateSpecialization(NewFD,
7080 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7081 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007082 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007083
7084 // C++ [dcl.stc]p1:
7085 // A storage-class-specifier shall not be specified in an explicit
7086 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007087 FunctionTemplateSpecializationInfo *Info =
7088 NewFD->getTemplateSpecializationInfo();
7089 if (Info && SC != SC_None) {
7090 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007091 Diag(NewFD->getLocation(),
7092 diag::err_explicit_specialization_inconsistent_storage_class)
7093 << SC
7094 << FixItHint::CreateRemoval(
7095 D.getDeclSpec().getStorageClassSpecLoc());
7096
7097 else
7098 Diag(NewFD->getLocation(),
7099 diag::ext_explicit_specialization_storage_class)
7100 << FixItHint::CreateRemoval(
7101 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007102 }
7103
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007104 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7105 if (CheckMemberSpecialization(NewFD, Previous))
7106 NewFD->setInvalidDecl();
7107 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007108
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007109 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007110 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007111 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7112 CheckMain(NewFD, D.getDeclSpec());
7113
David Majnemere9f6f332013-09-16 22:44:20 +00007114 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7115 CheckMSVCRTEntryPoint(NewFD);
7116
David Blaikie14068e82011-09-08 06:33:04 +00007117 if (NewFD->isInvalidDecl()) {
7118 // If this is a class member, mark the class invalid immediately.
7119 // This avoids some consistency errors later.
7120 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7121 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007122 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007123 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7124 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007125 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007126
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007127 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007128 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7129 "previous declaration set still overloaded");
7130
7131 NamedDecl *PrincipalDecl = (FunctionTemplate
7132 ? cast<NamedDecl>(FunctionTemplate)
7133 : NewFD);
7134
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007135 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007136 AccessSpecifier Access = AS_public;
7137 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007138 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007139
7140 NewFD->setAccess(Access);
7141 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007142 }
7143
7144 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7145 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7146 PrincipalDecl->setNonMemberOperator();
7147
7148 // If we have a function template, check the template parameter
7149 // list. This will check and merge default template arguments.
7150 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007151 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007152 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007153 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007154 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007155 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007156 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007157 ? TPC_FriendFunctionTemplateDefinition
7158 : TPC_FriendFunctionTemplate)
7159 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007160 DC && DC->isRecord() &&
7161 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007162 ? TPC_ClassTemplateMember
7163 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007164 }
7165
7166 if (NewFD->isInvalidDecl()) {
7167 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007168 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007169 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007170 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007171 // Fake up an access specifier if it's supposed to be a class member.
7172 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7173 NewFD->setAccess(AS_public);
7174
7175 // Qualified decls generally require a previous declaration.
7176 if (D.getCXXScopeSpec().isSet()) {
7177 // ...with the major exception of templated-scope or
7178 // dependent-scope friend declarations.
7179
7180 // TODO: we currently also suppress this check in dependent
7181 // contexts because (1) the parameter depth will be off when
7182 // matching friend templates and (2) we might actually be
7183 // selecting a friend based on a dependent factor. But there
7184 // are situations where these conditions don't apply and we
7185 // can actually do this check immediately.
7186 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007187 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007188 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7189 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007190 // ignore these
7191 } else {
7192 // The user tried to provide an out-of-line definition for a
7193 // function that is a member of a class or namespace, but there
7194 // was no such member function declared (C++ [class.mfct]p2,
7195 // C++ [namespace.memdef]p2). For example:
7196 //
7197 // class X {
7198 // void f() const;
7199 // };
7200 //
7201 // void X::f() { } // ill-formed
7202 //
7203 // Complain about this problem, and attempt to suggest close
7204 // matches (e.g., those that differ only in cv-qualifiers and
7205 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007206
Richard Smith4e9686b2013-08-09 04:35:01 +00007207 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7208 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007209 AddToScope = ExtraArgs.AddToScope;
7210 return Result;
7211 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007212 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007213
7214 // Unqualified local friend declarations are required to resolve
7215 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007216 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007217 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7218 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007219 AddToScope = ExtraArgs.AddToScope;
7220 return Result;
7221 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007222 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007223
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007224 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007225 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007226 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007227 // An out-of-line member function declaration must also be a
7228 // definition (C++ [dcl.meaning]p1).
7229 // Note that this is not the case for explicit specializations of
7230 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007231 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7232 // extension for compatibility with old SWIG code which likes to
7233 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007234 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7235 << D.getCXXScopeSpec().getRange();
7236 }
7237 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007238
Rafael Espindola65611bf2013-03-02 21:41:48 +00007239 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007240 checkAttributesAfterMerging(*this, *NewFD);
7241
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007242 AddKnownFunctionAttributes(NewFD);
7243
Douglas Gregord9455382010-08-06 13:50:58 +00007244 if (NewFD->hasAttr<OverloadableAttr>() &&
7245 !NewFD->getType()->getAs<FunctionProtoType>()) {
7246 Diag(NewFD->getLocation(),
7247 diag::err_attribute_overloadable_no_prototype)
7248 << NewFD;
7249
7250 // Turn this into a variadic function with no parameters.
7251 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007252 FunctionProtoType::ExtProtoInfo EPI(
7253 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007254 EPI.Variadic = true;
7255 EPI.ExtInfo = FT->getExtInfo();
7256
Dmitri Gribenko55431692013-05-05 00:41:58 +00007257 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007258 NewFD->setType(R);
7259 }
7260
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007261 // If there's a #pragma GCC visibility in scope, and this isn't a class
7262 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007263 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007264 AddPushedVisibilityAttribute(NewFD);
7265
John McCall8dfac0b2011-09-30 05:12:12 +00007266 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7267 // marking the function.
7268 AddCFAuditedAttribute(NewFD);
7269
Richard Smithaa4bc182013-06-30 09:48:50 +00007270 // If this is the first declaration of an extern C variable, update
7271 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007272 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007273 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007274 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007275
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007276 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007277 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007278
David Blaikie4e4d0842012-03-11 07:00:24 +00007279 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007280 if (FunctionTemplate) {
7281 if (NewFD->isInvalidDecl())
7282 FunctionTemplate->setInvalidDecl();
7283 return FunctionTemplate;
7284 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007285 }
Mike Stump1eb44332009-09-09 15:08:12 +00007286
Guy Benyeie6b9d802013-01-20 12:31:11 +00007287 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007288 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7289 if ((getLangOpts().OpenCLVersion >= 120)
7290 && (SC == SC_Static)) {
7291 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7292 D.setInvalidType();
7293 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007294
7295 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7296 if (!NewFD->getResultType()->isVoidType()) {
7297 Diag(D.getIdentifierLoc(),
7298 diag::err_expected_kernel_void_return_type);
7299 D.setInvalidType();
7300 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007301
7302 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007303 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7304 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007305 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007306 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007307 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007308 }
7309
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007310 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007311
David Blaikie4e4d0842012-03-11 07:00:24 +00007312 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007313 if (IdentifierInfo *II = NewFD->getIdentifier())
7314 if (!NewFD->isInvalidDecl() &&
7315 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7316 if (II->isStr("cudaConfigureCall")) {
7317 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7318 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7319
7320 Context.setcudaConfigureCallDecl(NewFD);
7321 }
7322 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007323
7324 // Here we have an function template explicit specialization at class scope.
7325 // The actually specialization will be postponed to template instatiation
7326 // time via the ClassScopeFunctionSpecializationDecl node.
7327 if (isDependentClassScopeExplicitSpecialization) {
7328 ClassScopeFunctionSpecializationDecl *NewSpec =
7329 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007330 Context, CurContext, SourceLocation(),
7331 cast<CXXMethodDecl>(NewFD),
7332 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007333 CurContext->addDecl(NewSpec);
7334 AddToScope = false;
7335 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007336
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007337 return NewFD;
7338}
7339
7340/// \brief Perform semantic checking of a new function declaration.
7341///
7342/// Performs semantic analysis of the new function declaration
7343/// NewFD. This routine performs all semantic checking that does not
7344/// require the actual declarator involved in the declaration, and is
7345/// used both for the declaration of functions as they are parsed
7346/// (called via ActOnDeclarator) and for the declaration of functions
7347/// that have been instantiated via C++ template instantiation (called
7348/// via InstantiateDecl).
7349///
James Dennettefce31f2012-06-22 08:10:18 +00007350/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007351/// an explicit specialization of the previous declaration.
7352///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007353/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007354///
James Dennettefce31f2012-06-22 08:10:18 +00007355/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007356bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007357 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007358 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007359 assert(!NewFD->getResultType()->isVariablyModifiedType()
7360 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007361
Richard Smithdd9459f2013-08-13 18:18:50 +00007362 // Determine whether the type of this function should be merged with
7363 // a previous visible declaration. This never happens for functions in C++,
7364 // and always happens in C if the previous declaration was visible.
7365 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7366 !Previous.isShadowed();
7367
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007368 // Filter out any non-conflicting previous declarations.
7369 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7370
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007371 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007372 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007373
Douglas Gregor04495c82009-02-24 01:23:02 +00007374 // Merge or overload the declaration with an existing declaration of
7375 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007376 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007377 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007378 // a declaration that requires merging. If it's an overload,
7379 // there's no more work to do here; we'll just add the new
7380 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007381 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007382 NamedDecl *Candidate = Previous.getFoundDecl();
7383 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7384 Redeclaration = true;
7385 OldDecl = Candidate;
7386 }
John McCall871b2e72009-12-09 03:35:25 +00007387 } else {
John McCallad00b772010-06-16 08:42:20 +00007388 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7389 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007390 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007391 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007392 break;
7393
7394 case Ovl_NonFunction:
7395 Redeclaration = true;
7396 break;
7397
7398 case Ovl_Overload:
7399 Redeclaration = false;
7400 break;
John McCall68263142009-11-18 22:49:29 +00007401 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007402
David Blaikie4e4d0842012-03-11 07:00:24 +00007403 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007404 // If a function name is overloadable in C, then every function
7405 // with that name must be marked "overloadable".
7406 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7407 << Redeclaration << NewFD;
7408 NamedDecl *OverloadedDecl = 0;
7409 if (Redeclaration)
7410 OverloadedDecl = OldDecl;
7411 else if (!Previous.empty())
7412 OverloadedDecl = Previous.getRepresentativeDecl();
7413 if (OverloadedDecl)
7414 Diag(OverloadedDecl->getLocation(),
7415 diag::note_attribute_overloadable_prev_overload);
7416 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7417 Context));
7418 }
John McCall68263142009-11-18 22:49:29 +00007419 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007420 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007421
Richard Smithaa4bc182013-06-30 09:48:50 +00007422 // Check for a previous extern "C" declaration with this name.
7423 if (!Redeclaration &&
7424 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7425 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7426 if (!Previous.empty()) {
7427 // This is an extern "C" declaration with the same name as a previous
7428 // declaration, and thus redeclares that entity...
7429 Redeclaration = true;
7430 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007431 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007432
7433 // ... except in the presence of __attribute__((overloadable)).
7434 if (OldDecl->hasAttr<OverloadableAttr>()) {
7435 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7436 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7437 << Redeclaration << NewFD;
7438 Diag(Previous.getFoundDecl()->getLocation(),
7439 diag::note_attribute_overloadable_prev_overload);
7440 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7441 Context));
7442 }
7443 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7444 Redeclaration = false;
7445 OldDecl = 0;
7446 }
7447 }
7448 }
7449 }
7450
Richard Smith21c8fa82013-01-14 05:37:29 +00007451 // C++11 [dcl.constexpr]p8:
7452 // A constexpr specifier for a non-static member function that is not
7453 // a constructor declares that member function to be const.
7454 //
7455 // This needs to be delayed until we know whether this is an out-of-line
7456 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007457 //
7458 // This rule is not present in C++1y, so we produce a backwards
7459 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007460 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007461 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7462 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007463 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7464 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7465 if (FunctionTemplateDecl *OldTD =
7466 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7467 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7468 if (!OldMD || !OldMD->isStatic()) {
7469 const FunctionProtoType *FPT =
7470 MD->getType()->castAs<FunctionProtoType>();
7471 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7472 EPI.TypeQuals |= Qualifiers::Const;
7473 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007474 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007475
7476 // Warn that we did this, if we're not performing template instantiation.
7477 // In that case, we'll have warned already when the template was defined.
7478 if (ActiveTemplateInstantiations.empty()) {
7479 SourceLocation AddConstLoc;
7480 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7481 .IgnoreParens().getAs<FunctionTypeLoc>())
7482 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7483
7484 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7485 << FixItHint::CreateInsertion(AddConstLoc, " const");
7486 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007487 }
7488 }
7489
7490 if (Redeclaration) {
7491 // NewFD and OldDecl represent declarations that need to be
7492 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007493 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007494 NewFD->setInvalidDecl();
7495 return Redeclaration;
7496 }
7497
7498 Previous.clear();
7499 Previous.addDecl(OldDecl);
7500
7501 if (FunctionTemplateDecl *OldTemplateDecl
7502 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7503 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7504 FunctionTemplateDecl *NewTemplateDecl
7505 = NewFD->getDescribedFunctionTemplate();
7506 assert(NewTemplateDecl && "Template/non-template mismatch");
7507 if (CXXMethodDecl *Method
7508 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7509 Method->setAccess(OldTemplateDecl->getAccess());
7510 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007511 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007512
7513 // If this is an explicit specialization of a member that is a function
7514 // template, mark it as a member specialization.
7515 if (IsExplicitSpecialization &&
7516 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7517 NewTemplateDecl->setMemberSpecialization();
7518 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007519 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007520
7521 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007522 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007523 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007524
7525 if (isa<CXXMethodDecl>(NewFD)) {
7526 // A valid redeclaration of a C++ method must be out-of-line,
7527 // but (unfortunately) it's not necessarily a definition
7528 // because of templates, which means that the previous
7529 // declaration is not necessarily from the class definition.
7530
7531 // For just setting the access, that doesn't matter.
7532 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7533 NewFD->setAccess(oldMethod->getAccess());
7534
7535 // Update the key-function state if necessary for this ABI.
7536 if (NewFD->isInlined() &&
7537 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7538 // setNonKeyFunction needs to work with the original
7539 // declaration from the class definition, and isVirtual() is
7540 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007541 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007542 if (oldMethod->isVirtual()) {
7543 Context.setNonKeyFunction(oldMethod);
7544 }
7545 }
7546 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007547 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007548 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007549
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007550 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007551 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007552 // C++-specific checks.
7553 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7554 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007555 } else if (CXXDestructorDecl *Destructor =
7556 dyn_cast<CXXDestructorDecl>(NewFD)) {
7557 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007558 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007559
Douglas Gregor4923aa22010-07-02 20:37:36 +00007560 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007561 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007562 if (!ClassType->isDependentType()) {
7563 DeclarationName Name
7564 = Context.DeclarationNames.getCXXDestructorName(
7565 Context.getCanonicalType(ClassType));
7566 if (NewFD->getDeclName() != Name) {
7567 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007568 NewFD->setInvalidDecl();
7569 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007570 }
7571 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007572 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007573 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007574 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007575 }
7576
7577 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007578 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7579 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007580 !Method->getDescribedFunctionTemplate() &&
7581 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007582 if (AddOverriddenMethods(Method->getParent(), Method)) {
7583 // If the function was marked as "static", we have a problem.
7584 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007585 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007586 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007587 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007588 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007589
7590 if (Method->isStatic())
7591 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007592 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007593
7594 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7595 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007596 CheckOverloadedOperatorDeclaration(NewFD)) {
7597 NewFD->setInvalidDecl();
7598 return Redeclaration;
7599 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007600
7601 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7602 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007603 CheckLiteralOperatorDeclaration(NewFD)) {
7604 NewFD->setInvalidDecl();
7605 return Redeclaration;
7606 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007607
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007608 // In C++, check default arguments now that we have merged decls. Unless
7609 // the lexical context is the class, because in this case this is done
7610 // during delayed parsing anyway.
7611 if (!CurContext->isRecord())
7612 CheckCXXDefaultArguments(NewFD);
Douglas Gregorb68e3992010-12-21 19:47:46 +00007613
7614 // If this function declares a builtin function, check the type of this
7615 // declaration against the expected type for the builtin.
7616 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7617 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007618 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007619 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7620 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7621 // The type of this function differs from the type of the builtin,
7622 // so forget about the builtin entirely.
7623 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7624 }
7625 }
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007626
7627 // If this function is declared as being extern "C", then check to see if
7628 // the function returns a UDT (class, struct, or union type) that is not C
7629 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007630 // But, issue any diagnostic on the first declaration only.
7631 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007632 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007633 if (R->isIncompleteType() && !R->isVoidType())
7634 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7635 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007636 else if (!R.isPODType(Context) && !R->isVoidType() &&
7637 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007638 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007639 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007640 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007641 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007642}
7643
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007644static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7645 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7646 if (!TSI)
7647 return SourceRange();
7648
7649 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007650 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007651 if (!FunctionTL)
7652 return SourceRange();
7653
David Blaikie39e6ab42013-02-18 22:06:02 +00007654 TypeLoc ResultTL = FunctionTL.getResultLoc();
7655 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007656 return ResultTL.getSourceRange();
7657
7658 return SourceRange();
7659}
7660
David Blaikie14068e82011-09-08 06:33:04 +00007661void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007662 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7663 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007664 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7665 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007666 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007667 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007668 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007669 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007670 ? diag::err_static_main : diag::warn_static_main)
7671 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7672 if (FD->isInlineSpecified())
7673 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7674 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007675 if (DS.isNoreturnSpecified()) {
7676 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7677 SourceRange NoreturnRange(NoreturnLoc,
7678 PP.getLocForEndOfToken(NoreturnLoc));
7679 Diag(NoreturnLoc, diag::ext_noreturn_main);
7680 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7681 << FixItHint::CreateRemoval(NoreturnRange);
7682 }
Richard Smitha5065862012-02-04 06:10:17 +00007683 if (FD->isConstexpr()) {
7684 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7685 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7686 FD->setConstexpr(false);
7687 }
John McCall13591ed2009-07-25 04:36:53 +00007688
7689 QualType T = FD->getType();
7690 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007691 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007692
John McCall75d8ba32012-02-14 19:50:52 +00007693 // All the standards say that main() should should return 'int'.
7694 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7695 // In C and C++, main magically returns 0 if you fall off the end;
7696 // set the flag which tells us that.
7697 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7698 FD->setHasImplicitReturnZero(true);
7699
7700 // In C with GNU extensions we allow main() to have non-integer return
7701 // type, but we should warn about the extension, and we disable the
7702 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007703 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007704 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7705
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007706 SourceRange ResultRange = getResultSourceRange(FD);
7707 if (ResultRange.isValid())
7708 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7709 << FixItHint::CreateReplacement(ResultRange, "int");
7710
John McCall75d8ba32012-02-14 19:50:52 +00007711 // Otherwise, this is just a flat-out error.
7712 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007713 SourceRange ResultRange = getResultSourceRange(FD);
7714 if (ResultRange.isValid())
7715 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7716 << FixItHint::CreateReplacement(ResultRange, "int");
7717 else
7718 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7719
John McCall13591ed2009-07-25 04:36:53 +00007720 FD->setInvalidDecl(true);
7721 }
7722
7723 // Treat protoless main() as nullary.
7724 if (isa<FunctionNoProtoType>(FT)) return;
7725
7726 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7727 unsigned nparams = FTP->getNumArgs();
7728 assert(FD->getNumParams() == nparams);
7729
John McCall66755862009-12-24 09:58:38 +00007730 bool HasExtraParameters = (nparams > 3);
7731
7732 // Darwin passes an undocumented fourth argument of type char**. If
7733 // other platforms start sprouting these, the logic below will start
7734 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007735 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007736 HasExtraParameters = false;
7737
7738 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007739 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7740 FD->setInvalidDecl(true);
7741 nparams = 3;
7742 }
7743
7744 // FIXME: a lot of the following diagnostics would be improved
7745 // if we had some location information about types.
7746
7747 QualType CharPP =
7748 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007749 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007750
7751 for (unsigned i = 0; i < nparams; ++i) {
7752 QualType AT = FTP->getArgType(i);
7753
7754 bool mismatch = true;
7755
7756 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7757 mismatch = false;
7758 else if (Expected[i] == CharPP) {
7759 // As an extension, the following forms are okay:
7760 // char const **
7761 // char const * const *
7762 // char * const *
7763
John McCall0953e762009-09-24 19:53:00 +00007764 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007765 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007766 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7767 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007768 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7769 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007770 qs.removeConst();
7771 mismatch = !qs.empty();
7772 }
7773 }
7774
7775 if (mismatch) {
7776 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7777 // TODO: suggest replacing given type with expected type
7778 FD->setInvalidDecl(true);
7779 }
7780 }
7781
7782 if (nparams == 1 && !FD->isInvalidDecl()) {
7783 Diag(FD->getLocation(), diag::warn_main_one_arg);
7784 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007785
7786 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007787 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7788 FD->setInvalidDecl();
7789 }
7790}
7791
7792void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7793 QualType T = FD->getType();
7794 assert(T->isFunctionType() && "function decl is not of function type");
7795 const FunctionType *FT = T->castAs<FunctionType>();
7796
7797 // Set an implicit return of 'zero' if the function can return some integral,
7798 // enumeration, pointer or nullptr type.
7799 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7800 FT->getResultType()->isAnyPointerType() ||
7801 FT->getResultType()->isNullPtrType())
7802 // DllMain is exempt because a return value of zero means it failed.
7803 if (FD->getName() != "DllMain")
7804 FD->setHasImplicitReturnZero(true);
7805
7806 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7807 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007808 FD->setInvalidDecl();
7809 }
John McCall8c4859a2009-07-24 03:03:21 +00007810}
7811
Eli Friedmanc594b322008-05-20 13:48:25 +00007812bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007813 // FIXME: Need strict checking. In C89, we need to check for
7814 // any assignment, increment, decrement, function-calls, or
7815 // commas outside of a sizeof. In C99, it's the same list,
7816 // except that the aforementioned are allowed in unevaluated
7817 // expressions. Everything else falls under the
7818 // "may accept other forms of constant expressions" exception.
7819 // (We never end up here for C++, so the constant expression
7820 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007821 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007822 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007823 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7824 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007825 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007826}
7827
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007828namespace {
7829 // Visits an initialization expression to see if OrigDecl is evaluated in
7830 // its own initialization and throws a warning if it does.
7831 class SelfReferenceChecker
7832 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7833 Sema &S;
7834 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007835 bool isRecordType;
7836 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007837 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007838
7839 public:
7840 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7841
7842 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007843 S(S), OrigDecl(OrigDecl) {
7844 isPODType = false;
7845 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007846 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007847 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7848 isPODType = VD->getType().isPODType(S.Context);
7849 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007850 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007851 }
7852 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007853
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007854 // For most expressions, the cast is directly above the DeclRefExpr.
7855 // For conditional operators, the cast can be outside the conditional
7856 // operator if both expressions are DeclRefExpr's.
7857 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007858 if (isReferenceType)
7859 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007860 E = E->IgnoreParenImpCasts();
7861 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7862 HandleDeclRefExpr(DRE);
7863 return;
7864 }
7865
7866 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7867 HandleValue(CO->getTrueExpr());
7868 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007869 return;
7870 }
7871
7872 if (isa<MemberExpr>(E)) {
7873 Expr *Base = E->IgnoreParenImpCasts();
7874 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7875 // Check for static member variables and don't warn on them.
7876 if (!isa<FieldDecl>(ME->getMemberDecl()))
7877 return;
7878 Base = ME->getBase()->IgnoreParenImpCasts();
7879 }
7880 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7881 HandleDeclRefExpr(DRE);
7882 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007883 }
7884 }
7885
Richard Trieu568f7852012-10-01 17:39:51 +00007886 // Reference types are handled here since all uses of references are
7887 // bad, not just r-value uses.
7888 void VisitDeclRefExpr(DeclRefExpr *E) {
7889 if (isReferenceType)
7890 HandleDeclRefExpr(E);
7891 }
7892
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007893 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007894 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007895 (isRecordType && E->getCastKind() == CK_NoOp))
7896 HandleValue(E->getSubExpr());
7897
7898 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007899 }
7900
Richard Trieu898267f2011-09-01 21:44:13 +00007901 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007902 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007903 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007904
Richard Trieu6b2cc422012-10-03 00:41:36 +00007905 // Warn when a non-static method call is followed by non-static member
7906 // field accesses, which is followed by a DeclRefExpr.
7907 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7908 bool Warn = (MD && !MD->isStatic());
7909 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7910 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7911 if (!isa<FieldDecl>(ME->getMemberDecl()))
7912 Warn = false;
7913 Base = ME->getBase()->IgnoreParenImpCasts();
7914 }
Richard Trieu898267f2011-09-01 21:44:13 +00007915
Richard Trieu6b2cc422012-10-03 00:41:36 +00007916 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7917 if (Warn)
7918 HandleDeclRefExpr(DRE);
7919 return;
7920 }
7921
7922 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7923 // Visit that expression.
7924 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007925 }
7926
Richard Trieu8af742a2013-03-26 03:41:40 +00007927 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7928 if (E->getNumArgs() > 0)
7929 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7930 HandleDeclRefExpr(DRE);
7931
7932 Inherited::VisitCXXOperatorCallExpr(E);
7933 }
7934
Richard Trieu898267f2011-09-01 21:44:13 +00007935 void VisitUnaryOperator(UnaryOperator *E) {
7936 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007937 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7938 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7939 if (!isPODType)
7940 HandleValue(E->getSubExpr());
7941 return;
7942 }
Richard Trieu898267f2011-09-01 21:44:13 +00007943 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007944 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007945
7946 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7947
Richard Trieu898267f2011-09-01 21:44:13 +00007948 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007949 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007950 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007951 unsigned diag;
7952 if (isReferenceType) {
7953 diag = diag::warn_uninit_self_reference_in_reference_init;
7954 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7955 diag = diag::warn_static_self_reference_in_init;
7956 } else {
7957 diag = diag::warn_uninit_self_reference_in_init;
7958 }
7959
Richard Trieu898267f2011-09-01 21:44:13 +00007960 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007961 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007962 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007963 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007964 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007965 }
7966 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007967
Richard Trieu568f7852012-10-01 17:39:51 +00007968 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7969 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7970 bool DirectInit) {
7971 // Parameters arguments are occassionially constructed with itself,
7972 // for instance, in recursive functions. Skip them.
7973 if (isa<ParmVarDecl>(OrigDecl))
7974 return;
7975
7976 E = E->IgnoreParens();
7977
7978 // Skip checking T a = a where T is not a record or reference type.
7979 // Doing so is a way to silence uninitialized warnings.
7980 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7981 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7982 if (ICE->getCastKind() == CK_LValueToRValue)
7983 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7984 if (DRE->getDecl() == OrigDecl)
7985 return;
7986
7987 SelfReferenceChecker(S, OrigDecl).Visit(E);
7988 }
Richard Trieu898267f2011-09-01 21:44:13 +00007989}
7990
Douglas Gregor09f41cf2009-01-14 15:45:31 +00007991/// AddInitializerToDecl - Adds the initializer Init to the
7992/// declaration dcl. If DirectInit is true, this is C++ direct
7993/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00007994void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
7995 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00007996 // If there is no declaration, there was an error parsing it. Just ignore
7997 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00007998 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00007999 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008000
Douglas Gregor021c3b32009-03-11 23:00:04 +00008001 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8002 // With declarators parsed the way they are, the parser cannot
8003 // distinguish between a normal initializer and a pure-specifier.
8004 // Thus this grotesque test.
8005 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008006 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008007 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8008 CheckPureMethod(Method, Init->getSourceRange());
8009 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008010 Diag(Method->getLocation(), diag::err_member_function_initialization)
8011 << Method->getDeclName() << Init->getSourceRange();
8012 Method->setInvalidDecl();
8013 }
8014 return;
8015 }
8016
Steve Naroff410e3e22007-09-12 20:13:48 +00008017 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8018 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008019 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8020 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008021 RealDecl->setInvalidDecl();
8022 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008023 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008024 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8025
Richard Smith01888722011-12-15 19:20:59 +00008026 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008027 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008028 Expr *DeduceInit = Init;
8029 // Initializer could be a C++ direct-initializer. Deduction only works if it
8030 // contains exactly one expression.
8031 if (CXXDirectInit) {
8032 if (CXXDirectInit->getNumExprs() == 0) {
8033 // It isn't possible to write this directly, but it is possible to
8034 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008035 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008036 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8037 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008038 << VDecl->getDeclName() << VDecl->getType()
8039 << VDecl->getSourceRange();
8040 RealDecl->setInvalidDecl();
8041 return;
8042 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008043 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008044 VDecl->isInitCapture()
8045 ? diag::err_init_capture_multiple_expressions
8046 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008047 << VDecl->getDeclName() << VDecl->getType()
8048 << VDecl->getSourceRange();
8049 RealDecl->setInvalidDecl();
8050 return;
8051 } else {
8052 DeduceInit = CXXDirectInit->getExpr(0);
8053 }
8054 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008055
8056 // Expressions default to 'id' when we're in a debugger.
8057 bool DefaultedToAuto = false;
8058 if (getLangOpts().DebuggerCastResultToId &&
8059 Init->getType() == Context.UnknownAnyTy) {
8060 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8061 if (Result.isInvalid()) {
8062 VDecl->setInvalidDecl();
8063 return;
8064 }
8065 Init = Result.take();
8066 DefaultedToAuto = true;
8067 }
Richard Smith9b131752013-04-30 21:23:01 +00008068
8069 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008070 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008071 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008072 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008073 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008074 RealDecl->setInvalidDecl();
8075 return;
8076 }
Richard Smith9b131752013-04-30 21:23:01 +00008077 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008078 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008079
John McCallf85e1932011-06-15 23:02:42 +00008080 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008081 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008082 VDecl->setInvalidDecl();
8083
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008084 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8085 // 'id' instead of a specific object type prevents most of our usual checks.
8086 // We only want to warn outside of template instantiations, though:
8087 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008088 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008089 DeducedType->isObjCIdType()) {
8090 SourceLocation Loc =
8091 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008092 Diag(Loc, diag::warn_auto_var_is_id)
8093 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8094 }
8095
Richard Smith34b41d92011-02-20 03:19:35 +00008096 // If this is a redeclaration, check that the type we just deduced matches
8097 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008098 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8099 // We never need to merge the type, because we cannot form an incomplete
8100 // array of auto, nor deduce such a type.
8101 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8102 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008103
8104 // Check the deduced type is valid for a variable declaration.
8105 CheckVariableDeclarationType(VDecl);
8106 if (VDecl->isInvalidDecl())
8107 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008108 }
Richard Smith01888722011-12-15 19:20:59 +00008109
8110 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8111 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8112 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8113 VDecl->setInvalidDecl();
8114 return;
8115 }
8116
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008117 if (!VDecl->getType()->isDependentType()) {
8118 // A definition must end up with a complete type, which means it must be
8119 // complete with the restriction that an array type might be completed by
8120 // the initializer; note that later code assumes this restriction.
8121 QualType BaseDeclType = VDecl->getType();
8122 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8123 BaseDeclType = Array->getElementType();
8124 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8125 diag::err_typecheck_decl_incomplete_type)) {
8126 RealDecl->setInvalidDecl();
8127 return;
8128 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008129
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008130 // The variable can not have an abstract class type.
8131 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8132 diag::err_abstract_type_in_decl,
8133 AbstractVariableType))
8134 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008135 }
8136
Sebastian Redl31310a22010-02-01 20:16:42 +00008137 const VarDecl *Def;
8138 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008139 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008140 << VDecl->getDeclName();
8141 Diag(Def->getLocation(), diag::note_previous_definition);
8142 VDecl->setInvalidDecl();
8143 return;
8144 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008145
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008146 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008147 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008148 // C++ [class.static.data]p4
8149 // If a static data member is of const integral or const
8150 // enumeration type, its declaration in the class definition can
8151 // specify a constant-initializer which shall be an integral
8152 // constant expression (5.19). In that case, the member can appear
8153 // in integral constant expressions. The member shall still be
8154 // defined in a namespace scope if it is used in the program and the
8155 // namespace scope definition shall not contain an initializer.
8156 //
8157 // We already performed a redefinition check above, but for static
8158 // data members we also need to check whether there was an in-class
8159 // declaration with an initializer.
8160 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008161 Diag(VDecl->getLocation(), diag::err_redefinition)
8162 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008163 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8164 return;
8165 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008166
Douglas Gregora31040f2010-12-16 01:31:22 +00008167 if (VDecl->hasLocalStorage())
8168 getCurFunction()->setHasBranchProtectedScope();
8169
8170 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8171 VDecl->setInvalidDecl();
8172 return;
8173 }
8174 }
John McCalle46f62c2010-08-01 01:24:59 +00008175
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008176 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8177 // a kernel function cannot be initialized."
8178 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8179 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8180 VDecl->setInvalidDecl();
8181 return;
8182 }
8183
Steve Naroffbb204692007-09-12 14:07:44 +00008184 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008185 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008186 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008187
Douglas Gregor1344e942013-03-07 22:57:58 +00008188 // Expressions default to 'id' when we're in a debugger
8189 // and we are assigning it to a variable of Objective-C pointer type.
8190 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8191 Init->getType() == Context.UnknownAnyTy) {
8192 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8193 if (Result.isInvalid()) {
8194 VDecl->setInvalidDecl();
8195 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008196 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008197 Init = Result.take();
8198 }
Richard Smith01888722011-12-15 19:20:59 +00008199
8200 // Perform the initialization.
8201 if (!VDecl->isInvalidDecl()) {
8202 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8203 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008204 = DirectInit ?
8205 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8206 Init->getLocStart(),
8207 Init->getLocEnd())
8208 : InitializationKind::CreateDirectList(
8209 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008210 : InitializationKind::CreateCopy(VDecl->getLocation(),
8211 Init->getLocStart());
8212
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008213 MultiExprArg Args = Init;
8214 if (CXXDirectInit)
8215 Args = MultiExprArg(CXXDirectInit->getExprs(),
8216 CXXDirectInit->getNumExprs());
8217
8218 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8219 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008220 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008221 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008222 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008223 }
Richard Smith01888722011-12-15 19:20:59 +00008224
8225 Init = Result.takeAs<Expr>();
8226 }
8227
Richard Trieu568f7852012-10-01 17:39:51 +00008228 // Check for self-references within variable initializers.
8229 // Variables declared within a function/method body (except for references)
8230 // are handled by a dataflow analysis.
8231 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8232 VDecl->getType()->isReferenceType()) {
8233 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8234 }
8235
Richard Smith01888722011-12-15 19:20:59 +00008236 // If the type changed, it means we had an incomplete type that was
8237 // completed by the initializer. For example:
8238 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008239 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008240 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008241 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008242
Jordan Rosee10f4d32012-09-15 02:48:31 +00008243 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008244 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8245
Jordan Rosee10f4d32012-09-15 02:48:31 +00008246 if (VDecl->hasAttr<BlocksAttr>())
8247 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008248
8249 // It is safe to assign a weak reference into a strong variable.
8250 // Although this code can still have problems:
8251 // id x = self.weakProp;
8252 // id y = self.weakProp;
8253 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8254 // paths through the function. This should be revisited if
8255 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008256 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008257 DiagnosticsEngine::Level Level =
8258 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8259 Init->getLocStart());
8260 if (Level != DiagnosticsEngine::Ignored)
8261 getCurFunction()->markSafeWeakUse(Init);
8262 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008263 }
8264
Richard Smith41956372013-01-14 22:39:08 +00008265 // The initialization is usually a full-expression.
8266 //
8267 // FIXME: If this is a braced initialization of an aggregate, it is not
8268 // an expression, and each individual field initializer is a separate
8269 // full-expression. For instance, in:
8270 //
8271 // struct Temp { ~Temp(); };
8272 // struct S { S(Temp); };
8273 // struct T { S a, b; } t = { Temp(), Temp() }
8274 //
8275 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008276 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8277 false,
8278 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008279 if (Result.isInvalid()) {
8280 VDecl->setInvalidDecl();
8281 return;
8282 }
8283 Init = Result.take();
8284
Richard Smith01888722011-12-15 19:20:59 +00008285 // Attach the initializer to the decl.
8286 VDecl->setInit(Init);
8287
8288 if (VDecl->isLocalVarDecl()) {
8289 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8290 // static storage duration shall be constant expressions or string literals.
8291 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008292 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8293 if (VDecl->getStorageClass() == SC_Static)
8294 CheckForConstantInitializer(Init, DclT);
8295 // C89 is stricter than C99 for non-static aggregate types.
8296 // C89 6.5.7p3: All the expressions [...] in an initializer list
8297 // for an object that has aggregate or union type shall be
8298 // constant expressions.
8299 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008300 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008301 !Init->isConstantInitializer(Context, false))
8302 Diag(Init->getExprLoc(),
8303 diag::ext_aggregate_init_not_constant)
8304 << Init->getSourceRange();
8305 }
Mike Stump1eb44332009-09-09 15:08:12 +00008306 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008307 VDecl->getLexicalDeclContext()->isRecord()) {
8308 // This is an in-class initialization for a static data member, e.g.,
8309 //
8310 // struct S {
8311 // static const int value = 17;
8312 // };
8313
Douglas Gregor021c3b32009-03-11 23:00:04 +00008314 // C++ [class.mem]p4:
8315 // A member-declarator can contain a constant-initializer only
8316 // if it declares a static member (9.4) of const integral or
8317 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008318 //
Richard Smith01888722011-12-15 19:20:59 +00008319 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008320 // If a non-volatile const static data member is of integral or
8321 // enumeration type, its declaration in the class definition can
8322 // specify a brace-or-equal-initializer in which every initalizer-clause
8323 // that is an assignment-expression is a constant expression. A static
8324 // data member of literal type can be declared in the class definition
8325 // with the constexpr specifier; if so, its declaration shall specify a
8326 // brace-or-equal-initializer in which every initializer-clause that is
8327 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008328
8329 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008330 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008331
Richard Smithc6d990a2011-09-29 19:11:37 +00008332 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008333 // type. We separately check that every constexpr variable is of literal
8334 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008335 } else if (VDecl->isConstexpr()) {
8336
John McCall4e635642010-09-10 23:21:22 +00008337 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008338 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008339 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8340 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008341 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008342
8343 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008344 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008345 // Check whether the expression is a constant expression.
8346 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008347 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008348 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008349 // in-class initializer cannot be volatile.
8350 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8351 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008352 ; // Nothing to check.
8353 else if (Init->isIntegerConstantExpr(Context, &Loc))
8354 ; // Ok, it's an ICE!
8355 else if (Init->isEvaluatable(Context)) {
8356 // If we can constant fold the initializer through heroics, accept it,
8357 // but report this as a use of an extension for -pedantic.
8358 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8359 << Init->getSourceRange();
8360 } else {
8361 // Otherwise, this is some crazy unknown case. Report the issue at the
8362 // location provided by the isIntegerConstantExpr failed check.
8363 Diag(Loc, diag::err_in_class_initializer_non_constant)
8364 << Init->getSourceRange();
8365 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008366 }
8367
Richard Smith01888722011-12-15 19:20:59 +00008368 // We allow foldable floating-point constants as an extension.
8369 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008370 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8371 // it anyway and provide a fixit to add the 'constexpr'.
8372 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008373 Diag(VDecl->getLocation(),
8374 diag::ext_in_class_initializer_float_type_cxx11)
8375 << DclT << Init->getSourceRange();
8376 Diag(VDecl->getLocStart(),
8377 diag::note_in_class_initializer_float_type_cxx11)
8378 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008379 } else {
8380 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8381 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008382
Richard Smithb4b1d692013-01-25 04:22:16 +00008383 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8384 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8385 << Init->getSourceRange();
8386 VDecl->setInvalidDecl();
8387 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008388 }
Richard Smith947be192011-09-29 23:18:34 +00008389
Richard Smith01888722011-12-15 19:20:59 +00008390 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008391 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008392 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008393 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008394 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8395 VDecl->setConstexpr(true);
8396
Richard Smithc6d990a2011-09-29 19:11:37 +00008397 } else {
8398 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008399 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008400 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008401 }
Steve Naroff248a7532008-04-15 22:42:06 +00008402 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008403 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008404 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008405 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008406 VDecl->isExternC())) &&
8407 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008408 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008409
Richard Smith01888722011-12-15 19:20:59 +00008410 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008411 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008412 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008413 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8414 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8415 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008416 !Init->isConstantInitializer(
8417 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008418 // GNU C++98 edits for __thread, [basic.start.init]p4:
8419 // An object of thread storage duration shall not require dynamic
8420 // initialization.
8421 // FIXME: Need strict checking here.
8422 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8423 if (getLangOpts().CPlusPlus11)
8424 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8425 }
Steve Naroffbb204692007-09-12 14:07:44 +00008426 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008427
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008428 // We will represent direct-initialization similarly to copy-initialization:
8429 // int x(1); -as-> int x = 1;
8430 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8431 //
8432 // Clients that want to distinguish between the two forms, can check for
8433 // direct initializer using VarDecl::getInitStyle().
8434 // A major benefit is that clients that don't particularly care about which
8435 // exactly form was it (like the CodeGen) can handle both cases without
8436 // special case code.
8437
8438 // C++ 8.5p11:
8439 // The form of initialization (using parentheses or '=') is generally
8440 // insignificant, but does matter when the entity being initialized has a
8441 // class type.
8442 if (CXXDirectInit) {
8443 assert(DirectInit && "Call-style initializer must be direct init.");
8444 VDecl->setInitStyle(VarDecl::CallInit);
8445 } else if (DirectInit) {
8446 // This must be list-initialization. No other way is direct-initialization.
8447 VDecl->setInitStyle(VarDecl::ListInit);
8448 }
8449
John McCall2998d6b2011-01-19 11:48:09 +00008450 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008451}
8452
John McCall7727acf2010-03-31 02:13:20 +00008453/// ActOnInitializerError - Given that there was an error parsing an
8454/// initializer for the given declaration, try to return to some form
8455/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008456void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008457 // Our main concern here is re-establishing invariants like "a
8458 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008459 if (!D || D->isInvalidDecl()) return;
8460
8461 VarDecl *VD = dyn_cast<VarDecl>(D);
8462 if (!VD) return;
8463
Richard Smith34b41d92011-02-20 03:19:35 +00008464 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008465 if (ParsingInitForAutoVars.count(D)) {
8466 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008467 return;
8468 }
8469
John McCall7727acf2010-03-31 02:13:20 +00008470 QualType Ty = VD->getType();
8471 if (Ty->isDependentType()) return;
8472
8473 // Require a complete type.
8474 if (RequireCompleteType(VD->getLocation(),
8475 Context.getBaseElementType(Ty),
8476 diag::err_typecheck_decl_incomplete_type)) {
8477 VD->setInvalidDecl();
8478 return;
8479 }
8480
8481 // Require an abstract type.
8482 if (RequireNonAbstractType(VD->getLocation(), Ty,
8483 diag::err_abstract_type_in_decl,
8484 AbstractVariableType)) {
8485 VD->setInvalidDecl();
8486 return;
8487 }
8488
8489 // Don't bother complaining about constructors or destructors,
8490 // though.
8491}
8492
John McCalld226f652010-08-21 09:40:31 +00008493void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008494 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008495 // If there is no declaration, there was an error parsing it. Just ignore it.
8496 if (RealDecl == 0)
8497 return;
8498
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008499 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8500 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008501
Richard Smithdd4b3502011-12-25 21:17:58 +00008502 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008503 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008504 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8505 << Var->getDeclName() << Type;
8506 Var->setInvalidDecl();
8507 return;
8508 }
Mike Stump1eb44332009-09-09 15:08:12 +00008509
Richard Smithdd4b3502011-12-25 21:17:58 +00008510 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008511 // the constexpr specifier; if so, its declaration shall specify
8512 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008513 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8514 // the definition of a variable [...] or the declaration of a static data
8515 // member.
8516 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8517 if (Var->isStaticDataMember())
8518 Diag(Var->getLocation(),
8519 diag::err_constexpr_static_mem_var_requires_init)
8520 << Var->getDeclName();
8521 else
8522 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008523 Var->setInvalidDecl();
8524 return;
8525 }
8526
Douglas Gregor60c93c92010-02-09 07:26:29 +00008527 switch (Var->isThisDeclarationADefinition()) {
8528 case VarDecl::Definition:
8529 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8530 break;
8531
8532 // We have an out-of-line definition of a static data member
8533 // that has an in-class initializer, so we type-check this like
8534 // a declaration.
8535 //
8536 // Fall through
8537
8538 case VarDecl::DeclarationOnly:
8539 // It's only a declaration.
8540
8541 // Block scope. C99 6.7p7: If an identifier for an object is
8542 // declared with no linkage (C99 6.2.2p6), the type for the
8543 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008544 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008545 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008546 RequireCompleteType(Var->getLocation(), Type,
8547 diag::err_typecheck_decl_incomplete_type))
8548 Var->setInvalidDecl();
8549
8550 // Make sure that the type is not abstract.
8551 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8552 RequireNonAbstractType(Var->getLocation(), Type,
8553 diag::err_abstract_type_in_decl,
8554 AbstractVariableType))
8555 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008556 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008557 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008558 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008559 Diag(Var->getLocation(), diag::note_private_extern);
8560 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008561
Douglas Gregor60c93c92010-02-09 07:26:29 +00008562 return;
8563
8564 case VarDecl::TentativeDefinition:
8565 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8566 // object that has file scope without an initializer, and without a
8567 // storage-class specifier or with the storage-class specifier "static",
8568 // constitutes a tentative definition. Note: A tentative definition with
8569 // external linkage is valid (C99 6.2.2p5).
8570 if (!Var->isInvalidDecl()) {
8571 if (const IncompleteArrayType *ArrayT
8572 = Context.getAsIncompleteArrayType(Type)) {
8573 if (RequireCompleteType(Var->getLocation(),
8574 ArrayT->getElementType(),
8575 diag::err_illegal_decl_array_incomplete_type))
8576 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008577 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008578 // C99 6.9.2p3: If the declaration of an identifier for an object is
8579 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8580 // declared type shall not be an incomplete type.
8581 // NOTE: code such as the following
8582 // static struct s;
8583 // struct s { int a; };
8584 // is accepted by gcc. Hence here we issue a warning instead of
8585 // an error and we do not invalidate the static declaration.
8586 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008587 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008588 RequireCompleteType(Var->getLocation(), Type,
8589 diag::ext_typecheck_decl_incomplete_type);
8590 }
8591 }
8592
8593 // Record the tentative definition; we're done.
8594 if (!Var->isInvalidDecl())
8595 TentativeDefinitions.push_back(Var);
8596 return;
8597 }
8598
8599 // Provide a specific diagnostic for uninitialized variable
8600 // definitions with incomplete array type.
8601 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008602 Diag(Var->getLocation(),
8603 diag::err_typecheck_incomplete_array_needs_initializer);
8604 Var->setInvalidDecl();
8605 return;
8606 }
8607
John McCallb567a8b2010-08-01 01:25:24 +00008608 // Provide a specific diagnostic for uninitialized variable
8609 // definitions with reference type.
8610 if (Type->isReferenceType()) {
8611 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8612 << Var->getDeclName()
8613 << SourceRange(Var->getLocation(), Var->getLocation());
8614 Var->setInvalidDecl();
8615 return;
8616 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008617
8618 // Do not attempt to type-check the default initializer for a
8619 // variable with dependent type.
8620 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008621 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008622
Douglas Gregor60c93c92010-02-09 07:26:29 +00008623 if (Var->isInvalidDecl())
8624 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008625
Douglas Gregor60c93c92010-02-09 07:26:29 +00008626 if (RequireCompleteType(Var->getLocation(),
8627 Context.getBaseElementType(Type),
8628 diag::err_typecheck_decl_incomplete_type)) {
8629 Var->setInvalidDecl();
8630 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008631 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008632
Douglas Gregor60c93c92010-02-09 07:26:29 +00008633 // The variable can not have an abstract class type.
8634 if (RequireNonAbstractType(Var->getLocation(), Type,
8635 diag::err_abstract_type_in_decl,
8636 AbstractVariableType)) {
8637 Var->setInvalidDecl();
8638 return;
8639 }
8640
Douglas Gregor4337dc72011-05-21 17:52:48 +00008641 // Check for jumps past the implicit initializer. C++0x
8642 // clarifies that this applies to a "variable with automatic
8643 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008644 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008645 // A program that jumps from a point where a variable with automatic
8646 // storage duration is not in scope to a point where it is in scope is
8647 // ill-formed unless the variable has scalar type, class type with a
8648 // trivial default constructor and a trivial destructor, a cv-qualified
8649 // version of one of these types, or an array of one of the preceding
8650 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008651 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008652 if (const RecordType *Record
8653 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008654 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008655 // Mark the function for further checking even if the looser rules of
8656 // C++11 do not require such checks, so that we can diagnose
8657 // incompatibilities with C++98.
8658 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008659 getCurFunction()->setHasBranchProtectedScope();
8660 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008661 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008662
8663 // C++03 [dcl.init]p9:
8664 // If no initializer is specified for an object, and the
8665 // object is of (possibly cv-qualified) non-POD class type (or
8666 // array thereof), the object shall be default-initialized; if
8667 // the object is of const-qualified type, the underlying class
8668 // type shall have a user-declared default
8669 // constructor. Otherwise, if no initializer is specified for
8670 // a non- static object, the object and its subobjects, if
8671 // any, have an indeterminate initial value); if the object
8672 // or any of its subobjects are of const-qualified type, the
8673 // program is ill-formed.
8674 // C++0x [dcl.init]p11:
8675 // If no initializer is specified for an object, the object is
8676 // default-initialized; [...].
8677 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8678 InitializationKind Kind
8679 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008680
8681 InitializationSequence InitSeq(*this, Entity, Kind, None);
8682 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008683 if (Init.isInvalid())
8684 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008685 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008686 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008687 // This is important for template substitution.
8688 Var->setInitStyle(VarDecl::CallInit);
8689 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008690
John McCall2998d6b2011-01-19 11:48:09 +00008691 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008692 }
8693}
8694
Richard Smithad762fc2011-04-14 22:09:26 +00008695void Sema::ActOnCXXForRangeDecl(Decl *D) {
8696 VarDecl *VD = dyn_cast<VarDecl>(D);
8697 if (!VD) {
8698 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8699 D->setInvalidDecl();
8700 return;
8701 }
8702
8703 VD->setCXXForRangeDecl(true);
8704
8705 // for-range-declaration cannot be given a storage class specifier.
8706 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008707 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008708 case SC_None:
8709 break;
8710 case SC_Extern:
8711 Error = 0;
8712 break;
8713 case SC_Static:
8714 Error = 1;
8715 break;
8716 case SC_PrivateExtern:
8717 Error = 2;
8718 break;
8719 case SC_Auto:
8720 Error = 3;
8721 break;
8722 case SC_Register:
8723 Error = 4;
8724 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008725 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008726 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008727 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008728 if (VD->isConstexpr())
8729 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008730 if (Error != -1) {
8731 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8732 << VD->getDeclName() << Error;
8733 D->setInvalidDecl();
8734 }
8735}
8736
John McCall2998d6b2011-01-19 11:48:09 +00008737void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8738 if (var->isInvalidDecl()) return;
8739
John McCallf85e1932011-06-15 23:02:42 +00008740 // In ARC, don't allow jumps past the implicit initialization of a
8741 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008742 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008743 var->hasLocalStorage()) {
8744 switch (var->getType().getObjCLifetime()) {
8745 case Qualifiers::OCL_None:
8746 case Qualifiers::OCL_ExplicitNone:
8747 case Qualifiers::OCL_Autoreleasing:
8748 break;
8749
8750 case Qualifiers::OCL_Weak:
8751 case Qualifiers::OCL_Strong:
8752 getCurFunction()->setHasBranchProtectedScope();
8753 break;
8754 }
8755 }
8756
Eli Friedmane4851f22012-10-23 20:19:32 +00008757 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008758 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008759 getDiagnostics().getDiagnosticLevel(
8760 diag::warn_missing_variable_declarations,
8761 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008762 // Find a previous declaration that's not a definition.
8763 VarDecl *prev = var->getPreviousDecl();
8764 while (prev && prev->isThisDeclarationADefinition())
8765 prev = prev->getPreviousDecl();
8766
8767 if (!prev)
8768 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8769 }
8770
Richard Smith6a570f62013-04-14 20:11:31 +00008771 if (var->getTLSKind() == VarDecl::TLS_Static &&
8772 var->getType().isDestructedType()) {
8773 // GNU C++98 edits for __thread, [basic.start.term]p3:
8774 // The type of an object with thread storage duration shall not
8775 // have a non-trivial destructor.
8776 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8777 if (getLangOpts().CPlusPlus11)
8778 Diag(var->getLocation(), diag::note_use_thread_local);
8779 }
8780
John McCall2998d6b2011-01-19 11:48:09 +00008781 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008782 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008783
Richard Smitha67d5032012-11-09 23:03:14 +00008784 QualType type = var->getType();
8785 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008786
8787 // __block variables might require us to capture a copy-initializer.
8788 if (var->hasAttr<BlocksAttr>()) {
8789 // It's currently invalid to ever have a __block variable with an
8790 // array type; should we diagnose that here?
8791
8792 // Regardless, we don't want to ignore array nesting when
8793 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008794 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008795 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008796 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008797 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008798 ExprResult result
8799 = PerformMoveOrCopyInitialization(
8800 InitializedEntity::InitializeBlock(poi, type, false),
8801 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008802 if (!result.isInvalid()) {
8803 result = MaybeCreateExprWithCleanups(result);
8804 Expr *init = result.takeAs<Expr>();
8805 Context.setBlockVarCopyInits(var, init);
8806 }
8807 }
8808 }
8809
Richard Smith66f85712011-11-07 22:16:17 +00008810 Expr *Init = var->getInit();
8811 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008812 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008813
Richard Smith9568f0c2012-10-29 18:26:47 +00008814 if (!var->getDeclContext()->isDependentContext() &&
8815 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008816 if (IsGlobal && !var->isConstexpr() &&
8817 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8818 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008819 != DiagnosticsEngine::Ignored) {
8820 // Warn about globals which don't have a constant initializer. Don't
8821 // warn about globals with a non-trivial destructor because we already
8822 // warned about them.
8823 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8824 if (!(RD && !RD->hasTrivialDestructor()) &&
8825 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8826 Diag(var->getLocation(), diag::warn_global_constructor)
8827 << Init->getSourceRange();
8828 }
Richard Smith099e7f62011-12-19 06:19:21 +00008829
Richard Smith099e7f62011-12-19 06:19:21 +00008830 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008831 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008832 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8833 SourceLocation DiagLoc = var->getLocation();
8834 // If the note doesn't add any useful information other than a source
8835 // location, fold it into the primary diagnostic.
8836 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8837 diag::note_invalid_subexpr_in_const_expr) {
8838 DiagLoc = Notes[0].first;
8839 Notes.clear();
8840 }
8841 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8842 << var << Init->getSourceRange();
8843 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8844 Diag(Notes[I].first, Notes[I].second);
8845 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008846 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008847 // Check whether the initializer of a const variable of integral or
8848 // enumeration type is an ICE now, since we can't tell whether it was
8849 // initialized by a constant expression if we check later.
8850 var->checkInitIsICE();
8851 }
Richard Smith66f85712011-11-07 22:16:17 +00008852 }
John McCall2998d6b2011-01-19 11:48:09 +00008853
8854 // Require the destructor.
8855 if (const RecordType *recordType = baseType->getAs<RecordType>())
8856 FinalizeVarWithDestructor(var, recordType);
8857}
8858
Richard Smith483b9f32011-02-21 20:05:19 +00008859/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8860/// any semantic actions necessary after any initializer has been attached.
8861void
8862Sema::FinalizeDeclaration(Decl *ThisDecl) {
8863 // Note that we are no longer parsing the initializer for this declaration.
8864 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008865
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008866 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008867 if (!VD)
8868 return;
8869
Rafael Espindola29535ba2013-08-16 23:18:50 +00008870 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8871 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8872 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8873 VD->dropAttr<UsedAttr>();
8874 }
8875 }
8876
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008877 if (!VD->isInvalidDecl() &&
8878 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8879 if (const VarDecl *Def = VD->getDefinition()) {
8880 if (Def->hasAttr<AliasAttr>()) {
8881 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8882 << VD->getDeclName();
8883 Diag(Def->getLocation(), diag::note_previous_definition);
8884 VD->setInvalidDecl();
8885 }
8886 }
8887 }
8888
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008889 const DeclContext *DC = VD->getDeclContext();
8890 // If there's a #pragma GCC visibility in scope, and this isn't a class
8891 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008892 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008893 AddPushedVisibilityAttribute(VD);
8894
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008895 if (VD->isFileVarDecl())
8896 MarkUnusedFileScopedDecl(VD);
8897
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008898 // Now we have parsed the initializer and can update the table of magic
8899 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008900 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8901 !VD->getType()->isIntegralOrEnumerationType())
8902 return;
8903
8904 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8905 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8906 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8907 I != E; ++I) {
8908 const Expr *MagicValueExpr = VD->getInit();
8909 if (!MagicValueExpr) {
8910 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008911 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008912 llvm::APSInt MagicValueInt;
8913 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8914 Diag(I->getRange().getBegin(),
8915 diag::err_type_tag_for_datatype_not_ice)
8916 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8917 continue;
8918 }
8919 if (MagicValueInt.getActiveBits() > 64) {
8920 Diag(I->getRange().getBegin(),
8921 diag::err_type_tag_for_datatype_too_large)
8922 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8923 continue;
8924 }
8925 uint64_t MagicValue = MagicValueInt.getZExtValue();
8926 RegisterTypeTagForDatatype(I->getArgumentKind(),
8927 MagicValue,
8928 I->getMatchingCType(),
8929 I->getLayoutCompatible(),
8930 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008931 }
Richard Smith483b9f32011-02-21 20:05:19 +00008932}
8933
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008934Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8935 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008936 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008937
8938 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008939 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008940
David Majnemeraa824612013-09-17 23:57:10 +00008941 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008942 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008943 if (Decl *D = Group[i]) {
8944 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8945 if (!FirstDeclaratorInGroup)
8946 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008947 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008948 }
Richard Smith406c38e2011-02-23 00:37:57 +00008949
Eli Friedman5e867c82013-07-10 00:30:46 +00008950 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008951 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008952 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008953 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8954 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8955 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008956 }
David Blaikie66cff722012-11-14 01:52:05 +00008957
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008958 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008959}
8960
8961/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8962/// group, performing any necessary semantic checking.
8963Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008964Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008965 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008966 // C++0x [dcl.spec.auto]p7:
8967 // If the type deduced for the template parameter U is not the same in each
8968 // deduction, the program is ill-formed.
8969 // FIXME: When initializer-list support is added, a distinction is needed
8970 // between the deduced type U and the deduced type which 'auto' stands for.
8971 // auto a = 0, b = { 1, 2, 3 };
8972 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008973 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008974 QualType Deduced;
8975 CanQualType DeducedCanon;
8976 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008977 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00008978 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8979 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00008980 // Don't reissue diagnostics when instantiating a template.
8981 if (AT && D->isInvalidDecl())
8982 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00008983 QualType U = AT ? AT->getDeducedType() : QualType();
8984 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008985 CanQualType UCanon = Context.getCanonicalType(U);
8986 if (Deduced.isNull()) {
8987 Deduced = U;
8988 DeducedCanon = UCanon;
8989 DeducedDecl = D;
8990 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00008991 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
8992 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00008993 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00008994 << Deduced << DeducedDecl->getDeclName()
8995 << U << D->getDeclName()
8996 << DeducedDecl->getInit()->getSourceRange()
8997 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00008998 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008999 break;
9000 }
9001 }
9002 }
9003 }
9004 }
9005
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009006 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009007
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009008 return DeclGroupPtrTy::make(
9009 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009010}
Steve Naroffe1223f72007-08-28 03:03:08 +00009011
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009012void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009013 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009014}
9015
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009016void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009017 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009018 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009019 return;
9020
9021 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9022 Group[0]->getLocation())
9023 == DiagnosticsEngine::Ignored)
9024 return;
9025
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009026 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009027 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009028 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009029 // additional declaration references:
9030 // 'typedef struct S {} S;'
9031 // 'typedef struct S *S;'
9032 // 'struct S *pS;'
9033 // FinalizeDeclaratorGroup adds these as separate declarations.
9034 Decl *MaybeTagDecl = Group[0];
9035 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009036 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009037 }
9038 }
9039
9040 // See if there are any new comments that are not attached to a decl.
9041 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9042 if (!Comments.empty() &&
9043 !Comments.back()->isAttached()) {
9044 // There is at least one comment that not attached to a decl.
9045 // Maybe it should be attached to one of these decls?
9046 //
9047 // Note that this way we pick up not only comments that precede the
9048 // declaration, but also comments that *follow* the declaration -- thanks to
9049 // the lookahead in the lexer: we've consumed the semicolon and looked
9050 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009051 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009052 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009053 }
9054}
Chris Lattner682bf922009-03-29 16:50:03 +00009055
Chris Lattner04421082008-04-08 04:40:51 +00009056/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9057/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009058Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009059 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009060
Chris Lattner04421082008-04-08 04:40:51 +00009061 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009062
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009063 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009064 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009065 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009066 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009067 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009068 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9069 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009070 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009071 Diag(DS.getStorageClassSpecLoc(),
9072 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009073 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009074 }
Eli Friedman63054b32009-04-19 20:27:55 +00009075
Richard Smithec642442013-04-12 22:46:28 +00009076 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9077 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9078 << DeclSpec::getSpecifierName(TSCS);
9079 if (DS.isConstexprSpecified())
9080 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009081 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009082
Richard Smithec642442013-04-12 22:46:28 +00009083 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009084
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009085 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009086 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009087
David Blaikie4e4d0842012-03-11 07:00:24 +00009088 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009089 // Check that there are no default arguments inside the type of this
9090 // parameter.
9091 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009092
9093 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9094 if (D.getCXXScopeSpec().isSet()) {
9095 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9096 << D.getCXXScopeSpec().getRange();
9097 D.getCXXScopeSpec().clear();
9098 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009099 }
9100
Sean Hunt7533a5b2010-11-03 01:07:06 +00009101 // Ensure we have a valid name
9102 IdentifierInfo *II = 0;
9103 if (D.hasName()) {
9104 II = D.getIdentifier();
9105 if (!II) {
9106 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9107 << GetNameForDeclarator(D).getName().getAsString();
9108 D.setInvalidType(true);
9109 }
9110 }
9111
Chris Lattnerd84aac12010-02-22 00:40:25 +00009112 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009113 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009114 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9115 ForRedeclaration);
9116 LookupName(R, S);
9117 if (R.isSingleResult()) {
9118 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009119 if (PrevDecl->isTemplateParameter()) {
9120 // Maybe we will complain about the shadowed template parameter.
9121 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9122 // Just pretend that we didn't see the previous declaration.
9123 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009124 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009125 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009126 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009127
Chris Lattnercf79b012009-01-21 02:38:50 +00009128 // Recover by removing the name
9129 II = 0;
9130 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009131 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009132 }
Chris Lattner04421082008-04-08 04:40:51 +00009133 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009134 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009135
John McCall7a9813c2010-01-22 00:28:27 +00009136 // Temporarily put parameter variables in the translation unit, not
9137 // the enclosing context. This prevents them from accidentally
9138 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009139 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009140 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009141 D.getIdentifierLoc(), II,
9142 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009143 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009144
Chris Lattnereaaebc72009-04-25 08:06:05 +00009145 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009146 New->setInvalidDecl();
9147
9148 assert(S->isFunctionPrototypeScope());
9149 assert(S->getFunctionPrototypeDepth() >= 1);
9150 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9151 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009152
Douglas Gregor44b43212008-12-11 16:49:14 +00009153 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009154 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009155 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009156 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009157
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009158 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009159
Douglas Gregore3895852011-09-12 18:37:38 +00009160 if (D.getDeclSpec().isModulePrivateSpecified())
9161 Diag(New->getLocation(), diag::err_module_private_local)
9162 << 1 << New->getDeclName()
9163 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9164 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9165
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009166 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009167 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9168 }
John McCalld226f652010-08-21 09:40:31 +00009169 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009170}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009171
John McCall82dc0092010-06-04 11:21:44 +00009172/// \brief Synthesizes a variable for a parameter arising from a
9173/// typedef.
9174ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9175 SourceLocation Loc,
9176 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009177 /* FIXME: setting StartLoc == Loc.
9178 Would it be worth to modify callers so as to provide proper source
9179 location for the unnamed parameters, embedding the parameter's type? */
9180 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009181 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009182 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009183 Param->setImplicit();
9184 return Param;
9185}
9186
John McCallfbce0e12010-08-24 09:05:15 +00009187void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9188 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009189 // Don't diagnose unused-parameter errors in template instantiations; we
9190 // will already have done so in the template itself.
9191 if (!ActiveTemplateInstantiations.empty())
9192 return;
9193
9194 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009195 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009196 !(*Param)->hasAttr<UnusedAttr>()) {
9197 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9198 << (*Param)->getDeclName();
9199 }
9200 }
9201}
9202
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009203void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9204 ParmVarDecl * const *ParamEnd,
9205 QualType ReturnTy,
9206 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009207 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009208 return;
9209
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009210 // Warn if the return value is pass-by-value and larger than the specified
9211 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009212 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009213 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009214 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009215 Diag(D->getLocation(), diag::warn_return_value_size)
9216 << D->getDeclName() << Size;
9217 }
9218
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009219 // Warn if any parameter is pass-by-value and larger than the specified
9220 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009221 for (; Param != ParamEnd; ++Param) {
9222 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009223 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009224 continue;
9225 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009226 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009227 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9228 << (*Param)->getDeclName() << Size;
9229 }
9230}
9231
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009232ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9233 SourceLocation NameLoc, IdentifierInfo *Name,
9234 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009235 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009236 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009237 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009238 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009239 T->isObjCLifetimeType()) {
9240
9241 Qualifiers::ObjCLifetime lifetime;
9242
9243 // Special cases for arrays:
9244 // - if it's const, use __unsafe_unretained
9245 // - otherwise, it's an error
9246 if (T->isArrayType()) {
9247 if (!T.isConstQualified()) {
9248 DelayedDiagnostics.add(
9249 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009250 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009251 }
9252 lifetime = Qualifiers::OCL_ExplicitNone;
9253 } else {
9254 lifetime = T->getObjCARCImplicitLifetime();
9255 }
9256 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009257 }
9258
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009259 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009260 Context.getAdjustedParameterType(T),
9261 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009262 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009263
9264 // Parameters can not be abstract class types.
9265 // For record types, this is done by the AbstractClassUsageDiagnoser once
9266 // the class has been completely parsed.
9267 if (!CurContext->isRecord() &&
9268 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9269 AbstractParamType))
9270 New->setInvalidDecl();
9271
9272 // Parameter declarators cannot be interface types. All ObjC objects are
9273 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009274 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009275 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009276 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009277 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009278 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009279 T = Context.getObjCObjectPointerType(T);
9280 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009281 }
9282
9283 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9284 // duration shall not be qualified by an address-space qualifier."
9285 // Since all parameters have automatic store duration, they can not have
9286 // an address space.
9287 if (T.getAddressSpace() != 0) {
9288 Diag(NameLoc, diag::err_arg_with_address_space);
9289 New->setInvalidDecl();
9290 }
9291
9292 return New;
9293}
9294
Douglas Gregora3a83512009-04-01 23:51:29 +00009295void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9296 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009297 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009298
Reid Spencer5f016e22007-07-11 17:01:13 +00009299 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9300 // for a K&R function.
9301 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009302 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9303 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009304 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009305 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009306 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009307 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009308 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009309 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009310 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009311 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009312
Reid Spencer5f016e22007-07-11 17:01:13 +00009313 // Implicitly declare the argument as type 'int' for lack of a better
9314 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009315 AttributeFactory attrs;
9316 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009317 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009318 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009319 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009320 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009321 // Use the identifier location for the type source range.
9322 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9323 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009324 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9325 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009326 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009327 }
9328 }
Mike Stump1eb44332009-09-09 15:08:12 +00009329 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009330}
9331
Richard Smith87162c22012-04-17 22:30:01 +00009332Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009333 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009334 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009335 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009336
Douglas Gregor45fa5602011-11-07 20:56:01 +00009337 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009338 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009339 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009340}
9341
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009342static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9343 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009344 // Don't warn about invalid declarations.
9345 if (FD->isInvalidDecl())
9346 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009347
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009348 // Or declarations that aren't global.
9349 if (!FD->isGlobal())
9350 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009351
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009352 // Don't warn about C++ member functions.
9353 if (isa<CXXMethodDecl>(FD))
9354 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009355
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009356 // Don't warn about 'main'.
9357 if (FD->isMain())
9358 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009359
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009360 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009361 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009362 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009363
9364 // Don't warn about function templates.
9365 if (FD->getDescribedFunctionTemplate())
9366 return false;
9367
9368 // Don't warn about function template specializations.
9369 if (FD->isFunctionTemplateSpecialization())
9370 return false;
9371
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009372 // Don't warn for OpenCL kernels.
9373 if (FD->hasAttr<OpenCLKernelAttr>())
9374 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009375
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009376 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009377 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9378 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009379 // Ignore any declarations that occur in function or method
9380 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009381 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009382 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009383
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009384 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009385 if (FD->getNumParams() == 0)
9386 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009387 break;
9388 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009389
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009390 return MissingPrototype;
9391}
9392
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009393void
9394Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9395 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009396 // Don't complain if we're in GNU89 mode and the previous definition
9397 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009398 const FunctionDecl *Definition = EffectiveDefinition;
9399 if (!Definition)
9400 if (!FD->isDefined(Definition))
9401 return;
9402
9403 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009404 return;
9405
9406 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9407 Definition->getStorageClass() == SC_Extern)
9408 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009409 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009410 else
9411 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9412
9413 Diag(Definition->getLocation(), diag::note_previous_definition);
9414 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009415}
Faisal Valibef582b2013-10-23 16:10:50 +00009416static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9417 Sema &S) {
9418 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9419 S.PushLambdaScope();
9420 LambdaScopeInfo *LSI = S.getCurLambda();
9421 LSI->CallOperator = CallOperator;
9422 LSI->Lambda = LambdaClass;
9423 LSI->ReturnType = CallOperator->getResultType();
9424 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9425
9426 if (LCD == LCD_None)
9427 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9428 else if (LCD == LCD_ByCopy)
9429 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9430 else if (LCD == LCD_ByRef)
9431 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9432 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9433
9434 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9435 LSI->Mutable = !CallOperator->isConst();
9436
9437 // FIXME: Add the captures to the LSI.
9438}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009439
John McCalld226f652010-08-21 09:40:31 +00009440Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009441 // Clear the last template instantiation error context.
9442 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9443
Douglas Gregor52591bf2009-06-24 00:54:41 +00009444 if (!D)
9445 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009446 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009447
John McCalld226f652010-08-21 09:40:31 +00009448 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009449 FD = FunTmpl->getTemplatedDecl();
9450 else
John McCalld226f652010-08-21 09:40:31 +00009451 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009452 // If we are instantiating a generic lambda call operator, push
9453 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009454 // that's already been calculated (ActOnLambdaExpr) to prime the current
9455 // LambdaScopeInfo.
9456 // When the template operator is being specialized, the LambdaScopeInfo,
9457 // has to be properly restored so that tryCaptureVariable doesn't try
9458 // and capture any new variables. In addition when calculating potential
9459 // captures during transformation of nested lambdas, it is necessary to
9460 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009461 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009462 assert(ActiveTemplateInstantiations.size() &&
9463 "There should be an active template instantiation on the stack "
9464 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009465 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009466 }
9467 else
9468 // Enter a new function scope
9469 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009470
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009471 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009472 if (!FD->isLateTemplateParsed())
9473 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009474
Douglas Gregorcda9c672009-02-16 17:45:42 +00009475 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009476 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009477 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9478 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009479 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009480 FD->setInvalidDecl();
9481 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009482 }
9483
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009484 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009485 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9486 QualType ResultType = FD->getResultType();
9487 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009488 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009489 RequireCompleteType(FD->getLocation(), ResultType,
9490 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009491 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009492
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009493 // GNU warning -Wmissing-prototypes:
9494 // Warn if a global function is defined without a previous
9495 // prototype declaration. This warning is issued even if the
9496 // definition itself provides a prototype. The aim is to detect
9497 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009498 const FunctionDecl *PossibleZeroParamPrototype = 0;
9499 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009500 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009501
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009502 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009503 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009504 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009505 if (TypeSourceInfo *TI =
9506 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9507 TypeLoc TL = TI->getTypeLoc();
9508 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9509 Diag(PossibleZeroParamPrototype->getLocation(),
9510 diag::note_declaration_not_a_prototype)
9511 << PossibleZeroParamPrototype
9512 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9513 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009514 }
9515 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009516
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009517 if (FnBodyScope)
9518 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009519
Chris Lattner04421082008-04-08 04:40:51 +00009520 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009521 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9522 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009523
9524 // Introduce our parameters into the function scope
9525 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9526 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009527 Param->setOwningFunction(FD);
9528
Chris Lattner04421082008-04-08 04:40:51 +00009529 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009530 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009531 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009532
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009533 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009534 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009535 }
Chris Lattner04421082008-04-08 04:40:51 +00009536
James Molloy16f1f712012-02-29 10:24:19 +00009537 // If we had any tags defined in the function prototype,
9538 // introduce them into the function scope.
9539 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009540 for (ArrayRef<NamedDecl *>::iterator
9541 I = FD->getDeclsInPrototypeScope().begin(),
9542 E = FD->getDeclsInPrototypeScope().end();
9543 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009544 NamedDecl *D = *I;
9545
9546 // Some of these decls (like enums) may have been pinned to the translation unit
9547 // for lack of a real context earlier. If so, remove from the translation unit
9548 // and reattach to the current context.
9549 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9550 // Is the decl actually in the context?
9551 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9552 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9553 if (*DI == D) {
9554 Context.getTranslationUnitDecl()->removeDecl(D);
9555 break;
9556 }
9557 }
9558 // Either way, reassign the lexical decl context to our FunctionDecl.
9559 D->setLexicalDeclContext(CurContext);
9560 }
9561
9562 // If the decl has a non-null name, make accessible in the current scope.
9563 if (!D->getName().empty())
9564 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9565
9566 // Similarly, dive into enums and fish their constants out, making them
9567 // accessible in this scope.
9568 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9569 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9570 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009571 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009572 }
9573 }
9574 }
9575
Richard Smith87162c22012-04-17 22:30:01 +00009576 // Ensure that the function's exception specification is instantiated.
9577 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9578 ResolveExceptionSpec(D->getLocation(), FPT);
9579
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009580 // Checking attributes of current function definition
9581 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009582 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9583 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9584 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009585 // Microsoft accepts dllimport for functions defined within class scope.
9586 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009587 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009588 Diag(FD->getLocation(),
9589 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9590 << "dllimport";
9591 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009592 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009593 }
9594
9595 // Visual C++ appears to not think this is an issue, so only issue
9596 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009597 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009598 // If a symbol previously declared dllimport is later defined, the
9599 // attribute is ignored in subsequent references, and a warning is
9600 // emitted.
9601 Diag(FD->getLocation(),
9602 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009603 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009604 }
9605 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009606 // We want to attach documentation to original Decl (which might be
9607 // a function template).
9608 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009609 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009610}
9611
Douglas Gregor5077c382010-05-15 06:01:05 +00009612/// \brief Given the set of return statements within a function body,
9613/// compute the variables that are subject to the named return value
9614/// optimization.
9615///
9616/// Each of the variables that is subject to the named return value
9617/// optimization will be marked as NRVO variables in the AST, and any
9618/// return statement that has a marked NRVO variable as its NRVO candidate can
9619/// use the named return value optimization.
9620///
9621/// This function applies a very simplistic algorithm for NRVO: if every return
9622/// statement in the function has the same NRVO candidate, that candidate is
9623/// the NRVO variable.
9624///
9625/// FIXME: Employ a smarter algorithm that accounts for multiple return
9626/// statements and the lifetimes of the NRVO candidates. We should be able to
9627/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009628void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009629 ReturnStmt **Returns = Scope->Returns.data();
9630
Douglas Gregor5077c382010-05-15 06:01:05 +00009631 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009632 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009633 if (!Returns[I]->getNRVOCandidate())
9634 return;
9635
9636 if (!NRVOCandidate)
9637 NRVOCandidate = Returns[I]->getNRVOCandidate();
9638 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9639 return;
9640 }
9641
9642 if (NRVOCandidate)
9643 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9644}
9645
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009646bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009647 if (!Consumer.shouldSkipFunctionBody(D))
9648 return false;
9649
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009650 if (isa<ObjCMethodDecl>(D))
9651 return true;
9652
9653 FunctionDecl *FD = 0;
9654 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9655 FD = FTD->getTemplatedDecl();
9656 else
9657 FD = cast<FunctionDecl>(D);
9658
9659 // We cannot skip the body of a function (or function template) which is
9660 // constexpr, since we may need to evaluate its body in order to parse the
9661 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009662 // We cannot skip the body of a function with an undeduced return type,
9663 // because any callers of that function need to know the type.
9664 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009665}
9666
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009667Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009668 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009669 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009670 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009671 MD->setHasSkippedBody();
9672 return ActOnFinishFunctionBody(Decl, 0);
9673}
9674
John McCallf312b1e2010-08-26 23:41:50 +00009675Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009676 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009677}
9678
John McCall9ae2f072010-08-23 23:25:46 +00009679Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9680 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009681 FunctionDecl *FD = 0;
9682 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9683 if (FunTmpl)
9684 FD = FunTmpl->getTemplatedDecl();
9685 else
9686 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9687
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009688 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009689 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009690
Douglas Gregord83d0402009-08-22 00:34:47 +00009691 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009692 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009693
Richard Smith25d8c852013-05-10 04:31:10 +00009694 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9695 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9696 // If the function has a deduced result type but contains no 'return'
9697 // statements, the result type as written must be exactly 'auto', and
9698 // the deduced result type is 'void'.
9699 if (!FD->getResultType()->getAs<AutoType>()) {
9700 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9701 << FD->getResultType();
9702 FD->setInvalidDecl();
9703 } else {
9704 // Substitute 'void' for the 'auto' in the type.
9705 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9706 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9707 Context.adjustDeducedFunctionResultType(
9708 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009709 }
9710 }
9711
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009712 // The only way to be included in UndefinedButUsed is if there is an
9713 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009714 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009715 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009716 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009717 UndefinedButUsed.erase(FD);
9718 else if (FD->isInlined() &&
9719 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9720 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9721 UndefinedButUsed.erase(FD);
9722 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009723
John McCall75d8ba32012-02-14 19:50:52 +00009724 // If the function implicitly returns zero (like 'main') or is naked,
9725 // don't complain about missing return statements.
9726 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009727 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009728
Francois Pichet6a247472011-05-11 02:14:46 +00009729 // MSVC permits the use of pure specifier (=0) on function definition,
9730 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009731 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009732 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9733
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009734 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009735 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009736 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9737 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009738
9739 // If this is a constructor, we need a vtable.
9740 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9741 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009742
Jordan Rose7dd900e2012-07-02 21:19:23 +00009743 // Try to apply the named return value optimization. We have to check
9744 // if we can do this here because lambdas keep return statements around
9745 // to deduce an implicit return type.
9746 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9747 !FD->isDependentContext())
9748 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009749 }
9750
Douglas Gregor76e3da52012-02-08 20:17:14 +00009751 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9752 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009753 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009754 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009755 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009756 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009757 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009758 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9759 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009760
9761 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009762 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009763 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009764 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009765 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9766 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009767 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009768 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009769 } else {
John McCalld226f652010-08-21 09:40:31 +00009770 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009771 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009772
Jordan Rose535a5d02012-10-19 16:05:26 +00009773 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009774 "This should only be set for ObjC methods, which should have been "
9775 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009776
Reid Spencer5f016e22007-07-11 17:01:13 +00009777 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009778 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009779 // C++ constructors that have function-try-blocks can't have return
9780 // statements in the handlers of that block. (C++ [except.handle]p14)
9781 // Verify this.
9782 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9783 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9784
Richard Smith37bee672011-08-12 18:44:32 +00009785 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009786 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009787 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009788 !hasAnyUnrecoverableErrorsInThisFunction() &&
9789 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009790 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009791
John McCall15442822010-08-04 01:04:25 +00009792 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9793 if (!Destructor->getParent()->isDependentType())
9794 CheckDestructor(Destructor);
9795
John McCallef027fe2010-03-16 21:39:52 +00009796 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9797 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009798 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009799
9800 // If any errors have occurred, clear out any temporaries that may have
9801 // been leftover. This ensures that these temporaries won't be picked up for
9802 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009803 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009804 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009805 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009806 }
9807 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9808 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009809 // Since the body is valid, issue any analysis-based warnings that are
9810 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009811 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009812 }
9813
Richard Smith86c3ae42012-02-13 03:54:03 +00009814 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9815 (!CheckConstexprFunctionDecl(FD) ||
9816 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009817 FD->setInvalidDecl();
9818
John McCall80ee6e82011-11-10 05:35:25 +00009819 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009820 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009821 assert(MaybeODRUseExprs.empty() &&
9822 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009823 }
9824
John McCall90f97892010-03-25 22:08:03 +00009825 if (!IsInstantiation)
9826 PopDeclContext();
9827
Eli Friedmanec9ea722012-01-05 03:35:19 +00009828 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009829 // If any errors have occurred, clear out any temporaries that may have
9830 // been leftover. This ensures that these temporaries won't be picked up for
9831 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009832 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009833 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009834 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009835
John McCalld226f652010-08-21 09:40:31 +00009836 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009837}
9838
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009839
9840/// When we finish delayed parsing of an attribute, we must attach it to the
9841/// relevant Decl.
9842void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9843 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009844 // Always attach attributes to the underlying decl.
9845 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9846 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009847 ProcessDeclAttributeList(S, D, Attrs.getList());
9848
9849 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9850 if (Method->isStatic())
9851 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009852}
9853
9854
Reid Spencer5f016e22007-07-11 17:01:13 +00009855/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9856/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009857NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009858 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009859 // Before we produce a declaration for an implicitly defined
9860 // function, see whether there was a locally-scoped declaration of
9861 // this name as a function or variable. If so, use that
9862 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009863 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9864 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9865 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9866 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009867 }
9868
Chris Lattner37d10842008-05-05 21:18:06 +00009869 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009870 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009871 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009872 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009873 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009874 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009875 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009876 diag_id = diag::warn_implicit_function_decl;
9877 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009878
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009879 // Because typo correction is expensive, only do it if the implicit
9880 // function declaration is going to be treated as an error.
9881 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9882 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009883 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009884 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009885 LookupOrdinaryName, S, 0, Validator)))
9886 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9887 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009888 }
9889
Reid Spencer5f016e22007-07-11 17:01:13 +00009890 // Set a Declarator for the implicit definition: int foo();
9891 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009892 AttributeFactory attrFactory;
9893 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009894 unsigned DiagID;
9895 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009896 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009897 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009898 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009899 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009900 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9901 /*IsAmbiguous=*/false,
9902 /*RParenLoc=*/NoLoc,
9903 /*ArgInfo=*/0,
9904 /*NumArgs=*/0,
9905 /*EllipsisLoc=*/NoLoc,
9906 /*RParenLoc=*/NoLoc,
9907 /*TypeQuals=*/0,
9908 /*RefQualifierIsLvalueRef=*/true,
9909 /*RefQualifierLoc=*/NoLoc,
9910 /*ConstQualifierLoc=*/NoLoc,
9911 /*VolatileQualifierLoc=*/NoLoc,
9912 /*MutableLoc=*/NoLoc,
9913 EST_None,
9914 /*ESpecLoc=*/NoLoc,
9915 /*Exceptions=*/0,
9916 /*ExceptionRanges=*/0,
9917 /*NumExceptions=*/0,
9918 /*NoexceptExpr=*/0,
9919 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009920 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009921 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009922 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009923
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009924 // Insert this function into translation-unit scope.
9925
9926 DeclContext *PrevDC = CurContext;
9927 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009928
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009929 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009930 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009931
9932 CurContext = PrevDC;
9933
Douglas Gregor3c385e52009-02-14 18:57:46 +00009934 AddKnownFunctionAttributes(FD);
9935
Steve Naroffe2ef8152008-04-04 14:32:09 +00009936 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009937}
9938
Douglas Gregor3c385e52009-02-14 18:57:46 +00009939/// \brief Adds any function attributes that we know a priori based on
9940/// the declaration of this function.
9941///
9942/// These attributes can apply both to implicitly-declared builtins
9943/// (like __builtin___printf_chk) or to library-declared functions
9944/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009945///
9946/// We need to check for duplicate attributes both here and where user-written
9947/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009948void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9949 if (FD->isInvalidDecl())
9950 return;
9951
9952 // If this is a built-in function, map its builtin attributes to
9953 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009954 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00009955 // Handle printf-formatting attributes.
9956 unsigned FormatIdx;
9957 bool HasVAListArg;
9958 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009959 if (!FD->getAttr<FormatAttr>()) {
9960 const char *fmt = "printf";
9961 unsigned int NumParams = FD->getNumParams();
9962 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9963 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9964 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +00009965 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009966 &Context.Idents.get(fmt),
9967 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00009968 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009969 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00009970 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00009971 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9972 HasVAListArg)) {
9973 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009974 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009975 &Context.Idents.get("scanf"),
9976 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00009977 HasVAListArg ? 0 : FormatIdx+2));
9978 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009979
9980 // Mark const if we don't care about errno and that is the only
9981 // thing preventing the function from being const. This allows
9982 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +00009983 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009984 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009985 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009986 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009987 }
Mike Stump0feecbb2009-07-27 19:14:18 +00009988
Rafael Espindola67004152011-10-12 19:51:18 +00009989 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
9990 !FD->getAttr<ReturnsTwiceAttr>())
9991 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009992 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009993 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009994 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009995 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +00009996 }
9997
9998 IdentifierInfo *Name = FD->getIdentifier();
9999 if (!Name)
10000 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010001 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010002 FD->getDeclContext()->isTranslationUnit()) ||
10003 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010004 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010005 LinkageSpecDecl::lang_c)) {
10006 // Okay: this could be a libc/libm/Objective-C function we know
10007 // about.
10008 } else
10009 return;
10010
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010011 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010012 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010013 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010014 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010015 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010016 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010017 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010018 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010019
10020 if (Name->isStr("__CFStringMakeConstantString")) {
10021 // We already have a __builtin___CFStringMakeConstantString,
10022 // but builds that use -fno-constant-cfstrings don't go through that.
10023 if (!FD->getAttr<FormatArgAttr>())
10024 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10025 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010026}
Reid Spencer5f016e22007-07-11 17:01:13 +000010027
John McCallba6a9bd2009-10-24 08:00:42 +000010028TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010029 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010030 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010031 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010032
John McCalla93c9342009-12-07 02:54:59 +000010033 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010034 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010035 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010036 }
10037
Reid Spencer5f016e22007-07-11 17:01:13 +000010038 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010039 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010040 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010041 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010042 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010043 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010044
John McCallcde5a402011-02-01 08:20:08 +000010045 // Bail out immediately if we have an invalid declaration.
10046 if (D.isInvalidType()) {
10047 NewTD->setInvalidDecl();
10048 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010049 }
10050
Douglas Gregore3895852011-09-12 18:37:38 +000010051 if (D.getDeclSpec().isModulePrivateSpecified()) {
10052 if (CurContext->isFunctionOrMethod())
10053 Diag(NewTD->getLocation(), diag::err_module_private_local)
10054 << 2 << NewTD->getDeclName()
10055 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10056 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10057 else
10058 NewTD->setModulePrivate();
10059 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010060
John McCallcde5a402011-02-01 08:20:08 +000010061 // C++ [dcl.typedef]p8:
10062 // If the typedef declaration defines an unnamed class (or
10063 // enum), the first typedef-name declared by the declaration
10064 // to be that class type (or enum type) is used to denote the
10065 // class type (or enum type) for linkage purposes only.
10066 // We need to check whether the type was declared in the declaration.
10067 switch (D.getDeclSpec().getTypeSpecType()) {
10068 case TST_enum:
10069 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010070 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010071 case TST_union:
10072 case TST_class: {
10073 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10074
10075 // Do nothing if the tag is not anonymous or already has an
10076 // associated typedef (from an earlier typedef in this decl group).
10077 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010078 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010079
10080 // A well-formed anonymous tag must always be a TUK_Definition.
10081 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10082
10083 // The type must match the tag exactly; no qualifiers allowed.
10084 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10085 break;
10086
10087 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010088 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010089 break;
10090 }
10091
10092 default:
10093 break;
10094 }
10095
Steve Naroff5912a352007-08-28 20:14:24 +000010096 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010097}
10098
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010099
Richard Smithf1c66b42012-03-14 23:13:10 +000010100/// \brief Check that this is a valid underlying type for an enum declaration.
10101bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10102 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10103 QualType T = TI->getType();
10104
Eli Friedman2fcff832012-12-18 02:37:32 +000010105 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010106 return false;
10107
Eli Friedman2fcff832012-12-18 02:37:32 +000010108 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10109 if (BT->isInteger())
10110 return false;
10111
Richard Smithf1c66b42012-03-14 23:13:10 +000010112 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10113 return true;
10114}
10115
10116/// Check whether this is a valid redeclaration of a previous enumeration.
10117/// \return true if the redeclaration was invalid.
10118bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10119 QualType EnumUnderlyingTy,
10120 const EnumDecl *Prev) {
10121 bool IsFixed = !EnumUnderlyingTy.isNull();
10122
10123 if (IsScoped != Prev->isScoped()) {
10124 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10125 << Prev->isScoped();
10126 Diag(Prev->getLocation(), diag::note_previous_use);
10127 return true;
10128 }
10129
10130 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010131 if (!EnumUnderlyingTy->isDependentType() &&
10132 !Prev->getIntegerType()->isDependentType() &&
10133 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010134 Prev->getIntegerType())) {
10135 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10136 << EnumUnderlyingTy << Prev->getIntegerType();
10137 Diag(Prev->getLocation(), diag::note_previous_use);
10138 return true;
10139 }
10140 } else if (IsFixed != Prev->isFixed()) {
10141 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10142 << Prev->isFixed();
10143 Diag(Prev->getLocation(), diag::note_previous_use);
10144 return true;
10145 }
10146
10147 return false;
10148}
10149
Joao Matos6666ed42012-08-31 18:45:21 +000010150/// \brief Get diagnostic %select index for tag kind for
10151/// redeclaration diagnostic message.
10152/// WARNING: Indexes apply to particular diagnostics only!
10153///
10154/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010155static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010156 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010157 case TTK_Struct: return 0;
10158 case TTK_Interface: return 1;
10159 case TTK_Class: return 2;
10160 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010161 }
Joao Matos6666ed42012-08-31 18:45:21 +000010162}
10163
10164/// \brief Determine if tag kind is a class-key compatible with
10165/// class for redeclaration (class, struct, or __interface).
10166///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010167/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010168static bool isClassCompatTagKind(TagTypeKind Tag)
10169{
10170 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10171}
10172
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010173/// \brief Determine whether a tag with a given kind is acceptable
10174/// as a redeclaration of the given tag declaration.
10175///
10176/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010177bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010178 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010179 SourceLocation NewTagLoc,
10180 const IdentifierInfo &Name) {
10181 // C++ [dcl.type.elab]p3:
10182 // The class-key or enum keyword present in the
10183 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010184 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010185 // refers. This rule also applies to the form of
10186 // elaborated-type-specifier that declares a class-name or
10187 // friend class since it can be construed as referring to the
10188 // definition of the class. Thus, in any
10189 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010190 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010191 // used to refer to a union (clause 9), and either the class or
10192 // struct class-key shall be used to refer to a class (clause 9)
10193 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010194 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010195 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010196 if (OldTag == NewTag)
10197 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010198
Joao Matos6666ed42012-08-31 18:45:21 +000010199 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010200 // Warn about the struct/class tag mismatch.
10201 bool isTemplate = false;
10202 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10203 isTemplate = Record->getDescribedClassTemplate();
10204
Richard Trieubbf34c02011-06-10 03:11:26 +000010205 if (!ActiveTemplateInstantiations.empty()) {
10206 // In a template instantiation, do not offer fix-its for tag mismatches
10207 // since they usually mess up the template instead of fixing the problem.
10208 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010209 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10210 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010211 return true;
10212 }
10213
10214 if (isDefinition) {
10215 // On definitions, check previous tags and issue a fix-it for each
10216 // one that doesn't match the current tag.
10217 if (Previous->getDefinition()) {
10218 // Don't suggest fix-its for redefinitions.
10219 return true;
10220 }
10221
10222 bool previousMismatch = false;
10223 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10224 E(Previous->redecls_end()); I != E; ++I) {
10225 if (I->getTagKind() != NewTag) {
10226 if (!previousMismatch) {
10227 previousMismatch = true;
10228 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010229 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10230 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010231 }
10232 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010233 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010234 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010235 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010236 }
10237 }
10238 return true;
10239 }
10240
10241 // Check for a previous definition. If current tag and definition
10242 // are same type, do nothing. If no definition, but disagree with
10243 // with previous tag type, give a warning, but no fix-it.
10244 const TagDecl *Redecl = Previous->getDefinition() ?
10245 Previous->getDefinition() : Previous;
10246 if (Redecl->getTagKind() == NewTag) {
10247 return true;
10248 }
10249
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010250 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010251 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10252 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010253 Diag(Redecl->getLocation(), diag::note_previous_use);
10254
10255 // If there is a previous defintion, suggest a fix-it.
10256 if (Previous->getDefinition()) {
10257 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010258 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010259 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010260 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010261 }
10262
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010263 return true;
10264 }
10265 return false;
10266}
10267
Steve Naroff08d92e42007-09-15 18:49:24 +000010268/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010269/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010270/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010271/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010272Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010273 SourceLocation KWLoc, CXXScopeSpec &SS,
10274 IdentifierInfo *Name, SourceLocation NameLoc,
10275 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010276 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010277 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010278 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010279 SourceLocation ScopedEnumKWLoc,
10280 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010281 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010282 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010283 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010284 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010285 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010286 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010287
Douglas Gregor402abb52009-05-28 23:31:59 +000010288 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010289 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010290 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010291
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010292 // FIXME: Check explicit specializations more carefully.
10293 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010294 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010295
10296 // We only need to do this matching if we have template parameters
10297 // or a scope specifier, which also conveniently avoids this work
10298 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010299 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010300 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010301 if (TemplateParameterList *TemplateParams =
10302 MatchTemplateParametersToScopeSpecifier(
10303 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10304 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010305 if (Kind == TTK_Enum) {
10306 Diag(KWLoc, diag::err_enum_template);
10307 return 0;
10308 }
10309
Douglas Gregord85bea22009-09-26 06:47:28 +000010310 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010311 // This is a declaration or definition of a class template (which may
10312 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010313
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010314 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010315 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010316
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010317 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010318 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010319 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010320 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010321 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010322 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010323 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010324 return Result.get();
10325 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010326 // The "template<>" header is extraneous.
10327 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010328 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010329 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010330 }
Mike Stump1eb44332009-09-09 15:08:12 +000010331 }
10332 }
10333
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010334 // Figure out the underlying type if this a enum declaration. We need to do
10335 // this early, because it's needed to detect if this is an incompatible
10336 // redeclaration.
10337 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10338
10339 if (Kind == TTK_Enum) {
10340 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10341 // No underlying type explicitly specified, or we failed to parse the
10342 // type, default to int.
10343 EnumUnderlying = Context.IntTy.getTypePtr();
10344 else if (UnderlyingType.get()) {
10345 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10346 // integral type; any cv-qualification is ignored.
10347 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010348 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010349 EnumUnderlying = TI;
10350
Richard Smithf1c66b42012-03-14 23:13:10 +000010351 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010352 // Recover by falling back to int.
10353 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010354
Richard Smithf1c66b42012-03-14 23:13:10 +000010355 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010356 UPPC_FixedUnderlyingType))
10357 EnumUnderlying = Context.IntTy.getTypePtr();
10358
David Blaikie4e4d0842012-03-11 07:00:24 +000010359 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010360 // Microsoft enums are always of int type.
10361 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010362 }
10363
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010364 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010365 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010366 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010367
Chandler Carruth7bf36002010-03-01 21:17:36 +000010368 RedeclarationKind Redecl = ForRedeclaration;
10369 if (TUK == TUK_Friend || TUK == TUK_Reference)
10370 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010371
10372 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010373 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010374 if (Name && SS.isNotEmpty()) {
10375 // We have a nested-name tag ('struct foo::bar').
10376
10377 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010378 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010379 Name = 0;
10380 goto CreateNewDecl;
10381 }
10382
John McCallc4e70192009-09-11 04:59:25 +000010383 // If this is a friend or a reference to a class in a dependent
10384 // context, don't try to make a decl for it.
10385 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10386 DC = computeDeclContext(SS, false);
10387 if (!DC) {
10388 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010389 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010390 }
John McCall77bb1aa2010-05-01 00:40:08 +000010391 } else {
10392 DC = computeDeclContext(SS, true);
10393 if (!DC) {
10394 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10395 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010396 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010397 }
John McCallc4e70192009-09-11 04:59:25 +000010398 }
10399
John McCall77bb1aa2010-05-01 00:40:08 +000010400 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010401 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010402
Douglas Gregor1931b442009-02-03 00:34:39 +000010403 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010404 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010405 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010406
John McCall68263142009-11-18 22:49:29 +000010407 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010408 return 0;
John McCall6e247262009-10-10 05:48:19 +000010409
John McCall68263142009-11-18 22:49:29 +000010410 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010411 // Name lookup did not find anything. However, if the
10412 // nested-name-specifier refers to the current instantiation,
10413 // and that current instantiation has any dependent base
10414 // classes, we might find something at instantiation time: treat
10415 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010416 // But this only makes any sense for reference-like lookups.
10417 if (Previous.wasNotFoundInCurrentInstantiation() &&
10418 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010419 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010420 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010421 }
10422
10423 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010424 Diag(NameLoc, diag::err_not_tag_in_scope)
10425 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010426 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010427 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010428 goto CreateNewDecl;
10429 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010430 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010431 // If this is a named struct, check to see if there was a previous forward
10432 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010433 // FIXME: We're looking into outer scopes here, even when we
10434 // shouldn't be. Doing so can result in ambiguities that we
10435 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010436 LookupName(Previous, S);
10437
John McCallc96cd7a2013-03-20 01:53:00 +000010438 // When declaring or defining a tag, ignore ambiguities introduced
10439 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010440 if (Previous.isAmbiguous() &&
10441 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010442 LookupResult::Filter F = Previous.makeFilter();
10443 while (F.hasNext()) {
10444 NamedDecl *ND = F.next();
10445 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10446 F.erase();
10447 }
10448 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010449 }
John McCallc96cd7a2013-03-20 01:53:00 +000010450
10451 // C++11 [namespace.memdef]p3:
10452 // If the name in a friend declaration is neither qualified nor
10453 // a template-id and the declaration is a function or an
10454 // elaborated-type-specifier, the lookup to determine whether
10455 // the entity has been previously declared shall not consider
10456 // any scopes outside the innermost enclosing namespace.
10457 //
10458 // Does it matter that this should be by scope instead of by
10459 // semantic context?
10460 if (!Previous.empty() && TUK == TUK_Friend) {
10461 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10462 LookupResult::Filter F = Previous.makeFilter();
10463 while (F.hasNext()) {
10464 NamedDecl *ND = F.next();
10465 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010466 if (DC->isFileContext() &&
10467 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010468 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010469 FriendSawTagOutsideEnclosingNamespace = true;
10470 }
John McCallc96cd7a2013-03-20 01:53:00 +000010471 }
10472 F.done();
10473 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010474
John McCall68263142009-11-18 22:49:29 +000010475 // Note: there used to be some attempt at recovery here.
10476 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010477 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010478
David Blaikie4e4d0842012-03-11 07:00:24 +000010479 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010480 // FIXME: This makes sure that we ignore the contexts associated
10481 // with C structs, unions, and enums when looking for a matching
10482 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010483 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010484 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10485 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010486 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010487 } else if (S->isFunctionPrototypeScope()) {
10488 // If this is an enum declaration in function prototype scope, set its
10489 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010490 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010491 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010492 }
10493
John McCall68263142009-11-18 22:49:29 +000010494 if (Previous.isSingleResult() &&
10495 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010496 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010497 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010498 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010499 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010500 }
10501
David Blaikie4e4d0842012-03-11 07:00:24 +000010502 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010503 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010504 // This is a declaration of or a reference to "std::bad_alloc".
10505 isStdBadAlloc = true;
10506
John McCall68263142009-11-18 22:49:29 +000010507 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010508 // std::bad_alloc has been implicitly declared (but made invisible to
10509 // name lookup). Fill in this implicit declaration as the previous
10510 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010511 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010512 }
10513 }
John McCall68263142009-11-18 22:49:29 +000010514
John McCall9c86b512010-03-25 21:28:06 +000010515 // If we didn't find a previous declaration, and this is a reference
10516 // (or friend reference), move to the correct scope. In C++, we
10517 // also need to do a redeclaration lookup there, just in case
10518 // there's a shadow friend decl.
10519 if (Name && Previous.empty() &&
10520 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10521 if (Invalid) goto CreateNewDecl;
10522 assert(SS.isEmpty());
10523
10524 if (TUK == TUK_Reference) {
10525 // C++ [basic.scope.pdecl]p5:
10526 // -- for an elaborated-type-specifier of the form
10527 //
10528 // class-key identifier
10529 //
10530 // if the elaborated-type-specifier is used in the
10531 // decl-specifier-seq or parameter-declaration-clause of a
10532 // function defined in namespace scope, the identifier is
10533 // declared as a class-name in the namespace that contains
10534 // the declaration; otherwise, except as a friend
10535 // declaration, the identifier is declared in the smallest
10536 // non-class, non-function-prototype scope that contains the
10537 // declaration.
10538 //
10539 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10540 // C structs and unions.
10541 //
10542 // It is an error in C++ to declare (rather than define) an enum
10543 // type, including via an elaborated type specifier. We'll
10544 // diagnose that later; for now, declare the enum in the same
10545 // scope as we would have picked for any other tag type.
10546 //
10547 // GNU C also supports this behavior as part of its incomplete
10548 // enum types extension, while GNU C++ does not.
10549 //
10550 // Find the context where we'll be declaring the tag.
10551 // FIXME: We would like to maintain the current DeclContext as the
10552 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010553 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010554 SearchDC = SearchDC->getParent();
10555
10556 // Find the scope where we'll be declaring the tag.
10557 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010558 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010559 S->isFunctionPrototypeScope()) ||
10560 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010561 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010562 S = S->getParent();
10563 } else {
10564 assert(TUK == TUK_Friend);
10565 // C++ [namespace.memdef]p3:
10566 // If a friend declaration in a non-local class first declares a
10567 // class or function, the friend class or function is a member of
10568 // the innermost enclosing namespace.
10569 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010570 }
10571
John McCall0d6b1642010-04-23 18:46:30 +000010572 // In C++, we need to do a redeclaration lookup to properly
10573 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010574 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010575 Previous.setRedeclarationKind(ForRedeclaration);
10576 LookupQualifiedName(Previous, SearchDC);
10577 }
10578 }
10579
John McCall68263142009-11-18 22:49:29 +000010580 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010581 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010582
10583 // It's okay to have a tag decl in the same scope as a typedef
10584 // which hides a tag decl in the same scope. Finding this
10585 // insanity with a redeclaration lookup can only actually happen
10586 // in C++.
10587 //
10588 // This is also okay for elaborated-type-specifiers, which is
10589 // technically forbidden by the current standard but which is
10590 // okay according to the likely resolution of an open issue;
10591 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010592 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010593 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010594 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10595 TagDecl *Tag = TT->getDecl();
10596 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010597 Tag->getDeclContext()->getRedeclContext()
10598 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010599 PrevDecl = Tag;
10600 Previous.clear();
10601 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010602 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010603 }
10604 }
10605 }
10606 }
10607
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010608 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010609 // If this is a use of a previous tag, or if the tag is already declared
10610 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010611 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010612 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010613 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010614 // Make sure that this wasn't declared as an enum and now used as a
10615 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010616 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10617 TUK == TUK_Definition, KWLoc,
10618 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010619 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010620 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10621 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010622 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010623 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010624 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010625 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10626 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010627 else
10628 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010629 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010630
Mike Stump1eb44332009-09-09 15:08:12 +000010631 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010632 Kind = PrevTagDecl->getTagKind();
10633 else {
10634 // Recover by making this an anonymous redefinition.
10635 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010636 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010637 Invalid = true;
10638 }
10639 }
10640
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010641 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10642 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10643
Richard Smithbdad7a22012-01-10 01:33:14 +000010644 // If this is an elaborated-type-specifier for a scoped enumeration,
10645 // the 'class' keyword is not necessary and not permitted.
10646 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10647 if (ScopedEnum)
10648 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10649 << PrevEnum->isScoped()
10650 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10651 return PrevTagDecl;
10652 }
10653
Richard Smithf1c66b42012-03-14 23:13:10 +000010654 QualType EnumUnderlyingTy;
10655 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10656 EnumUnderlyingTy = TI->getType();
10657 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10658 EnumUnderlyingTy = QualType(T, 0);
10659
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010660 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010661 // returning the previous declaration, unless this is a definition,
10662 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010663 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10664 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010665 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010666 }
10667
David Majnemer2ec2b842013-06-11 03:51:23 +000010668 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010669 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010670 // except that a nested class or member class template can be declared
10671 // and then later defined.
10672 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10673 S->isDeclScope(PrevDecl)) {
10674 Diag(NameLoc, diag::ext_member_redeclared);
10675 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10676 }
10677
Douglas Gregora3a83512009-04-01 23:51:29 +000010678 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010679 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010680
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010681 // FIXME: In the future, return a variant or some other clue
10682 // for the consumer of this Decl to know it doesn't own it.
10683 // For our current ASTs this shouldn't be a problem, but will
10684 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010685 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010686 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010687 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010688
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010689 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010690 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010691 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010692 // If we're defining a specialization and the previous definition
10693 // is from an implicit instantiation, don't emit an error
10694 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010695 bool IsExplicitSpecializationAfterInstantiation = false;
10696 if (isExplicitSpecialization) {
10697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10698 IsExplicitSpecializationAfterInstantiation =
10699 RD->getTemplateSpecializationKind() !=
10700 TSK_ExplicitSpecialization;
10701 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10702 IsExplicitSpecializationAfterInstantiation =
10703 ED->getTemplateSpecializationKind() !=
10704 TSK_ExplicitSpecialization;
10705 }
10706
10707 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010708 // A redeclaration in function prototype scope in C isn't
10709 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010710 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010711 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10712 else
10713 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010714 Diag(Def->getLocation(), diag::note_previous_definition);
10715 // If this is a redefinition, recover by making this
10716 // struct be anonymous, which will make any later
10717 // references get the previous definition.
10718 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010719 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010720 Invalid = true;
10721 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010722 } else {
10723 // If the type is currently being defined, complain
10724 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010725 const TagType *Tag
10726 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010727 if (Tag->isBeingDefined()) {
10728 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010729 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010730 diag::note_previous_definition);
10731 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010732 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010733 Invalid = true;
10734 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010735 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010736
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010737 // Okay, this is definition of a previously declared or referenced
10738 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010739 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010740 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010741 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010742 // have a definition. Just create a new decl.
10743
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010744 } else {
10745 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010746 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010747 // new decl/type. We set PrevDecl to NULL so that the entities
10748 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010749 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010750 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010751 // If we get here, we're going to create a new Decl. If PrevDecl
10752 // is non-NULL, it's a definition of the tag declared by
10753 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010754
10755
10756 // Otherwise, PrevDecl is not a tag, but was found with tag
10757 // lookup. This is only actually possible in C++, where a few
10758 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010759 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010760 // Use a better diagnostic if an elaborated-type-specifier
10761 // found the wrong kind of type on the first
10762 // (non-redeclaration) lookup.
10763 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10764 !Previous.isForRedeclaration()) {
10765 unsigned Kind = 0;
10766 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010767 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10768 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010769 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10770 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10771 Invalid = true;
10772
10773 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010774 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10775 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010776 // do nothing
10777
10778 // Diagnose implicit declarations introduced by elaborated types.
10779 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10780 unsigned Kind = 0;
10781 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010782 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10783 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010784 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10785 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10786 Invalid = true;
10787
10788 // Otherwise it's a declaration. Call out a particularly common
10789 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010790 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10791 unsigned Kind = 0;
10792 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010793 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010794 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010795 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10796 Invalid = true;
10797
10798 // Otherwise, diagnose.
10799 } else {
10800 // The tag name clashes with something else in the target scope,
10801 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010802 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010803 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010804 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010805 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010806 }
John McCall0d6b1642010-04-23 18:46:30 +000010807
10808 // The existing declaration isn't relevant to us; we're in a
10809 // new scope, so clear out the previous declaration.
10810 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010811 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010812 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010813
Chris Lattnercc98eac2008-12-17 07:13:27 +000010814CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010815
John McCall68263142009-11-18 22:49:29 +000010816 TagDecl *PrevDecl = 0;
10817 if (Previous.isSingleResult())
10818 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10819
Reid Spencer5f016e22007-07-11 17:01:13 +000010820 // If there is an identifier, use the location of the identifier as the
10821 // location of the decl, otherwise use the location of the struct/union
10822 // keyword.
10823 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010824
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010825 // Otherwise, create a new declaration. If there is a previous
10826 // declaration of the same entity, the two will be linked via
10827 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010828 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010829
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010830 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010831 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010832 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10833 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010834 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010835 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010836 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010837 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010838 if (TUK != TUK_Definition && !Invalid) {
10839 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010840 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10841 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010842 // C++0x: 7.2p2: opaque-enum-declaration.
10843 // Conflicts are diagnosed above. Do nothing.
10844 }
10845 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010846 Diag(Loc, diag::ext_forward_ref_enum_def)
10847 << New;
10848 Diag(Def->getLocation(), diag::note_previous_definition);
10849 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010850 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010851 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010852 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010853 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010854 DiagID = diag::err_forward_ref_enum;
10855 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010856
10857 // If this is a forward-declared reference to an enumeration, make a
10858 // note of it; we won't actually be introducing the declaration into
10859 // the declaration context.
10860 if (TUK == TUK_Reference)
10861 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010862 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010863 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010864
10865 if (EnumUnderlying) {
10866 EnumDecl *ED = cast<EnumDecl>(New);
10867 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10868 ED->setIntegerTypeSourceInfo(TI);
10869 else
10870 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10871 ED->setPromotionType(ED->getIntegerType());
10872 }
10873
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010874 } else {
10875 // struct/union/class
10876
Reid Spencer5f016e22007-07-11 17:01:13 +000010877 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10878 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010879 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010880 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010881 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010882 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010883
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010884 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010885 StdBadAlloc = cast<CXXRecordDecl>(New);
10886 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010887 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010888 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010889 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010890
John McCallb6217662010-03-15 10:12:16 +000010891 // Maybe add qualifier info.
10892 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010893 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010894 // If this is either a declaration or a definition, check the
10895 // nested-name-specifier against the current context. We don't do this
10896 // for explicit specializations, because they have similar checking
10897 // (with more specific diagnostics) in the call to
10898 // CheckMemberSpecialization, below.
10899 if (!isExplicitSpecialization &&
10900 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10901 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10902 Invalid = true;
10903
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010904 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010905 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010906 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010907 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010908 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010909 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010910 }
10911 else
10912 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010913 }
10914
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010915 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10916 // Add alignment attributes if necessary; these attributes are checked when
10917 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010918 //
10919 // It is important for implementing the correct semantics that this
10920 // happen here (in act on tag decl). The #pragma pack stack is
10921 // maintained as a result of parser callbacks which can occur at
10922 // many points during the parsing of a struct declaration (because
10923 // the #pragma tokens are effectively skipped over during the
10924 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010925 if (TUK == TUK_Definition) {
10926 AddAlignmentAttributesForRecord(RD);
10927 AddMsStructLayoutForRecord(RD);
10928 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010929 }
10930
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010931 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010932 if (isExplicitSpecialization)
10933 Diag(New->getLocation(), diag::err_module_private_specialization)
10934 << 2
10935 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010936 // __module_private__ does not apply to local classes. However, we only
10937 // diagnose this as an error when the declaration specifiers are
10938 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010939 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010940 New->setModulePrivate();
10941 }
10942
Douglas Gregorf6b11852009-10-08 15:14:33 +000010943 // If this is a specialization of a member class (of a class template),
10944 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000010945 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000010946 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000010947
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010948 if (Invalid)
10949 New->setInvalidDecl();
10950
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010951 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010952 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010953
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010954 // If we're declaring or defining a tag in function prototype scope
10955 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000010956 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000010957 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10958
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010959 // Set the lexical context. If the tag has a C++ scope specifier, the
10960 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000010961 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010962
John McCall02cace72009-08-28 07:59:38 +000010963 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000010964 // In Microsoft mode, a friend declaration also acts as a forward
10965 // declaration so we always pass true to setObjectOfFriendDecl to make
10966 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000010967 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000010968 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10969 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000010970
Anders Carlsson0cf88302009-03-26 01:19:02 +000010971 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000010972 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000010973 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000010974
John McCall0f434ec2009-07-31 02:45:11 +000010975 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010976 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000010977
Reid Spencer5f016e22007-07-11 17:01:13 +000010978 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000010979 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000010980 // We might be replacing an existing declaration in the lookup tables;
10981 // if so, borrow its access specifier.
10982 if (PrevDecl)
10983 New->setAccess(PrevDecl->getAccess());
10984
Sebastian Redl7a126a42010-08-31 00:36:30 +000010985 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010986 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000010987 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000010988 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10989 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000010990 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000010991 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010992 PushOnScopeChains(New, S, !IsForwardReference);
10993 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010994 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010995
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010996 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010997 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000010998 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000010999
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011000 // If this is the C FILE type, notify the AST context.
11001 if (IdentifierInfo *II = New->getIdentifier())
11002 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011003 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011004 II->isStr("FILE"))
11005 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011006
James Molloy16f1f712012-02-29 10:24:19 +000011007 // If we were in function prototype scope (and not in C++ mode), add this
11008 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011009 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011010 InFunctionDeclarator && Name)
11011 DeclsInPrototypeScope.push_back(New);
11012
Rafael Espindola98ae8342012-05-10 02:50:16 +000011013 if (PrevDecl)
11014 mergeDeclAttributes(New, PrevDecl);
11015
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011016 // If there's a #pragma GCC visibility in scope, set the visibility of this
11017 // record.
11018 AddPushedVisibilityAttribute(New);
11019
Douglas Gregor402abb52009-05-28 23:31:59 +000011020 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011021 // In C++, don't return an invalid declaration. We can't recover well from
11022 // the cases where we make the type anonymous.
11023 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011024}
11025
John McCalld226f652010-08-21 09:40:31 +000011026void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011027 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011028 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011029
Douglas Gregor72de6672009-01-08 20:45:30 +000011030 // Enter the tag context.
11031 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011032
11033 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011034
11035 // If there's a #pragma GCC visibility in scope, set the visibility of this
11036 // record.
11037 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011038}
Douglas Gregor72de6672009-01-08 20:45:30 +000011039
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011040Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011041 assert(isa<ObjCContainerDecl>(IDecl) &&
11042 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11043 DeclContext *OCD = cast<DeclContext>(IDecl);
11044 assert(getContainingDC(OCD) == CurContext &&
11045 "The next DeclContext should be lexically contained in the current one.");
11046 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011047 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011048}
11049
John McCalld226f652010-08-21 09:40:31 +000011050void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011051 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011052 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011053 SourceLocation LBraceLoc) {
11054 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011055 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011056
John McCallf9368152009-12-20 07:58:13 +000011057 FieldCollector->StartClass();
11058
11059 if (!Record->getIdentifier())
11060 return;
11061
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011062 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011063 Record->addAttr(new (Context)
11064 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11065
John McCallf9368152009-12-20 07:58:13 +000011066 // C++ [class]p2:
11067 // [...] The class-name is also inserted into the scope of the
11068 // class itself; this is known as the injected-class-name. For
11069 // purposes of access checking, the injected-class-name is treated
11070 // as if it were a public member name.
11071 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011072 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11073 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011074 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011075 /*PrevDecl=*/0,
11076 /*DelayTypeCreation=*/true);
11077 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011078 InjectedClassName->setImplicit();
11079 InjectedClassName->setAccess(AS_public);
11080 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11081 InjectedClassName->setDescribedClassTemplate(Template);
11082 PushOnScopeChains(InjectedClassName, S);
11083 assert(InjectedClassName->isInjectedClassName() &&
11084 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011085}
11086
John McCalld226f652010-08-21 09:40:31 +000011087void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011088 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011089 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011090 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011091 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011092
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011093 // Make sure we "complete" the definition even it is invalid.
11094 if (Tag->isBeingDefined()) {
11095 assert(Tag->isInvalidDecl() && "We should already have completed it");
11096 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11097 RD->completeDefinition();
11098 }
11099
Douglas Gregor72de6672009-01-08 20:45:30 +000011100 if (isa<CXXRecordDecl>(Tag))
11101 FieldCollector->FinishClass();
11102
11103 // Exit this scope of this tag's definition.
11104 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011105
11106 if (getCurLexicalContext()->isObjCContainer() &&
11107 Tag->getDeclContext()->isFileContext())
11108 Tag->setTopLevelDeclInObjCContainer();
11109
Douglas Gregor72de6672009-01-08 20:45:30 +000011110 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011111 if (!Tag->isInvalidDecl())
11112 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011113}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011114
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011115void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011116 // Exit this scope of this interface definition.
11117 PopDeclContext();
11118}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011119
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011120void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011121 assert(DC == CurContext && "Mismatch of container contexts");
11122 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011123 ActOnObjCContainerFinishDefinition();
11124}
11125
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011126void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11127 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011128 OriginalLexicalContext = 0;
11129}
11130
John McCalld226f652010-08-21 09:40:31 +000011131void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011132 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011133 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011134 Tag->setInvalidDecl();
11135
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011136 // Make sure we "complete" the definition even it is invalid.
11137 if (Tag->isBeingDefined()) {
11138 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11139 RD->completeDefinition();
11140 }
11141
John McCalla8cab012010-03-17 19:25:57 +000011142 // We're undoing ActOnTagStartDefinition here, not
11143 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11144 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011145
11146 PopDeclContext();
11147}
11148
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011149// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011150ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11151 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011152 QualType FieldTy, bool IsMsStruct,
11153 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011154 // Default to true; that shouldn't confuse checks for emptiness
11155 if (ZeroWidth)
11156 *ZeroWidth = true;
11157
Chris Lattner24793662009-03-05 22:45:59 +000011158 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011159 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011160 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011161 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011162 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011163 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011164 if (FieldName)
11165 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11166 << FieldName << FieldTy << BitWidth->getSourceRange();
11167 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11168 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011169 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11170 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011171 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011172
11173 // If the bit-width is type- or value-dependent, don't try to check
11174 // it now.
11175 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011176 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011177
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011178 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011179 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11180 if (ICE.isInvalid())
11181 return ICE;
11182 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011183
Eli Friedman1d954f62009-08-15 21:55:26 +000011184 if (Value != 0 && ZeroWidth)
11185 *ZeroWidth = false;
11186
Chris Lattnercd087072008-12-12 04:56:04 +000011187 // Zero-width bitfield is ok for anonymous field.
11188 if (Value == 0 && FieldName)
11189 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011190
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011191 if (Value.isSigned() && Value.isNegative()) {
11192 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011193 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011194 << FieldName << Value.toString(10);
11195 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11196 << Value.toString(10);
11197 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011198
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011199 if (!FieldTy->isDependentType()) {
11200 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011201 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011202 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011203 if (FieldName)
11204 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11205 << FieldName << (unsigned)Value.getZExtValue()
11206 << (unsigned)TypeSize;
11207
11208 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11209 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11210 }
11211
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011212 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011213 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11214 << FieldName << (unsigned)Value.getZExtValue()
11215 << (unsigned)TypeSize;
11216 else
11217 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11218 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011219 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011220 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011221
Richard Smith282e7e62012-02-04 09:53:13 +000011222 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011223}
11224
Richard Smith7a614d82011-06-11 17:19:42 +000011225/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011226/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011227Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011228 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011229 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011230 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011231 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011232 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011233}
11234
11235/// HandleField - Analyze a field of a C struct or a C++ data member.
11236///
11237FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11238 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011239 Declarator &D, Expr *BitWidth,
11240 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011241 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011242 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011243 SourceLocation Loc = DeclStart;
11244 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011245
John McCallbf1a0282010-06-04 23:28:52 +000011246 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11247 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011248 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011249 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011250
Douglas Gregore1862692010-12-15 23:18:36 +000011251 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11252 UPPC_DataMemberType)) {
11253 D.setInvalidType();
11254 T = Context.IntTy;
11255 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11256 }
11257 }
11258
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011259 // TR 18037 does not allow fields to be declared with address spaces.
11260 if (T.getQualifiers().hasAddressSpace()) {
11261 Diag(Loc, diag::err_field_with_address_space);
11262 D.setInvalidType();
11263 }
11264
Guy Benyeie6b9d802013-01-20 12:31:11 +000011265 // OpenCL 1.2 spec, s6.9 r:
11266 // The event type cannot be used to declare a structure or union field.
11267 if (LangOpts.OpenCL && T->isEventT()) {
11268 Diag(Loc, diag::err_event_t_struct_field);
11269 D.setInvalidType();
11270 }
11271
Richard Smithc7f81162013-03-18 22:52:47 +000011272 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011273
Richard Smithec642442013-04-12 22:46:28 +000011274 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11275 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11276 diag::err_invalid_thread)
11277 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011278
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011279 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011280 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011281 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11282 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011283 switch (Previous.getResultKind()) {
11284 case LookupResult::Found:
11285 case LookupResult::FoundUnresolvedValue:
11286 PrevDecl = Previous.getAsSingle<NamedDecl>();
11287 break;
11288
11289 case LookupResult::FoundOverloaded:
11290 PrevDecl = Previous.getRepresentativeDecl();
11291 break;
11292
11293 case LookupResult::NotFound:
11294 case LookupResult::NotFoundInCurrentInstantiation:
11295 case LookupResult::Ambiguous:
11296 break;
11297 }
11298 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011299
11300 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11301 // Maybe we will complain about the shadowed template parameter.
11302 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11303 // Just pretend that we didn't see the previous declaration.
11304 PrevDecl = 0;
11305 }
11306
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011307 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11308 PrevDecl = 0;
11309
Steve Naroffea218b82009-07-14 14:58:18 +000011310 bool Mutable
11311 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011312 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011313 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011314 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011315 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011316
11317 if (NewFD->isInvalidDecl())
11318 Record->setInvalidDecl();
11319
Douglas Gregor591dc842011-09-12 16:11:24 +000011320 if (D.getDeclSpec().isModulePrivateSpecified())
11321 NewFD->setModulePrivate();
11322
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011323 if (NewFD->isInvalidDecl() && PrevDecl) {
11324 // Don't introduce NewFD into scope; there's already something
11325 // with the same name in the same scope.
11326 } else if (II) {
11327 PushOnScopeChains(NewFD, S);
11328 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011329 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011330
11331 return NewFD;
11332}
11333
11334/// \brief Build a new FieldDecl and check its well-formedness.
11335///
11336/// This routine builds a new FieldDecl given the fields name, type,
11337/// record, etc. \p PrevDecl should refer to any previous declaration
11338/// with the same name and in the same scope as the field to be
11339/// created.
11340///
11341/// \returns a new FieldDecl.
11342///
Mike Stump1eb44332009-09-09 15:08:12 +000011343/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011344FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011345 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011346 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011347 bool Mutable, Expr *BitWidth,
11348 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011349 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011350 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011351 Declarator *D) {
11352 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011353 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011354 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011355
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011356 // If we receive a broken type, recover by assuming 'int' and
11357 // marking this declaration as invalid.
11358 if (T.isNull()) {
11359 InvalidDecl = true;
11360 T = Context.IntTy;
11361 }
11362
Eli Friedman721e77d2009-12-07 00:22:08 +000011363 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011364 if (!EltTy->isDependentType()) {
11365 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11366 // Fields of incomplete type force their record to be invalid.
11367 Record->setInvalidDecl();
11368 InvalidDecl = true;
11369 } else {
11370 NamedDecl *Def;
11371 EltTy->isIncompleteType(&Def);
11372 if (Def && Def->isInvalidDecl()) {
11373 Record->setInvalidDecl();
11374 InvalidDecl = true;
11375 }
11376 }
John McCall2d7d2d92010-08-16 23:42:35 +000011377 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011378
Joey Gouly617bb312013-01-17 17:35:00 +000011379 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11380 if (BitWidth && getLangOpts().OpenCL) {
11381 Diag(Loc, diag::err_opencl_bitfields);
11382 InvalidDecl = true;
11383 }
11384
Reid Spencer5f016e22007-07-11 17:01:13 +000011385 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11386 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011387 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011388 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011389 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011390
11391 TypeSourceInfo *FixedTInfo =
11392 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11393 SizeIsNegative,
11394 Oversized);
11395 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011396 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011397 TInfo = FixedTInfo;
11398 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011399 } else {
11400 if (SizeIsNegative)
11401 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011402 else if (Oversized.getBoolValue())
11403 Diag(Loc, diag::err_array_too_large)
11404 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011405 else
11406 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011407 InvalidDecl = true;
11408 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011409 }
Mike Stump1eb44332009-09-09 15:08:12 +000011410
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011411 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011412 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11413 diag::err_abstract_type_in_decl,
11414 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011415 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011416
Eli Friedman1d954f62009-08-15 21:55:26 +000011417 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011418 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011419 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011420 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11421 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011422 if (!BitWidth) {
11423 InvalidDecl = true;
11424 BitWidth = 0;
11425 ZeroWidth = false;
11426 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011427 }
Mike Stump1eb44332009-09-09 15:08:12 +000011428
John McCall4bde1e12010-06-04 08:34:12 +000011429 // Check that 'mutable' is consistent with the type of the declaration.
11430 if (!InvalidDecl && Mutable) {
11431 unsigned DiagID = 0;
11432 if (T->isReferenceType())
11433 DiagID = diag::err_mutable_reference;
11434 else if (T.isConstQualified())
11435 DiagID = diag::err_mutable_const;
11436
11437 if (DiagID) {
11438 SourceLocation ErrLoc = Loc;
11439 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11440 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11441 Diag(ErrLoc, DiagID);
11442 Mutable = false;
11443 InvalidDecl = true;
11444 }
11445 }
11446
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011447 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011448 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011449 if (InvalidDecl)
11450 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011451
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011452 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11453 Diag(Loc, diag::err_duplicate_member) << II;
11454 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11455 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011456 }
11457
David Blaikie4e4d0842012-03-11 07:00:24 +000011458 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011459 if (Record->isUnion()) {
11460 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11461 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11462 if (RDecl->getDefinition()) {
11463 // C++ [class.union]p1: An object of a class with a non-trivial
11464 // constructor, a non-trivial copy constructor, a non-trivial
11465 // destructor, or a non-trivial copy assignment operator
11466 // cannot be a member of a union, nor can an array of such
11467 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011468 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011469 NewFD->setInvalidDecl();
11470 }
11471 }
11472
11473 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011474 // the program is ill-formed, except when compiling with MSVC extensions
11475 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011476 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011477 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11478 diag::ext_union_member_of_reference_type :
11479 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011480 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011481 if (!getLangOpts().MicrosoftExt)
11482 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011483 }
11484 }
11485 }
11486
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011487 // FIXME: We need to pass in the attributes given an AST
11488 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011489 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011490 // FIXME: The current scope is almost... but not entirely... correct here.
11491 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011492
Richard Smithbe507b62013-02-01 08:12:08 +000011493 if (NewFD->hasAttrs())
11494 CheckAlignasUnderalignment(NewFD);
11495 }
11496
John McCallf85e1932011-06-15 23:02:42 +000011497 // In auto-retain/release, infer strong retension for fields of
11498 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011499 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011500 NewFD->setInvalidDecl();
11501
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011502 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011503 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011504
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011505 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011506 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011507}
11508
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011509bool Sema::CheckNontrivialField(FieldDecl *FD) {
11510 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011511 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011512
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011513 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11514 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011515
11516 QualType EltTy = Context.getBaseElementType(FD->getType());
11517 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011518 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011519 if (RDecl->getDefinition()) {
11520 // We check for copy constructors before constructors
11521 // because otherwise we'll never get complaints about
11522 // copy constructors.
11523
11524 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011525 // We're required to check for any non-trivial constructors. Since the
11526 // implicit default constructor is suppressed if there are any
11527 // user-declared constructors, we just need to check that there is a
11528 // trivial default constructor and a trivial copy constructor. (We don't
11529 // worry about move constructors here, since this is a C++98 check.)
11530 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011531 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011532 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011533 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011534 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011535 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011536 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011537 member = CXXDestructor;
11538
11539 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011540 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011541 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011542 // Objective-C++ ARC: it is an error to have a non-trivial field of
11543 // a union. However, system headers in Objective-C programs
11544 // occasionally have Objective-C lifetime objects within unions,
11545 // and rather than cause the program to fail, we make those
11546 // members unavailable.
11547 SourceLocation Loc = FD->getLocation();
11548 if (getSourceManager().isInSystemHeader(Loc)) {
11549 if (!FD->hasAttr<UnavailableAttr>())
11550 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011551 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011552 return false;
11553 }
11554 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011555
Richard Smith80ad52f2013-01-02 11:42:31 +000011556 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011557 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11558 diag::err_illegal_union_or_anon_struct_member)
11559 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011560 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011561 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011562 }
11563 }
11564 }
Richard Smithac713512012-12-08 02:53:02 +000011565
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011566 return false;
11567}
11568
Mike Stump1eb44332009-09-09 15:08:12 +000011569/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011570/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011571static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011572TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011573 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011574 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011575 case tok::objc_private: return ObjCIvarDecl::Private;
11576 case tok::objc_public: return ObjCIvarDecl::Public;
11577 case tok::objc_protected: return ObjCIvarDecl::Protected;
11578 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011579 }
11580}
11581
Mike Stump1eb44332009-09-09 15:08:12 +000011582/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011583/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011584Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011585 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011586 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011587 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011588
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011589 IdentifierInfo *II = D.getIdentifier();
11590 Expr *BitWidth = (Expr*)BitfieldWidth;
11591 SourceLocation Loc = DeclStart;
11592 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011593
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011594 // FIXME: Unnamed fields can be handled in various different ways, for
11595 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011596
John McCallbf1a0282010-06-04 23:28:52 +000011597 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11598 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011599
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011600 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011601 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011602 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011603 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011604 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011605 } else {
11606 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011607
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011608 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011609
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011610 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011611 if (T->isReferenceType()) {
11612 Diag(Loc, diag::err_ivar_reference_type);
11613 D.setInvalidType();
11614 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011615 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11616 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011617 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011618 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011619 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011620 }
Mike Stump1eb44332009-09-09 15:08:12 +000011621
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011622 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011623 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011624 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11625 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011626 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011627 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011628 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11629 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011630 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011631 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011632 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011633 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011634 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011635 EnclosingContext = IMPDecl->getClassInterface();
11636 assert(EnclosingContext && "Implementation has no class interface!");
11637 }
11638 else
11639 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011640 } else {
11641 if (ObjCCategoryDecl *CDecl =
11642 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011643 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011644 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011645 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011646 }
11647 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011648 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011649 }
Mike Stump1eb44332009-09-09 15:08:12 +000011650
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011651 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011652 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11653 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011654 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011655
Douglas Gregor72de6672009-01-08 20:45:30 +000011656 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011657 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011658 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011659 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011660 && !isa<TagDecl>(PrevDecl)) {
11661 Diag(Loc, diag::err_duplicate_member) << II;
11662 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11663 NewID->setInvalidDecl();
11664 }
11665 }
11666
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011667 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011668 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011669
Chris Lattnereaaebc72009-04-25 08:06:05 +000011670 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011671 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011672
John McCallf85e1932011-06-15 23:02:42 +000011673 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011674 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011675 NewID->setInvalidDecl();
11676
Douglas Gregor591dc842011-09-12 16:11:24 +000011677 if (D.getDeclSpec().isModulePrivateSpecified())
11678 NewID->setModulePrivate();
11679
Douglas Gregor72de6672009-01-08 20:45:30 +000011680 if (II) {
11681 // FIXME: When interfaces are DeclContexts, we'll need to add
11682 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011683 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011684 IdResolver.AddDecl(NewID);
11685 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011686
John McCall260611a2012-06-20 06:18:46 +000011687 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011688 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011689 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011690
John McCalld226f652010-08-21 09:40:31 +000011691 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011692}
11693
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011694/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011695/// class and class extensions. For every class \@interface and class
11696/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011697/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011698void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011699 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011700 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011701 return;
11702
11703 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11704 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11705
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011706 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011707 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011708 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011709 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011710 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011711 if (!CD->IsClassExtension())
11712 return;
11713 }
11714 // No need to add this to end of @implementation.
11715 else
11716 return;
11717 }
11718 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011719 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11720 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011721
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011722 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011723 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011724 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011725 Context.getTrivialTypeSourceInfo(Context.CharTy,
11726 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011727 ObjCIvarDecl::Private, BW,
11728 true);
11729 AllIvarDecls.push_back(Ivar);
11730}
11731
Robert Wilhelm834c0582013-08-09 18:02:13 +000011732void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11733 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11734 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011735 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011736
Eric Christopher6dba4a12012-07-19 22:22:51 +000011737 // If this is an Objective-C @implementation or category and we have
11738 // new fields here we should reset the layout of the interface since
11739 // it will now change.
11740 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11741 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11742 switch (DC->getKind()) {
11743 default: break;
11744 case Decl::ObjCCategory:
11745 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11746 break;
11747 case Decl::ObjCImplementation:
11748 Context.
11749 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11750 break;
11751 }
11752 }
11753
Eli Friedman11e70d72012-02-07 05:00:47 +000011754 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11755
11756 // Start counting up the number of named members; make sure to include
11757 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011758 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011759 if (Record) {
11760 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11761 e = Record->decls_end(); i != e; i++) {
11762 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11763 if (IFD->getDeclName())
11764 ++NumNamedMembers;
11765 }
11766 }
11767
11768 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011769 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011770
John McCallf85e1932011-06-15 23:02:42 +000011771 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011772 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011773 i != end; ++i) {
11774 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011775
Reid Spencer5f016e22007-07-11 17:01:13 +000011776 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011777 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011778
Douglas Gregor72de6672009-01-08 20:45:30 +000011779 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011780 // Remember all fields written by the user.
11781 RecFields.push_back(FD);
11782 }
Mike Stump1eb44332009-09-09 15:08:12 +000011783
Chris Lattner24793662009-03-05 22:45:59 +000011784 // If the field is already invalid for some reason, don't emit more
11785 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011786 if (FD->isInvalidDecl()) {
11787 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011788 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011789 }
Mike Stump1eb44332009-09-09 15:08:12 +000011790
Douglas Gregore7450f52009-03-24 19:52:54 +000011791 // C99 6.7.2.1p2:
11792 // A structure or union shall not contain a member with
11793 // incomplete or function type (hence, a structure shall not
11794 // contain an instance of itself, but may contain a pointer to
11795 // an instance of itself), except that the last member of a
11796 // structure with more than one named member may have incomplete
11797 // array type; such a structure (and any union containing,
11798 // possibly recursively, a member that is such a structure)
11799 // shall not be a member of a structure or an element of an
11800 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011801 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011802 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011803 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011804 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011805 FD->setInvalidDecl();
11806 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011807 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011808 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011809 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011810 ((getLangOpts().MicrosoftExt ||
11811 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011812 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011813 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011814 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011815 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011816 // as the sole element of a struct/class.
David Blaikie4e4d0842012-03-11 07:00:24 +000011817 if (getLangOpts().MicrosoftExt) {
Francois Pichet09246182010-09-15 00:14:08 +000011818 if (Record->isUnion())
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011819 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichet09246182010-09-15 00:14:08 +000011820 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +000011821 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011822 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichet09246182010-09-15 00:14:08 +000011823 << FD->getDeclName() << Record->getTagKind();
David Blaikie4e4d0842012-03-11 07:00:24 +000011824 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011825 if (Record->isUnion())
11826 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11827 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +000011828 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011829 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
11830 << FD->getDeclName() << Record->getTagKind();
David Chisnall0961a012012-03-16 12:15:37 +000011831 } else if (!getLangOpts().C99) {
11832 if (Record->isUnion())
11833 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11834 << FD->getDeclName();
11835 else
11836 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11837 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011838 } else if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011839 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011840 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011841 FD->setInvalidDecl();
11842 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011843 continue;
11844 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011845 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011846 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011847 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011848 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011849 FD->setInvalidDecl();
11850 EnclosingDecl->setInvalidDecl();
11851 continue;
11852 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011853 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011854 if (Record)
11855 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011856 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011857 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011858 diag::err_field_incomplete)) {
11859 // Incomplete type
11860 FD->setInvalidDecl();
11861 EnclosingDecl->setInvalidDecl();
11862 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011863 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011864 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11865 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011866 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011867 Record->setHasFlexibleArrayMember(true);
11868 } else {
11869 // If this is a struct/class and this is not the last element, reject
11870 // it. Note that GCC supports variable sized arrays in the middle of
11871 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011872 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011873 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011874 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011875 else {
11876 // We support flexible arrays at the end of structs in
11877 // other structs as an extension.
11878 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11879 << FD->getDeclName();
11880 if (Record)
11881 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011882 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011883 }
11884 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011885 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11886 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11887 diag::err_abstract_type_in_decl,
11888 AbstractIvarType)) {
11889 // Ivars can not have abstract class types
11890 FD->setInvalidDecl();
11891 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011892 if (Record && FDTTy->getDecl()->hasObjectMember())
11893 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011894 if (Record && FDTTy->getDecl()->hasVolatileMember())
11895 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011896 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011897 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011898 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11899 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11900 QualType T = Context.getObjCObjectPointerType(FD->getType());
11901 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011902 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11903 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11904 // It's an error in ARC if a field has lifetime.
11905 // We don't want to report this in a system header, though,
11906 // so we just make the field unavailable.
11907 // FIXME: that's really not sufficient; we need to make the type
11908 // itself invalid to, say, initialize or copy.
11909 QualType T = FD->getType();
11910 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11911 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11912 SourceLocation loc = FD->getLocation();
11913 if (getSourceManager().isInSystemHeader(loc)) {
11914 if (!FD->hasAttr<UnavailableAttr>()) {
11915 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11916 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011917 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011918 } else {
11919 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011920 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011921 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011922 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011923 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011924 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011925 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011926 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011927 if (FD->getType()->isObjCObjectPointerType() ||
11928 FD->getType().isObjCGCStrong())
11929 Record->setHasObjectMember(true);
11930 else if (Context.getAsArrayType(FD->getType())) {
11931 QualType BaseType = Context.getBaseElementType(FD->getType());
11932 if (BaseType->isRecordType() &&
11933 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011934 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011935 else if (BaseType->isObjCObjectPointerType() ||
11936 BaseType.isObjCGCStrong())
11937 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011938 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011939 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011940 if (Record && FD->getType().isVolatileQualified())
11941 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011942 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000011943 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000011944 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000011945 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011946
Reid Spencer5f016e22007-07-11 17:01:13 +000011947 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000011948 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011949 bool Completed = false;
11950 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11951 if (!CXXRecord->isInvalidDecl()) {
11952 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011953 for (CXXRecordDecl::conversion_iterator
11954 I = CXXRecord->conversion_begin(),
11955 E = CXXRecord->conversion_end(); I != E; ++I)
11956 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011957
11958 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000011959 if (CXXRecord->hasUserDeclaredDestructor()) {
11960 // Adjust user-defined destructor exception spec.
11961 if (getLangOpts().CPlusPlus11)
11962 AdjustDestructorExceptionSpec(CXXRecord,
11963 CXXRecord->getDestructor());
11964
11965 // The Microsoft ABI requires that we perform the destructor body
11966 // checks (i.e. operator delete() lookup) at every declaration, as
11967 // any translation unit may need to emit a deleting destructor.
11968 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11969 CheckDestructor(CXXRecord->getDestructor());
11970 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000011971
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011972 // Add any implicitly-declared members to this class.
11973 AddImplicitlyDeclaredMembersToClass(CXXRecord);
11974
11975 // If we have virtual base classes, we may end up finding multiple
11976 // final overriders for a given virtual function. Check for this
11977 // problem now.
11978 if (CXXRecord->getNumVBases()) {
11979 CXXFinalOverriderMap FinalOverriders;
11980 CXXRecord->getFinalOverriders(FinalOverriders);
11981
11982 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
11983 MEnd = FinalOverriders.end();
11984 M != MEnd; ++M) {
11985 for (OverridingMethods::iterator SO = M->second.begin(),
11986 SOEnd = M->second.end();
11987 SO != SOEnd; ++SO) {
11988 assert(SO->second.size() > 0 &&
11989 "Virtual function without overridding functions?");
11990 if (SO->second.size() == 1)
11991 continue;
11992
11993 // C++ [class.virtual]p2:
11994 // In a derived class, if a virtual member function of a base
11995 // class subobject has more than one final overrider the
11996 // program is ill-formed.
11997 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000011998 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011999 Diag(M->first->getLocation(),
12000 diag::note_overridden_virtual_function);
12001 for (OverridingMethods::overriding_iterator
12002 OM = SO->second.begin(),
12003 OMEnd = SO->second.end();
12004 OM != OMEnd; ++OM)
12005 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012006 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012007
12008 Record->setInvalidDecl();
12009 }
12010 }
12011 CXXRecord->completeDefinition(&FinalOverriders);
12012 Completed = true;
12013 }
12014 }
12015 }
12016 }
12017
12018 if (!Completed)
12019 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012020
Richard Smithbe507b62013-02-01 08:12:08 +000012021 if (Record->hasAttrs())
12022 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012023
12024 // Check if the structure/union declaration is a language extension.
12025 if (!getLangOpts().CPlusPlus) {
12026 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012027 bool IsEmpty = true;
12028 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012029 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012030 E = Record->field_end();
12031 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12032 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012033 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012034 if (I->getBitWidthValue(Context) > 0)
12035 ZeroSize = false;
12036 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012037 ++NonBitFields;
12038 QualType FieldType = I->getType();
12039 if (FieldType->isIncompleteType() ||
12040 !Context.getTypeSizeInChars(FieldType).isZero())
12041 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012042 }
12043 }
12044
12045 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
12046 // C++.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012047 if (ZeroSize)
12048 Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
12049 << Record->isUnion() << (NonBitFields > 1);
Serge Pavlov122e6012013-06-08 13:29:58 +000012050
12051 // Structs without named members are extension in C (C99 6.7.2.1p7), but
12052 // are accepted by GCC.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012053 if (NonBitFields == 0) {
12054 if (IsEmpty)
Serge Pavlov122e6012013-06-08 13:29:58 +000012055 Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
12056 else
12057 Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
12058 }
12059 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012060 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012061 ObjCIvarDecl **ClsFields =
12062 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012063 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012064 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012065 // Add ivar's to class's DeclContext.
12066 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12067 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012068 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012069 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012070 // Must enforce the rule that ivars in the base classes may not be
12071 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012072 if (ID->getSuperClass())
12073 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012074 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012075 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012076 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012077 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12078 // Ivar declared in @implementation never belongs to the implementation.
12079 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012080 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012081 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012082 IMPDecl->setIvarLBraceLoc(LBrac);
12083 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012084 } else if (ObjCCategoryDecl *CDecl =
12085 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012086 // case of ivars in class extension; all other cases have been
12087 // reported as errors elsewhere.
12088 // FIXME. Class extension does not have a LocEnd field.
12089 // CDecl->setLocEnd(RBrac);
12090 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012091 // Diagnose redeclaration of private ivars.
12092 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012093 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012094 if (IDecl) {
12095 if (const ObjCIvarDecl *ClsIvar =
12096 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12097 Diag(ClsFields[i]->getLocation(),
12098 diag::err_duplicate_ivar_declaration);
12099 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12100 continue;
12101 }
Douglas Gregord3297242013-01-16 23:00:23 +000012102 for (ObjCInterfaceDecl::known_extensions_iterator
12103 Ext = IDecl->known_extensions_begin(),
12104 ExtEnd = IDecl->known_extensions_end();
12105 Ext != ExtEnd; ++Ext) {
12106 if (const ObjCIvarDecl *ClsExtIvar
12107 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012108 Diag(ClsFields[i]->getLocation(),
12109 diag::err_duplicate_ivar_declaration);
12110 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12111 continue;
12112 }
12113 }
12114 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012115 ClsFields[i]->setLexicalDeclContext(CDecl);
12116 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012117 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012118 CDecl->setIvarLBraceLoc(LBrac);
12119 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012120 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012121 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012122
12123 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012124 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012125}
12126
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012127/// \brief Determine whether the given integral value is representable within
12128/// the given type T.
12129static bool isRepresentableIntegerValue(ASTContext &Context,
12130 llvm::APSInt &Value,
12131 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012132 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012133 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012134
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012135 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012136 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012137 --BitWidth;
12138 return Value.getActiveBits() <= BitWidth;
12139 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012140 return Value.getMinSignedBits() <= BitWidth;
12141}
12142
12143// \brief Given an integral type, return the next larger integral type
12144// (or a NULL type of no such type exists).
12145static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12146 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12147 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012148 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012149 const unsigned NumTypes = 4;
12150 QualType SignedIntegralTypes[NumTypes] = {
12151 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12152 };
12153 QualType UnsignedIntegralTypes[NumTypes] = {
12154 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12155 Context.UnsignedLongLongTy
12156 };
12157
12158 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012159 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12160 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012161 for (unsigned I = 0; I != NumTypes; ++I)
12162 if (Context.getTypeSize(Types[I]) > BitWidth)
12163 return Types[I];
12164
12165 return QualType();
12166}
12167
Douglas Gregor879fd492009-03-17 19:05:46 +000012168EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12169 EnumConstantDecl *LastEnumConst,
12170 SourceLocation IdLoc,
12171 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012172 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012173 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012174 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012175 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012176
12177 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12178 Val = 0;
12179
Eli Friedman19efa3e2011-12-06 00:10:34 +000012180 if (Val)
12181 Val = DefaultLvalueConversion(Val).take();
12182
Douglas Gregor4912c342009-11-06 00:03:12 +000012183 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012184 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012185 EltTy = Context.DependentTy;
12186 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012187 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012188 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012189 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012190 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12191 // constant-expression in the enumerator-definition shall be a converted
12192 // constant expression of the underlying type.
12193 EltTy = Enum->getIntegerType();
12194 ExprResult Converted =
12195 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12196 CCEK_Enumerator);
12197 if (Converted.isInvalid())
12198 Val = 0;
12199 else
12200 Val = Converted.take();
12201 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012202 !(Val = VerifyIntegerConstantExpression(Val,
12203 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012204 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012205 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012206 if (Enum->isFixed()) {
12207 EltTy = Enum->getIntegerType();
12208
Richard Smith8ef7b202012-01-18 23:55:52 +000012209 // In Obj-C and Microsoft mode, require the enumeration value to be
12210 // representable in the underlying type of the enumeration. In C++11,
12211 // we perform a non-narrowing conversion as part of converted constant
12212 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012213 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012214 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012215 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012216 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012217 } else
12218 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012219 } else
John Wiegley429bb272011-04-08 18:41:53 +000012220 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012221 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012222 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012223 // If the underlying type is not fixed, the type of each enumerator
12224 // is the type of its initializing value:
12225 // - If an initializer is specified for an enumerator, the
12226 // initializing value has the same type as the expression.
12227 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012228 } else {
12229 // C99 6.7.2.2p2:
12230 // The expression that defines the value of an enumeration constant
12231 // shall be an integer constant expression that has a value
12232 // representable as an int.
12233
12234 // Complain if the value is not representable in an int.
12235 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12236 Diag(IdLoc, diag::ext_enum_value_not_int)
12237 << EnumVal.toString(10) << Val->getSourceRange()
12238 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12239 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12240 // Force the type of the expression to 'int'.
12241 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12242 }
12243 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012244 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012245 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012246 }
12247 }
Mike Stump1eb44332009-09-09 15:08:12 +000012248
Douglas Gregor879fd492009-03-17 19:05:46 +000012249 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012250 if (Enum->isDependentType())
12251 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012252 else if (!LastEnumConst) {
12253 // C++0x [dcl.enum]p5:
12254 // If the underlying type is not fixed, the type of each enumerator
12255 // is the type of its initializing value:
12256 // - If no initializer is specified for the first enumerator, the
12257 // initializing value has an unspecified integral type.
12258 //
12259 // GCC uses 'int' for its unspecified integral type, as does
12260 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012261 if (Enum->isFixed()) {
12262 EltTy = Enum->getIntegerType();
12263 }
12264 else {
12265 EltTy = Context.IntTy;
12266 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012267 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012268 // Assign the last value + 1.
12269 EnumVal = LastEnumConst->getInitVal();
12270 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012271 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012272
12273 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012274 if (EnumVal < LastEnumConst->getInitVal()) {
12275 // C++0x [dcl.enum]p5:
12276 // If the underlying type is not fixed, the type of each enumerator
12277 // is the type of its initializing value:
12278 //
12279 // - Otherwise the type of the initializing value is the same as
12280 // the type of the initializing value of the preceding enumerator
12281 // unless the incremented value is not representable in that type,
12282 // in which case the type is an unspecified integral type
12283 // sufficient to contain the incremented value. If no such type
12284 // exists, the program is ill-formed.
12285 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012286 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012287 // There is no integral type larger enough to represent this
12288 // value. Complain, then allow the value to wrap around.
12289 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012290 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012291 ++EnumVal;
12292 if (Enum->isFixed())
12293 // When the underlying type is fixed, this is ill-formed.
12294 Diag(IdLoc, diag::err_enumerator_wrapped)
12295 << EnumVal.toString(10)
12296 << EltTy;
12297 else
12298 Diag(IdLoc, diag::warn_enumerator_too_large)
12299 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012300 } else {
12301 EltTy = T;
12302 }
12303
12304 // Retrieve the last enumerator's value, extent that type to the
12305 // type that is supposed to be large enough to represent the incremented
12306 // value, then increment.
12307 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012308 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012309 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012310 ++EnumVal;
12311
12312 // If we're not in C++, diagnose the overflow of enumerator values,
12313 // which in C99 means that the enumerator value is not representable in
12314 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12315 // permits enumerator values that are representable in some larger
12316 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012317 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012318 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012319 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012320 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12321 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12322 Diag(IdLoc, diag::ext_enum_value_not_int)
12323 << EnumVal.toString(10) << 1;
12324 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012325 }
12326 }
Mike Stump1eb44332009-09-09 15:08:12 +000012327
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012328 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012329 // Make the enumerator value match the signedness and size of the
12330 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012331 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012332 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012333 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012334
Douglas Gregor879fd492009-03-17 19:05:46 +000012335 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012336 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012337}
12338
12339
John McCall5b629aa2010-10-22 23:36:17 +000012340Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12341 SourceLocation IdLoc, IdentifierInfo *Id,
12342 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012343 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012344 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012345 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012346 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012347
Chris Lattner31e05722007-08-26 06:24:45 +000012348 // The scope passed in may not be a decl scope. Zip up the scope tree until
12349 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012350 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012351
Reid Spencer5f016e22007-07-11 17:01:13 +000012352 // Verify that there isn't already something declared with this name in this
12353 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012354 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012355 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012356 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012357 // Maybe we will complain about the shadowed template parameter.
12358 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12359 // Just pretend that we didn't see the previous declaration.
12360 PrevDecl = 0;
12361 }
12362
12363 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012364 // When in C++, we may get a TagDecl with the same name; in this case the
12365 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012366 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012367 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012368 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012369 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012370 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012371 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012372 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012373 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012374 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012375 }
12376 }
12377
Aaron Ballmanf8167872012-07-19 03:12:23 +000012378 // C++ [class.mem]p15:
12379 // If T is the name of a class, then each of the following shall have a name
12380 // different from T:
12381 // - every enumerator of every member of class T that is an unscoped
12382 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012383 if (CXXRecordDecl *Record
12384 = dyn_cast<CXXRecordDecl>(
12385 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012386 if (!TheEnumDecl->isScoped() &&
12387 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012388 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12389
John McCall5b629aa2010-10-22 23:36:17 +000012390 EnumConstantDecl *New =
12391 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012392
John McCall92f88312010-01-23 00:46:32 +000012393 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012394 // Process attributes.
12395 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12396
12397 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012398 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012399 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012400 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012401
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012402 ActOnDocumentableDecl(New);
12403
John McCalld226f652010-08-21 09:40:31 +000012404 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012405}
12406
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012407// Returns true when the enum initial expression does not trigger the
12408// duplicate enum warning. A few common cases are exempted as follows:
12409// Element2 = Element1
12410// Element2 = Element1 + 1
12411// Element2 = Element1 - 1
12412// Where Element2 and Element1 are from the same enum.
12413static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12414 Expr *InitExpr = ECD->getInitExpr();
12415 if (!InitExpr)
12416 return true;
12417 InitExpr = InitExpr->IgnoreImpCasts();
12418
12419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12420 if (!BO->isAdditiveOp())
12421 return true;
12422 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12423 if (!IL)
12424 return true;
12425 if (IL->getValue() != 1)
12426 return true;
12427
12428 InitExpr = BO->getLHS();
12429 }
12430
12431 // This checks if the elements are from the same enum.
12432 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12433 if (!DRE)
12434 return true;
12435
12436 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12437 if (!EnumConstant)
12438 return true;
12439
12440 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12441 Enum)
12442 return true;
12443
12444 return false;
12445}
12446
12447struct DupKey {
12448 int64_t val;
12449 bool isTombstoneOrEmptyKey;
12450 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12451 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12452};
12453
12454static DupKey GetDupKey(const llvm::APSInt& Val) {
12455 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12456 false);
12457}
12458
12459struct DenseMapInfoDupKey {
12460 static DupKey getEmptyKey() { return DupKey(0, true); }
12461 static DupKey getTombstoneKey() { return DupKey(1, true); }
12462 static unsigned getHashValue(const DupKey Key) {
12463 return (unsigned)(Key.val * 37);
12464 }
12465 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12466 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12467 LHS.val == RHS.val;
12468 }
12469};
12470
12471// Emits a warning when an element is implicitly set a value that
12472// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012473static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12474 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012475 QualType EnumType) {
12476 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12477 Enum->getLocation()) ==
12478 DiagnosticsEngine::Ignored)
12479 return;
12480 // Avoid anonymous enums
12481 if (!Enum->getIdentifier())
12482 return;
12483
12484 // Only check for small enums.
12485 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12486 return;
12487
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012488 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12489 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012490
12491 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12492 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12493 ValueToVectorMap;
12494
12495 DuplicatesVector DupVector;
12496 ValueToVectorMap EnumMap;
12497
12498 // Populate the EnumMap with all values represented by enum constants without
12499 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012500 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012501 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012502
12503 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12504 // this constant. Skip this enum since it may be ill-formed.
12505 if (!ECD) {
12506 return;
12507 }
12508
12509 if (ECD->getInitExpr())
12510 continue;
12511
12512 DupKey Key = GetDupKey(ECD->getInitVal());
12513 DeclOrVector &Entry = EnumMap[Key];
12514
12515 // First time encountering this value.
12516 if (Entry.isNull())
12517 Entry = ECD;
12518 }
12519
12520 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012521 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012522 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12523 if (!ValidDuplicateEnum(ECD, Enum))
12524 continue;
12525
12526 DupKey Key = GetDupKey(ECD->getInitVal());
12527
12528 DeclOrVector& Entry = EnumMap[Key];
12529 if (Entry.isNull())
12530 continue;
12531
12532 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12533 // Ensure constants are different.
12534 if (D == ECD)
12535 continue;
12536
12537 // Create new vector and push values onto it.
12538 ECDVector *Vec = new ECDVector();
12539 Vec->push_back(D);
12540 Vec->push_back(ECD);
12541
12542 // Update entry to point to the duplicates vector.
12543 Entry = Vec;
12544
12545 // Store the vector somewhere we can consult later for quick emission of
12546 // diagnostics.
12547 DupVector.push_back(Vec);
12548 continue;
12549 }
12550
12551 ECDVector *Vec = Entry.get<ECDVector*>();
12552 // Make sure constants are not added more than once.
12553 if (*Vec->begin() == ECD)
12554 continue;
12555
12556 Vec->push_back(ECD);
12557 }
12558
12559 // Emit diagnostics.
12560 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12561 DupVectorEnd = DupVector.end();
12562 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12563 ECDVector *Vec = *DupVectorIter;
12564 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12565
12566 // Emit warning for one enum constant.
12567 ECDVector::iterator I = Vec->begin();
12568 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12569 << (*I)->getName() << (*I)->getInitVal().toString(10)
12570 << (*I)->getSourceRange();
12571 ++I;
12572
12573 // Emit one note for each of the remaining enum constants with
12574 // the same value.
12575 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12576 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12577 << (*I)->getName() << (*I)->getInitVal().toString(10)
12578 << (*I)->getSourceRange();
12579 delete Vec;
12580 }
12581}
12582
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012583void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012584 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012585 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012586 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012587 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012588 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012589
12590 if (Attr)
12591 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012592
Eli Friedmaned0716b2009-12-11 01:34:50 +000012593 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012594 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012595 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012596 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012597 if (!ECD) continue;
12598
12599 ECD->setType(EnumType);
12600 }
12601
John McCall1b5a6182010-05-06 08:49:23 +000012602 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012603 return;
12604 }
12605
Chris Lattnere37f0be2007-08-28 05:10:31 +000012606 // TODO: If the result value doesn't fit in an int, it must be a long or long
12607 // long value. ISO C does not support this, but GCC does as an extension,
12608 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012609 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12610 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12611 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012612
Chris Lattnerac609682007-08-28 06:15:15 +000012613 // Verify that all the values are okay, compute the size of the values, and
12614 // reverse the list.
12615 unsigned NumNegativeBits = 0;
12616 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012617
Chris Lattnerac609682007-08-28 06:15:15 +000012618 // Keep track of whether all elements have type int.
12619 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012620
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012621 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012622 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012623 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012624 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012625
Chris Lattner211a30e2007-08-28 05:27:00 +000012626 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012627
Chris Lattnerac609682007-08-28 06:15:15 +000012628 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012629 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012630 NumPositiveBits = std::max(NumPositiveBits,
12631 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012632 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012633 NumNegativeBits = std::max(NumNegativeBits,
12634 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012635
Chris Lattnerac609682007-08-28 06:15:15 +000012636 // Keep track of whether every enum element has type int (very commmon).
12637 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012638 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012639 }
Mike Stump1eb44332009-09-09 15:08:12 +000012640
Chris Lattnerac609682007-08-28 06:15:15 +000012641 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012642 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012643 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012644
John McCall842aef82009-12-09 09:09:27 +000012645 // C++0x N3000 [conv.prom]p3:
12646 // An rvalue of an unscoped enumeration type whose underlying
12647 // type is not fixed can be converted to an rvalue of the first
12648 // of the following types that can represent all the values of
12649 // the enumeration: int, unsigned int, long int, unsigned long
12650 // int, long long int, or unsigned long long int.
12651 // C99 6.4.4.3p2:
12652 // An identifier declared as an enumeration constant has type int.
12653 // The C99 rule is modified by a gcc extension
12654 QualType BestPromotionType;
12655
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012656 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012657 // -fshort-enums is the equivalent to specifying the packed attribute on all
12658 // enum definitions.
12659 if (LangOpts.ShortEnums)
12660 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012661
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012662 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012663 BestType = Enum->getIntegerType();
12664 if (BestType->isPromotableIntegerType())
12665 BestPromotionType = Context.getPromotedIntegerType(BestType);
12666 else
12667 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012668 // We don't need to set BestWidth, because BestType is going to be the type
12669 // of the enumerators, but we do anyway because otherwise some compilers
12670 // warn that it might be used uninitialized.
12671 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012672 }
12673 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012674 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012675 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012676 // If it's packed, check also if it fits a char or a short.
12677 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012678 BestType = Context.SignedCharTy;
12679 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012680 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012681 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012682 BestType = Context.ShortTy;
12683 BestWidth = ShortWidth;
12684 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012685 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012686 BestWidth = IntWidth;
12687 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012688 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012689
John McCall842aef82009-12-09 09:09:27 +000012690 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012691 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012692 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012693 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012694
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012695 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012696 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12697 BestType = Context.LongLongTy;
12698 }
12699 }
John McCall842aef82009-12-09 09:09:27 +000012700 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012701 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012702 // If there is no negative value, figure out the smallest type that fits
12703 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012704 // If it's packed, check also if it fits a char or a short.
12705 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012706 BestType = Context.UnsignedCharTy;
12707 BestPromotionType = Context.IntTy;
12708 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012709 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012710 BestType = Context.UnsignedShortTy;
12711 BestPromotionType = Context.IntTy;
12712 BestWidth = ShortWidth;
12713 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012714 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012715 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012716 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012717 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012718 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012719 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012720 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012721 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012722 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012723 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012724 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012725 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012726 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012727 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012728 "How could an initializer get larger than ULL?");
12729 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012730 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012731 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012732 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012733 }
12734 }
Mike Stump1eb44332009-09-09 15:08:12 +000012735
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012736 // Loop over all of the enumerator constants, changing their types to match
12737 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012738 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012739 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012740 if (!ECD) continue; // Already issued a diagnostic.
12741
12742 // Standard C says the enumerators have int type, but we allow, as an
12743 // extension, the enumerators to be larger than int size. If each
12744 // enumerator value fits in an int, type it as an int, otherwise type it the
12745 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12746 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012747
12748 // Determine whether the value fits into an int.
12749 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012750
12751 // If it fits into an integer type, force it. Otherwise force it to match
12752 // the enum decl type.
12753 QualType NewTy;
12754 unsigned NewWidth;
12755 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012756 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012757 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012758 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012759 NewTy = Context.IntTy;
12760 NewWidth = IntWidth;
12761 NewSign = true;
12762 } else if (ECD->getType() == BestType) {
12763 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012764 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012765 // C++ [dcl.enum]p4: Following the closing brace of an
12766 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012767 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012768 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012769 continue;
12770 } else {
12771 NewTy = BestType;
12772 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012773 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012774 }
12775
12776 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012777 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012778 InitVal.setIsSigned(NewSign);
12779 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012780
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012781 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012782 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012783 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012784 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012785 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012786 ECD->getInitExpr(),
12787 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012788 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012789 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012790 // C++ [dcl.enum]p4: Following the closing brace of an
12791 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012792 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012793 ECD->setType(EnumType);
12794 else
12795 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012796 }
Mike Stump1eb44332009-09-09 15:08:12 +000012797
John McCall1b5a6182010-05-06 08:49:23 +000012798 Enum->completeDefinition(BestType, BestPromotionType,
12799 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012800
12801 // If we're declaring a function, ensure this decl isn't forgotten about -
12802 // it needs to go into the function scope.
12803 if (InFunctionDeclarator)
12804 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012805
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012806 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012807
12808 // Now that the enum type is defined, ensure it's not been underaligned.
12809 if (Enum->hasAttrs())
12810 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012811}
12812
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012813Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12814 SourceLocation StartLoc,
12815 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012816 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012817
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012818 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012819 AsmString, StartLoc,
12820 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012821 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012822 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012823}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012824
Douglas Gregor5948ae12012-01-03 18:04:46 +000012825DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12826 SourceLocation ImportLoc,
12827 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012828 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012829 Module::AllVisible,
12830 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012831 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012832 return true;
12833
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012834 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012835 Module *ModCheck = Mod;
12836 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12837 // If we've run out of module parents, just drop the remaining identifiers.
12838 // We need the length to be consistent.
12839 if (!ModCheck)
12840 break;
12841 ModCheck = ModCheck->Parent;
12842
12843 IdentifierLocs.push_back(Path[I].second);
12844 }
12845
12846 ImportDecl *Import = ImportDecl::Create(Context,
12847 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012848 AtLoc.isValid()? AtLoc : ImportLoc,
12849 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012850 Context.getTranslationUnitDecl()->addDecl(Import);
12851 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012852}
12853
Douglas Gregorca2ab452013-01-12 01:29:50 +000012854void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12855 // Create the implicit import declaration.
12856 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12857 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12858 Loc, Mod, Loc);
12859 TU->addDecl(ImportD);
12860 Consumer.HandleImplicitImportDecl(ImportD);
12861
12862 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012863 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12864 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012865}
12866
David Chisnall5f3c1632012-02-18 16:12:34 +000012867void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12868 IdentifierInfo* AliasName,
12869 SourceLocation PragmaLoc,
12870 SourceLocation NameLoc,
12871 SourceLocation AliasNameLoc) {
12872 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12873 LookupOrdinaryName);
12874 AsmLabelAttr *Attr =
12875 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012876
12877 if (PrevDecl)
12878 PrevDecl->addAttr(Attr);
12879 else
12880 (void)ExtnameUndeclaredIdentifiers.insert(
12881 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12882}
12883
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012884void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12885 SourceLocation PragmaLoc,
12886 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012887 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012888
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012889 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012890 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012891 } else {
12892 (void)WeakUndeclaredIdentifiers.insert(
12893 std::pair<IdentifierInfo*,WeakInfo>
12894 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012895 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012896}
12897
12898void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12899 IdentifierInfo* AliasName,
12900 SourceLocation PragmaLoc,
12901 SourceLocation NameLoc,
12902 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012903 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12904 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012905 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012906
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012907 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012908 if (!PrevDecl->hasAttr<AliasAttr>())
12909 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012910 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012911 } else {
12912 (void)WeakUndeclaredIdentifiers.insert(
12913 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012914 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012915}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012916
12917Decl *Sema::getObjCDeclContext() const {
12918 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12919}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012920
12921AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000012922 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012923 return D->getAvailability();
12924}