blob: c0be341b663ea828295ddd3dd27cb306eb4f2963 [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"
Faisal Valic00e4192013-11-07 05:17:06 +000043#include "clang/Sema/Template.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000044#include "llvm/ADT/SmallString.h"
John McCall66755862009-12-24 09:58:38 +000045#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000046#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000047#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000048#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000050using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Richard Smithc89edf52011-07-01 19:46:12 +000052Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53 if (OwnedType) {
54 Decl *Group[2] = { OwnedType, Ptr };
55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56 }
57
John McCalld226f652010-08-21 09:40:31 +000058 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner682bf922009-03-29 16:50:03 +000059}
60
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000061namespace {
62
63class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64 public:
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000067 WantExpressionKeywords = false;
68 WantCXXNamedCasts = false;
69 WantRemainingKeywords = false;
70 }
71
72 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
73 if (NamedDecl *ND = candidate.getCorrectionDecl())
74 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
75 (AllowInvalidDecl || !ND->isInvalidDecl());
76 else
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000077 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000078 }
79
80 private:
81 bool AllowInvalidDecl;
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000082 bool WantClassName;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000083};
84
85}
86
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +000087/// \brief Determine whether the token kind starts a simple-type-specifier.
88bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
89 switch (Kind) {
90 // FIXME: Take into account the current language when deciding whether a
91 // token kind is a valid type specifier
92 case tok::kw_short:
93 case tok::kw_long:
94 case tok::kw___int64:
95 case tok::kw___int128:
96 case tok::kw_signed:
97 case tok::kw_unsigned:
98 case tok::kw_void:
99 case tok::kw_char:
100 case tok::kw_int:
101 case tok::kw_half:
102 case tok::kw_float:
103 case tok::kw_double:
104 case tok::kw_wchar_t:
105 case tok::kw_bool:
106 case tok::kw___underlying_type:
107 return true;
108
109 case tok::annot_typename:
110 case tok::kw_char16_t:
111 case tok::kw_char32_t:
112 case tok::kw_typeof:
David Majnemerff989a82013-09-22 01:24:26 +0000113 case tok::annot_decltype:
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +0000114 case tok::kw_decltype:
115 return getLangOpts().CPlusPlus;
116
117 default:
118 break;
119 }
120
121 return false;
122}
123
Douglas Gregord6efafa2009-02-04 19:16:12 +0000124/// \brief If the identifier refers to a type name within this scope,
125/// return the declaration of that type.
126///
127/// This routine performs ordinary name lookup of the identifier II
128/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000129/// determine whether the name refers to a type. If so, returns an
130/// opaque pointer (actually a QualType) corresponding to that
131/// type. Otherwise, returns NULL.
Dmitri Gribenko8eead162013-05-03 13:12:11 +0000132ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallb3d87482010-08-24 05:47:05 +0000133 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000134 bool isClassName, bool HasTrailingDot,
Douglas Gregor9e876872011-03-01 18:12:44 +0000135 ParsedType ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000136 bool IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000137 bool WantNontrivialTypeSourceInfo,
138 IdentifierInfo **CorrectedII) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000139 // Determine where we will perform name lookup.
140 DeclContext *LookupCtx = 0;
141 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +0000142 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000143 if (ObjectType->isRecordType())
144 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +0000145 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000146 LookupCtx = computeDeclContext(*SS, false);
147
148 if (!LookupCtx) {
149 if (isDependentScopeSpecifier(*SS)) {
150 // C++ [temp.res]p3:
151 // A qualified-id that refers to a type and in which the
152 // nested-name-specifier depends on a template-parameter (14.6.2)
153 // shall be prefixed by the keyword typename to indicate that the
154 // qualified-id denotes a type, forming an
155 // elaborated-type-specifier (7.1.5.3).
156 //
157 // We therefore do not perform any name lookup if the result would
158 // refer to a member of an unknown specialization.
Richard Smithc5a89a12012-04-02 01:30:27 +0000159 if (!isClassName && !IsCtorOrDtorName)
John McCallb3d87482010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000161
John McCall33500952010-06-11 00:33:02 +0000162 // We know from the grammar that this name refers to a type,
163 // so build a dependent node to describe the type.
Douglas Gregor9e876872011-03-01 18:12:44 +0000164 if (WantNontrivialTypeSourceInfo)
165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166
167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallb3d87482010-08-24 05:47:05 +0000168 QualType T =
Douglas Gregor9e876872011-03-01 18:12:44 +0000169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +0000170 II, NameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +0000171
172 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000173 }
174
John McCallb3d87482010-08-24 05:47:05 +0000175 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000176 }
177
John McCall77bb1aa2010-05-01 00:40:08 +0000178 if (!LookupCtx->isDependentContext() &&
179 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000181 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000182
183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184 // lookup for class-names.
185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186 LookupOrdinaryName;
187 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000188 if (LookupCtx) {
189 // Perform "qualified" name lookup into the declaration context we
190 // computed, which is either the type of the base of a member access
191 // expression or the declaration context associated with a prior
192 // nested-name-specifier.
193 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000194
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000195 if (ObjectTypePtr && Result.empty()) {
196 // C++ [basic.lookup.classref]p3:
197 // If the unqualified-id is ~type-name, the type-name is looked up
198 // in the context of the entire postfix-expression. If the type T of
199 // the object expression is of a class type C, the type-name is also
200 // looked up in the scope of class C. At least one of the lookups shall
201 // find a name that refers to (possibly cv-qualified) T.
202 LookupName(Result, S);
203 }
204 } else {
205 // Perform unqualified name lookup.
206 LookupName(Result, S);
207 }
208
Chris Lattner22bd9052009-02-16 22:07:16 +0000209 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000210 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000211 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000212 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000213 if (CorrectedII) {
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +0000214 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000216 Kind, S, SS, Validator);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218 TemplateTy Template;
219 bool MemberOfUnknownSpecialization;
220 UnqualifiedId TemplateName;
221 TemplateName.setIdentifier(NewII, NameLoc);
222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223 CXXScopeSpec NewSS, *NewSSPtr = SS;
224 if (SS && NNS) {
225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226 NewSSPtr = &NewSS;
227 }
228 if (Correction && (NNS || NewII != &II) &&
229 // Ignore a correction to a template type as the to-be-corrected
230 // identifier is not a template (typo correction for template names
231 // is handled elsewhere).
David Blaikie4e4d0842012-03-11 07:00:24 +0000232 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234 false, Template, MemberOfUnknownSpecialization))) {
235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000237 IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000238 WantNontrivialTypeSourceInfo);
239 if (Ty) {
Richard Smith2d670972013-08-17 00:46:16 +0000240 diagnoseTypo(Correction,
241 PDiag(diag::err_unknown_type_or_class_name_suggest)
242 << Result.getLookupName() << isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000243 if (SS && NNS)
244 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
245 *CorrectedII = NewII;
246 return Ty;
247 }
248 }
249 }
250 // If typo correction failed or was not performed, fall through
Chris Lattner22bd9052009-02-16 22:07:16 +0000251 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000252 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000253 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000254 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000255
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000256 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000257 // Recover from type-hiding ambiguities by hiding the type. We'll
258 // do the lookup again when looking for an object, and we can
259 // diagnose the error then. If we don't do this, then the error
260 // about hiding the type will be immediately followed by an error
261 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
263 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000264 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000265 }
John McCall6e247262009-10-10 05:48:19 +0000266
Douglas Gregor31a19b62009-04-01 21:51:26 +0000267 // Look to see if we have a type anywhere in the list of results.
268 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
269 Res != ResEnd; ++Res) {
270 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000271 if (!IIDecl ||
272 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000273 IIDecl->getLocation().getRawEncoding())
274 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000275 }
276 }
277
278 if (!IIDecl) {
279 // None of the entities we found is a type, so there is no way
280 // to even assume that the result is a type. In this case, don't
281 // complain about the ambiguity. The parser will either try to
282 // perform this lookup again (e.g., as an object name), which
283 // will produce the ambiguity, or will complain that it expected
284 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000285 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000286 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000287 }
288
289 // We found a type within the ambiguous lookup; diagnose the
290 // ambiguity and then return that type. This might be the right
291 // answer, or it might not be, but it suppresses any attempt to
292 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000293 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000294
Chris Lattner22bd9052009-02-16 22:07:16 +0000295 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000296 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000297 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000298 }
299
Chris Lattner10ca3372009-10-25 17:16:46 +0000300 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000301
Chris Lattner10ca3372009-10-25 17:16:46 +0000302 QualType T;
303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000304 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000305
Chris Lattner10ca3372009-10-25 17:16:46 +0000306 if (T.isNull())
307 T = Context.getTypeDeclType(TD);
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000308
309 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
310 // constructor or destructor name (in such a case, the scope specifier
311 // will be attached to the enclosing Expr or Decl node).
312 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor9e876872011-03-01 18:12:44 +0000313 if (WantNontrivialTypeSourceInfo) {
314 // Construct a type with type-source information.
315 TypeLocBuilder Builder;
316 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
317
318 T = getElaboratedType(ETK_None, *SS, T);
319 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +0000320 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor9e876872011-03-01 18:12:44 +0000321 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
322 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
323 } else {
324 T = getElaboratedType(ETK_None, *SS, T);
325 }
326 }
Chris Lattner10ca3372009-10-25 17:16:46 +0000327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000328 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000329 if (!HasTrailingDot)
330 T = Context.getObjCInterfaceType(IDecl);
331 }
332
333 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000334 // If it's not plausibly a type, suppress diagnostics.
335 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000336 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000337 }
John McCallb3d87482010-08-24 05:47:05 +0000338 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
Chris Lattner4c97d762009-04-12 21:49:30 +0000341/// isTagName() - This method is called *for error recovery purposes only*
342/// to determine if the specified name is a valid tag name ("struct foo"). If
343/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matos6666ed42012-08-31 18:45:21 +0000344/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
345/// cases in C where the user forgot to specify the tag.
Chris Lattner4c97d762009-04-12 21:49:30 +0000346DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
347 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000348 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
349 LookupName(R, S, false);
350 R.suppressDiagnostics();
351 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000353 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000354 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matos6666ed42012-08-31 18:45:21 +0000355 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000356 case TTK_Union: return DeclSpec::TST_union;
357 case TTK_Class: return DeclSpec::TST_class;
358 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000359 }
360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattner4c97d762009-04-12 21:49:30 +0000362 return DeclSpec::TST_unspecified;
363}
364
Francois Pichet6943e9b2011-04-13 02:38:49 +0000365/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
366/// if a CXXScopeSpec's type is equal to the type of one of the base classes
367/// then downgrade the missing typename error to a warning.
368/// This is needed for MSVC compatibility; Example:
369/// @code
370/// template<class T> class A {
371/// public:
372/// typedef int TYPE;
373/// };
374/// template<class T> class B : public A<T> {
375/// public:
376/// A<T>::TYPE a; // no typename required because A<T> is a base class.
377/// };
378/// @endcode
Francois Pichetf11dbe92011-10-11 01:50:09 +0000379bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000380 if (CurContext->isRecord()) {
Francois Pichet3441a522011-04-13 02:44:57 +0000381 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000382
383 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
384 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
385 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
386 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
387 return true;
Francois Pichetf11dbe92011-10-11 01:50:09 +0000388 return S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000389 }
Francois Pichetf11dbe92011-10-11 01:50:09 +0000390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000391}
392
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000393bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000394 SourceLocation IILoc,
395 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000396 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000397 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000398 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000399 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000400
Douglas Gregor546be3c2009-12-30 17:04:44 +0000401 // There may have been a typo in the name of the type. Look up typo
402 // results, in case we have something that we can suggest.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000403 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000405 LookupOrdinaryName, S, SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000406 Validator)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000407 if (Corrected.isKeyword()) {
408 // We corrected to a keyword.
Richard Smith2d670972013-08-17 00:46:16 +0000409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
410 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000411 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000412 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000413 if (!SS || !SS->isSet()) {
Richard Smith2d670972013-08-17 00:46:16 +0000414 diagnoseTypo(Corrected,
415 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +0000417 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000419 II->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected,
421 PDiag(diag::err_unknown_nested_typename_suggest)
422 << II << DC << DroppedSpecifier << SS->getRange());
423 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000424 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000425 }
Douglas Gregor546be3c2009-12-30 17:04:44 +0000426
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000427 CXXScopeSpec tmpSS;
428 if (Corrected.getCorrectionSpecifier())
429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
430 SourceRange(IILoc));
Richard Smith2d670972013-08-17 00:46:16 +0000431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
433 false, ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000434 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000435 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor546be3c2009-12-30 17:04:44 +0000436 }
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000437 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000438 }
439
David Blaikie4e4d0842012-03-11 07:00:24 +0000440 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000441 // See if II is a class template that the user forgot to pass arguments to.
442 UnqualifiedId Name;
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000443 Name.setIdentifier(II, IILoc);
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000444 CXXScopeSpec EmptySS;
445 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000446 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000448 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000449 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov18062392013-08-27 13:15:56 +0000450 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000451 Diag(IILoc, diag::err_template_missing_args) << TplName;
452 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
453 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
454 << TplDecl->getTemplateParameters()->getSourceRange();
455 }
456 return true;
457 }
458 }
459
Douglas Gregora786fdb2009-10-13 23:27:22 +0000460 // FIXME: Should we move the logic that tries to recover from a missing tag
461 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
462
Douglas Gregor546be3c2009-12-30 17:04:44 +0000463 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000464 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregora786fdb2009-10-13 23:27:22 +0000465 else if (DeclContext *DC = computeDeclContext(*SS, false))
466 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000467 << II << DC << SS->getRange();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000468 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000469 unsigned DiagID = diag::err_typename_missing;
David Blaikie4e4d0842012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichetcf320c62011-04-22 08:25:24 +0000471 DiagID = diag::warn_typename_missing;
Francois Pichet6943e9b2011-04-13 02:38:49 +0000472
473 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000474 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000475 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000477 SuggestedType = ActOnTypenameType(S, SourceLocation(),
478 *SS, *II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000479 } else {
480 assert(SS && SS->isInvalid() &&
481 "Invalid scope specifier has already been diagnosed");
482 }
483
484 return true;
485}
Chris Lattner4c97d762009-04-12 21:49:30 +0000486
Douglas Gregor312eadb2011-04-24 05:37:28 +0000487/// \brief Determine whether the given result set contains either a type name
488/// or
489static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000491 NextToken.is(tok::less);
492
493 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
494 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
495 return true;
496
497 if (CheckTemplate && isa<TemplateDecl>(*I))
498 return true;
499 }
500
501 return false;
502}
503
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000504static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505 Scope *S, CXXScopeSpec &SS,
506 IdentifierInfo *&Name,
507 SourceLocation NameLoc) {
Richard Smith69e48262012-09-06 01:37:56 +0000508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
509 SemaRef.LookupParsedName(R, S, &SS);
510 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000511 const char *TagName = 0;
512 const char *FixItTagName = 0;
513 switch (Tag->getTagKind()) {
514 case TTK_Class:
515 TagName = "class";
516 FixItTagName = "class ";
517 break;
518
519 case TTK_Enum:
520 TagName = "enum";
521 FixItTagName = "enum ";
522 break;
523
524 case TTK_Struct:
525 TagName = "struct";
526 FixItTagName = "struct ";
527 break;
528
Joao Matos6666ed42012-08-31 18:45:21 +0000529 case TTK_Interface:
530 TagName = "__interface";
531 FixItTagName = "__interface ";
532 break;
533
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000534 case TTK_Union:
535 TagName = "union";
536 FixItTagName = "union ";
537 break;
538 }
539
540 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
541 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
542 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
543
Richard Smith69e48262012-09-06 01:37:56 +0000544 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
545 I != IEnd; ++I)
546 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
547 << Name << TagName;
548
549 // Replace lookup results with just the tag decl.
550 Result.clear(Sema::LookupTagName);
551 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000552 return true;
553 }
554
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000555 return false;
556}
557
Richard Smith05766812012-08-18 00:55:03 +0000558/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
559static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
560 QualType T, SourceLocation NameLoc) {
561 ASTContext &Context = S.Context;
562
563 TypeLocBuilder Builder;
564 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
565
566 T = S.getElaboratedType(ETK_None, SS, T);
567 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
568 ElabTL.setElaboratedKeywordLoc(SourceLocation());
569 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
570 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
571}
572
Douglas Gregor312eadb2011-04-24 05:37:28 +0000573Sema::NameClassification Sema::ClassifyName(Scope *S,
574 CXXScopeSpec &SS,
575 IdentifierInfo *&Name,
576 SourceLocation NameLoc,
Richard Smith05766812012-08-18 00:55:03 +0000577 const Token &NextToken,
578 bool IsAddressOfOperand,
579 CorrectionCandidateCallback *CCC) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000580 DeclarationNameInfo NameInfo(Name, NameLoc);
581 ObjCMethodDecl *CurMethod = getCurMethodDecl();
582
583 if (NextToken.is(tok::coloncolon)) {
584 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
585 QualType(), false, SS, 0, false);
586
587 }
588
589 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
590 LookupParsedName(Result, S, &SS, !CurMethod);
591
592 // Perform lookup for Objective-C instance variables (including automatically
593 // synthesized instance variables), if we're in an Objective-C method.
594 // FIXME: This lookup really, really needs to be folded in to the normal
595 // unqualified lookup mechanism.
596 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
597 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorec385cf2011-04-25 15:05:41 +0000598 if (E.get() || E.isInvalid())
Douglas Gregor312eadb2011-04-24 05:37:28 +0000599 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000600 }
601
602 bool SecondTry = false;
603 bool IsFilteredTemplateName = false;
604
605Corrected:
606 switch (Result.getResultKind()) {
607 case LookupResult::NotFound:
608 // If an unqualified-id is followed by a '(', then we have a function
609 // call.
610 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
611 // In C++, this is an ADL-only call.
612 // FIXME: Reference?
David Blaikie4e4d0842012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus)
Douglas Gregor312eadb2011-04-24 05:37:28 +0000614 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
615
616 // C90 6.3.2.2:
617 // If the expression that precedes the parenthesized argument list in a
618 // function call consists solely of an identifier, and if no
619 // declaration is visible for this identifier, the identifier is
620 // implicitly declared exactly as if, in the innermost block containing
621 // the function call, the declaration
622 //
623 // extern int identifier ();
624 //
625 // appeared.
626 //
627 // We also allow this in C99 as an extension.
628 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
629 Result.addDecl(D);
630 Result.resolveKind();
631 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
632 }
633 }
634
635 // In C, we first see whether there is a tag type by the same name, in
636 // which case it's likely that the user just forget to write "enum",
637 // "struct", or "union".
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000638 if (!getLangOpts().CPlusPlus && !SecondTry &&
639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640 break;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000641 }
642
643 // Perform typo correction to determine if there is another name that is
644 // close to this name.
Richard Smith05766812012-08-18 00:55:03 +0000645 if (!SecondTry && CCC) {
Douglas Gregor3a348c82011-07-14 04:54:23 +0000646 SecondTry = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikied662a792011-10-19 22:56:21 +0000648 Result.getLookupKind(), S,
Richard Smith05766812012-08-18 00:55:03 +0000649 &SS, *CCC)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smith2d670972013-08-17 00:46:16 +0000652
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor3b887352011-04-27 04:48:22 +0000654 NamedDecl *UnderlyingFirstDecl
655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikie4e4d0842012-03-11 07:00:24 +0000656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000658 UnqualifiedDiag = diag::err_no_template_suggest;
659 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor3b887352011-04-27 04:48:22 +0000660 } else if (UnderlyingFirstDecl &&
661 (isa<TypeDecl>(UnderlyingFirstDecl) ||
662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie30262b72013-03-21 21:35:15 +0000664 UnqualifiedDiag = diag::err_unknown_typename_suggest;
665 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000667
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000668 if (SS.isEmpty()) {
Richard Smith2d670972013-08-17 00:46:16 +0000669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000670 } else {// FIXME: is this even reachable? Test it.
Richard Smith2d670972013-08-17 00:46:16 +0000671 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000673 Name->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675 << Name << computeDeclContext(SS, false)
676 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000677 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000678
679 // Update the name, so that the caller has the new name.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000680 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smith2d670972013-08-17 00:46:16 +0000681
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000682 // Typo correction corrected to a keyword.
683 if (Corrected.isKeyword())
Richard Smith2d670972013-08-17 00:46:16 +0000684 return Name;
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000685
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000686 // Also update the LookupResult...
687 // FIXME: This should probably go away at some point
688 Result.clear();
689 Result.setLookupName(Corrected.getCorrection());
Richard Smith2d670972013-08-17 00:46:16 +0000690 if (FirstDecl)
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000691 Result.addDecl(FirstDecl);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000692
693 // If we found an Objective-C instance variable, let
694 // LookupInObjCMethod build the appropriate expression to
695 // reference the ivar.
696 // FIXME: This is a gross hack.
697 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
698 Result.clear();
699 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000700 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000701 }
702
703 goto Corrected;
704 }
705 }
706
707 // We failed to correct; just fall through and let the parser deal with it.
708 Result.suppressDiagnostics();
709 return NameClassification::Unknown();
710
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000711 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000712 // We performed name lookup into the current instantiation, and there were
713 // dependent bases, so we treat this result the same way as any other
714 // dependent nested-name-specifier.
715
716 // C++ [temp.res]p2:
717 // A name used in a template declaration or definition and that is
718 // dependent on a template-parameter is assumed not to name a type
719 // unless the applicable name lookup finds a type name or the name is
720 // qualified by the keyword typename.
721 //
722 // FIXME: If the next token is '<', we might want to ask the parser to
723 // perform some heroics to see if we actually have a
724 // template-argument-list, which would indicate a missing 'template'
725 // keyword here.
Richard Smith05766812012-08-18 00:55:03 +0000726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727 NameInfo, IsAddressOfOperand,
728 /*TemplateArgs=*/0);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000729 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000730
731 case LookupResult::Found:
732 case LookupResult::FoundOverloaded:
733 case LookupResult::FoundUnresolvedValue:
734 break;
735
736 case LookupResult::Ambiguous:
David Blaikie4e4d0842012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000738 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000739 // C++ [temp.local]p3:
740 // A lookup that finds an injected-class-name (10.2) can result in an
741 // ambiguity in certain cases (for example, if it is found in more than
742 // one base class). If all of the injected-class-names that are found
743 // refer to specializations of the same class template, and if the name
744 // is followed by a template-argument-list, the reference refers to the
745 // class template itself and not a specialization thereof, and is not
746 // ambiguous.
747 //
748 // This filtering can make an ambiguous result into an unambiguous one,
749 // so try again after filtering out template names.
750 FilterAcceptableTemplateNames(Result);
751 if (!Result.isAmbiguous()) {
752 IsFilteredTemplateName = true;
753 break;
754 }
755 }
756
757 // Diagnose the ambiguity and return an error.
758 return NameClassification::Error();
759 }
760
David Blaikie4e4d0842012-03-11 07:00:24 +0000761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000762 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
763 // C++ [temp.names]p3:
764 // After name lookup (3.4) finds that a name is a template-name or that
765 // an operator-function-id or a literal- operator-id refers to a set of
766 // overloaded functions any member of which is a function template if
767 // this is followed by a <, the < is always taken as the delimiter of a
768 // template-argument-list and never as the less-than operator.
769 if (!IsFilteredTemplateName)
770 FilterAcceptableTemplateNames(Result);
771
Douglas Gregor3b887352011-04-27 04:48:22 +0000772 if (!Result.empty()) {
773 bool IsFunctionTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000774 bool IsVarTemplate;
Douglas Gregor3b887352011-04-27 04:48:22 +0000775 TemplateName Template;
776 if (Result.end() - Result.begin() > 1) {
777 IsFunctionTemplate = true;
778 Template = Context.getOverloadedTemplateName(Result.begin(),
779 Result.end());
780 } else {
781 TemplateDecl *TD
782 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
783 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000784 IsVarTemplate = isa<VarTemplateDecl>(TD);
785
Douglas Gregor3b887352011-04-27 04:48:22 +0000786 if (SS.isSet() && !SS.isInvalid())
787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000788 /*TemplateKeyword=*/false,
Douglas Gregor3b887352011-04-27 04:48:22 +0000789 TD);
790 else
791 Template = TemplateName(TD);
792 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000793
Douglas Gregor3b887352011-04-27 04:48:22 +0000794 if (IsFunctionTemplate) {
795 // Function templates always go through overload resolution, at which
796 // point we'll perform the various checks (e.g., accessibility) we need
797 // to based on which function we selected.
798 Result.suppressDiagnostics();
799
800 return NameClassification::FunctionTemplate(Template);
801 }
Larisse Voufoef4579c2013-08-06 01:03:05 +0000802
803 return IsVarTemplate ? NameClassification::VarTemplate(Template)
804 : NameClassification::TypeTemplate(Template);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000805 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000806 }
Richard Smith05766812012-08-18 00:55:03 +0000807
Douglas Gregor3b887352011-04-27 04:48:22 +0000808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810 DiagnoseUseOfDecl(Type, NameLoc);
811 QualType T = Context.getTypeDeclType(Type);
Richard Smith05766812012-08-18 00:55:03 +0000812 if (SS.isNotEmpty())
813 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000814 return ParsedType::make(T);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000815 }
Richard Smith05766812012-08-18 00:55:03 +0000816
Douglas Gregor312eadb2011-04-24 05:37:28 +0000817 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
818 if (!Class) {
819 // FIXME: It's unfortunate that we don't have a Type node for handling this.
820 if (ObjCCompatibleAliasDecl *Alias
821 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
822 Class = Alias->getClassInterface();
823 }
824
825 if (Class) {
826 DiagnoseUseOfDecl(Class, NameLoc);
827
828 if (NextToken.is(tok::period)) {
829 // Interface. <something> is parsed as a property reference expression.
830 // Just return "unknown" as a fall-through for now.
831 Result.suppressDiagnostics();
832 return NameClassification::Unknown();
833 }
834
835 QualType T = Context.getObjCInterfaceType(Class);
836 return ParsedType::make(T);
837 }
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000838
Richard Smith05766812012-08-18 00:55:03 +0000839 // We can have a type template here if we're classifying a template argument.
840 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
841 return NameClassification::TypeTemplate(
842 TemplateName(cast<TemplateDecl>(FirstDecl)));
843
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000844 // Check for a tag type hidden by a non-type decl in a few cases where it
845 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidis99e9fe02013-05-07 19:54:28 +0000846 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
847 if ((NextToken.is(tok::identifier) ||
848 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
849 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
850 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
851 DiagnoseUseOfDecl(Type, NameLoc);
852 QualType T = Context.getTypeDeclType(Type);
853 if (SS.isNotEmpty())
854 return buildNestedType(*this, SS, T, NameLoc);
855 return ParsedType::make(T);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000856 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000857
Richard Smith05766812012-08-18 00:55:03 +0000858 if (FirstDecl->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor3b887352011-04-27 04:48:22 +0000860
Douglas Gregor312eadb2011-04-24 05:37:28 +0000861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
862 return BuildDeclarationNameExpr(SS, Result, ADL);
863}
864
John McCall88232aa2009-08-18 00:00:49 +0000865// Determines the context to return to after temporarily entering a
866// context. This depends in an unnecessarily complicated way on the
867// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000868DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000869
John McCall88232aa2009-08-18 00:00:49 +0000870 // Functions defined inline within classes aren't parsed until we've
871 // finished parsing the top-level class, so the top-level class is
872 // the context we'll need to return to.
873 if (isa<FunctionDecl>(DC)) {
874 DC = DC->getLexicalParent();
875
876 // A function not defined within a class will always return to its
877 // lexical context.
878 if (!isa<CXXRecordDecl>(DC))
879 return DC;
880
881 // A C++ inline method/friend is parsed *after* the topmost class
882 // it was declared in is fully parsed ("complete"); the topmost
883 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000884 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000885 DC = RD;
886
887 // Return the declaration context of the topmost class the inline method is
888 // declared in.
889 return DC;
890 }
891
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000892 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893}
894
Douglas Gregor44b43212008-12-11 16:49:14 +0000895void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000896 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000897 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000898 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000899 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000900}
901
Chris Lattnerb048c982008-04-06 04:47:34 +0000902void Sema::PopDeclContext() {
903 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000904
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000905 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000906 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000907}
908
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000909/// EnterDeclaratorContext - Used when we must lookup names in the context
910/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000911///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000912void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000913 // C++0x [basic.lookup.unqual]p13:
914 // A name used in the definition of a static data member of class
915 // X (after the qualified-id of the static member) is looked up as
916 // if the name was used in a member function of X.
917 // C++0x [basic.lookup.unqual]p14:
918 // If a variable member of a namespace is defined outside of the
919 // scope of its namespace then any name used in the definition of
920 // the variable member (after the declarator-id) is looked up as
921 // if the definition of the variable member occurred in its
922 // namespace.
923 // Both of these imply that we should push a scope whose context
924 // is the semantic context of the declaration. We can't use
925 // PushDeclContext here because that context is not necessarily
926 // lexically contained in the current context. Fortunately,
927 // the containing scope should have the appropriate information.
928
929 assert(!S->getEntity() && "scope already has entity");
930
931#ifndef NDEBUG
932 Scope *Ancestor = S->getParent();
933 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
934 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
935#endif
936
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000937 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000938 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000939}
940
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000941void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000942 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000943
John McCall7a1dc562009-12-19 10:49:29 +0000944 // Switch back to the lexical context. The safety of this is
945 // enforced by an assert in EnterDeclaratorContext.
946 Scope *Ancestor = S->getParent();
947 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekf0d58612013-10-08 17:08:03 +0000948 CurContext = Ancestor->getEntity();
John McCall7a1dc562009-12-19 10:49:29 +0000949
950 // We don't need to do anything with the scope, which is going to
951 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000952}
953
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000954
955void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
956 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
957 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
958 // We assume that the caller has already called
959 // ActOnReenterTemplateScope
960 FD = TFD->getTemplatedDecl();
961 }
962 if (!FD)
963 return;
964
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000965 // Same implementation as PushDeclContext, but enters the context
966 // from the lexical parent, rather than the top-level class.
967 assert(CurContext == FD->getLexicalParent() &&
968 "The next DeclContext should be lexically contained in the current one.");
969 CurContext = FD;
970 S->setEntity(CurContext);
971
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000972 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
973 ParmVarDecl *Param = FD->getParamDecl(P);
974 // If the parameter has an identifier, then add it to the scope
975 if (Param->getIdentifier()) {
976 S->AddDecl(Param);
977 IdResolver.AddDecl(Param);
978 }
979 }
980}
981
982
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000983void Sema::ActOnExitFunctionContext() {
984 // Same implementation as PopDeclContext, but returns to the lexical parent,
985 // rather than the top-level class.
986 assert(CurContext && "DeclContext imbalance!");
987 CurContext = CurContext->getLexicalParent();
988 assert(CurContext && "Popped translation unit!");
989}
990
991
Douglas Gregorf9201e02009-02-11 23:02:49 +0000992/// \brief Determine whether we allow overloading of the function
993/// PrevDecl with another declaration.
994///
995/// This routine determines whether overloading is possible, not
996/// whether some new function is actually an overload. It will return
997/// true in C++ (where we can always provide overloads) or, as an
998/// extension, in C when the previous function is already an
999/// overloaded function declaration or has the "overloadable"
1000/// attribute.
John McCall68263142009-11-18 22:49:29 +00001001static bool AllowOverloadingOfFunction(LookupResult &Previous,
1002 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001003 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001004 return true;
1005
John McCall68263142009-11-18 22:49:29 +00001006 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001007 return true;
1008
John McCall68263142009-11-18 22:49:29 +00001009 return (Previous.getResultKind() == LookupResult::Found
1010 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +00001011}
1012
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001013/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +00001014void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +00001015 // Move up the scope chain until we find the nearest enclosing
1016 // non-transparent context. The declaration will be introduced into this
1017 // scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00001018 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor074149e2009-01-05 19:45:36 +00001019 S = S->getParent();
1020
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001021 // Add scoped declarations into their context, so that they can be
1022 // found later. Declarations without a context won't be inserted
1023 // into any context.
John McCallab88d972009-08-31 22:39:49 +00001024 if (AddToContext)
1025 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001026
Richard Smitha41c97a2013-09-20 01:15:31 +00001027 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1028 // are function-local declarations.
1029 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +00001030 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smitha41c97a2013-09-20 01:15:31 +00001031 D->getLexicalDeclContext()->getRedeclContext()) &&
1032 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruth8761d682010-02-21 07:08:09 +00001033 return;
1034
1035 // Template instantiations should also not be pushed into scope.
1036 if (isa<FunctionDecl>(D) &&
1037 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +00001038 return;
1039
John McCallf36e02d2009-10-09 21:13:30 +00001040 // If this replaces anything in the current scope,
1041 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1042 IEnd = IdResolver.end();
1043 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001044 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1045 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +00001046 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001047
John McCallf36e02d2009-10-09 21:13:30 +00001048 // Should only need to replace one decl.
1049 break;
Douglas Gregor516ff432009-04-24 02:57:34 +00001050 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001051 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052
John McCalld226f652010-08-21 09:40:31 +00001053 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001054
1055 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1056 // Implicitly-generated labels may end up getting generated in an order that
1057 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1058 // the label at the appropriate place in the identifier chain.
1059 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +00001060 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +00001061 if (IDC == CurContext) {
1062 if (!S->isDeclScope(*I))
1063 continue;
1064 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001065 break;
1066 }
1067
Douglas Gregor250e7a72011-03-16 16:39:03 +00001068 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001069 } else {
1070 IdResolver.AddDecl(D);
1071 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001072}
1073
Douglas Gregoreee242f2011-10-27 09:33:13 +00001074void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1075 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1076 TUScope->AddDecl(D);
1077}
1078
Richard Smithdd9459f2013-08-13 18:18:50 +00001079bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001080 bool ExplicitInstantiationOrSpecialization) {
Nico Weber355a1662012-12-17 03:51:09 +00001081 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001082 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001083}
1084
John McCall5f1e0942010-08-24 08:50:51 +00001085Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1086 DeclContext *TargetDC = DC->getPrimaryContext();
1087 do {
Ted Kremenekf0d58612013-10-08 17:08:03 +00001088 if (DeclContext *ScopeDC = S->getEntity())
John McCall5f1e0942010-08-24 08:50:51 +00001089 if (ScopeDC->getPrimaryContext() == TargetDC)
1090 return S;
1091 } while ((S = S->getParent()));
1092
1093 return 0;
1094}
1095
John McCall68263142009-11-18 22:49:29 +00001096static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1097 DeclContext*,
1098 ASTContext&);
1099
1100/// Filters out lookup results that don't fall within the given scope
1101/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001102void Sema::FilterLookupForScope(LookupResult &R,
1103 DeclContext *Ctx, Scope *S,
1104 bool ConsiderLinkage,
1105 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001106 LookupResult::Filter F = R.makeFilter();
1107 while (F.hasNext()) {
1108 NamedDecl *D = F.next();
1109
Richard Smith3e4c6c42011-05-05 21:57:07 +00001110 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001111 continue;
1112
1113 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001114 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001115 continue;
1116
1117 F.erase();
1118 }
1119
1120 F.done();
1121}
1122
1123static bool isUsingDecl(NamedDecl *D) {
1124 return isa<UsingShadowDecl>(D) ||
1125 isa<UnresolvedUsingTypenameDecl>(D) ||
1126 isa<UnresolvedUsingValueDecl>(D);
1127}
1128
1129/// Removes using shadow declarations from the lookup results.
1130static void RemoveUsingDecls(LookupResult &R) {
1131 LookupResult::Filter F = R.makeFilter();
1132 while (F.hasNext())
1133 if (isUsingDecl(F.next()))
1134 F.erase();
1135
1136 F.done();
1137}
1138
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001139/// \brief Check for this common pattern:
1140/// @code
1141/// class S {
1142/// S(const S&); // DO NOT IMPLEMENT
1143/// void operator=(const S&); // DO NOT IMPLEMENT
1144/// };
1145/// @endcode
1146static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1147 // FIXME: Should check for private access too but access is set after we get
1148 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001149 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001150 return false;
1151
1152 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1153 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001154 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1155 return Method->isCopyAssignmentOperator();
1156 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001157}
1158
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001159// We need this to handle
1160//
1161// typedef struct {
1162// void *foo() { return 0; }
1163// } A;
1164//
1165// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1166// for example. If 'A', foo will have external linkage. If we have '*A',
1167// foo will have no linkage. Since we can't know untill we get to the end
1168// of the typedef, this function finds out if D might have non external linkage.
1169// Callers should verify at the end of the TU if it D has external linkage or
1170// not.
1171bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1172 const DeclContext *DC = D->getDeclContext();
1173 while (!DC->isTranslationUnit()) {
1174 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1175 if (!RD->hasNameForLinkage())
1176 return true;
1177 }
1178 DC = DC->getParent();
1179 }
1180
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001181 return !D->isExternallyVisible();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001182}
1183
Eli Friedman39bd3712013-09-10 03:05:56 +00001184// FIXME: This needs to be refactored; some other isInMainFile users want
1185// these semantics.
1186static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1187 if (S.TUKind != TU_Complete)
1188 return false;
1189 return S.SourceMgr.isInMainFile(Loc);
1190}
1191
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001192bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1193 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001194
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001195 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1196 return false;
1197
1198 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001199 if (D->getDeclContext()->isDependentContext() ||
1200 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001201 return false;
1202
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001204 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1205 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001206
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1208 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1209 return false;
1210 } else {
Eli Friedman39bd3712013-09-10 03:05:56 +00001211 // 'static inline' functions are defined in headers; don't warn.
1212 if (FD->isInlineSpecified() &&
1213 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001214 return false;
1215 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001216
Sean Hunt10620eb2011-05-06 20:44:56 +00001217 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001218 Context.DeclMustBeEmitted(FD))
1219 return false;
John McCall82b96592010-10-27 01:41:35 +00001220 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman39bd3712013-09-10 03:05:56 +00001221 // Constants and utility variables are defined in headers with internal
1222 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1223 // like "inline".)
1224 if (!isMainFileLoc(*this, VD->getLocation()))
1225 return false;
1226
Eli Friedman39bd3712013-09-10 03:05:56 +00001227 if (Context.DeclMustBeEmitted(VD))
John McCall82b96592010-10-27 01:41:35 +00001228 return false;
1229
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001230 if (VD->isStaticDataMember() &&
1231 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1232 return false;
John McCall82b96592010-10-27 01:41:35 +00001233 } else {
1234 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001235 }
1236
John McCall82b96592010-10-27 01:41:35 +00001237 // Only warn for unused decls internal to the translation unit.
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001238 return mightHaveNonExternalLinkage(D);
John McCall82b96592010-10-27 01:41:35 +00001239}
1240
1241void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001242 if (!D)
1243 return;
1244
1245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001246 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001247 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1248 return; // First should already be in the vector.
1249 }
1250
1251 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001252 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001253 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254 return; // First should already be in the vector.
1255 }
1256
David Blaikie7f7c42b2012-05-26 05:35:39 +00001257 if (ShouldWarnIfUnusedFileScopedDecl(D))
1258 UnusedFileScopedDecls.push_back(D);
1259}
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001260
Anders Carlsson99a000e2009-11-07 07:18:14 +00001261static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001262 if (D->isInvalidDecl())
1263 return false;
1264
Eli Friedmandd9d6452012-01-13 23:41:25 +00001265 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001266 return false;
John McCall86ff3082010-02-04 22:26:26 +00001267
Chris Lattner57ad3782011-02-17 20:34:02 +00001268 if (isa<LabelDecl>(D))
1269 return true;
1270
John McCall86ff3082010-02-04 22:26:26 +00001271 // White-list anything that isn't a local variable.
1272 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1273 !D->getDeclContext()->isFunctionOrMethod())
1274 return false;
1275
1276 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001277 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001278
1279 // White-list anything with an __attribute__((unused)) type.
1280 QualType Ty = VD->getType();
1281
1282 // Only look at the outermost level of typedef.
Douglas Gregor2c8e81e2012-09-14 05:10:40 +00001283 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallaec58602010-03-31 02:47:45 +00001284 if (TT->getDecl()->hasAttr<UnusedAttr>())
1285 return false;
1286 }
1287
Douglas Gregor5764f612010-05-08 23:05:03 +00001288 // If we failed to complete the type for some reason, or if the type is
1289 // dependent, don't diagnose the variable.
1290 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001291 return false;
1292
John McCallaec58602010-03-31 02:47:45 +00001293 if (const TagType *TT = Ty->getAs<TagType>()) {
1294 const TagDecl *Tag = TT->getDecl();
1295 if (Tag->hasAttr<UnusedAttr>())
1296 return false;
1297
1298 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001299 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001300 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001301
1302 if (const Expr *Init = VD->getInit()) {
David Blaikie39e17762012-10-24 21:29:06 +00001303 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1304 Init = Cleanups->getSubExpr();
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001305 const CXXConstructExpr *Construct =
1306 dyn_cast<CXXConstructExpr>(Init);
1307 if (Construct && !Construct->isElidable()) {
1308 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001309 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001310 return false;
1311 }
1312 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001313 }
1314 }
John McCallaec58602010-03-31 02:47:45 +00001315
Ted Kremenek1f64cfc2013-11-14 01:42:17 +00001316 // Under ARC, bridged casts can have side-effects on memory
1317 // management semantics. Some users assign a bridged
1318 // value to a temporary to adjust reference counts.
1319 const Expr *Init = VD->getInit();
1320 if (Init) {
1321 if (const ExprWithCleanups *EC = dyn_cast<ExprWithCleanups>(Init))
1322 Init = EC->getSubExpr();
1323 Init = Init->IgnoreParens();
1324 if (const ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(Init)) {
1325 switch (IC->getCastKind()) {
1326 case CK_ARCProduceObject:
1327 case CK_ARCConsumeObject:
1328 case CK_ARCReclaimReturnedObject:
1329 case CK_ARCExtendBlockObject:
1330 case CK_CopyAndAutoreleaseBlockObject:
1331 return false;
1332 default:
1333 break;
1334 }
1335 }
1336 }
1337
John McCallaec58602010-03-31 02:47:45 +00001338 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001339 }
1340
John McCall86ff3082010-02-04 22:26:26 +00001341 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001342}
1343
Anna Zaksd5612a22011-07-28 20:52:06 +00001344static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1345 FixItHint &Hint) {
1346 if (isa<LabelDecl>(D)) {
1347 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001348 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001349 if (AfterColon.isInvalid())
1350 return;
1351 Hint = FixItHint::CreateRemoval(CharSourceRange::
1352 getCharRange(D->getLocStart(), AfterColon));
1353 }
1354 return;
1355}
1356
Chris Lattner337e5502011-02-18 01:27:55 +00001357/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1358/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001359void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001360 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001361 if (!ShouldDiagnoseUnusedDecl(D))
1362 return;
1363
Anna Zaksd5612a22011-07-28 20:52:06 +00001364 GenerateFixForUnusedDecl(D, Context, Hint);
1365
Chris Lattner57ad3782011-02-17 20:34:02 +00001366 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001367 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001368 DiagID = diag::warn_unused_exception_param;
1369 else if (isa<LabelDecl>(D))
1370 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001371 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001372 DiagID = diag::warn_unused_variable;
1373
Anna Zaksd5612a22011-07-28 20:52:06 +00001374 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001375}
1376
Chris Lattner337e5502011-02-18 01:27:55 +00001377static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1378 // Verify that we have no forward references left. If so, there was a goto
1379 // or address of a label taken, but no definition of it. Label fwd
1380 // definitions are indicated with a null substmt.
1381 if (L->getStmt() == 0)
1382 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1383}
1384
Steve Naroffb216c882007-10-09 22:01:59 +00001385void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001386 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001387 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001388 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1391 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001392 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001393 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001394
Douglas Gregor44b43212008-12-11 16:49:14 +00001395 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1396 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001397
Douglas Gregor44b43212008-12-11 16:49:14 +00001398 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001399
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001400 // Diagnose unused variables in this scope.
Matt Beaumont-Gay59d8ccb2013-03-28 21:46:45 +00001401 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001402 DiagnoseUnusedDecl(D);
1403
Chris Lattner337e5502011-02-18 01:27:55 +00001404 // If this was a forward reference to a label, verify it was defined.
1405 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1406 CheckPoppedLabel(LD, *this);
1407
Douglas Gregor44b43212008-12-11 16:49:14 +00001408 // Remove this name from our lexical scope.
1409 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 }
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00001411 DiagnoseUnusedBackingIvarInAccessor(S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001412}
1413
James Molloy16f1f712012-02-29 10:24:19 +00001414void Sema::ActOnStartFunctionDeclarator() {
1415 ++InFunctionDeclarator;
1416}
1417
1418void Sema::ActOnEndFunctionDeclarator() {
1419 assert(InFunctionDeclarator);
1420 --InFunctionDeclarator;
1421}
1422
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001423/// \brief Look for an Objective-C class in the translation unit.
1424///
1425/// \param Id The name of the Objective-C class we're looking for. If
1426/// typo-correction fixes this name, the Id will be updated
1427/// to the fixed name.
1428///
1429/// \param IdLoc The location of the name in the translation unit.
1430///
James Dennett16ae9de2012-06-22 10:16:05 +00001431/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001432/// if there is no class with the given name.
1433///
1434/// \returns The declaration of the named Objective-C class, or NULL if the
1435/// class could not be found.
1436ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1437 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001438 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001439 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1440 // creation from this context.
1441 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1442
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001443 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001444 // Perform typo correction at the given location, but only if we
1445 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001446 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1447 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1448 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001449 Validator)) {
Richard Smith2d670972013-08-17 00:46:16 +00001450 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001451 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001452 Id = IDecl->getIdentifier();
1453 }
1454 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001455 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1456 // This routine must always return a class definition, if any.
1457 if (Def && Def->getDefinition())
1458 Def = Def->getDefinition();
1459 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001460}
1461
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001462/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1463/// from S, where a non-field would be declared. This routine copes
1464/// with the difference between C and C++ scoping rules in structs and
1465/// unions. For example, the following code is well-formed in C but
1466/// ill-formed in C++:
1467/// @code
1468/// struct S6 {
1469/// enum { BAR } e;
1470/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001471///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001472/// void test_S6() {
1473/// struct S6 a;
1474/// a.e = BAR;
1475/// }
1476/// @endcode
1477/// For the declaration of BAR, this routine will return a different
1478/// scope. The scope S will be the scope of the unnamed enumeration
1479/// within S6. In C++, this routine will return the scope associated
1480/// with S6, because the enumeration's scope is a transparent
1481/// context but structures can contain non-field names. In C, this
1482/// routine will return the translation unit scope, since the
1483/// enumeration's scope is a transparent context and structures cannot
1484/// contain non-field names.
1485Scope *Sema::getNonFieldDeclScope(Scope *S) {
1486 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001487 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001488 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001489 S = S->getParent();
1490 return S;
1491}
1492
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001493/// \brief Looks up the declaration of "struct objc_super" and
1494/// saves it for later use in building builtin declaration of
1495/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1496/// pre-existing declaration exists no action takes place.
1497static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1498 IdentifierInfo *II) {
1499 if (!II->isStr("objc_msgSendSuper"))
1500 return;
1501 ASTContext &Context = ThisSema.Context;
1502
1503 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1504 SourceLocation(), Sema::LookupTagName);
1505 ThisSema.LookupName(Result, S);
1506 if (Result.getResultKind() == LookupResult::Found)
1507 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1508 Context.setObjCSuperType(Context.getTagDeclType(TD));
1509}
1510
Douglas Gregor3e41d602009-02-13 23:20:09 +00001511/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1512/// file scope. lazily create a decl for it. ForRedeclaration is true
1513/// if we're creating this built-in in anticipation of redeclaring the
1514/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001515NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001516 Scope *S, bool ForRedeclaration,
1517 SourceLocation Loc) {
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001518 LookupPredefedObjCSuperType(*this, S, II);
1519
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 Builtin::ID BID = (Builtin::ID)bid;
1521
Chris Lattner86df27b2009-06-14 00:45:47 +00001522 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001523 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001524 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001525 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001526 // Okay
1527 break;
1528
Mike Stumpf711c412009-07-28 23:57:15 +00001529 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001530 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001531 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001532 << Context.BuiltinInfo.GetName(BID);
1533 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001534
Mike Stumpf711c412009-07-28 23:57:15 +00001535 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001536 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001537 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001538 << Context.BuiltinInfo.GetName(BID);
1539 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001540
1541 case ASTContext::GE_Missing_ucontext:
1542 if (ForRedeclaration)
1543 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1544 << Context.BuiltinInfo.GetName(BID);
1545 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001546 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001547
1548 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1549 Diag(Loc, diag::ext_implicit_lib_function_decl)
1550 << Context.BuiltinInfo.GetName(BID)
1551 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001552 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001553 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001554 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001555 Diag(Loc, diag::note_please_include_header)
1556 << Context.BuiltinInfo.getHeaderName(BID)
1557 << Context.BuiltinInfo.GetName(BID);
1558 }
1559
Warren Hunt2d023ec2013-11-01 23:46:51 +00001560 DeclContext *Parent = Context.getTranslationUnitDecl();
1561 if (getLangOpts().CPlusPlus) {
1562 LinkageSpecDecl *CLinkageDecl =
1563 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1564 LinkageSpecDecl::lang_c, false);
1565 Parent->addDecl(CLinkageDecl);
1566 Parent = CLinkageDecl;
1567 }
1568
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001569 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt2d023ec2013-11-01 23:46:51 +00001570 Parent,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001571 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001572 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001573 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001574 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001575 New->setImplicit();
1576
Chris Lattner95e2c712008-05-05 22:18:14 +00001577 // Create Decl objects for each parameter, adding them to the
1578 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001579 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001580 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001581 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1582 ParmVarDecl *parm =
1583 ParmVarDecl::Create(Context, New, SourceLocation(),
1584 SourceLocation(), 0,
1585 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001586 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001587 parm->setScopeInfo(0, i);
1588 Params.push_back(parm);
1589 }
David Blaikie4278c652011-09-21 18:16:56 +00001590 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
1593 AddKnownFunctionAttributes(New);
Warren Hunt2d023ec2013-11-01 23:46:51 +00001594 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Chris Lattner7f925cc2008-04-11 07:00:53 +00001596 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001597 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1598 // relate Scopes to DeclContexts, and probably eliminate CurContext
1599 // entirely, but we're not there yet.
1600 DeclContext *SavedContext = CurContext;
Warren Hunt2d023ec2013-11-01 23:46:51 +00001601 CurContext = Parent;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001602 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001603 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 return New;
1605}
1606
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001607/// \brief Filter out any previous declarations that the given declaration
1608/// should not consider because they are not permitted to conflict, e.g.,
1609/// because they come from hidden sub-modules and do not refer to the same
1610/// entity.
1611static void filterNonConflictingPreviousDecls(ASTContext &context,
1612 NamedDecl *decl,
1613 LookupResult &previous){
1614 // This is only interesting when modules are enabled.
1615 if (!context.getLangOpts().Modules)
1616 return;
1617
1618 // Empty sets are uninteresting.
1619 if (previous.empty())
1620 return;
1621
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001622 LookupResult::Filter filter = previous.makeFilter();
1623 while (filter.hasNext()) {
1624 NamedDecl *old = filter.next();
1625
1626 // Non-hidden declarations are never ignored.
1627 if (!old->isHidden())
1628 continue;
1629
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001630 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001631 filter.erase();
1632 }
1633
1634 filter.done();
1635}
1636
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001637bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1638 QualType OldType;
1639 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1640 OldType = OldTypedef->getUnderlyingType();
1641 else
1642 OldType = Context.getTypeDeclType(Old);
1643 QualType NewType = New->getUnderlyingType();
1644
Douglas Gregorec3bd722012-01-11 22:33:48 +00001645 if (NewType->isVariablyModifiedType()) {
1646 // Must not redefine a typedef with a variably-modified type.
1647 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1648 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1649 << Kind << NewType;
1650 if (Old->getLocation().isValid())
1651 Diag(Old->getLocation(), diag::note_previous_definition);
1652 New->setInvalidDecl();
1653 return true;
1654 }
1655
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001656 if (OldType != NewType &&
1657 !OldType->isDependentType() &&
1658 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001659 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001660 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1661 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1662 << Kind << NewType << OldType;
1663 if (Old->getLocation().isValid())
1664 Diag(Old->getLocation(), diag::note_previous_definition);
1665 New->setInvalidDecl();
1666 return true;
1667 }
1668 return false;
1669}
1670
Richard Smith162e1c12011-04-15 14:24:37 +00001671/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001672/// same name and scope as a previous declaration 'Old'. Figure out
1673/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001674/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001675///
Richard Smith162e1c12011-04-15 14:24:37 +00001676void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001677 // If the new decl is known invalid already, don't bother doing any
1678 // merging checks.
1679 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Steve Naroff2b255c42008-09-09 14:32:20 +00001681 // Allow multiple definitions for ObjC built-in typedefs.
1682 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001683 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001684 const IdentifierInfo *TypeID = New->getIdentifier();
1685 switch (TypeID->getLength()) {
1686 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001687 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001688 {
1689 if (!TypeID->isStr("id"))
1690 break;
1691 QualType T = New->getUnderlyingType();
1692 if (!T->isPointerType())
1693 break;
1694 if (!T->isVoidPointerType()) {
1695 QualType PT = T->getAs<PointerType>()->getPointeeType();
1696 if (!PT->isStructureType())
1697 break;
1698 }
1699 Context.setObjCIdRedefinitionType(T);
1700 // Install the built-in type for 'id', ignoring the current definition.
1701 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1702 return;
1703 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001704 case 5:
1705 if (!TypeID->isStr("Class"))
1706 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001707 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001708 // Install the built-in type for 'Class', ignoring the current definition.
1709 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001710 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001711 case 3:
1712 if (!TypeID->isStr("SEL"))
1713 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001714 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001715 // Install the built-in type for 'SEL', ignoring the current definition.
1716 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001717 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001718 }
1719 // Fall through - the typedef name was not a builtin type.
1720 }
John McCall68263142009-11-18 22:49:29 +00001721
Douglas Gregor66973122009-01-28 17:15:10 +00001722 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001723 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1724 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001725 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001726 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001727
1728 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001729 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001730 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001731
Chris Lattnereaaebc72009-04-25 08:06:05 +00001732 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 }
Douglas Gregor66973122009-01-28 17:15:10 +00001734
John McCall68263142009-11-18 22:49:29 +00001735 // If the old declaration is invalid, just give up here.
1736 if (Old->isInvalidDecl())
1737 return New->setInvalidDecl();
1738
Chris Lattner99cb9972008-07-25 18:44:27 +00001739 // If the typedef types are not identical, reject them in all languages and
1740 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001741 if (isIncompatibleTypedef(Old, New))
1742 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Justin Bogner2dd68de2013-10-08 00:19:09 +00001744 // The types match. Link up the redeclaration chain and merge attributes if
1745 // the old declaration was a typedef.
1746 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001747 New->setPreviousDecl(Typedef);
Justin Bogner2dd68de2013-10-08 00:19:09 +00001748 mergeDeclAttributes(New, Old);
1749 }
Eli Friedman9ec40992013-07-16 02:07:49 +00001750
David Blaikie4e4d0842012-03-11 07:00:24 +00001751 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001752 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001753
David Blaikie4e4d0842012-03-11 07:00:24 +00001754 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001755 // C++ [dcl.typedef]p2:
1756 // In a given non-class scope, a typedef specifier can be used to
1757 // redefine the name of any type declared in that scope to refer
1758 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001759 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001760 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001761
1762 // C++0x [dcl.typedef]p4:
1763 // In a given class scope, a typedef specifier can be used to redefine
1764 // any class-name declared in that scope that is not also a typedef-name
1765 // to refer to the type to which it already refers.
1766 //
1767 // This wording came in via DR424, which was a correction to the
1768 // wording in DR56, which accidentally banned code like:
1769 //
1770 // struct S {
1771 // typedef struct A { } A;
1772 // };
1773 //
1774 // in the C++03 standard. We implement the C++0x semantics, which
1775 // allow the above but disallow
1776 //
1777 // struct S {
1778 // typedef int I;
1779 // typedef int I;
1780 // };
1781 //
1782 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001783 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001784 return;
1785
Chris Lattner32b06752009-04-17 22:04:20 +00001786 Diag(New->getLocation(), diag::err_redefinition)
1787 << New->getDeclName();
1788 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001789 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001790 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001791
Douglas Gregorc0004df2012-01-11 04:25:01 +00001792 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001793 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001794 return;
1795
Chris Lattner32b06752009-04-17 22:04:20 +00001796 // If we have a redefinition of a typedef in C, emit a warning. This warning
1797 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001798 // -Wtypedef-redefinition. If either the original or the redefinition is
1799 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001800 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001801 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1802 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001803 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Chris Lattner32b06752009-04-17 22:04:20 +00001805 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1806 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001807 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001808 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001809}
1810
Chris Lattner6b6b5372008-06-26 18:38:35 +00001811/// DeclhasAttr - returns true if decl Declaration already has the target
1812/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001813static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001814DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001815 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1816 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1817 // responsible for making sure they are consistent.
1818 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1819 if (AA)
1820 return false;
1821
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001822 // The following thread safety attributes can also be duplicated.
1823 switch (A->getKind()) {
1824 case attr::ExclusiveLocksRequired:
1825 case attr::SharedLocksRequired:
1826 case attr::LocksExcluded:
1827 case attr::ExclusiveLockFunction:
1828 case attr::SharedLockFunction:
1829 case attr::UnlockFunction:
1830 case attr::ExclusiveTrylockFunction:
1831 case attr::SharedTrylockFunction:
1832 case attr::GuardedBy:
1833 case attr::PtGuardedBy:
1834 case attr::AcquiredBefore:
1835 case attr::AcquiredAfter:
1836 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001837 default:
1838 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001839 }
1840
Sean Huntcf807c42010-08-18 23:23:40 +00001841 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001842 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001843 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1844 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001845 if (Ann) {
1846 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1847 return true;
1848 continue;
1849 }
Sean Huntcf807c42010-08-18 23:23:40 +00001850 // FIXME: Don't hardcode this check
1851 if (OA && isa<OwnershipAttr>(*i))
1852 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001853 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001854 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001855
1856 return false;
1857}
1858
Richard Smith671b3212013-02-22 04:55:39 +00001859static bool isAttributeTargetADefinition(Decl *D) {
1860 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1861 return VD->isThisDeclarationADefinition();
1862 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1863 return TD->isCompleteDefinition() || TD->isBeingDefined();
1864 return true;
1865}
1866
1867/// Merge alignment attributes from \p Old to \p New, taking into account the
1868/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1869///
1870/// \return \c true if any attributes were added to \p New.
1871static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1872 // Look for alignas attributes on Old, and pick out whichever attribute
1873 // specifies the strictest alignment requirement.
1874 AlignedAttr *OldAlignasAttr = 0;
1875 AlignedAttr *OldStrictestAlignAttr = 0;
1876 unsigned OldAlign = 0;
1877 for (specific_attr_iterator<AlignedAttr>
1878 I = Old->specific_attr_begin<AlignedAttr>(),
1879 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1880 // FIXME: We have no way of representing inherited dependent alignments
1881 // in a case like:
1882 // template<int A, int B> struct alignas(A) X;
1883 // template<int A, int B> struct alignas(B) X {};
1884 // For now, we just ignore any alignas attributes which are not on the
1885 // definition in such a case.
1886 if (I->isAlignmentDependent())
1887 return false;
1888
1889 if (I->isAlignas())
1890 OldAlignasAttr = *I;
1891
1892 unsigned Align = I->getAlignment(S.Context);
1893 if (Align > OldAlign) {
1894 OldAlign = Align;
1895 OldStrictestAlignAttr = *I;
1896 }
1897 }
1898
1899 // Look for alignas attributes on New.
1900 AlignedAttr *NewAlignasAttr = 0;
1901 unsigned NewAlign = 0;
1902 for (specific_attr_iterator<AlignedAttr>
1903 I = New->specific_attr_begin<AlignedAttr>(),
1904 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1905 if (I->isAlignmentDependent())
1906 return false;
1907
1908 if (I->isAlignas())
1909 NewAlignasAttr = *I;
1910
1911 unsigned Align = I->getAlignment(S.Context);
1912 if (Align > NewAlign)
1913 NewAlign = Align;
1914 }
1915
1916 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1917 // Both declarations have 'alignas' attributes. We require them to match.
1918 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1919 // fall short. (If two declarations both have alignas, they must both match
1920 // every definition, and so must match each other if there is a definition.)
1921
1922 // If either declaration only contains 'alignas(0)' specifiers, then it
1923 // specifies the natural alignment for the type.
1924 if (OldAlign == 0 || NewAlign == 0) {
1925 QualType Ty;
1926 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1927 Ty = VD->getType();
1928 else
1929 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1930
1931 if (OldAlign == 0)
1932 OldAlign = S.Context.getTypeAlign(Ty);
1933 if (NewAlign == 0)
1934 NewAlign = S.Context.getTypeAlign(Ty);
1935 }
1936
1937 if (OldAlign != NewAlign) {
1938 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1939 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1940 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1941 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1942 }
1943 }
1944
1945 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1946 // C++11 [dcl.align]p6:
1947 // if any declaration of an entity has an alignment-specifier,
1948 // every defining declaration of that entity shall specify an
1949 // equivalent alignment.
1950 // C11 6.7.5/7:
1951 // If the definition of an object does not have an alignment
1952 // specifier, any other declaration of that object shall also
1953 // have no alignment specifier.
1954 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1955 << OldAlignasAttr->isC11();
1956 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1957 << OldAlignasAttr->isC11();
1958 }
1959
1960 bool AnyAdded = false;
1961
1962 // Ensure we have an attribute representing the strictest alignment.
1963 if (OldAlign > NewAlign) {
1964 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1965 Clone->setInherited(true);
1966 New->addAttr(Clone);
1967 AnyAdded = true;
1968 }
1969
1970 // Ensure we have an alignas attribute if the old declaration had one.
1971 if (OldAlignasAttr && !NewAlignasAttr &&
1972 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1973 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1974 Clone->setInherited(true);
1975 New->addAttr(Clone);
1976 AnyAdded = true;
1977 }
1978
1979 return AnyAdded;
1980}
1981
1982static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1983 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001984 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001985 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001986 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001987 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1988 AA->getIntroduced(), AA->getDeprecated(),
1989 AA->getObsoleted(), AA->getUnavailable(),
1990 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001991 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001992 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1993 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1994 AttrSpellingListIndex);
1995 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1996 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1997 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001998 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001999 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2000 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00002001 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00002002 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2003 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00002004 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00002005 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2006 FA->getFormatIdx(), FA->getFirstArg(),
2007 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00002008 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00002009 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2010 AttrSpellingListIndex);
2011 else if (isa<AlignedAttr>(Attr))
2012 // AlignedAttrs are handled separately, because we need to handle all
2013 // such attributes on a declaration at the same time.
2014 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00002015 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00002016 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00002017
Rafael Espindola599f1b72012-05-13 03:25:18 +00002018 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00002019 NewAttr->setInherited(true);
2020 D->addAttr(NewAttr);
2021 return true;
2022 }
2023
2024 return false;
2025}
2026
Rafael Espindola4b044c62012-07-15 01:05:36 +00002027static const Decl *getDefinition(const Decl *D) {
2028 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00002029 return TD->getDefinition();
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2031 const VarDecl *Def = VD->getDefinition();
2032 if (Def)
2033 return Def;
2034 return VD->getActingDefinition();
2035 }
Rafael Espindola4b044c62012-07-15 01:05:36 +00002036 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00002037 const FunctionDecl* Def;
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002038 if (FD->isDefined(Def))
Rafael Espindola3f664062012-05-18 01:47:00 +00002039 return Def;
2040 }
2041 return NULL;
2042}
2043
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002044static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2045 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2046 I != E; ++I) {
2047 Attr *Attribute = *I;
2048 if (Attribute->getKind() == Kind)
2049 return true;
2050 }
2051 return false;
2052}
2053
2054/// checkNewAttributesAfterDef - If we already have a definition, check that
2055/// there are no new attributes in this declaration.
2056static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2057 if (!New->hasAttrs())
2058 return;
2059
2060 const Decl *Def = getDefinition(Old);
2061 if (!Def || Def == New)
2062 return;
2063
2064 AttrVec &NewAttributes = New->getAttrs();
2065 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2066 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002067
2068 if (isa<AliasAttr>(NewAttribute)) {
2069 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2070 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2071 else {
2072 VarDecl *VD = cast<VarDecl>(New);
2073 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2074 VarDecl::TentativeDefinition
2075 ? diag::err_alias_after_tentative
2076 : diag::err_redefinition;
2077 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2078 S.Diag(Def->getLocation(), diag::note_previous_definition);
2079 VD->setInvalidDecl();
2080 }
2081 ++I;
2082 continue;
2083 }
2084
2085 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2086 // Tentative definitions are only interesting for the alias check above.
2087 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2088 ++I;
2089 continue;
2090 }
2091 }
2092
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002093 if (hasAttribute(Def, NewAttribute->getKind())) {
2094 ++I;
2095 continue; // regular attr merging will take care of validating this.
2096 }
Richard Smith671b3212013-02-22 04:55:39 +00002097
Richard Smith7586a6e2013-01-30 05:45:05 +00002098 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002099 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002100 ++I;
2101 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002102 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2103 if (AA->isAlignas()) {
2104 // C++11 [dcl.align]p6:
2105 // if any declaration of an entity has an alignment-specifier,
2106 // every defining declaration of that entity shall specify an
2107 // equivalent alignment.
2108 // C11 6.7.5/7:
2109 // If the definition of an object does not have an alignment
2110 // specifier, any other declaration of that object shall also
2111 // have no alignment specifier.
2112 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2113 << AA->isC11();
2114 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2115 << AA->isC11();
2116 NewAttributes.erase(NewAttributes.begin() + I);
2117 --E;
2118 continue;
2119 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002120 }
Richard Smith671b3212013-02-22 04:55:39 +00002121
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002122 S.Diag(NewAttribute->getLocation(),
2123 diag::warn_attribute_precede_definition);
2124 S.Diag(Def->getLocation(), diag::note_previous_definition);
2125 NewAttributes.erase(NewAttributes.begin() + I);
2126 --E;
2127 }
2128}
2129
John McCalleca5d222011-03-02 04:00:57 +00002130/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002131void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002132 AvailabilityMergeKind AMK) {
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002133 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2134 UsedAttr *NewAttr = OldAttr->clone(Context);
2135 NewAttr->setInherited(true);
2136 New->addAttr(NewAttr);
2137 }
2138
Richard Smith3a2b7a12013-01-28 22:42:45 +00002139 if (!Old->hasAttrs() && !New->hasAttrs())
2140 return;
2141
Rafael Espindola3f664062012-05-18 01:47:00 +00002142 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002143 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002144
Douglas Gregor27c6da22012-01-01 20:30:41 +00002145 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002146 return;
John McCalleca5d222011-03-02 04:00:57 +00002147
Douglas Gregor27c6da22012-01-01 20:30:41 +00002148 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002149
Sean Huntcf807c42010-08-18 23:23:40 +00002150 // Ensure that any moving of objects within the allocated map is done before
2151 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002152 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002153
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002154 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002155 i = Old->specific_attr_begin<InheritableAttr>(),
2156 e = Old->specific_attr_end<InheritableAttr>();
2157 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002158 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002159 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002160 if (isa<DeprecatedAttr>(*i) ||
2161 isa<UnavailableAttr>(*i) ||
2162 isa<AvailabilityAttr>(*i)) {
2163 switch (AMK) {
2164 case AMK_None:
2165 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002166
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002167 case AMK_Redeclaration:
2168 break;
2169
2170 case AMK_Override:
2171 Override = true;
2172 break;
2173 }
2174 }
2175
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002176 // Already handled.
2177 if (isa<UsedAttr>(*i))
2178 continue;
2179
Richard Smith671b3212013-02-22 04:55:39 +00002180 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002181 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002182 }
John McCalleca5d222011-03-02 04:00:57 +00002183
Richard Smith671b3212013-02-22 04:55:39 +00002184 if (mergeAlignedAttrs(*this, New, Old))
2185 foundAny = true;
2186
Douglas Gregor27c6da22012-01-01 20:30:41 +00002187 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002188}
2189
2190/// mergeParamDeclAttributes - Copy attributes from the old parameter
2191/// to the new one.
2192static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2193 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002194 Sema &S) {
2195 // C++11 [dcl.attr.depend]p2:
2196 // The first declaration of a function shall specify the
2197 // carries_dependency attribute for its declarator-id if any declaration
2198 // of the function specifies the carries_dependency attribute.
2199 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2200 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2201 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2202 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2203 // Find the first declaration of the parameter.
2204 // FIXME: Should we build redeclaration chains for function parameters?
2205 const FunctionDecl *FirstFD =
Rafael Espindolabc650912013-10-17 15:37:26 +00002206 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smith3a2b7a12013-01-28 22:42:45 +00002207 const ParmVarDecl *FirstVD =
2208 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2209 S.Diag(FirstVD->getLocation(),
2210 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2211 }
2212
John McCalleca5d222011-03-02 04:00:57 +00002213 if (!oldDecl->hasAttrs())
2214 return;
2215
2216 bool foundAny = newDecl->hasAttrs();
2217
2218 // Ensure that any moving of objects within the allocated map is
2219 // done before we process them.
2220 if (!foundAny) newDecl->setAttrs(AttrVec());
2221
2222 for (specific_attr_iterator<InheritableParamAttr>
2223 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2224 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2225 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002226 InheritableAttr *newAttr =
2227 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002228 newAttr->setInherited(true);
2229 newDecl->addAttr(newAttr);
2230 foundAny = true;
2231 }
2232 }
2233
2234 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002235}
2236
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002237namespace {
2238
Douglas Gregorc8376562009-03-06 22:43:54 +00002239/// Used in MergeFunctionDecl to keep track of function parameters in
2240/// C.
2241struct GNUCompatibleParamWarning {
2242 ParmVarDecl *OldParm;
2243 ParmVarDecl *NewParm;
2244 QualType PromotedType;
2245};
2246
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002247}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002248
2249/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002250Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002251 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002252 if (Ctor->isDefaultConstructor())
2253 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002254
2255 if (Ctor->isCopyConstructor())
2256 return Sema::CXXCopyConstructor;
2257
2258 if (Ctor->isMoveConstructor())
2259 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002260 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002261 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002262 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002263 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002264 } else if (MD->isMoveAssignmentOperator()) {
2265 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002266 }
Sean Huntf961ea52011-05-10 19:08:14 +00002267
Sean Huntf961ea52011-05-10 19:08:14 +00002268 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002269}
2270
Sebastian Redl515ddd82010-06-09 21:17:41 +00002271/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002272/// only extern inline functions can be redefined, and even then only in
2273/// GNU89 mode.
2274static bool canRedefineFunction(const FunctionDecl *FD,
2275 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002276 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2277 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002278 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002279 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002280}
2281
Reid Kleckneref072032013-08-27 23:08:25 +00002282const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2283 const AttributedType *AT = T->getAs<AttributedType>();
2284 while (AT && !AT->isCallingConv())
2285 AT = AT->getModifiedType()->getAs<AttributedType>();
2286 return AT;
John McCallfb609142012-08-25 02:00:03 +00002287}
2288
Benjamin Kramera574c892013-02-15 12:30:38 +00002289template <typename T>
2290static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002291 const DeclContext *DC = Old->getDeclContext();
2292 if (DC->isRecord())
2293 return false;
2294
2295 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002296 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002297 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002298 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002299 return true;
2300 return false;
2301}
2302
Chris Lattner04421082008-04-08 04:40:51 +00002303/// MergeFunctionDecl - We just parsed a function 'New' from
2304/// declarator D which has the same name and scope as a previous
2305/// declaration 'Old'. Figure out how to resolve this situation,
2306/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002307///
2308/// In C++, New and Old must be declarations that are not
2309/// overloaded. Use IsOverload to determine whether New and Old are
2310/// overloaded, and to select the Old declaration that New should be
2311/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002312///
2313/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002314bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2315 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002317 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002318 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002319 = dyn_cast<FunctionTemplateDecl>(OldD))
2320 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002321 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002322 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002324 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002325 if (New->getFriendObjectKind()) {
2326 Diag(New->getLocation(), diag::err_using_decl_friend);
2327 Diag(Shadow->getTargetDecl()->getLocation(),
2328 diag::note_using_decl_target);
2329 Diag(Shadow->getUsingDecl()->getLocation(),
2330 diag::note_using_decl) << 0;
2331 return true;
2332 }
2333
John McCall41ce66f2009-12-10 19:51:03 +00002334 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2335 Diag(Shadow->getTargetDecl()->getLocation(),
2336 diag::note_using_decl_target);
2337 Diag(Shadow->getUsingDecl()->getLocation(),
2338 diag::note_using_decl) << 0;
2339 return true;
2340 }
2341
Chris Lattner5dc266a2008-11-20 06:13:02 +00002342 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002343 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002344 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002345 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002347
David Majnemerbcd06502013-07-07 23:49:50 +00002348 // If the old declaration is invalid, just give up here.
2349 if (Old->isInvalidDecl())
2350 return true;
2351
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002352 // Determine whether the previous declaration was a definition,
2353 // implicit declaration, or a declaration.
2354 diag::kind PrevDiag;
2355 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002356 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002357 else if (Old->isImplicit())
2358 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002359 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002360 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002362 // Don't complain about this if we're in GNU89 mode and the old function
2363 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002364 // Don't complain about specializations. They are not supposed to have
2365 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002366 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002367 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002368 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002369 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002370 !canRedefineFunction(Old, getLangOpts())) {
2371 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002372 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2373 Diag(Old->getLocation(), PrevDiag);
2374 } else {
2375 Diag(New->getLocation(), diag::err_static_non_static) << New;
2376 Diag(Old->getLocation(), PrevDiag);
2377 return true;
2378 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002379 }
2380
Reid Kleckneref072032013-08-27 23:08:25 +00002381
2382 // If a function is first declared with a calling convention, but is later
2383 // declared or defined without one, all following decls assume the calling
2384 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002385 //
John McCallfb609142012-08-25 02:00:03 +00002386 // It's OK if a function is first declared without a calling convention,
2387 // but is later declared or defined with the default calling convention.
2388 //
Reid Kleckneref072032013-08-27 23:08:25 +00002389 // To test if either decl has an explicit calling convention, we look for
2390 // AttributedType sugar nodes on the type as written. If they are missing or
2391 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002392 //
2393 // Note also that we DO NOT return at this point, because we still have
2394 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002395 QualType OldQType = Context.getCanonicalType(Old->getType());
2396 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002397 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002398 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002399 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2400 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2401 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002402
Reid Kleckneref072032013-08-27 23:08:25 +00002403 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002404 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckneref072032013-08-27 23:08:25 +00002405 const FunctionType *FT =
2406 First->getType().getCanonicalType()->castAs<FunctionType>();
2407 FunctionType::ExtInfo FI = FT->getExtInfo();
2408 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2409 if (!NewCCExplicit) {
2410 // Inherit the CC from the previous declaration if it was specified
2411 // there but not here.
2412 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2413 RequiresAdjustment = true;
2414 } else {
2415 // Calling conventions aren't compatible, so complain.
2416 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2417 Diag(New->getLocation(), diag::err_cconv_change)
2418 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2419 << !FirstCCExplicit
2420 << (!FirstCCExplicit ? "" :
2421 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002422
Reid Kleckneref072032013-08-27 23:08:25 +00002423 // Put the note on the first decl, since it is the one that matters.
2424 Diag(First->getLocation(), diag::note_previous_declaration);
2425 return true;
2426 }
John McCallf82b4e82010-02-04 05:44:44 +00002427 }
2428
John McCall04a67a62010-02-05 21:31:56 +00002429 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002430 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2431 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2432 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002433 }
2434
Douglas Gregord2c64902010-06-18 21:30:25 +00002435 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002436 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2437 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2438 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002439 Diag(New->getLocation(), diag::err_regparm_mismatch)
2440 << NewType->getRegParmType()
2441 << OldType->getRegParmType();
2442 Diag(Old->getLocation(), diag::note_previous_declaration);
2443 return true;
2444 }
John McCalle6a365d2010-12-19 02:44:49 +00002445
2446 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2447 RequiresAdjustment = true;
2448 }
2449
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002450 // Merge ns_returns_retained attribute.
2451 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2452 if (NewTypeInfo.getProducesResult()) {
2453 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2454 Diag(Old->getLocation(), diag::note_previous_declaration);
2455 return true;
2456 }
2457
2458 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2459 RequiresAdjustment = true;
2460 }
2461
John McCalle6a365d2010-12-19 02:44:49 +00002462 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002463 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2464 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2465 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002466 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002467 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002468 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002469
2470 // If this redeclaration makes the function inline, we may need to add it to
2471 // UndefinedButUsed.
2472 if (!Old->isInlined() && New->isInlined() &&
2473 !New->hasAttr<GNUInlineAttr>() &&
2474 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2475 Old->isUsed(false) &&
2476 !Old->isDefined() && !New->isThisDeclarationADefinition())
2477 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2478 SourceLocation()));
2479
2480 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2481 // about it.
2482 if (New->hasAttr<GNUInlineAttr>() &&
2483 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2484 UndefinedButUsed.erase(Old->getCanonicalDecl());
2485 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002486
David Blaikie4e4d0842012-03-11 07:00:24 +00002487 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002488 // (C++98 13.1p2):
2489 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002490 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002491 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002492
2493 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002494 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002495 // Redeclarations or specializations of a function or function template
2496 // with a declared return type that uses a placeholder type shall also
2497 // use that placeholder, not a deduced type.
2498 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2499 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2500 : OldType)->getResultType();
2501 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2502 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2503 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002504 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002505 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2506 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2507 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002508 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2509 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002510 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2511 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002512 if (New->isCXXClassMember() && New->isOutOfLine())
2513 Diag(New->getLocation(),
2514 diag::err_member_def_does_not_match_ret_type) << New;
2515 else
2516 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002517 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2518 return true;
2519 }
2520 else
2521 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002522 }
2523
Richard Smith60e141e2013-05-04 07:00:32 +00002524 QualType OldReturnType = OldType->getResultType();
2525 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2526 if (OldReturnType != NewReturnType) {
2527 // If this function has a deduced return type and has already been
2528 // defined, copy the deduced value from the old declaration.
2529 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2530 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002531 New->setType(
2532 SubstAutoType(New->getType(),
2533 OldAT->isDependentType() ? Context.DependentTy
2534 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002535 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002536 SubstAutoType(NewQType,
2537 OldAT->isDependentType() ? Context.DependentTy
2538 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002539 }
2540 }
2541
2542 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2543 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002544 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002545 // Preserve triviality.
2546 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002547
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002548 // MSVC allows explicit template specialization at class scope:
2549 // 2 CXMethodDecls referring to the same function will be injected.
2550 // We don't want a redeclartion error.
2551 bool IsClassScopeExplicitSpecialization =
2552 OldMethod->isFunctionTemplateSpecialization() &&
2553 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002554 bool isFriend = NewMethod->getFriendObjectKind();
2555
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002556 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2557 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002558 // -- Member function declarations with the same name and the
2559 // same parameter types cannot be overloaded if any of them
2560 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002561 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002562 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2563 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2564 return true;
2565 }
Richard Smith838925d2012-07-13 04:12:04 +00002566
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002567 // C++ [class.mem]p1:
2568 // [...] A member shall not be declared twice in the
2569 // member-specification, except that a nested class or member
2570 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002571 if (ActiveTemplateInstantiations.empty()) {
2572 unsigned NewDiag;
2573 if (isa<CXXConstructorDecl>(OldMethod))
2574 NewDiag = diag::err_constructor_redeclared;
2575 else if (isa<CXXDestructorDecl>(NewMethod))
2576 NewDiag = diag::err_destructor_redeclared;
2577 else if (isa<CXXConversionDecl>(NewMethod))
2578 NewDiag = diag::err_conv_function_redeclared;
2579 else
2580 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002581
Richard Smith838925d2012-07-13 04:12:04 +00002582 Diag(New->getLocation(), NewDiag);
2583 } else {
2584 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2585 << New << New->getType();
2586 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002587 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002588
2589 // Complain if this is an explicit declaration of a special
2590 // member that was initially declared implicitly.
2591 //
2592 // As an exception, it's okay to befriend such methods in order
2593 // to permit the implicit constructor/destructor/operator calls.
2594 } else if (OldMethod->isImplicit()) {
2595 if (isFriend) {
2596 NewMethod->setImplicit();
2597 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002598 Diag(NewMethod->getLocation(),
2599 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002600 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002601 return true;
2602 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002603 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002604 Diag(NewMethod->getLocation(),
2605 diag::err_definition_of_explicitly_defaulted_member)
2606 << getSpecialMember(OldMethod);
2607 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002608 }
2609 }
2610
Richard Smithcd8ab512013-01-17 01:30:42 +00002611 // C++11 [dcl.attr.noreturn]p1:
2612 // The first declaration of a function shall specify the noreturn
2613 // attribute if any declaration of that function specifies the noreturn
2614 // attribute.
2615 if (New->hasAttr<CXX11NoReturnAttr>() &&
2616 !Old->hasAttr<CXX11NoReturnAttr>()) {
2617 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2618 diag::err_noreturn_missing_on_first_decl);
Rafael Espindolabc650912013-10-17 15:37:26 +00002619 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithcd8ab512013-01-17 01:30:42 +00002620 diag::note_noreturn_missing_first_decl);
2621 }
2622
Richard Smith3a2b7a12013-01-28 22:42:45 +00002623 // C++11 [dcl.attr.depend]p2:
2624 // The first declaration of a function shall specify the
2625 // carries_dependency attribute for its declarator-id if any declaration
2626 // of the function specifies the carries_dependency attribute.
2627 if (New->hasAttr<CarriesDependencyAttr>() &&
2628 !Old->hasAttr<CarriesDependencyAttr>()) {
2629 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2630 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindolabc650912013-10-17 15:37:26 +00002631 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002632 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2633 }
2634
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002635 // (C++98 8.3.5p3):
2636 // All declarations for a function shall agree exactly in both the
2637 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002638 // We also want to respect all the extended bits except noreturn.
2639
2640 // noreturn should now match unless the old type info didn't have it.
2641 QualType OldQTypeForComparison = OldQType;
2642 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2643 assert(OldQType == QualType(OldType, 0));
2644 const FunctionType *OldTypeForComparison
2645 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2646 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2647 assert(OldQTypeForComparison.isCanonical());
2648 }
2649
Rafael Espindola950fee22013-02-14 01:18:37 +00002650 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokera8a2ebe2013-10-22 22:53:01 +00002651 // As a special case, retain the language linkage from previous
2652 // declarations of a friend function as an extension.
2653 //
2654 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2655 // and is useful because there's otherwise no way to specify language
2656 // linkage within class scope.
2657 //
2658 // Check cautiously as the friend object kind isn't yet complete.
2659 if (New->getFriendObjectKind() != Decl::FOK_None) {
2660 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2661 Diag(Old->getLocation(), PrevDiag);
2662 } else {
2663 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2664 Diag(Old->getLocation(), PrevDiag);
2665 return true;
2666 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002667 }
2668
John McCalle6a365d2010-12-19 02:44:49 +00002669 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002670 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002671
Richard Smitha41c97a2013-09-20 01:15:31 +00002672 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2673 New->isLocalExternDecl()) {
2674 // It's OK if we couldn't merge types for a local function declaraton
2675 // if either the old or new type is dependent. We'll merge the types
2676 // when we instantiate the function.
2677 return false;
2678 }
2679
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002680 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002681 }
Chris Lattner04421082008-04-08 04:40:51 +00002682
2683 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002684 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002685 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002686 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002687 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2688 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002689 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002690 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002691 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002692 // The old declaration provided a function prototype, but the
2693 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002694 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002695 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002696 OldProto->arg_type_end());
2697 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002698 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002699 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002700 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002701 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002702
2703 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002704 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002705 for (FunctionProtoType::arg_type_iterator
2706 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002707 ParamEnd = OldProto->arg_type_end();
2708 ParamType != ParamEnd; ++ParamType) {
2709 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002710 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002711 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002712 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002713 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002714 0);
John McCallfb44de92011-05-01 22:35:37 +00002715 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002716 Param->setImplicit();
2717 Params.push_back(Param);
2718 }
2719
David Blaikie4278c652011-09-21 18:16:56 +00002720 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002721 }
Douglas Gregor68719812009-02-16 18:20:44 +00002722
Richard Smithdd9459f2013-08-13 18:18:50 +00002723 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002724 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002725
Douglas Gregorc8376562009-03-06 22:43:54 +00002726 // GNU C permits a K&R definition to follow a prototype declaration
2727 // if the declared types of the parameters in the K&R definition
2728 // match the types in the prototype declaration, even when the
2729 // promoted types of the parameters from the K&R definition differ
2730 // from the types in the prototype. GCC then keeps the types from
2731 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002732 //
2733 // If a variadic prototype is followed by a non-variadic K&R definition,
2734 // the K&R definition becomes variadic. This is sort of an edge case, but
2735 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2736 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002737 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002738 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002739 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002740 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002741 SmallVector<QualType, 16> ArgTypes;
2742 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002743 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002744 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002745 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002746 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Douglas Gregorc8376562009-03-06 22:43:54 +00002748 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002749 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2750 NewProto->getResultType());
2751 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002752 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002753 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002754 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2755 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002756 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002757 NewProto->getArgType(Idx))) {
2758 ArgTypes.push_back(NewParm->getType());
2759 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002760 NewParm->getType(),
2761 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002762 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002763 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2764 Warnings.push_back(Warn);
2765 ArgTypes.push_back(NewParm->getType());
2766 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002767 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002768 }
2769
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002770 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002771 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2772 Diag(Warnings[Warn].NewParm->getLocation(),
2773 diag::ext_param_promoted_not_compatible_with_prototype)
2774 << Warnings[Warn].PromotedType
2775 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002776 if (Warnings[Warn].OldParm->getLocation().isValid())
2777 Diag(Warnings[Warn].OldParm->getLocation(),
2778 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002779 }
2780
Richard Smithdd9459f2013-08-13 18:18:50 +00002781 if (MergeTypeWithOld)
2782 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2783 OldProto->getExtProtoInfo()));
2784 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002785 }
2786
2787 // Fall through to diagnose conflicting types.
2788 }
2789
John McCall088831d2013-04-14 08:50:55 +00002790 // A function that has already been declared has been redeclared or
2791 // defined with a different type; show an appropriate diagnostic.
2792
2793 // If the previous declaration was an implicitly-generated builtin
2794 // declaration, then at the very least we should use a specialized note.
2795 unsigned BuiltinID;
2796 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2797 // If it's actually a library-defined builtin function like 'malloc'
2798 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002799 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002800 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2801 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2802 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002803
2804 // If this is a global redeclaration, just forget hereafter
2805 // about the "builtin-ness" of the function.
2806 //
2807 // Doing this for local extern declarations is problematic. If
2808 // the builtin declaration remains visible, a second invalid
2809 // local declaration will produce a hard error; if it doesn't
2810 // remain visible, a single bogus local redeclaration (which is
2811 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002812 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002813 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2814
Douglas Gregor374e1562009-03-23 17:47:24 +00002815 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002816 }
Steve Naroff837618c2008-01-16 15:01:34 +00002817
Douglas Gregorcda9c672009-02-16 17:45:42 +00002818 PrevDiag = diag::note_previous_builtin_declaration;
2819 }
2820
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002821 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002822 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002823 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824}
2825
Douglas Gregor04495c82009-02-24 01:23:02 +00002826/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002827/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002828///
2829/// This routine handles the merging of attributes and other
Alp Toker89673e02013-10-22 09:00:49 +00002830/// properties of function declarations from the old declaration to
Douglas Gregor04495c82009-02-24 01:23:02 +00002831/// the new declaration, once we know that New is in fact a
2832/// redeclaration of Old.
2833///
2834/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002835bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002836 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002837 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002838 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002839
Douglas Gregor04495c82009-02-24 01:23:02 +00002840 // Merge "pure" flag.
2841 if (Old->isPure())
2842 New->setPure();
2843
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002844 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00002845 if (Old->getMostRecentDecl()->isUsed(false))
2846 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002847
John McCalleca5d222011-03-02 04:00:57 +00002848 // Merge attributes from the parameters. These can mismatch with K&R
2849 // declarations.
2850 if (New->getNumParams() == Old->getNumParams())
2851 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2852 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002853 *this);
John McCalleca5d222011-03-02 04:00:57 +00002854
David Blaikie4e4d0842012-03-11 07:00:24 +00002855 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002856 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002857
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002858 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002859 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2860 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002861 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002862 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002863 New->setType(Merged);
2864
Douglas Gregor04495c82009-02-24 01:23:02 +00002865 return false;
2866}
2867
John McCallf85e1932011-06-15 23:02:42 +00002868
John McCalleca5d222011-03-02 04:00:57 +00002869void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002870 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002871
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002872 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002873 AvailabilityMergeKind MergeKind =
2874 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2875 : AMK_Override;
2876 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002877
2878 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002879 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2880 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002881 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002882 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002883 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002884 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002885
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002886 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002887}
2888
Sebastian Redl60618fa2011-03-12 11:50:43 +00002889/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2890/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002891/// emitting diagnostics as appropriate.
2892///
2893/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002894/// to here in AddInitializerToDecl. We can't check them before the initializer
2895/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002896void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2897 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002898 if (New->isInvalidDecl() || Old->isInvalidDecl())
2899 return;
2900
2901 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002902 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002903 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002904 // We don't know what the new type is until the initializer is attached.
2905 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002906 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2907 // These could still be something that needs exception specs checked.
2908 return MergeVarDeclExceptionSpecs(New, Old);
2909 }
Richard Smith34b41d92011-02-20 03:19:35 +00002910 // C++ [basic.link]p10:
2911 // [...] the types specified by all declarations referring to a given
2912 // object or function shall be identical, except that declarations for an
2913 // array object can specify array types that differ by the presence or
2914 // absence of a major array bound (8.3.4).
2915 else if (Old->getType()->isIncompleteArrayType() &&
2916 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002917 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2918 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2919 if (Context.hasSameType(OldArray->getElementType(),
2920 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002921 MergedT = New->getType();
2922 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002923 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002924 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2925 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2926 if (Context.hasSameType(OldArray->getElementType(),
2927 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002928 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002929 } else if (New->getType()->isObjCObjectPointerType() &&
2930 Old->getType()->isObjCObjectPointerType()) {
2931 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2932 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002933 }
2934 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002935 // C 6.2.7p2:
2936 // All declarations that refer to the same object or function shall have
2937 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002938 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2939 }
2940 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002941 // It's OK if we couldn't merge types if either type is dependent, for a
2942 // block-scope variable. In other cases (static data members of class
2943 // templates, variable templates, ...), we require the types to be
2944 // equivalent.
2945 // FIXME: The C++ standard doesn't say anything about this.
2946 if ((New->getType()->isDependentType() ||
2947 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2948 // If the old type was dependent, we can't merge with it, so the new type
2949 // becomes dependent for now. We'll reproduce the original type when we
2950 // instantiate the TypeSourceInfo for the variable.
2951 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2952 New->setType(Context.DependentTy);
2953 return;
2954 }
2955
2956 // FIXME: Even if this merging succeeds, some other non-visible declaration
2957 // of this variable might have an incompatible type. For instance:
2958 //
2959 // extern int arr[];
2960 // void f() { extern int arr[2]; }
2961 // void g() { extern int arr[3]; }
2962 //
2963 // Neither C nor C++ requires a diagnostic for this, but we should still try
2964 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002965 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002966 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002967 Diag(Old->getLocation(), diag::note_previous_definition);
2968 return New->setInvalidDecl();
2969 }
John McCall5b8740f2013-04-01 18:34:28 +00002970
2971 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002972 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002973 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002974 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002975}
2976
Richard Smith99a72382013-09-03 21:00:58 +00002977static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2978 LookupResult &Previous) {
2979 // C11 6.2.7p4:
2980 // For an identifier with internal or external linkage declared
2981 // in a scope in which a prior declaration of that identifier is
2982 // visible, if the prior declaration specifies internal or
2983 // external linkage, the type of the identifier at the later
2984 // declaration becomes the composite type.
2985 //
2986 // If the variable isn't visible, we do not merge with its type.
2987 if (Previous.isShadowed())
2988 return false;
2989
2990 if (S.getLangOpts().CPlusPlus) {
2991 // C++11 [dcl.array]p3:
2992 // If there is a preceding declaration of the entity in the same
2993 // scope in which the bound was specified, an omitted array bound
2994 // is taken to be the same as in that earlier declaration.
2995 return NewVD->isPreviousDeclInSameBlockScope() ||
2996 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2997 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2998 } else {
2999 // If the old declaration was function-local, don't merge with its
3000 // type unless we're in the same function.
3001 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3002 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3003 }
3004}
3005
Reid Spencer5f016e22007-07-11 17:01:13 +00003006/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3007/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3008/// situation, merging decls or emitting diagnostics as appropriate.
3009///
Mike Stump1eb44332009-09-09 15:08:12 +00003010/// Tentative definition rules (C99 6.9.2p2) are checked by
3011/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00003012/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00003013///
Richard Smith99a72382013-09-03 21:00:58 +00003014void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00003015 // If the new decl is already invalid, don't do any other checking.
3016 if (New->isInvalidDecl())
3017 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Larisse Voufo4a919892013-08-14 03:09:19 +00003019 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00003020 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00003021 if (Previous.isSingleResult() &&
3022 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00003023 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00003024 Old = Old->getDescribedVarTemplate() ? Old : 0;
3025 else
3026 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3027 }
3028 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003029 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00003030 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00003031 Diag(Previous.getRepresentativeDecl()->getLocation(),
3032 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003033 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003035
Rafael Espindola90cc3902013-04-15 12:49:13 +00003036 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3037 return;
3038
Douglas Gregor7f6ff022010-08-30 14:32:14 +00003039 // C++ [class.mem]p1:
3040 // A member shall not be declared twice in the member-specification [...]
3041 //
3042 // Here, we need only consider static data members.
3043 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3044 Diag(New->getLocation(), diag::err_duplicate_member)
3045 << New->getIdentifier();
3046 Diag(Old->getLocation(), diag::note_previous_declaration);
3047 New->setInvalidDecl();
3048 }
3049
Douglas Gregor27c6da22012-01-01 20:30:41 +00003050 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00003051 // Warn if an already-declared variable is made a weak_import in a subsequent
3052 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00003053 if (New->getAttr<WeakImportAttr>() &&
3054 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003055 !Old->getAttr<WeakImportAttr>()) {
3056 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3057 Diag(Old->getLocation(), diag::note_previous_definition);
3058 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00003059 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003060 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003061
Richard Smith34b41d92011-02-20 03:19:35 +00003062 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00003063 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3064
Richard Smith34b41d92011-02-20 03:19:35 +00003065 if (New->isInvalidDecl())
3066 return;
Douglas Gregor656de632009-03-11 23:52:16 +00003067
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003068 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00003069 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003070 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00003071 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003072 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003073 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003074 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003077 // For an identifier declared with the storage-class specifier
3078 // extern in a scope in which a prior declaration of that
3079 // identifier is visible,23) if the prior declaration specifies
3080 // internal or external linkage, the linkage of the identifier at
3081 // the later declaration is the same as the linkage specified at
3082 // the prior declaration. If no prior declaration is visible, or
3083 // if the prior declaration specifies no linkage, then the
3084 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00003085 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003086 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003087 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003088 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003089 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003090 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003091 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003092 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003093 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003094
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003095 // Check if extern is followed by non-extern and vice-versa.
3096 if (New->hasExternalStorage() &&
3097 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3098 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3099 Diag(Old->getLocation(), diag::note_previous_definition);
3100 return New->setInvalidDecl();
3101 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003102 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3103 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003104 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3105 Diag(Old->getLocation(), diag::note_previous_definition);
3106 return New->setInvalidDecl();
3107 }
3108
Steve Naroff094cefb2008-09-17 14:05:40 +00003109 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003111 // FIXME: The test for external storage here seems wrong? We still
3112 // need to check for mismatches.
3113 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003114 // Don't complain about out-of-line definitions of static members.
3115 !(Old->getLexicalDeclContext()->isRecord() &&
3116 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003117 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003118 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003119 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003120 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003121
Richard Smith38afbc72013-04-13 02:43:54 +00003122 if (New->getTLSKind() != Old->getTLSKind()) {
3123 if (!Old->getTLSKind()) {
3124 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3125 Diag(Old->getLocation(), diag::note_previous_declaration);
3126 } else if (!New->getTLSKind()) {
3127 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3128 Diag(Old->getLocation(), diag::note_previous_declaration);
3129 } else {
3130 // Do not allow redeclaration to change the variable between requiring
3131 // static and dynamic initialization.
3132 // FIXME: GCC allows this, but uses the TLS keyword on the first
3133 // declaration to determine the kind. Do we need to be compatible here?
3134 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3135 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3136 Diag(Old->getLocation(), diag::note_previous_declaration);
3137 }
Eli Friedman63054b32009-04-19 20:27:55 +00003138 }
3139
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003140 // C++ doesn't have tentative definitions, so go right ahead and check here.
3141 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003142 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003143 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003144 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003145 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003146 Diag(Def->getLocation(), diag::note_previous_definition);
3147 New->setInvalidDecl();
3148 return;
3149 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003150
Rafael Espindola950fee22013-02-14 01:18:37 +00003151 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003152 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3153 Diag(Old->getLocation(), diag::note_previous_definition);
3154 New->setInvalidDecl();
3155 return;
3156 }
3157
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003158 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00003159 if (Old->getMostRecentDecl()->isUsed(false))
3160 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003161
Douglas Gregor275a3692009-03-10 23:43:53 +00003162 // Keep a chain of previous declarations.
Rafael Espindolabc650912013-10-17 15:37:26 +00003163 New->setPreviousDecl(Old);
John McCall46460a62010-01-20 21:53:11 +00003164
3165 // Inherit access appropriately.
3166 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003167
3168 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3169 if (New->isStaticDataMember() && New->isOutOfLine())
3170 VTD->setAccess(New->getAccess());
3171 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003172}
3173
3174/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3175/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003176Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003177 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003178 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003179}
3180
Eli Friedman5e867c82013-07-10 00:30:46 +00003181static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003182 if (!S.Context.getLangOpts().CPlusPlus)
3183 return;
3184
Eli Friedman5e867c82013-07-10 00:30:46 +00003185 if (isa<CXXRecordDecl>(Tag->getParent())) {
3186 // If this tag is the direct child of a class, number it if
3187 // it is anonymous.
3188 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3189 return;
3190 MangleNumberingContext &MCtx =
3191 S.Context.getManglingNumberContext(Tag->getParent());
3192 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3193 return;
3194 }
3195
3196 // If this tag isn't a direct child of a class, number it if it is local.
3197 Decl *ManglingContextDecl;
3198 if (MangleNumberingContext *MCtx =
3199 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3200 ManglingContextDecl)) {
3201 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3202 }
3203}
3204
Chandler Carruth0f4be742011-05-03 18:35:10 +00003205/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003206/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003207/// parameters to cope with template friend declarations.
3208Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3209 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003210 MultiTemplateParamsArg TemplateParams,
3211 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003212 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003213 TagDecl *Tag = 0;
3214 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3215 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003216 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003217 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003218 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003219 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003220
3221 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003222 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003223
John McCall67d1a672009-08-06 02:15:43 +00003224 // Note that the above type specs guarantee that the
3225 // type rep is a Decl, whereas in many of the others
3226 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003227 if (isa<TagDecl>(TagD))
3228 Tag = cast<TagDecl>(TagD);
3229 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3230 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003231 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003232
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003233 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003234 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003235 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003236 if (Tag->isInvalidDecl())
3237 return Tag;
3238 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003239
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003240 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3241 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3242 // or incomplete types shall not be restrict-qualified."
3243 if (TypeQuals & DeclSpec::TQ_restrict)
3244 Diag(DS.getRestrictSpecLoc(),
3245 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3246 << DS.getSourceRange();
3247 }
3248
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003249 if (DS.isConstexprSpecified()) {
3250 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3251 // and definitions of functions and variables.
3252 if (Tag)
3253 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3254 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3255 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003256 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3257 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003258 else
3259 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3260 // Don't emit warnings after this error.
3261 return TagD;
3262 }
3263
Richard Smithc7f81162013-03-18 22:52:47 +00003264 DiagnoseFunctionSpecifiers(DS);
3265
Douglas Gregord85bea22009-09-26 06:47:28 +00003266 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003267 // If we're dealing with a decl but not a TagDecl, assume that
3268 // whatever routines created it handled the friendship aspect.
3269 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003270 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003271 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003272 }
John McCallac4df242011-03-22 23:00:04 +00003273
Richard Smithc7f81162013-03-18 22:52:47 +00003274 CXXScopeSpec &SS = DS.getTypeSpecScope();
3275 bool IsExplicitSpecialization =
3276 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3277 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3278 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3279 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3280 // nested-name-specifier unless it is an explicit instantiation
3281 // or an explicit specialization.
3282 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3283 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3284 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3285 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3286 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3287 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3288 << SS.getRange();
3289 return 0;
3290 }
3291
3292 // Track whether this decl-specifier declares anything.
3293 bool DeclaresAnything = true;
3294
3295 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003296 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003297 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003298 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003299 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003300 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003301 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003302
Richard Smithc7f81162013-03-18 22:52:47 +00003303 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003304 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003305 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003306
Richard Smithc7f81162013-03-18 22:52:47 +00003307 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003308 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003309 CurContext->isRecord() &&
3310 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3311 // Handle 2 kinds of anonymous struct:
3312 // struct STRUCT;
3313 // and
3314 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3315 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003316 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003317 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3318 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003319 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003320 << DS.getSourceRange();
3321 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3322 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003323 }
Richard Smithc7f81162013-03-18 22:52:47 +00003324
3325 // Skip all the checks below if we have a type error.
3326 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3327 (TagD && TagD->isInvalidDecl()))
3328 return TagD;
3329
3330 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003331 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3332 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3333 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003334 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3335 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003336
John McCallac4df242011-03-22 23:00:04 +00003337 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003338 // Customize diagnostic for a typedef missing a name.
3339 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003340 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003341 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003342 else
3343 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003344 }
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Richard Smithc7f81162013-03-18 22:52:47 +00003346 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003347 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3348 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3349 << Tag->getTagKind()
3350 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3351
Richard Smithc7f81162013-03-18 22:52:47 +00003352 ActOnDocumentableDecl(TagD);
3353
3354 // C 6.7/2:
3355 // A declaration [...] shall declare at least a declarator [...], a tag,
3356 // or the members of an enumeration.
3357 // C++ [dcl.dcl]p3:
3358 // [If there are no declarators], and except for the declaration of an
3359 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3360 // names into the program, or shall redeclare a name introduced by a
3361 // previous declaration.
3362 if (!DeclaresAnything) {
3363 // In C, we allow this as a (popular) extension / bug. Don't bother
3364 // producing further diagnostics for redundant qualifiers after this.
3365 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3366 return TagD;
3367 }
3368
3369 // C++ [dcl.stc]p1:
3370 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3371 // init-declarator-list of the declaration shall not be empty.
3372 // C++ [dcl.fct.spec]p1:
3373 // If a cv-qualifier appears in a decl-specifier-seq, the
3374 // init-declarator-list of the declaration shall not be empty.
3375 //
3376 // Spurious qualifiers here appear to be valid in C.
3377 unsigned DiagID = diag::warn_standalone_specifier;
3378 if (getLangOpts().CPlusPlus)
3379 DiagID = diag::ext_standalone_specifier;
3380
3381 // Note that a linkage-specification sets a storage class, but
3382 // 'extern "C" struct foo;' is actually valid and not theoretically
3383 // useless.
3384 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3385 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3386 Diag(DS.getStorageClassSpecLoc(), DiagID)
3387 << DeclSpec::getSpecifierName(SCS);
3388
Richard Smithec642442013-04-12 22:46:28 +00003389 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3390 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3391 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003392 if (DS.getTypeQualifiers()) {
3393 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3394 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3395 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3396 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3397 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003398 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3399 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003400 }
3401
Eli Friedmanfc038e92011-12-17 00:36:09 +00003402 // Warn about ignored type attributes, for example:
3403 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003404 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003405 if (!DS.getAttributes().empty()) {
3406 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3407 if (TypeSpecType == DeclSpec::TST_class ||
3408 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003409 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003410 TypeSpecType == DeclSpec::TST_union ||
3411 TypeSpecType == DeclSpec::TST_enum) {
3412 AttributeList* attrs = DS.getAttributes().getList();
3413 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003414 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003415 << attrs->getName()
3416 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3417 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003418 TypeSpecType == DeclSpec::TST_union ? 2 :
3419 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003420 attrs = attrs->getNext();
3421 }
3422 }
3423 }
John McCallac4df242011-03-22 23:00:04 +00003424
John McCalld226f652010-08-21 09:40:31 +00003425 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003426}
3427
John McCall1d7c5282009-12-18 10:40:03 +00003428/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003429/// check if there's an existing declaration that can't be overloaded.
3430///
3431/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003432static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3433 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003434 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003435 DeclarationName Name,
3436 SourceLocation NameLoc,
3437 unsigned diagnostic) {
3438 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3439 Sema::ForRedeclaration);
3440 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003441
John McCall1d7c5282009-12-18 10:40:03 +00003442 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003443 return false;
3444
3445 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003446 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003447 assert(PrevDecl && "Expected a non-null Decl");
3448
3449 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3450 return false;
John McCall68263142009-11-18 22:49:29 +00003451
John McCall1d7c5282009-12-18 10:40:03 +00003452 SemaRef.Diag(NameLoc, diagnostic) << Name;
3453 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003454
3455 return true;
3456}
3457
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003458/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3459/// anonymous struct or union AnonRecord into the owning context Owner
3460/// and scope S. This routine will be invoked just after we realize
3461/// that an unnamed union or struct is actually an anonymous union or
3462/// struct, e.g.,
3463///
3464/// @code
3465/// union {
3466/// int i;
3467/// float f;
3468/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3469/// // f into the surrounding scope.x
3470/// @endcode
3471///
3472/// This routine is recursive, injecting the names of nested anonymous
3473/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003474static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003475 DeclContext *Owner,
3476 RecordDecl *AnonRecord,
3477 AccessSpecifier AS,
3478 SmallVectorImpl<NamedDecl *> &Chaining,
3479 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003480 unsigned diagKind
3481 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3482 : diag::err_anonymous_struct_member_redecl;
3483
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003484 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003485
3486 // Look every FieldDecl and IndirectFieldDecl with a name.
3487 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3488 DEnd = AnonRecord->decls_end();
3489 D != DEnd; ++D) {
3490 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3491 cast<NamedDecl>(*D)->getDeclName()) {
3492 ValueDecl *VD = cast<ValueDecl>(*D);
3493 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3494 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003495 // C++ [class.union]p2:
3496 // The names of the members of an anonymous union shall be
3497 // distinct from the names of any other entity in the
3498 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003499 Invalid = true;
3500 } else {
3501 // C++ [class.union]p2:
3502 // For the purpose of name lookup, after the anonymous union
3503 // definition, the members of the anonymous union are
3504 // considered to have been defined in the scope in which the
3505 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003506 unsigned OldChainingSize = Chaining.size();
3507 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3508 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3509 PE = IF->chain_end(); PI != PE; ++PI)
3510 Chaining.push_back(*PI);
3511 else
3512 Chaining.push_back(VD);
3513
Francois Pichet87c2e122010-11-21 06:08:52 +00003514 assert(Chaining.size() >= 2);
3515 NamedDecl **NamedChain =
3516 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3517 for (unsigned i = 0; i < Chaining.size(); i++)
3518 NamedChain[i] = Chaining[i];
3519
3520 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003521 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3522 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003523 NamedChain, Chaining.size());
3524
3525 IndirectField->setAccess(AS);
3526 IndirectField->setImplicit();
3527 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003528
3529 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003530 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003531
Francois Pichet8e161ed2010-11-23 06:07:27 +00003532 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003533 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003534 }
3535 }
3536
3537 return Invalid;
3538}
3539
Douglas Gregor16573fa2010-04-19 22:54:31 +00003540/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3541/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003542/// illegal input values are mapped to SC_None.
3543static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003544StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3545 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3546 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3547 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003548 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003549 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003550 case DeclSpec::SCS_extern:
3551 if (DS.isExternInLinkageSpec())
3552 return SC_None;
3553 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003554 case DeclSpec::SCS_static: return SC_Static;
3555 case DeclSpec::SCS_auto: return SC_Auto;
3556 case DeclSpec::SCS_register: return SC_Register;
3557 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003558 // Illegal SCSs map to None: error reporting is up to the caller.
3559 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003560 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003561 }
3562 llvm_unreachable("unknown storage class specifier");
3563}
3564
Francois Pichet8e161ed2010-11-23 06:07:27 +00003565/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003566/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003567/// (C++ [class.union]) and a C11 feature; anonymous structures
3568/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003569Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3570 AccessSpecifier AS,
3571 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003572 DeclContext *Owner = Record->getDeclContext();
3573
3574 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003575 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003576 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003577 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003578 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003579 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003580 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003582 // C and C++ require different kinds of checks for anonymous
3583 // structs/unions.
3584 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003585 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003586 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003587 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003588 if (Record->isUnion()) {
3589 // C++ [class.union]p6:
3590 // Anonymous unions declared in a named namespace or in the
3591 // global namespace shall be declared static.
3592 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3593 (isa<TranslationUnitDecl>(Owner) ||
3594 (isa<NamespaceDecl>(Owner) &&
3595 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003596 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3597 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003598
3599 // Recover by adding 'static'.
3600 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3601 PrevSpec, DiagID);
3602 }
3603 // C++ [class.union]p6:
3604 // A storage class is not allowed in a declaration of an
3605 // anonymous union in a class scope.
3606 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3607 isa<RecordDecl>(Owner)) {
3608 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003609 diag::err_anonymous_union_with_storage_spec)
3610 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003611
3612 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003613 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3614 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003615 PrevSpec, DiagID);
3616 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003617 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003618
Douglas Gregor7604f642011-05-09 23:05:33 +00003619 // Ignore const/volatile/restrict qualifiers.
3620 if (DS.getTypeQualifiers()) {
3621 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3622 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003623 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003624 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3625 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003626 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003627 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003628 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003629 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3630 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003631 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003632 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003633 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003634 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003635 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3636 Diag(DS.getAtomicSpecLoc(),
3637 diag::ext_anonymous_struct_union_qualified)
3638 << Record->isUnion() << "_Atomic"
3639 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003640
3641 DS.ClearTypeQualifiers();
3642 }
3643
Mike Stump1eb44332009-09-09 15:08:12 +00003644 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003645 // The member-specification of an anonymous union shall only
3646 // define non-static data members. [Note: nested types and
3647 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003648 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3649 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003650 Mem != MemEnd; ++Mem) {
3651 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3652 // C++ [class.union]p3:
3653 // An anonymous union shall not have private or protected
3654 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003655 assert(FD->getAccess() != AS_none);
3656 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003657 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3658 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3659 Invalid = true;
3660 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003661
Sean Huntcf34e752011-05-16 22:41:40 +00003662 // C++ [class.union]p1
3663 // An object of a class with a non-trivial constructor, a non-trivial
3664 // copy constructor, a non-trivial destructor, or a non-trivial copy
3665 // assignment operator cannot be a member of a union, nor can an
3666 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003667 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003668 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003669 } else if ((*Mem)->isImplicit()) {
3670 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003671 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3672 // This is a type that showed up in an
3673 // elaborated-type-specifier inside the anonymous struct or
3674 // union, but which actually declares a type outside of the
3675 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003676 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3677 if (!MemRecord->isAnonymousStructOrUnion() &&
3678 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003679 // 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 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3682 << (int)Record->isUnion();
3683 else {
3684 // This is a nested type declaration.
3685 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3686 << (int)Record->isUnion();
3687 Invalid = true;
3688 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003689 } else {
3690 // This is an anonymous type definition within another anonymous type.
3691 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3692 // not part of standard C++.
3693 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003694 diag::ext_anonymous_record_with_anonymous_type)
3695 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003696 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003697 } else if (isa<AccessSpecDecl>(*Mem)) {
3698 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003699 } else {
3700 // We have something that isn't a non-static data
3701 // member. Complain about it.
3702 unsigned DK = diag::err_anonymous_record_bad_member;
3703 if (isa<TypeDecl>(*Mem))
3704 DK = diag::err_anonymous_record_with_type;
3705 else if (isa<FunctionDecl>(*Mem))
3706 DK = diag::err_anonymous_record_with_function;
3707 else if (isa<VarDecl>(*Mem))
3708 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003709
3710 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003711 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003712 DK == diag::err_anonymous_record_with_type)
3713 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003714 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003715 else {
3716 Diag((*Mem)->getLocation(), DK)
3717 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003718 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003719 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003720 }
3721 }
Mike Stump1eb44332009-09-09 15:08:12 +00003722 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003723
3724 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003725 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003726 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003727 Invalid = true;
3728 }
3729
John McCalleb692e02009-10-22 23:31:08 +00003730 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003731 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003732 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003733 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003734
Mike Stump1eb44332009-09-09 15:08:12 +00003735 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003736 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003737 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003738 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003739 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003740 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003741 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003742 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003743 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003744 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003745 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003746 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003747 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003748 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003749 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003750 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003751 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003752 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003753 // mutable can only appear on non-static class members, so it's always
3754 // an error here
3755 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3756 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003757 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003758 }
3759
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003760 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003761 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003762 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003763 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003764 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003765
3766 // Default-initialize the implicit variable. This initialization will be
3767 // trivial in almost all cases, except if a union member has an in-class
3768 // initializer:
3769 // union { int n = 0; };
3770 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003771 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003772 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003773
3774 // Add the anonymous struct/union object to the current
3775 // context. We'll be referencing this object when we refer to one of
3776 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003777 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003778
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003779 // Inject the members of the anonymous struct/union into the owning
3780 // context and into the identifier resolver chain for name lookup
3781 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003782 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003783 Chain.push_back(Anon);
3784
Francois Pichet8e161ed2010-11-23 06:07:27 +00003785 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3786 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003787 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003788
3789 // Mark this as an anonymous struct/union type. Note that we do not
3790 // do this until after we have already checked and injected the
3791 // members of this anonymous struct/union type, because otherwise
3792 // the members could be injected twice: once by DeclContext when it
3793 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003794 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003795 Record->setAnonymousStructOrUnion(true);
3796
3797 if (Invalid)
3798 Anon->setInvalidDecl();
3799
John McCalld226f652010-08-21 09:40:31 +00003800 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003801}
3802
Francois Pichet8e161ed2010-11-23 06:07:27 +00003803/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3804/// Microsoft C anonymous structure.
3805/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3806/// Example:
3807///
3808/// struct A { int a; };
3809/// struct B { struct A; int b; };
3810///
3811/// void foo() {
3812/// B var;
3813/// var.a = 3;
3814/// }
3815///
3816Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3817 RecordDecl *Record) {
3818
3819 // If there is no Record, get the record via the typedef.
3820 if (!Record)
3821 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3822
3823 // Mock up a declarator.
3824 Declarator Dc(DS, Declarator::TypeNameContext);
3825 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3826 assert(TInfo && "couldn't build declarator info for anonymous struct");
3827
3828 // Create a declaration for this anonymous struct.
3829 NamedDecl* Anon = FieldDecl::Create(Context,
3830 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003831 DS.getLocStart(),
3832 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003833 /*IdentifierInfo=*/0,
3834 Context.getTypeDeclType(Record),
3835 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003836 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003837 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003838 Anon->setImplicit();
3839
3840 // Add the anonymous struct object to the current context.
3841 CurContext->addDecl(Anon);
3842
3843 // Inject the members of the anonymous struct into the current
3844 // context and into the identifier resolver chain for name lookup
3845 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003846 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003847 Chain.push_back(Anon);
3848
Nico Weberee625af2012-02-01 00:41:00 +00003849 RecordDecl *RecordDef = Record->getDefinition();
3850 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3851 RecordDef, AS_none,
3852 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003853 Anon->setInvalidDecl();
3854
3855 return Anon;
3856}
Steve Narofff0090632007-09-02 02:04:30 +00003857
Douglas Gregor10bd3682008-11-17 22:58:34 +00003858/// GetNameForDeclarator - Determine the full declaration name for the
3859/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003860DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003861 return GetNameFromUnqualifiedId(D.getName());
3862}
3863
Abramo Bagnara25777432010-08-11 22:01:17 +00003864/// \brief Retrieves the declaration name from a parsed unqualified-id.
3865DeclarationNameInfo
3866Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3867 DeclarationNameInfo NameInfo;
3868 NameInfo.setLoc(Name.StartLocation);
3869
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003870 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003871
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003872 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003873 case UnqualifiedId::IK_Identifier:
3874 NameInfo.setName(Name.Identifier);
3875 NameInfo.setLoc(Name.StartLocation);
3876 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003877
Abramo Bagnara25777432010-08-11 22:01:17 +00003878 case UnqualifiedId::IK_OperatorFunctionId:
3879 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3880 Name.OperatorFunctionId.Operator));
3881 NameInfo.setLoc(Name.StartLocation);
3882 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3883 = Name.OperatorFunctionId.SymbolLocations[0];
3884 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3885 = Name.EndLocation.getRawEncoding();
3886 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003887
Abramo Bagnara25777432010-08-11 22:01:17 +00003888 case UnqualifiedId::IK_LiteralOperatorId:
3889 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3890 Name.Identifier));
3891 NameInfo.setLoc(Name.StartLocation);
3892 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3893 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003894
Abramo Bagnara25777432010-08-11 22:01:17 +00003895 case UnqualifiedId::IK_ConversionFunctionId: {
3896 TypeSourceInfo *TInfo;
3897 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3898 if (Ty.isNull())
3899 return DeclarationNameInfo();
3900 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3901 Context.getCanonicalType(Ty)));
3902 NameInfo.setLoc(Name.StartLocation);
3903 NameInfo.setNamedTypeInfo(TInfo);
3904 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003905 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003906
3907 case UnqualifiedId::IK_ConstructorName: {
3908 TypeSourceInfo *TInfo;
3909 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3910 if (Ty.isNull())
3911 return DeclarationNameInfo();
3912 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3913 Context.getCanonicalType(Ty)));
3914 NameInfo.setLoc(Name.StartLocation);
3915 NameInfo.setNamedTypeInfo(TInfo);
3916 return NameInfo;
3917 }
3918
3919 case UnqualifiedId::IK_ConstructorTemplateId: {
3920 // In well-formed code, we can only have a constructor
3921 // template-id that refers to the current context, so go there
3922 // to find the actual type being constructed.
3923 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3924 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3925 return DeclarationNameInfo();
3926
3927 // Determine the type of the class being constructed.
3928 QualType CurClassType = Context.getTypeDeclType(CurClass);
3929
3930 // FIXME: Check two things: that the template-id names the same type as
3931 // CurClassType, and that the template-id does not occur when the name
3932 // was qualified.
3933
3934 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3935 Context.getCanonicalType(CurClassType)));
3936 NameInfo.setLoc(Name.StartLocation);
3937 // FIXME: should we retrieve TypeSourceInfo?
3938 NameInfo.setNamedTypeInfo(0);
3939 return NameInfo;
3940 }
3941
3942 case UnqualifiedId::IK_DestructorName: {
3943 TypeSourceInfo *TInfo;
3944 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3945 if (Ty.isNull())
3946 return DeclarationNameInfo();
3947 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3948 Context.getCanonicalType(Ty)));
3949 NameInfo.setLoc(Name.StartLocation);
3950 NameInfo.setNamedTypeInfo(TInfo);
3951 return NameInfo;
3952 }
3953
3954 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003955 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003956 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3957 return Context.getNameForTemplate(TName, TNameLoc);
3958 }
3959
3960 } // switch (Name.getKind())
3961
David Blaikieb219cfc2011-09-23 05:06:16 +00003962 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003963}
3964
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003965static QualType getCoreType(QualType Ty) {
3966 do {
3967 if (Ty->isPointerType() || Ty->isReferenceType())
3968 Ty = Ty->getPointeeType();
3969 else if (Ty->isArrayType())
3970 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3971 else
3972 return Ty.withoutLocalFastQualifiers();
3973 } while (true);
3974}
3975
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003976/// hasSimilarParameters - Determine whether the C++ functions Declaration
3977/// and Definition have "nearly" matching parameters. This heuristic is
3978/// used to improve diagnostics in the case where an out-of-line function
3979/// definition doesn't match any declaration within the class or namespace.
3980/// Also sets Params to the list of indices to the parameters that differ
3981/// between the declaration and the definition. If hasSimilarParameters
3982/// returns true and Params is empty, then all of the parameters match.
3983static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003984 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003985 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003986 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003987 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003988 if (Declaration->param_size() != Definition->param_size())
3989 return false;
3990 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3991 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3992 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3993
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003994 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003995 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003996 continue;
3997
3998 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3999 QualType DefParamBaseTy = getCoreType(DefParamTy);
4000 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4001 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4002
4003 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4004 (DeclTyName && DeclTyName == DefTyName))
4005 Params.push_back(Idx);
4006 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00004007 return false;
4008 }
4009
4010 return true;
4011}
4012
John McCall63b43852010-04-29 23:50:39 +00004013/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4014/// declarator needs to be rebuilt in the current instantiation.
4015/// Any bits of declarator which appear before the name are valid for
4016/// consideration here. That's specifically the type in the decl spec
4017/// and the base type in any member-pointer chunks.
4018static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4019 DeclarationName Name) {
4020 // The types we specifically need to rebuild are:
4021 // - typenames, typeofs, and decltypes
4022 // - types which will become injected class names
4023 // Of course, we also need to rebuild any type referencing such a
4024 // type. It's safest to just say "dependent", but we call out a
4025 // few cases here.
4026
4027 DeclSpec &DS = D.getMutableDeclSpec();
4028 switch (DS.getTypeSpecType()) {
4029 case DeclSpec::TST_typename:
4030 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00004031 case DeclSpec::TST_underlyingType:
4032 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00004033 // Grab the type from the parser.
4034 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00004035 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00004036 if (T.isNull() || !T->isDependentType()) break;
4037
4038 // Make sure there's a type source info. This isn't really much
4039 // of a waste; most dependent types should have type source info
4040 // attached already.
4041 if (!TSI)
4042 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4043
4044 // Rebuild the type in the current instantiation.
4045 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4046 if (!TSI) return true;
4047
4048 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00004049 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4050 DS.UpdateTypeRep(LocType);
4051 break;
4052 }
4053
Richard Smithc4a83912012-10-01 20:35:07 +00004054 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00004055 case DeclSpec::TST_typeofExpr: {
4056 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00004057 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00004058 if (Result.isInvalid()) return true;
4059 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00004060 break;
4061 }
4062
4063 default:
4064 // Nothing to do for these decl specs.
4065 break;
4066 }
4067
4068 // It doesn't matter what order we do this in.
4069 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4070 DeclaratorChunk &Chunk = D.getTypeObject(I);
4071
4072 // The only type information in the declarator which can come
4073 // before the declaration name is the base type of a member
4074 // pointer.
4075 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4076 continue;
4077
4078 // Rebuild the scope specifier in-place.
4079 CXXScopeSpec &SS = Chunk.Mem.Scope();
4080 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4081 return true;
4082 }
4083
4084 return false;
4085}
4086
Anders Carlsson3242ee02011-07-04 16:28:17 +00004087Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00004088 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004089 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004090
4091 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004092 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004093 Dcl->setTopLevelDeclInObjCContainer();
4094
4095 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004096}
4097
Richard Smith162e1c12011-04-15 14:24:37 +00004098/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4099/// If T is the name of a class, then each of the following shall have a
4100/// name different from T:
4101/// - every static data member of class T;
4102/// - every member function of class T
4103/// - every member of class T that is itself a type;
4104/// \returns true if the declaration name violates these rules.
4105bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4106 DeclarationNameInfo NameInfo) {
4107 DeclarationName Name = NameInfo.getName();
4108
4109 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4110 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4111 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4112 return true;
4113 }
4114
4115 return false;
4116}
Douglas Gregor42acead2012-03-17 23:06:31 +00004117
Douglas Gregor69605872012-03-28 16:01:27 +00004118/// \brief Diagnose a declaration whose declarator-id has the given
4119/// nested-name-specifier.
4120///
4121/// \param SS The nested-name-specifier of the declarator-id.
4122///
4123/// \param DC The declaration context to which the nested-name-specifier
4124/// resolves.
4125///
4126/// \param Name The name of the entity being declared.
4127///
4128/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004129///
4130/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004131bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004132 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004133 SourceLocation Loc) {
4134 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004135 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004136 Cur = Cur->getParent();
4137
4138 // C++ [dcl.meaning]p1:
4139 // A declarator-id shall not be qualified except for the definition
4140 // of a member function (9.3) or static data member (9.4) outside of
4141 // its class, the definition or explicit instantiation of a function
4142 // or variable member of a namespace outside of its namespace, or the
4143 // definition of an explicit specialization outside of its namespace,
4144 // or the declaration of a friend function that is a member of
4145 // another class or namespace (11.3). [...]
4146
4147 // The user provided a superfluous scope specifier that refers back to the
4148 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004149 //
4150 // class X {
4151 // void X::f();
4152 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004153 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004154 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4155 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004156 << Name << FixItHint::CreateRemoval(SS.getRange());
4157 SS.clear();
4158 return false;
4159 }
Douglas Gregor69605872012-03-28 16:01:27 +00004160
4161 // Check whether the qualifying scope encloses the scope of the original
4162 // declaration.
4163 if (!Cur->Encloses(DC)) {
4164 if (Cur->isRecord())
4165 Diag(Loc, diag::err_member_qualification)
4166 << Name << SS.getRange();
4167 else if (isa<TranslationUnitDecl>(DC))
4168 Diag(Loc, diag::err_invalid_declarator_global_scope)
4169 << Name << SS.getRange();
4170 else if (isa<FunctionDecl>(Cur))
4171 Diag(Loc, diag::err_invalid_declarator_in_function)
4172 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004173 else if (isa<BlockDecl>(Cur))
4174 Diag(Loc, diag::err_invalid_declarator_in_block)
4175 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004176 else
4177 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004178 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004179
Douglas Gregor42acead2012-03-17 23:06:31 +00004180 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004181 }
4182
4183 if (Cur->isRecord()) {
4184 // Cannot qualify members within a class.
4185 Diag(Loc, diag::err_member_qualification)
4186 << Name << SS.getRange();
4187 SS.clear();
4188
4189 // C++ constructors and destructors with incorrect scopes can break
4190 // our AST invariants by having the wrong underlying types. If
4191 // that's the case, then drop this declaration entirely.
4192 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4193 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4194 !Context.hasSameType(Name.getCXXNameType(),
4195 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4196 return true;
4197
4198 return false;
4199 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004200
Douglas Gregor69605872012-03-28 16:01:27 +00004201 // C++11 [dcl.meaning]p1:
4202 // [...] "The nested-name-specifier of the qualified declarator-id shall
4203 // not begin with a decltype-specifer"
4204 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4205 while (SpecLoc.getPrefix())
4206 SpecLoc = SpecLoc.getPrefix();
4207 if (dyn_cast_or_null<DecltypeType>(
4208 SpecLoc.getNestedNameSpecifier()->getAsType()))
4209 Diag(Loc, diag::err_decltype_in_declarator)
4210 << SpecLoc.getTypeLoc().getSourceRange();
4211
Douglas Gregor42acead2012-03-17 23:06:31 +00004212 return false;
4213}
4214
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004215NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4216 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004217 // TODO: consider using NameInfo for diagnostic.
4218 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4219 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004220
Chris Lattnere80a59c2007-07-25 00:24:17 +00004221 // All of these full declarators require an identifier. If it doesn't have
4222 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004223 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004224 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004225 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004226 diag::err_declarator_need_ident)
4227 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004228 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004229 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4230 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004231
Chris Lattner31e05722007-08-26 06:24:45 +00004232 // The scope passed in may not be a decl scope. Zip up the scope tree until
4233 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004234 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004235 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004236 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004237
John McCall63b43852010-04-29 23:50:39 +00004238 DeclContext *DC = CurContext;
4239 if (D.getCXXScopeSpec().isInvalid())
4240 D.setInvalidType();
4241 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004242 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4243 UPPC_DeclarationQualifier))
4244 return 0;
4245
John McCall63b43852010-04-29 23:50:39 +00004246 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4247 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4248 if (!DC) {
4249 // If we could not compute the declaration context, it's because the
4250 // declaration context is dependent but does not refer to a class,
4251 // class template, or class template partial specialization. Complain
4252 // and return early, to avoid the coming semantic disaster.
4253 Diag(D.getIdentifierLoc(),
4254 diag::err_template_qualified_declarator_no_match)
4255 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4256 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004257 return 0;
John McCall63b43852010-04-29 23:50:39 +00004258 }
John McCall63b43852010-04-29 23:50:39 +00004259 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004260
John McCall63b43852010-04-29 23:50:39 +00004261 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004262 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004263 return 0;
John McCall63b43852010-04-29 23:50:39 +00004264
Douglas Gregor69605872012-03-28 16:01:27 +00004265 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4266 Diag(D.getIdentifierLoc(),
4267 diag::err_member_def_undefined_record)
4268 << Name << DC << D.getCXXScopeSpec().getRange();
4269 D.setInvalidType();
4270 } else if (!D.getDeclSpec().isFriendSpecified()) {
4271 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4272 Name, D.getIdentifierLoc())) {
4273 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004274 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004275
4276 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004277 }
John McCall63b43852010-04-29 23:50:39 +00004278 }
4279
4280 // Check whether we need to rebuild the type of the given
4281 // declaration in the current instantiation.
4282 if (EnteringContext && IsDependentContext &&
4283 TemplateParamLists.size() != 0) {
4284 ContextRAII SavedContext(*this, DC);
4285 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4286 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004287 }
4288 }
Richard Smith162e1c12011-04-15 14:24:37 +00004289
4290 if (DiagnoseClassNameShadow(DC, NameInfo))
4291 // If this is a typedef, we'll end up spewing multiple diagnostics.
4292 // Just return early; it's safer.
4293 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4294 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004295
John McCallbf1a0282010-06-04 23:28:52 +00004296 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4297 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004298
Douglas Gregord0937222010-12-13 22:49:22 +00004299 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4300 UPPC_DeclarationType))
4301 D.setInvalidType();
4302
Abramo Bagnara25777432010-08-11 22:01:17 +00004303 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004304 ForRedeclaration);
4305
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004306 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004307 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004308 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004309 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004310
4311 // If the declaration we're planning to build will be a function
4312 // or object with linkage, then look for another declaration with
4313 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004314 //
4315 // If the declaration we're planning to build will be declared with
4316 // external linkage in the translation unit, create any builtin with
4317 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004318 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4319 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004320 else if (CurContext->isFunctionOrMethod() &&
4321 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4322 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004323 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004324 CreateBuiltins =
4325 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4326 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4327 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4328 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004329
4330 if (IsLinkageLookup)
4331 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004332
Richard Smithdd9459f2013-08-13 18:18:50 +00004333 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004334 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004335 LookupQualifiedName(Previous, DC);
4336
Douglas Gregor69605872012-03-28 16:01:27 +00004337 // C++ [dcl.meaning]p1:
4338 // When the declarator-id is qualified, the declaration shall refer to a
4339 // previously declared member of the class or namespace to which the
4340 // qualifier refers (or, in the case of a namespace, of an element of the
4341 // inline namespace set of that namespace (7.3.1)) or to a specialization
4342 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004343 //
Douglas Gregor69605872012-03-28 16:01:27 +00004344 // Note that we already checked the context above, and that we do not have
4345 // enough information to make sure that Previous contains the declaration
4346 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004347 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004348 // class X {
4349 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004350 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004351 // };
4352 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004353 // void X::f(int) { } // ill-formed
4354 //
Douglas Gregor69605872012-03-28 16:01:27 +00004355 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004356 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004357 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004358
4359 // C++ [dcl.meaning]p1:
4360 // [...] the member shall not merely have been introduced by a
4361 // using-declaration in the scope of the class or namespace nominated by
4362 // the nested-name-specifier of the declarator-id.
4363 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004364 }
4365
John McCall68263142009-11-18 22:49:29 +00004366 if (Previous.isSingleResult() &&
4367 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004368 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004369 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004370 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4371 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004372
Douglas Gregor72c3f312008-12-05 18:15:24 +00004373 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004374 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004375 }
4376
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004377 // In C++, the previous declaration we find might be a tag type
4378 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004379 // tag type. Note that this does does not apply if we're declaring a
4380 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004381 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004382 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004383 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004384
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004385 // Check that there are no default arguments other than in the parameters
4386 // of a function declaration (C++ only).
4387 if (getLangOpts().CPlusPlus)
4388 CheckExtraCXXDefaultArguments(D);
4389
Nico Webere6bb76c2012-12-23 00:40:46 +00004390 NamedDecl *New;
4391
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004392 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004393 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004394 if (TemplateParamLists.size()) {
4395 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004396 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004397 }
Mike Stump1eb44332009-09-09 15:08:12 +00004398
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004399 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004400 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004401 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004402 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004403 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004404 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004405 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4406 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004407 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004408
4409 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004410 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004411
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004412 // If this has an identifier and is not an invalid redeclaration or
4413 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004414 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004415 !(D.isRedeclaration() && New->isInvalidDecl())) {
4416 // Only make a locally-scoped extern declaration visible if it is the first
4417 // declaration of this entity. Qualified lookup for such an entity should
4418 // only find this declaration if there is no visible declaration of it.
4419 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4420 PushOnScopeChains(New, S, AddToContext);
4421 if (!AddToContext)
4422 CurContext->addHiddenDecl(New);
4423 }
Mike Stump1eb44332009-09-09 15:08:12 +00004424
John McCalld226f652010-08-21 09:40:31 +00004425 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004426}
4427
Abramo Bagnara88adb982012-11-08 16:27:30 +00004428/// Helper method to turn variable array types into constant array
4429/// types in certain situations which would otherwise be errors (for
4430/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004431static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4432 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004433 bool &SizeIsNegative,
4434 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004435 // This method tries to turn a variable array into a constant
4436 // array even when the size isn't an ICE. This is necessary
4437 // for compatibility with code that depends on gcc's buggy
4438 // constant expression folding, like struct {char x[(int)(char*)2];}
4439 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004440 Oversized = 0;
4441
4442 if (T->isDependentType())
4443 return QualType();
4444
John McCall0953e762009-09-24 19:53:00 +00004445 QualifierCollector Qs;
4446 const Type *Ty = Qs.strip(T);
4447
4448 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004449 QualType Pointee = PTy->getPointeeType();
4450 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004451 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4452 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004453 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004454 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004455 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004456 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004457 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4458 QualType Inner = PTy->getInnerType();
4459 QualType FixedType =
4460 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4461 Oversized);
4462 if (FixedType.isNull()) return FixedType;
4463 FixedType = Context.getParenType(FixedType);
4464 return Qs.apply(Context, FixedType);
4465 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004466
4467 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004468 if (!VLATy)
4469 return QualType();
4470 // FIXME: We should probably handle this case
4471 if (VLATy->getElementType()->isVariablyModifiedType())
4472 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Richard Smithaa9c3502011-12-07 00:43:50 +00004474 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004475 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004476 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004477 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004478
Douglas Gregor2767ce22010-08-18 00:39:00 +00004479 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004480 if (Res.isSigned() && Res.isNegative()) {
4481 SizeIsNegative = true;
4482 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004483 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004484
Douglas Gregor2767ce22010-08-18 00:39:00 +00004485 // Check whether the array is too large to be addressed.
4486 unsigned ActiveSizeBits
4487 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4488 Res);
4489 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4490 Oversized = Res;
4491 return QualType();
4492 }
4493
4494 return Context.getConstantArrayType(VLATy->getElementType(),
4495 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004496}
4497
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004498static void
4499FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004500 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4501 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4502 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4503 DstPTL.getPointeeLoc());
4504 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004505 return;
4506 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004507 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4508 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4509 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4510 DstPTL.getInnerLoc());
4511 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4512 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004513 return;
4514 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004515 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4516 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4517 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4518 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004519 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004520 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4521 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4522 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004523}
4524
Abramo Bagnara88adb982012-11-08 16:27:30 +00004525/// Helper method to turn variable array types into constant array
4526/// types in certain situations which would otherwise be errors (for
4527/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004528static TypeSourceInfo*
4529TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4530 ASTContext &Context,
4531 bool &SizeIsNegative,
4532 llvm::APSInt &Oversized) {
4533 QualType FixedTy
4534 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4535 SizeIsNegative, Oversized);
4536 if (FixedTy.isNull())
4537 return 0;
4538 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4539 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4540 FixedTInfo->getTypeLoc());
4541 return FixedTInfo;
4542}
4543
Richard Smith5ea6ef42013-01-10 23:43:47 +00004544/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004545/// that it can be found later for redeclarations. We include any extern "C"
4546/// declaration that is not visible in the translation unit here, not just
4547/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004548void
Richard Smith662f41b2013-06-18 20:15:12 +00004549Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004550 if (!getLangOpts().CPlusPlus &&
4551 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4552 // Don't need to track declarations in the TU in C.
4553 return;
4554
Douglas Gregor63935192009-03-02 00:19:53 +00004555 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004556 // FIXME: There can be multiple such declarations if they are functions marked
4557 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004558 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004559}
4560
Richard Smith662f41b2013-06-18 20:15:12 +00004561NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004562 if (ExternalSource) {
4563 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004564 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004565 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004566 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004567 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4568 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004569 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4570 if (Pos == LocallyScopedExternCDecls.end())
4571 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004572 }
4573 }
Richard Smith662f41b2013-06-18 20:15:12 +00004574
4575 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola87bcee82013-10-19 16:55:03 +00004576 return D ? D->getMostRecentDecl() : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004577}
4578
Eli Friedman85a53192009-04-07 19:37:57 +00004579/// \brief Diagnose function specifiers on a declaration of an identifier that
4580/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004581void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004582 // FIXME: We should probably indicate the identifier in question to avoid
4583 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004584 if (DS.isInlineSpecified())
4585 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004586 diag::err_inline_non_function);
4587
Richard Smithc7f81162013-03-18 22:52:47 +00004588 if (DS.isVirtualSpecified())
4589 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004590 diag::err_virtual_non_function);
4591
Richard Smithc7f81162013-03-18 22:52:47 +00004592 if (DS.isExplicitSpecified())
4593 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004594 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004595
Richard Smithc7f81162013-03-18 22:52:47 +00004596 if (DS.isNoreturnSpecified())
4597 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004598 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004599}
4600
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004601NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004602Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004603 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004604 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4605 if (D.getCXXScopeSpec().isSet()) {
4606 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4607 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004608 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004609 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004610 DC = CurContext;
4611 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004612 }
4613
Richard Smithc7f81162013-03-18 22:52:47 +00004614 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004615
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004616 if (D.getDeclSpec().isConstexprSpecified())
4617 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4618 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004619
Douglas Gregoraef01992010-07-13 06:37:01 +00004620 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4621 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4622 << D.getName().getSourceRange();
4623 return 0;
4624 }
4625
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004626 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004627 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004628
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004629 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004630 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004631
Richard Smith3e4c6c42011-05-05 21:57:07 +00004632 CheckTypedefForVariablyModifiedType(S, NewTD);
4633
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004634 bool Redeclaration = D.isRedeclaration();
4635 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4636 D.setRedeclaration(Redeclaration);
4637 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004638}
4639
Richard Smith3e4c6c42011-05-05 21:57:07 +00004640void
4641Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004642 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4643 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004644 // Note that variably modified types must be fixed before merging the decl so
4645 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004646 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4647 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004648 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004649 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004650
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004651 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004652 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004653 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004654 TypeSourceInfo *FixedTInfo =
4655 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4656 SizeIsNegative,
4657 Oversized);
4658 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004659 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004660 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004661 } else {
4662 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004663 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004664 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004665 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004666 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004667 Diag(NewTD->getLocation(), diag::err_array_too_large)
4668 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004669 else
Richard Smith162e1c12011-04-15 14:24:37 +00004670 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004671 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004672 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004673 }
4674 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004675}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004676
Richard Smith3e4c6c42011-05-05 21:57:07 +00004677
4678/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4679/// declares a typedef-name, either using the 'typedef' type specifier or via
4680/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4681NamedDecl*
4682Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4683 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004684 // Merge the decl with the existing one if appropriate. If the decl is
4685 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004686 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004687 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004688 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004689 if (!Previous.empty()) {
4690 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004691 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004692 }
4693
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004694 // If this is the C FILE type, notify the AST context.
4695 if (IdentifierInfo *II = NewTD->getIdentifier())
4696 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004697 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004698 if (II->isStr("FILE"))
4699 Context.setFILEDecl(NewTD);
4700 else if (II->isStr("jmp_buf"))
4701 Context.setjmp_bufDecl(NewTD);
4702 else if (II->isStr("sigjmp_buf"))
4703 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004704 else if (II->isStr("ucontext_t"))
4705 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004706 }
4707
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004708 return NewTD;
4709}
4710
Douglas Gregor8f301052009-02-24 19:23:27 +00004711/// \brief Determines whether the given declaration is an out-of-scope
4712/// previous declaration.
4713///
4714/// This routine should be invoked when name lookup has found a
4715/// previous declaration (PrevDecl) that is not in the scope where a
4716/// new declaration by the same name is being introduced. If the new
4717/// declaration occurs in a local scope, previous declarations with
4718/// linkage may still be considered previous declarations (C99
4719/// 6.2.2p4-5, C++ [basic.link]p6).
4720///
4721/// \param PrevDecl the previous declaration found by name
4722/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004723///
Douglas Gregor8f301052009-02-24 19:23:27 +00004724/// \param DC the context in which the new declaration is being
4725/// declared.
4726///
4727/// \returns true if PrevDecl is an out-of-scope previous declaration
4728/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004729static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004730isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4731 ASTContext &Context) {
4732 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004733 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004734
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004735 if (!PrevDecl->hasLinkage())
4736 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004737
David Blaikie4e4d0842012-03-11 07:00:24 +00004738 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004739 // C++ [basic.link]p6:
4740 // If there is a visible declaration of an entity with linkage
4741 // having the same name and type, ignoring entities declared
4742 // outside the innermost enclosing namespace scope, the block
4743 // scope declaration declares that same entity and receives the
4744 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004745 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004746 if (!OuterContext->isFunctionOrMethod())
4747 // This rule only applies to block-scope declarations.
4748 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004749
4750 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4751 if (PrevOuterContext->isRecord())
4752 // We found a member function: ignore it.
4753 return false;
4754
4755 // Find the innermost enclosing namespace for the new and
4756 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004757 OuterContext = OuterContext->getEnclosingNamespaceContext();
4758 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Douglas Gregor757c6002010-08-27 22:55:10 +00004760 // The previous declaration is in a different namespace, so it
4761 // isn't the same function.
4762 if (!OuterContext->Equals(PrevOuterContext))
4763 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004764 }
4765
Douglas Gregor8f301052009-02-24 19:23:27 +00004766 return true;
4767}
4768
John McCallb6217662010-03-15 10:12:16 +00004769static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4770 CXXScopeSpec &SS = D.getCXXScopeSpec();
4771 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004772 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004773}
4774
John McCallf85e1932011-06-15 23:02:42 +00004775bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4776 QualType type = decl->getType();
4777 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4778 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4779 // Various kinds of declaration aren't allowed to be __autoreleasing.
4780 unsigned kind = -1U;
4781 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4782 if (var->hasAttr<BlocksAttr>())
4783 kind = 0; // __block
4784 else if (!var->hasLocalStorage())
4785 kind = 1; // global
4786 } else if (isa<ObjCIvarDecl>(decl)) {
4787 kind = 3; // ivar
4788 } else if (isa<FieldDecl>(decl)) {
4789 kind = 2; // field
4790 }
4791
4792 if (kind != -1U) {
4793 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4794 << kind;
4795 }
4796 } else if (lifetime == Qualifiers::OCL_None) {
4797 // Try to infer lifetime.
4798 if (!type->isObjCLifetimeType())
4799 return false;
4800
4801 lifetime = type->getObjCARCImplicitLifetime();
4802 type = Context.getLifetimeQualifiedType(type, lifetime);
4803 decl->setType(type);
4804 }
4805
4806 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4807 // Thread-local variables cannot have lifetime.
4808 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004809 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004810 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004811 << var->getType();
4812 return true;
4813 }
4814 }
4815
4816 return false;
4817}
4818
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004819static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4820 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004821 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004822 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004823 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4824 ND.dropAttr<WeakAttr>();
4825 }
4826 }
4827 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004828 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004829 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4830 ND.dropAttr<WeakRefAttr>();
4831 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004832 }
Reid Klecknera7225342013-05-20 14:02:37 +00004833
4834 // 'selectany' only applies to externally visible varable declarations.
4835 // It does not apply to functions.
4836 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4837 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4838 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4839 ND.dropAttr<SelectAnyAttr>();
4840 }
4841 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004842}
4843
John McCallb421d922013-04-02 02:48:58 +00004844/// Given that we are within the definition of the given function,
4845/// will that definition behave like C99's 'inline', where the
4846/// definition is discarded except for optimization purposes?
4847static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4848 // Try to avoid calling GetGVALinkageForFunction.
4849
4850 // All cases of this require the 'inline' keyword.
4851 if (!FD->isInlined()) return false;
4852
4853 // This is only possible in C++ with the gnu_inline attribute.
4854 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4855 return false;
4856
4857 // Okay, go ahead and call the relatively-more-expensive function.
4858
4859#ifndef NDEBUG
4860 // AST quite reasonably asserts that it's working on a function
4861 // definition. We don't really have a way to tell it that we're
4862 // currently defining the function, so just lie to it in +Asserts
4863 // builds. This is an awful hack.
4864 FD->setLazyBody(1);
4865#endif
4866
4867 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4868
4869#ifndef NDEBUG
4870 FD->setLazyBody(0);
4871#endif
4872
4873 return isC99Inline;
4874}
4875
Richard Smithaa4bc182013-06-30 09:48:50 +00004876/// Determine whether a variable is extern "C" prior to attaching
4877/// an initializer. We can't just call isExternC() here, because that
4878/// will also compute and cache whether the declaration is externally
4879/// visible, which might change when we attach the initializer.
4880///
4881/// This can only be used if the declaration is known to not be a
4882/// redeclaration of an internal linkage declaration.
4883///
4884/// For instance:
4885///
4886/// auto x = []{};
4887///
4888/// Attaching the initializer here makes this declaration not externally
4889/// visible, because its type has internal linkage.
4890///
4891/// FIXME: This is a hack.
4892template<typename T>
4893static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4894 if (S.getLangOpts().CPlusPlus) {
4895 // In C++, the overloadable attribute negates the effects of extern "C".
4896 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4897 return false;
4898 }
4899 return D->isExternC();
4900}
4901
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004902static bool shouldConsiderLinkage(const VarDecl *VD) {
4903 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4904 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004905 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004906 if (DC->isFileContext())
4907 return true;
4908 if (DC->isRecord())
4909 return false;
4910 llvm_unreachable("Unexpected context");
4911}
4912
4913static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4914 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4915 if (DC->isFileContext() || DC->isFunctionOrMethod())
4916 return true;
4917 if (DC->isRecord())
4918 return false;
4919 llvm_unreachable("Unexpected context");
4920}
4921
Richard Smitha41c97a2013-09-20 01:15:31 +00004922/// Adjust the \c DeclContext for a function or variable that might be a
4923/// function-local external declaration.
4924bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4925 if (!DC->isFunctionOrMethod())
4926 return false;
4927
4928 // If this is a local extern function or variable declared within a function
4929 // template, don't add it into the enclosing namespace scope until it is
4930 // instantiated; it might have a dependent type right now.
4931 if (DC->isDependentContext())
4932 return true;
4933
4934 // C++11 [basic.link]p7:
4935 // When a block scope declaration of an entity with linkage is not found to
4936 // refer to some other declaration, then that entity is a member of the
4937 // innermost enclosing namespace.
4938 //
4939 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4940 // semantically-enclosing namespace, not a lexically-enclosing one.
4941 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4942 DC = DC->getParent();
4943 return true;
4944}
4945
Larisse Voufoef4579c2013-08-06 01:03:05 +00004946NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004947Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004948 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004949 MultiTemplateParamsArg TemplateParamLists,
4950 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004951 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004952 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004953
Douglas Gregor16573fa2010-04-19 22:54:31 +00004954 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004955 VarDecl::StorageClass SC =
4956 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004957
Richard Smitha41c97a2013-09-20 01:15:31 +00004958 DeclContext *OriginalDC = DC;
4959 bool IsLocalExternDecl = SC == SC_Extern &&
4960 adjustContextForLocalExternDecl(DC);
4961
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004962 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004963 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4964 // half array type (unless the cl_khr_fp16 extension is enabled).
4965 if (Context.getBaseElementType(R)->isHalfType()) {
4966 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4967 D.setInvalidType();
4968 }
4969 }
4970
Douglas Gregor16573fa2010-04-19 22:54:31 +00004971 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004972 // mutable can only appear on non-static class members, so it's always
4973 // an error here
4974 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004975 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004976 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004977 }
John McCallb421d922013-04-02 02:48:58 +00004978
Richard Smith9109bf12013-06-17 01:34:01 +00004979 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4980 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4981 D.getDeclSpec().getStorageClassSpecLoc())) {
4982 // In C++11, the 'register' storage class specifier is deprecated.
4983 // Suppress the warning in system macros, it's used in macros in some
4984 // popular C system headers, such as in glibc's htonl() macro.
4985 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4986 diag::warn_deprecated_register)
4987 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4988 }
4989
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004990 IdentifierInfo *II = Name.getAsIdentifierInfo();
4991 if (!II) {
4992 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004993 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004994 return 0;
4995 }
4996
Richard Smithc7f81162013-03-18 22:52:47 +00004997 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004998
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004999 if (!DC->isRecord() && S->getFnParent() == 0) {
5000 // C99 6.9p2: The storage-class specifiers auto and register shall not
5001 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00005002 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00005003 // If this is a register variable with an asm label specified, then this
5004 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00005005 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00005006 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5007 else
5008 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00005009 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005010 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005011 }
Richard Smith9109bf12013-06-17 01:34:01 +00005012
David Blaikie4e4d0842012-03-11 07:00:24 +00005013 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005014 // Set up the special work-group-local storage class for variables in the
5015 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00005016 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005017 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00005018 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005019
Guy Benyei21f18c42013-02-07 10:55:47 +00005020 // OpenCL v1.2 s6.9.b p4:
5021 // The sampler type cannot be used with the __local and __global address
5022 // space qualifiers.
5023 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5024 R.getAddressSpace() == LangAS::opencl_global)) {
5025 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5026 }
5027
Guy Benyeie6b9d802013-01-20 12:31:11 +00005028 // OpenCL 1.2 spec, p6.9 r:
5029 // The event type cannot be used to declare a program scope variable.
5030 // The event type cannot be used with the __local, __constant and __global
5031 // address space qualifiers.
5032 if (R->isEventT()) {
5033 if (S->getParent() == 0) {
5034 Diag(D.getLocStart(), diag::err_event_t_global_var);
5035 D.setInvalidType();
5036 }
5037
5038 if (R.getAddressSpace()) {
5039 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5040 D.setInvalidType();
5041 }
5042 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005043 }
5044
Larisse Voufoef4579c2013-08-06 01:03:05 +00005045 bool IsExplicitSpecialization = false;
5046 bool IsVariableTemplateSpecialization = false;
5047 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00005048 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005049 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00005050 VarDecl *NewVD = 0;
5051 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00005052 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005053 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005054 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005055 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005056
5057 if (D.isInvalidType())
5058 NewVD->setInvalidDecl();
5059 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00005060 bool Invalid = false;
5061
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005062 if (DC->isRecord() && !CurContext->isRecord()) {
5063 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00005064 switch (SC) {
5065 case SC_None:
5066 break;
5067 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005068 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5069 diag::err_static_out_of_line)
5070 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00005071 break;
5072 case SC_Auto:
5073 case SC_Register:
5074 case SC_Extern:
5075 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5076 // to names of variables declared in a block or to function parameters.
5077 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5078 // of class members
5079
5080 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5081 diag::err_storage_class_for_static_member)
5082 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5083 break;
5084 case SC_PrivateExtern:
5085 llvm_unreachable("C storage class in c++!");
5086 case SC_OpenCLWorkGroupLocal:
5087 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00005088 }
Larisse Voufo06935f32013-08-06 03:43:07 +00005089 }
5090
Richard Smithb9c64d82012-02-16 20:41:22 +00005091 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005092 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5093 if (RD->isLocalClass())
5094 Diag(D.getIdentifierLoc(),
5095 diag::err_static_data_member_not_allowed_in_local_class)
5096 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005097
Richard Smithb9c64d82012-02-16 20:41:22 +00005098 // C++98 [class.union]p1: If a union contains a static data member,
5099 // the program is ill-formed. C++11 drops this restriction.
5100 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005101 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005102 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005103 ? diag::warn_cxx98_compat_static_data_member_in_union
5104 : diag::ext_static_data_member_in_union) << Name;
5105 // We conservatively disallow static data members in anonymous structs.
5106 else if (!RD->getDeclName())
5107 Diag(D.getIdentifierLoc(),
5108 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005109 << Name << RD->isUnion();
5110 }
5111 }
5112
Larisse Voufoef4579c2013-08-06 01:03:05 +00005113 NamedDecl *PrevDecl = 0;
5114 if (Previous.begin() != Previous.end())
5115 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5116 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5117
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005118 // Match up the template parameter lists with the scope specifier, then
5119 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005120 TemplateParameterList *TemplateParams =
5121 MatchTemplateParametersToScopeSpecifier(
5122 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5123 D.getCXXScopeSpec(), TemplateParamLists,
5124 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005125 if (TemplateParams) {
5126 if (!TemplateParams->size() &&
5127 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005128 // There is an extraneous 'template<>' for this variable. Complain
5129 // about it, but allow the declaration of the variable.
5130 Diag(TemplateParams->getTemplateLoc(),
5131 diag::err_template_variable_noparams)
5132 << II
5133 << SourceRange(TemplateParams->getTemplateLoc(),
5134 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005135 } else {
5136 // Only C++1y supports variable templates (N3651).
5137 Diag(D.getIdentifierLoc(),
5138 getLangOpts().CPlusPlus1y
5139 ? diag::warn_cxx11_compat_variable_template
5140 : diag::ext_variable_template);
5141
5142 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5143 // This is an explicit specialization or a partial specialization.
5144 // Check that we can declare a specialization here
5145
5146 IsVariableTemplateSpecialization = true;
5147 IsPartialSpecialization = TemplateParams->size() > 0;
5148
5149 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005150 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005151 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005152
5153 // Check that we can declare a template here.
5154 if (CheckTemplateDeclScope(S, TemplateParams))
5155 return 0;
5156
5157 // If there is a previous declaration with the same name, check
5158 // whether this is a valid redeclaration.
5159 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5160 PrevDecl = PrevVarTemplate = 0;
5161
5162 if (PrevVarTemplate) {
5163 // Ensure that the template parameter lists are compatible.
5164 if (!TemplateParameterListsAreEqual(
5165 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5166 /*Complain=*/true, TPL_TemplateMatch))
5167 return 0;
5168 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5169 // Maybe we will complain about the shadowed template parameter.
5170 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5171
5172 // Just pretend that we didn't see the previous declaration.
5173 PrevDecl = 0;
5174 } else if (PrevDecl) {
5175 // C++ [temp]p5:
5176 // ... a template name declared in namespace scope or in class
5177 // scope shall be unique in that scope.
5178 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5179 << Name;
5180 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5181 return 0;
5182 }
5183
5184 // Check the template parameter list of this declaration, possibly
5185 // merging in the template parameter list from the previous variable
5186 // template declaration.
5187 if (CheckTemplateParameterList(
5188 TemplateParams,
5189 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5190 : 0,
5191 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5192 DC->isDependentContext())
5193 ? TPC_ClassTemplateMember
5194 : TPC_VarTemplate))
5195 Invalid = true;
5196
5197 if (D.getCXXScopeSpec().isSet()) {
5198 // If the name of the template was qualified, we must be defining
5199 // the template out-of-line.
5200 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5201 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005202 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5203 << Name << DC << /*IsDefinition*/true
5204 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005205 Invalid = true;
5206 }
5207 }
5208 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005209 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005210 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5211 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5212
5213 // We have encountered something that the user meant to be a
5214 // specialization (because it has explicitly-specified template
5215 // arguments) but that was not introduced with a "template<>" (or had
5216 // too few of them).
5217 // FIXME: Differentiate between attempts for explicit instantiations
5218 // (starting with "template") and the rest.
5219 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5220 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5221 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5222 "template<> ");
5223 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005224 }
Mike Stump1eb44332009-09-09 15:08:12 +00005225
Larisse Voufoef4579c2013-08-06 01:03:05 +00005226 if (IsVariableTemplateSpecialization) {
5227 if (!PrevVarTemplate) {
5228 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5229 << IsPartialSpecialization;
5230 return 0;
5231 }
5232
5233 SourceLocation TemplateKWLoc =
5234 TemplateParamLists.size() > 0
5235 ? TemplateParamLists[0]->getTemplateLoc()
5236 : SourceLocation();
5237 DeclResult Res = ActOnVarTemplateSpecialization(
5238 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5239 IsPartialSpecialization);
5240 if (Res.isInvalid())
5241 return 0;
5242 NewVD = cast<VarDecl>(Res.get());
5243 AddToScope = false;
5244 } else
5245 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5246 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005247
Larisse Voufo567f9172013-08-22 00:59:14 +00005248 // If this is supposed to be a variable template, create it as such.
5249 if (IsVariableTemplate) {
5250 NewTemplate =
5251 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5252 TemplateParams, NewVD, PrevVarTemplate);
5253 NewVD->setDescribedVarTemplate(NewTemplate);
5254 }
5255
Richard Smith483b9f32011-02-21 20:05:19 +00005256 // If this decl has an auto type in need of deduction, make a note of the
5257 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005258 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005259 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005260
Larisse Voufo567f9172013-08-22 00:59:14 +00005261 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005262 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005263 if (NewTemplate)
5264 NewTemplate->setInvalidDecl();
5265 }
Mike Stump1eb44332009-09-09 15:08:12 +00005266
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005267 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005268
Larisse Voufoef4579c2013-08-06 01:03:05 +00005269 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5270 if (TemplateParams && TemplateParamLists.size() > 1 &&
5271 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5272 NewVD->setTemplateParameterListsInfo(
5273 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5274 } else if (IsVariableTemplateSpecialization ||
5275 (!TemplateParams && TemplateParamLists.size() > 0 &&
5276 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005277 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005278 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005279 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005280 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005281
Richard Smith7ca48502012-02-13 22:16:19 +00005282 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005283 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005284 }
5285
Douglas Gregore3895852011-09-12 18:37:38 +00005286 // Set the lexical context. If the declarator has a C++ scope specifier, the
5287 // lexical context will be different from the semantic context.
5288 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005289 if (NewTemplate)
5290 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005291
Richard Smitha41c97a2013-09-20 01:15:31 +00005292 if (IsLocalExternDecl)
5293 NewVD->setLocalExternDecl();
5294
Richard Smithec642442013-04-12 22:46:28 +00005295 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005296 if (NewVD->hasLocalStorage()) {
5297 // C++11 [dcl.stc]p4:
5298 // When thread_local is applied to a variable of block scope the
5299 // storage-class-specifier static is implied if it does not appear
5300 // explicitly.
5301 // Core issue: 'static' is not implied if the variable is declared
5302 // 'extern'.
5303 if (SCSpec == DeclSpec::SCS_unspecified &&
5304 TSCS == DeclSpec::TSCS_thread_local &&
5305 DC->isFunctionOrMethod())
5306 NewVD->setTSCSpec(TSCS);
5307 else
5308 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5309 diag::err_thread_non_global)
5310 << DeclSpec::getSpecifierName(TSCS);
5311 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005312 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5313 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005314 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005315 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005316 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005317
John McCallb421d922013-04-02 02:48:58 +00005318 // C99 6.7.4p3
5319 // An inline definition of a function with external linkage shall
5320 // not contain a definition of a modifiable object with static or
5321 // thread storage duration...
5322 // We only apply this when the function is required to be defined
5323 // elsewhere, i.e. when the function is not 'extern inline'. Note
5324 // that a local variable with thread storage duration still has to
5325 // be marked 'static'. Also note that it's possible to get these
5326 // semantics in C++ using __attribute__((gnu_inline)).
5327 if (SC == SC_Static && S->getFnParent() != 0 &&
5328 !NewVD->getType().isConstQualified()) {
5329 FunctionDecl *CurFD = getCurFunctionDecl();
5330 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5331 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5332 diag::warn_static_local_in_extern_inline);
5333 MaybeSuggestAddingStaticToDecl(CurFD);
5334 }
5335 }
5336
Douglas Gregord023aec2011-09-09 20:53:38 +00005337 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005338 if (IsVariableTemplateSpecialization)
5339 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5340 << (IsPartialSpecialization ? 1 : 0)
5341 << FixItHint::CreateRemoval(
5342 D.getDeclSpec().getModulePrivateSpecLoc());
5343 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005344 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5345 << 2
5346 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005347 else if (NewVD->hasLocalStorage())
5348 Diag(NewVD->getLocation(), diag::err_module_private_local)
5349 << 0 << NewVD->getDeclName()
5350 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5351 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005352 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005353 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005354 if (NewTemplate)
5355 NewTemplate->setModulePrivate();
5356 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005357 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005358
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005359 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005360 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005361
Richard Smithbe507b62013-02-01 08:12:08 +00005362 if (NewVD->hasAttrs())
5363 CheckAlignasUnderalignment(NewVD);
5364
Peter Collingbournec0c00662012-08-28 20:37:50 +00005365 if (getLangOpts().CUDA) {
5366 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5367 // storage [duration]."
5368 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005369 (NewVD->hasAttr<CUDASharedAttr>() ||
5370 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005371 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005372 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005373 }
5374
John McCallf85e1932011-06-15 23:02:42 +00005375 // In auto-retain/release, infer strong retension for variables of
5376 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005377 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005378 NewVD->setInvalidDecl();
5379
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005380 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005381 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005382 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005383 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005384 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005385 if (S->getFnParent() != 0) {
5386 switch (SC) {
5387 case SC_None:
5388 case SC_Auto:
5389 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5390 break;
5391 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005392 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005393 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5394 break;
5395 case SC_Static:
5396 case SC_Extern:
5397 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005398 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005399 break;
5400 }
5401 }
5402
5403 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005404 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005405 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5406 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5407 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5408 if (I != ExtnameUndeclaredIdentifiers.end()) {
5409 NewVD->addAttr(I->second);
5410 ExtnameUndeclaredIdentifiers.erase(I);
5411 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005412 }
5413
John McCall8472af42010-03-16 21:48:18 +00005414 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005415 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005416 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005417
John McCall68263142009-11-18 22:49:29 +00005418 // Don't consider existing declarations that are in a different
5419 // scope and are out-of-semantic-context declarations (if the new
5420 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005421 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005422 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005423 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5424
Richard Smithdd9459f2013-08-13 18:18:50 +00005425 // Check whether the previous declaration is in the same block scope. This
5426 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5427 if (getLangOpts().CPlusPlus &&
5428 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5429 NewVD->setPreviousDeclInSameBlockScope(
5430 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005431 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005432
David Blaikie4e4d0842012-03-11 07:00:24 +00005433 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005434 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5435 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005436 // Merge the decl with the existing one if appropriate.
5437 if (!Previous.empty()) {
5438 if (Previous.isSingleResult() &&
5439 isa<FieldDecl>(Previous.getFoundDecl()) &&
5440 D.getCXXScopeSpec().isSet()) {
5441 // The user tried to define a non-static data member
5442 // out-of-line (C++ [dcl.meaning]p1).
5443 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5444 << D.getCXXScopeSpec().getRange();
5445 Previous.clear();
5446 NewVD->setInvalidDecl();
5447 }
5448 } else if (D.getCXXScopeSpec().isSet()) {
5449 // No previous declaration in the qualifying scope.
5450 Diag(D.getIdentifierLoc(), diag::err_no_member)
5451 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005452 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005453 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005454 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005455
Larisse Voufoef4579c2013-08-06 01:03:05 +00005456 if (!IsVariableTemplateSpecialization) {
5457 if (PrevVarTemplate) {
5458 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5459 LookupOrdinaryName, ForRedeclaration);
5460 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005461 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005462 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005463 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005464 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005465
5466 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005467 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005468 CheckMemberSpecialization(NewVD, Previous))
5469 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005470 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005471
Rafael Espindola65611bf2013-03-02 21:41:48 +00005472 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005473 checkAttributesAfterMerging(*this, *NewVD);
5474
Richard Smithaa4bc182013-06-30 09:48:50 +00005475 // If this is the first declaration of an extern C variable, update
5476 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00005477 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00005478 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005479 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005480
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005481 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005482 Decl *ManglingContextDecl;
5483 if (MangleNumberingContext *MCtx =
5484 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5485 ManglingContextDecl)) {
5486 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5487 }
5488 }
5489
Larisse Voufoef4579c2013-08-06 01:03:05 +00005490 // If we are providing an explicit specialization of a static variable
5491 // template, make a note of that.
5492 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005493 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005494
Larisse Voufo567f9172013-08-22 00:59:14 +00005495 if (NewTemplate) {
5496 ActOnDocumentableDecl(NewTemplate);
5497 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005498 }
5499
Larisse Voufo567f9172013-08-22 00:59:14 +00005500 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005501}
5502
John McCall053f4bd2010-03-22 09:20:08 +00005503/// \brief Diagnose variable or built-in function shadowing. Implements
5504/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005505///
John McCall053f4bd2010-03-22 09:20:08 +00005506/// This method is called whenever a VarDecl is added to a "useful"
5507/// scope.
John McCall8472af42010-03-16 21:48:18 +00005508///
John McCalla369a952010-03-20 04:12:52 +00005509/// \param S the scope in which the shadowing name is being declared
5510/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005511///
John McCall053f4bd2010-03-22 09:20:08 +00005512void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005513 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005514 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005515 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005516 return;
5517
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005518 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005519 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005520 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005521
5522 DeclContext *NewDC = D->getDeclContext();
5523
John McCalla369a952010-03-20 04:12:52 +00005524 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005525 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005526 return;
John McCall8472af42010-03-16 21:48:18 +00005527
John McCall8472af42010-03-16 21:48:18 +00005528 NamedDecl* ShadowedDecl = R.getFoundDecl();
5529 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5530 return;
5531
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005532 // Fields are not shadowed by variables in C++ static methods.
5533 if (isa<FieldDecl>(ShadowedDecl))
5534 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5535 if (MD->isStatic())
5536 return;
5537
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005538 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5539 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005540 // For shadowing external vars, make sure that we point to the global
5541 // declaration, not a locally scoped extern declaration.
5542 for (VarDecl::redecl_iterator
5543 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5544 I != E; ++I)
5545 if (I->isFileVarDecl()) {
5546 ShadowedDecl = *I;
5547 break;
5548 }
5549 }
5550
5551 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5552
John McCalla369a952010-03-20 04:12:52 +00005553 // Only warn about certain kinds of shadowing for class members.
5554 if (NewDC && NewDC->isRecord()) {
5555 // In particular, don't warn about shadowing non-class members.
5556 if (!OldDC->isRecord())
5557 return;
5558
5559 // TODO: should we warn about static data members shadowing
5560 // static data members from base classes?
5561
5562 // TODO: don't diagnose for inaccessible shadowed members.
5563 // This is hard to do perfectly because we might friend the
5564 // shadowing context, but that's just a false negative.
5565 }
5566
5567 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005568 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005569 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005570 if (isa<FieldDecl>(ShadowedDecl))
5571 Kind = 3; // field
5572 else
5573 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005574 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005575 Kind = 1; // global
5576 else
5577 Kind = 0; // local
5578
John McCalla369a952010-03-20 04:12:52 +00005579 DeclarationName Name = R.getLookupName();
5580
John McCall8472af42010-03-16 21:48:18 +00005581 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005582 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005583 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5584}
5585
John McCall053f4bd2010-03-22 09:20:08 +00005586/// \brief Check -Wshadow without the advantage of a previous lookup.
5587void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005588 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005589 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005590 return;
5591
John McCall053f4bd2010-03-22 09:20:08 +00005592 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5593 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5594 LookupName(R, S);
5595 CheckShadow(S, D, R);
5596}
5597
Richard Smithaa4bc182013-06-30 09:48:50 +00005598/// Check for conflict between this global or extern "C" declaration and
5599/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005600template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005601static bool checkGlobalOrExternCConflict(
5602 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5603 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5604 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005605
Richard Smithaa4bc182013-06-30 09:48:50 +00005606 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5607 // The common case: this global doesn't conflict with any extern "C"
5608 // declaration.
5609 return false;
5610 }
5611
5612 if (Prev) {
5613 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5614 // Both the old and new declarations have C language linkage. This is a
5615 // redeclaration.
5616 Previous.clear();
5617 Previous.addDecl(Prev);
5618 return true;
5619 }
5620
5621 // This is a global, non-extern "C" declaration, and there is a previous
5622 // non-global extern "C" declaration. Diagnose if this is a variable
5623 // declaration.
5624 if (!isa<VarDecl>(ND))
5625 return false;
5626 } else {
5627 // The declaration is extern "C". Check for any declaration in the
5628 // translation unit which might conflict.
5629 if (IsGlobal) {
5630 // We have already performed the lookup into the translation unit.
5631 IsGlobal = false;
5632 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5633 I != E; ++I) {
5634 if (isa<VarDecl>(*I)) {
5635 Prev = *I;
5636 break;
5637 }
5638 }
5639 } else {
5640 DeclContext::lookup_result R =
5641 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5642 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5643 I != E; ++I) {
5644 if (isa<VarDecl>(*I)) {
5645 Prev = *I;
5646 break;
5647 }
5648 // FIXME: If we have any other entity with this name in global scope,
5649 // the declaration is ill-formed, but that is a defect: it breaks the
5650 // 'stat' hack, for instance. Only variables can have mangled name
5651 // clashes with extern "C" declarations, so only they deserve a
5652 // diagnostic.
5653 }
5654 }
5655
5656 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005657 return false;
5658 }
5659
Richard Smithaa4bc182013-06-30 09:48:50 +00005660 // Use the first declaration's location to ensure we point at something which
5661 // is lexically inside an extern "C" linkage-spec.
5662 assert(Prev && "should have found a previous declaration to diagnose");
5663 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindolabc650912013-10-17 15:37:26 +00005664 Prev = FD->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005665 else
Rafael Espindolabc650912013-10-17 15:37:26 +00005666 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005667
5668 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5669 << IsGlobal << ND;
5670 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5671 << IsGlobal;
5672 return false;
5673}
5674
5675/// Apply special rules for handling extern "C" declarations. Returns \c true
5676/// if we have found that this is a redeclaration of some prior entity.
5677///
5678/// Per C++ [dcl.link]p6:
5679/// Two declarations [for a function or variable] with C language linkage
5680/// with the same name that appear in different scopes refer to the same
5681/// [entity]. An entity with C language linkage shall not be declared with
5682/// the same name as an entity in global scope.
5683template<typename T>
5684static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5685 LookupResult &Previous) {
5686 if (!S.getLangOpts().CPlusPlus) {
5687 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005688 // variable declared in function scope. We don't need this in C++, because
5689 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005690 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5691 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5692 Previous.clear();
5693 Previous.addDecl(Prev);
5694 return true;
5695 }
5696 }
5697 return false;
5698 }
5699
5700 // A declaration in the translation unit can conflict with an extern "C"
5701 // declaration.
5702 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5703 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5704
5705 // An extern "C" declaration can conflict with a declaration in the
5706 // translation unit or can be a redeclaration of an extern "C" declaration
5707 // in another scope.
5708 if (isIncompleteDeclExternC(S,ND))
5709 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5710
5711 // Neither global nor extern "C": nothing to do.
5712 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005713}
5714
Richard Smithdc7a4f52013-04-30 13:56:41 +00005715void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005716 // If the decl is already known invalid, don't check it.
5717 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005718 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005720 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5721 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005722
Richard Smithdc7a4f52013-04-30 13:56:41 +00005723 // Defer checking an 'auto' type until its initializer is attached.
5724 if (T->isUndeducedType())
5725 return;
5726
John McCallc12c5bb2010-05-15 11:32:37 +00005727 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005728 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5729 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005730 T = Context.getObjCObjectPointerType(T);
5731 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005732 }
Mike Stump1eb44332009-09-09 15:08:12 +00005733
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005734 // Emit an error if an address space was applied to decl with local storage.
5735 // This includes arrays of objects with address space qualifiers, but not
5736 // automatic variables that point to other address spaces.
5737 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005738 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005739 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005740 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005741 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005742 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005743
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005744 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5745 // __constant address space.
5746 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5747 && T.getAddressSpace() != LangAS::opencl_constant
5748 && !T->isSamplerT()){
5749 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5750 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005751 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005752 }
5753
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005754 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5755 // scope.
5756 if ((getLangOpts().OpenCLVersion >= 120)
5757 && NewVD->isStaticLocal()) {
5758 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5759 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005760 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005761 }
5762
Mike Stumpf33651c2009-04-14 00:57:29 +00005763 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005764 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005765 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005766 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005767 else {
5768 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005769 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005770 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005771 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005772
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005773 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005774 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005775 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005776 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005777
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005778 if ((isVM && NewVD->hasLinkage()) ||
5779 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005780 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005781 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005782 TypeSourceInfo *FixedTInfo =
5783 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5784 SizeIsNegative, Oversized);
5785 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005786 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005787 // FIXME: This won't give the correct result for
5788 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005789 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005791 if (NewVD->isFileVarDecl())
5792 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005793 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005794 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005795 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005796 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005797 else
5798 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005799 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005800 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005801 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005802 }
5803
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005804 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005805 if (NewVD->isFileVarDecl())
5806 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5807 else
5808 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005809 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005810 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005811 }
Mike Stump1eb44332009-09-09 15:08:12 +00005812
Chris Lattnereaaebc72009-04-25 08:06:05 +00005813 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005814 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005815 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005816 }
5817
David Majnemeraa715672013-05-29 00:56:45 +00005818 if (T->isVoidType()) {
5819 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5820 // of objects and functions.
5821 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5822 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5823 << T;
5824 NewVD->setInvalidDecl();
5825 return;
5826 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005827 }
5828
5829 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5830 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5831 NewVD->setInvalidDecl();
5832 return;
5833 }
5834
5835 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5836 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5837 NewVD->setInvalidDecl();
5838 return;
5839 }
5840
5841 if (NewVD->isConstexpr() && !T->isDependentType() &&
5842 RequireLiteralType(NewVD->getLocation(), T,
5843 diag::err_constexpr_var_non_literal)) {
5844 // Can't perform this check until the type is deduced.
5845 NewVD->setInvalidDecl();
5846 return;
5847 }
5848}
5849
5850/// \brief Perform semantic checking on a newly-created variable
5851/// declaration.
5852///
5853/// This routine performs all of the type-checking required for a
5854/// variable declaration once it has been built. It is used both to
5855/// check variables after they have been parsed and their declarators
5856/// have been translated into a declaration, and to check variables
5857/// that have been instantiated from a template.
5858///
5859/// Sets NewVD->isInvalidDecl() if an error was encountered.
5860///
5861/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005862bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005863 CheckVariableDeclarationType(NewVD);
5864
5865 // If the decl is already known invalid, don't check it.
5866 if (NewVD->isInvalidDecl())
5867 return false;
5868
John McCall5b8740f2013-04-01 18:34:28 +00005869 // If we did not find anything by this name, look for a non-visible
5870 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005871 if (Previous.empty() &&
5872 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005873 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005874
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005875 // Filter out any non-conflicting previous declarations.
5876 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5877
John McCall68263142009-11-18 22:49:29 +00005878 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005879 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005880 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005881 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005882 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005883}
5884
Douglas Gregora8f32e02009-10-06 17:59:45 +00005885/// \brief Data used with FindOverriddenMethod
5886struct FindOverriddenMethodData {
5887 Sema *S;
5888 CXXMethodDecl *Method;
5889};
5890
5891/// \brief Member lookup function that determines whether a given C++
5892/// method overrides a method in a base class, to be used with
5893/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005894static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005895 CXXBasePath &Path,
5896 void *UserData) {
5897 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005898
Douglas Gregora8f32e02009-10-06 17:59:45 +00005899 FindOverriddenMethodData *Data
5900 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005901
5902 DeclarationName Name = Data->Method->getDeclName();
5903
5904 // FIXME: Do we care about other names here too?
5905 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005906 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005907 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5908 CanQualType CT = Data->S->Context.getCanonicalType(T);
5909
Anders Carlsson1a689722009-11-27 01:26:58 +00005910 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005911 }
5912
5913 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005914 !Path.Decls.empty();
5915 Path.Decls = Path.Decls.slice(1)) {
5916 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005917 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5918 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005919 return true;
5920 }
5921 }
5922
5923 return false;
5924}
5925
David Blaikie5708c182012-10-17 00:47:58 +00005926namespace {
5927 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5928}
5929/// \brief Report an error regarding overriding, along with any relevant
5930/// overriden methods.
5931///
5932/// \param DiagID the primary error to report.
5933/// \param MD the overriding method.
5934/// \param OEK which overrides to include as notes.
5935static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5936 OverrideErrorKind OEK = OEK_All) {
5937 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5938 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5939 E = MD->end_overridden_methods();
5940 I != E; ++I) {
5941 // This check (& the OEK parameter) could be replaced by a predicate, but
5942 // without lambdas that would be overkill. This is still nicer than writing
5943 // out the diag loop 3 times.
5944 if ((OEK == OEK_All) ||
5945 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5946 (OEK == OEK_Deleted && (*I)->isDeleted()))
5947 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5948 }
5949}
5950
Sebastian Redla165da02009-11-18 21:51:29 +00005951/// AddOverriddenMethods - See if a method overrides any in the base classes,
5952/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005953bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005954 // Look for virtual methods in base classes that this method might override.
5955 CXXBasePaths Paths;
5956 FindOverriddenMethodData Data;
5957 Data.Method = MD;
5958 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005959 bool hasDeletedOverridenMethods = false;
5960 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005961 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005962 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5963 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5964 E = Paths.found_decls_end(); I != E; ++I) {
5965 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005966 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005967 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005968 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005969 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005970 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005971 hasDeletedOverridenMethods |= OldMD->isDeleted();
5972 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005973 AddedAny = true;
5974 }
Sebastian Redla165da02009-11-18 21:51:29 +00005975 }
5976 }
5977 }
David Blaikie5708c182012-10-17 00:47:58 +00005978
5979 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5980 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5981 }
5982 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5983 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5984 }
5985
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005986 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005987}
5988
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005989namespace {
5990 // Struct for holding all of the extra arguments needed by
5991 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5992 struct ActOnFDArgs {
5993 Scope *S;
5994 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005995 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005996 bool AddToScope;
5997 };
5998}
5999
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006000namespace {
6001
6002// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006003// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006004class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6005 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006006 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6007 CXXRecordDecl *Parent)
6008 : Context(Context), OriginalFD(TypoFD),
6009 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006010
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006011 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006012 if (candidate.getEditDistance() == 0)
6013 return false;
6014
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006015 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006016 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6017 CDeclEnd = candidate.end();
6018 CDecl != CDeclEnd; ++CDecl) {
6019 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6020
6021 if (FD && !FD->hasBody() &&
6022 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6023 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6024 CXXRecordDecl *Parent = MD->getParent();
6025 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6026 return true;
6027 } else if (!ExpectedParent) {
6028 return true;
6029 }
6030 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006031 }
6032
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006033 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006034 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006035
6036 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006037 ASTContext &Context;
6038 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006039 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006040};
6041
6042}
6043
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006044/// \brief Generate diagnostics for an invalid function redeclaration.
6045///
6046/// This routine handles generating the diagnostic messages for an invalid
6047/// function redeclaration, including finding possible similar declarations
6048/// or performing typo correction if there are no previous declarations with
6049/// the same name.
6050///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006051/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006052/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00006053static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006054 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00006055 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006056 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006057 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006058 SmallVector<unsigned, 1> MismatchedParams;
6059 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006060 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00006061 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00006062 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6063 : diag::err_member_decl_does_not_match;
6064 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6065 IsLocalFriend ? Sema::LookupLocalFriendName
6066 : Sema::LookupOrdinaryName,
6067 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006068
6069 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00006070 if (IsLocalFriend)
6071 SemaRef.LookupName(Prev, S);
6072 else
6073 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00006074 assert(!Prev.isAmbiguous() &&
6075 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006076 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006077 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6078 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006079 if (!Prev.empty()) {
6080 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6081 Func != FuncEnd; ++Func) {
6082 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006083 if (FD &&
6084 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006085 // Add 1 to the index so that 0 can mean the mismatch didn't
6086 // involve a parameter
6087 unsigned ParamNum =
6088 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6089 NearMatches.push_back(std::make_pair(FD, ParamNum));
6090 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006091 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006092 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006093 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006094 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6095 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6096 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006097 // Set up everything for the call to ActOnFunctionDeclarator
6098 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6099 ExtraArgs.D.getIdentifierLoc());
6100 Previous.clear();
6101 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006102 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6103 CDeclEnd = Correction.end();
6104 CDecl != CDeclEnd; ++CDecl) {
6105 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006106 if (FD && !FD->hasBody() &&
6107 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006108 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006109 }
6110 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006111 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006112
6113 NamedDecl *Result;
6114 // Retry building the function declaration with the new previous
6115 // declarations, and with errors suppressed.
6116 {
6117 // Trap errors.
6118 Sema::SFINAETrap Trap(SemaRef);
6119
6120 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6121 // pieces need to verify the typo-corrected C++ declaration and hopefully
6122 // eliminate the need for the parameter pack ExtraArgs.
6123 Result = SemaRef.ActOnFunctionDeclarator(
6124 ExtraArgs.S, ExtraArgs.D,
6125 Correction.getCorrectionDecl()->getDeclContext(),
6126 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6127 ExtraArgs.AddToScope);
6128
6129 if (Trap.hasErrorOccurred())
6130 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006131 }
Richard Smith2d670972013-08-17 00:46:16 +00006132
6133 if (Result) {
6134 // Determine which correction we picked.
6135 Decl *Canonical = Result->getCanonicalDecl();
6136 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6137 I != E; ++I)
6138 if ((*I)->getCanonicalDecl() == Canonical)
6139 Correction.setCorrectionDecl(*I);
6140
6141 SemaRef.diagnoseTypo(
6142 Correction,
6143 SemaRef.PDiag(IsLocalFriend
6144 ? diag::err_no_matching_local_friend_suggest
6145 : diag::err_member_decl_does_not_match_suggest)
6146 << Name << NewDC << IsDefinition);
6147 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006148 }
Richard Smith2d670972013-08-17 00:46:16 +00006149
6150 // Pretend the typo correction never occurred
6151 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6152 ExtraArgs.D.getIdentifierLoc());
6153 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6154 Previous.clear();
6155 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006156 }
6157
Richard Smith2d670972013-08-17 00:46:16 +00006158 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6159 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006160
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006161 bool NewFDisConst = false;
6162 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006163 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006164
Craig Topper8bc99dd2013-07-04 03:15:42 +00006165 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006166 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6167 NearMatch != NearMatchEnd; ++NearMatch) {
6168 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006169 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6170 bool FDisConst = MD && MD->isConst();
6171 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006172
Richard Smitha41c97a2013-09-20 01:15:31 +00006173 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006174 if (unsigned Idx = NearMatch->second) {
6175 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006176 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6177 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006178 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6179 : diag::note_local_decl_close_param_match)
6180 << Idx << FDParam->getType()
6181 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006182 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006183 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006184 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006185 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006186 SemaRef.Diag(FD->getLocation(),
6187 IsMember ? diag::note_member_def_close_match
6188 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006189 }
Richard Smith2d670972013-08-17 00:46:16 +00006190 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006191}
6192
David Blaikied662a792011-10-19 22:56:21 +00006193static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6194 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006195 switch (D.getDeclSpec().getStorageClassSpec()) {
6196 default: llvm_unreachable("Unknown storage class!");
6197 case DeclSpec::SCS_auto:
6198 case DeclSpec::SCS_register:
6199 case DeclSpec::SCS_mutable:
6200 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6201 diag::err_typecheck_sclass_func);
6202 D.setInvalidType();
6203 break;
6204 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006205 case DeclSpec::SCS_extern:
6206 if (D.getDeclSpec().isExternInLinkageSpec())
6207 return SC_None;
6208 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006209 case DeclSpec::SCS_static: {
6210 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6211 // C99 6.7.1p5:
6212 // The declaration of an identifier for a function that has
6213 // block scope shall have no explicit storage-class specifier
6214 // other than extern
6215 // See also (C++ [dcl.stc]p4).
6216 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6217 diag::err_static_block_func);
6218 break;
6219 } else
6220 return SC_Static;
6221 }
6222 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6223 }
6224
6225 // No explicit storage class has already been returned
6226 return SC_None;
6227}
6228
6229static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6230 DeclContext *DC, QualType &R,
6231 TypeSourceInfo *TInfo,
6232 FunctionDecl::StorageClass SC,
6233 bool &IsVirtualOkay) {
6234 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6235 DeclarationName Name = NameInfo.getName();
6236
6237 FunctionDecl *NewFD = 0;
6238 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006239
David Blaikie4e4d0842012-03-11 07:00:24 +00006240 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006241 // Determine whether the function was written with a
6242 // prototype. This true when:
6243 // - there is a prototype in the declarator, or
6244 // - the type R of the function is some kind of typedef or other reference
6245 // to a type name (which eventually refers to a function type).
6246 bool HasPrototype =
6247 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6248 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6249
David Blaikied662a792011-10-19 22:56:21 +00006250 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006251 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006252 TInfo, SC, isInline,
6253 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006254 if (D.isInvalidType())
6255 NewFD->setInvalidDecl();
6256
6257 // Set the lexical context.
6258 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6259
6260 return NewFD;
6261 }
6262
6263 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6264 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6265
6266 // Check that the return type is not an abstract class type.
6267 // For record types, this is done by the AbstractClassUsageDiagnoser once
6268 // the class has been completely parsed.
6269 if (!DC->isRecord() &&
6270 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6271 R->getAs<FunctionType>()->getResultType(),
6272 diag::err_abstract_type_in_decl,
6273 SemaRef.AbstractReturnType))
6274 D.setInvalidType();
6275
6276 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6277 // This is a C++ constructor declaration.
6278 assert(DC->isRecord() &&
6279 "Constructors can only be declared in a member context");
6280
6281 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6282 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006283 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006284 R, TInfo, isExplicit, isInline,
6285 /*isImplicitlyDeclared=*/false,
6286 isConstexpr);
6287
6288 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6289 // This is a C++ destructor declaration.
6290 if (DC->isRecord()) {
6291 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6292 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6293 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6294 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006295 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006296 NameInfo, R, TInfo, isInline,
6297 /*isImplicitlyDeclared=*/false);
6298
6299 // If the class is complete, then we now create the implicit exception
6300 // specification. If the class is incomplete or dependent, we can't do
6301 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006302 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006303 Record->getDefinition() && !Record->isBeingDefined() &&
6304 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6305 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6306 }
6307
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006308 // The Microsoft ABI requires that we perform the destructor body
6309 // checks (i.e. operator delete() lookup) at every declaration, as
6310 // any translation unit may need to emit a deleting destructor.
6311 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6312 !Record->isDependentType() && Record->getDefinition() &&
6313 !Record->isBeingDefined()) {
6314 SemaRef.CheckDestructor(NewDD);
6315 }
6316
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006317 IsVirtualOkay = true;
6318 return NewDD;
6319
6320 } else {
6321 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6322 D.setInvalidType();
6323
6324 // Create a FunctionDecl to satisfy the function definition parsing
6325 // code path.
6326 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006327 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006328 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006329 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006330 /*hasPrototype=*/true, isConstexpr);
6331 }
6332
6333 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6334 if (!DC->isRecord()) {
6335 SemaRef.Diag(D.getIdentifierLoc(),
6336 diag::err_conv_function_not_member);
6337 return 0;
6338 }
6339
6340 SemaRef.CheckConversionDeclarator(D, R, SC);
6341 IsVirtualOkay = true;
6342 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006343 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006344 R, TInfo, isInline, isExplicit,
6345 isConstexpr, SourceLocation());
6346
6347 } else if (DC->isRecord()) {
6348 // If the name of the function is the same as the name of the record,
6349 // then this must be an invalid constructor that has a return type.
6350 // (The parser checks for a return type and makes the declarator a
6351 // constructor if it has no return type).
6352 if (Name.getAsIdentifierInfo() &&
6353 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6354 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6355 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6356 << SourceRange(D.getIdentifierLoc());
6357 return 0;
6358 }
6359
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006360 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006361 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6362 cast<CXXRecordDecl>(DC),
6363 D.getLocStart(), NameInfo, R,
6364 TInfo, SC, isInline,
6365 isConstexpr, SourceLocation());
6366 IsVirtualOkay = !Ret->isStatic();
6367 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006368 } else {
6369 // Determine whether the function was written with a
6370 // prototype. This true when:
6371 // - we're in C++ (where every function has a prototype),
6372 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006373 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006374 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006375 true/*HasPrototype*/, isConstexpr);
6376 }
6377}
6378
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006379void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6380 // In C++, the empty parameter-type-list must be spelled "void"; a
6381 // typedef of void is not permitted.
6382 if (getLangOpts().CPlusPlus &&
6383 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6384 bool IsTypeAlias = false;
6385 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6386 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6387 else if (const TemplateSpecializationType *TST =
6388 Param->getType()->getAs<TemplateSpecializationType>())
6389 IsTypeAlias = TST->isTypeAlias();
6390 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6391 << IsTypeAlias;
6392 }
6393}
6394
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006395enum OpenCLParamType {
6396 ValidKernelParam,
6397 PtrPtrKernelParam,
6398 PtrKernelParam,
6399 InvalidKernelParam,
6400 RecordKernelParam
6401};
6402
6403static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6404 if (PT->isPointerType()) {
6405 QualType PointeeType = PT->getPointeeType();
6406 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6407 }
6408
6409 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6410 // be used as builtin types.
6411
6412 if (PT->isImageType())
6413 return PtrKernelParam;
6414
6415 if (PT->isBooleanType())
6416 return InvalidKernelParam;
6417
6418 if (PT->isEventT())
6419 return InvalidKernelParam;
6420
6421 if (PT->isHalfType())
6422 return InvalidKernelParam;
6423
6424 if (PT->isRecordType())
6425 return RecordKernelParam;
6426
6427 return ValidKernelParam;
6428}
6429
6430static void checkIsValidOpenCLKernelParameter(
6431 Sema &S,
6432 Declarator &D,
6433 ParmVarDecl *Param,
6434 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6435 QualType PT = Param->getType();
6436
6437 // Cache the valid types we encounter to avoid rechecking structs that are
6438 // used again
6439 if (ValidTypes.count(PT.getTypePtr()))
6440 return;
6441
6442 switch (getOpenCLKernelParameterType(PT)) {
6443 case PtrPtrKernelParam:
6444 // OpenCL v1.2 s6.9.a:
6445 // A kernel function argument cannot be declared as a
6446 // pointer to a pointer type.
6447 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6448 D.setInvalidType();
6449 return;
6450
6451 // OpenCL v1.2 s6.9.k:
6452 // Arguments to kernel functions in a program cannot be declared with the
6453 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6454 // uintptr_t or a struct and/or union that contain fields declared to be
6455 // one of these built-in scalar types.
6456
6457 case InvalidKernelParam:
6458 // OpenCL v1.2 s6.8 n:
6459 // A kernel function argument cannot be declared
6460 // of event_t type.
6461 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6462 D.setInvalidType();
6463 return;
6464
6465 case PtrKernelParam:
6466 case ValidKernelParam:
6467 ValidTypes.insert(PT.getTypePtr());
6468 return;
6469
6470 case RecordKernelParam:
6471 break;
6472 }
6473
6474 // Track nested structs we will inspect
6475 SmallVector<const Decl *, 4> VisitStack;
6476
6477 // Track where we are in the nested structs. Items will migrate from
6478 // VisitStack to HistoryStack as we do the DFS for bad field.
6479 SmallVector<const FieldDecl *, 4> HistoryStack;
6480 HistoryStack.push_back((const FieldDecl *) 0);
6481
6482 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6483 VisitStack.push_back(PD);
6484
6485 assert(VisitStack.back() && "First decl null?");
6486
6487 do {
6488 const Decl *Next = VisitStack.pop_back_val();
6489 if (!Next) {
6490 assert(!HistoryStack.empty());
6491 // Found a marker, we have gone up a level
6492 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6493 ValidTypes.insert(Hist->getType().getTypePtr());
6494
6495 continue;
6496 }
6497
6498 // Adds everything except the original parameter declaration (which is not a
6499 // field itself) to the history stack.
6500 const RecordDecl *RD;
6501 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6502 HistoryStack.push_back(Field);
6503 RD = Field->getType()->castAs<RecordType>()->getDecl();
6504 } else {
6505 RD = cast<RecordDecl>(Next);
6506 }
6507
6508 // Add a null marker so we know when we've gone back up a level
6509 VisitStack.push_back((const Decl *) 0);
6510
6511 for (RecordDecl::field_iterator I = RD->field_begin(),
6512 E = RD->field_end(); I != E; ++I) {
6513 const FieldDecl *FD = *I;
6514 QualType QT = FD->getType();
6515
6516 if (ValidTypes.count(QT.getTypePtr()))
6517 continue;
6518
6519 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6520 if (ParamType == ValidKernelParam)
6521 continue;
6522
6523 if (ParamType == RecordKernelParam) {
6524 VisitStack.push_back(FD);
6525 continue;
6526 }
6527
6528 // OpenCL v1.2 s6.9.p:
6529 // Arguments to kernel functions that are declared to be a struct or union
6530 // do not allow OpenCL objects to be passed as elements of the struct or
6531 // union.
6532 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6533 S.Diag(Param->getLocation(),
6534 diag::err_record_with_pointers_kernel_param)
6535 << PT->isUnionType()
6536 << PT;
6537 } else {
6538 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6539 }
6540
6541 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6542 << PD->getDeclName();
6543
6544 // We have an error, now let's go back up through history and show where
6545 // the offending field came from
6546 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6547 E = HistoryStack.end(); I != E; ++I) {
6548 const FieldDecl *OuterField = *I;
6549 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6550 << OuterField->getType();
6551 }
6552
6553 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6554 << QT->isPointerType()
6555 << QT;
6556 D.setInvalidType();
6557 return;
6558 }
6559 } while (!VisitStack.empty());
6560}
6561
Mike Stump1eb44332009-09-09 15:08:12 +00006562NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006563Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006564 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006565 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006566 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006567 QualType R = TInfo->getType();
6568
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006569 assert(R.getTypePtr()->isFunctionType());
6570
Abramo Bagnara25777432010-08-11 22:01:17 +00006571 // TODO: consider using NameInfo for diagnostic.
6572 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6573 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006574 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006575
Richard Smithec642442013-04-12 22:46:28 +00006576 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6577 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6578 diag::err_invalid_thread)
6579 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006580
Reid Klecknerd1a32c32013-10-08 00:58:57 +00006581 if (D.isFirstDeclarationOfMember())
6582 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckneref072032013-08-27 23:08:25 +00006583
Douglas Gregor3922ed02010-12-10 19:28:19 +00006584 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006585 FunctionTemplateDecl *FunctionTemplate = 0;
6586 bool isExplicitSpecialization = false;
6587 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006588
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006589 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006590 bool HasExplicitTemplateArgs = false;
6591 TemplateArgumentListInfo TemplateArgs;
6592
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006593 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006594
Richard Smitha41c97a2013-09-20 01:15:31 +00006595 DeclContext *OriginalDC = DC;
6596 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6597
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006598 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6599 isVirtualOkay);
6600 if (!NewFD) return 0;
6601
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006602 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6603 NewFD->setTopLevelDeclInObjCContainer();
6604
Richard Smitha41c97a2013-09-20 01:15:31 +00006605 // Set the lexical context. If this is a function-scope declaration, or has a
6606 // C++ scope specifier, or is the object of a friend declaration, the lexical
6607 // context will be different from the semantic context.
6608 NewFD->setLexicalDeclContext(CurContext);
6609
6610 if (IsLocalExternDecl)
6611 NewFD->setLocalExternDecl();
6612
David Blaikie4e4d0842012-03-11 07:00:24 +00006613 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006614 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006615 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6616 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006617 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006618 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006619 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006620 // C++ [class.friend]p5
6621 // A function can be defined in a friend declaration of a
6622 // class . . . . Such a function is implicitly inline.
6623 NewFD->setImplicitlyInline();
6624 }
6625
John McCalle402e722012-09-25 07:32:39 +00006626 // If this is a method defined in an __interface, and is not a constructor
6627 // or an overloaded operator, then set the pure flag (isVirtual will already
6628 // return true).
6629 if (const CXXRecordDecl *Parent =
6630 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6631 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006632 NewFD->setPure(true);
6633 }
6634
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006635 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006636 isExplicitSpecialization = false;
6637 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006638 if (D.isInvalidType())
6639 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006640
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006641 // Match up the template parameter lists with the scope specifier, then
6642 // determine whether we have a template or a template specialization.
6643 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006644 if (TemplateParameterList *TemplateParams =
6645 MatchTemplateParametersToScopeSpecifier(
6646 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6647 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6648 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006649 if (TemplateParams->size() > 0) {
6650 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006651
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006652 // Check that we can declare a template here.
6653 if (CheckTemplateDeclScope(S, TemplateParams))
6654 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006655
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006656 // A destructor cannot be a template.
6657 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6658 Diag(NewFD->getLocation(), diag::err_destructor_template);
6659 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006660 }
Douglas Gregor20606502011-10-14 15:31:12 +00006661
6662 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006663 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006664 // now that we know what the current instantiation is.
6665 if (DC->isDependentContext()) {
6666 ContextRAII SavedContext(*this, DC);
6667 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6668 Invalid = true;
6669 }
6670
John McCall5fd378b2010-03-24 08:27:58 +00006671
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006672 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6673 NewFD->getLocation(),
6674 Name, TemplateParams,
6675 NewFD);
6676 FunctionTemplate->setLexicalDeclContext(CurContext);
6677 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6678
6679 // For source fidelity, store the other template param lists.
6680 if (TemplateParamLists.size() > 1) {
6681 NewFD->setTemplateParameterListsInfo(Context,
6682 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006683 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006684 }
6685 } else {
6686 // This is a function template specialization.
6687 isFunctionTemplateSpecialization = true;
6688 // For source fidelity, store all the template param lists.
6689 NewFD->setTemplateParameterListsInfo(Context,
6690 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006691 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006692
6693 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6694 if (isFriend) {
6695 // We want to remove the "template<>", found here.
6696 SourceRange RemoveRange = TemplateParams->getSourceRange();
6697
6698 // If we remove the template<> and the name is not a
6699 // template-id, we're actually silently creating a problem:
6700 // the friend declaration will refer to an untemplated decl,
6701 // and clearly the user wants a template specialization. So
6702 // we need to insert '<>' after the name.
6703 SourceLocation InsertLoc;
6704 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6705 InsertLoc = D.getName().getSourceRange().getEnd();
6706 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6707 }
6708
6709 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6710 << Name << RemoveRange
6711 << FixItHint::CreateRemoval(RemoveRange)
6712 << FixItHint::CreateInsertion(InsertLoc, "<>");
6713 }
6714 }
6715 }
6716 else {
6717 // All template param lists were matched against the scope specifier:
6718 // this is NOT (an explicit specialization of) a template.
6719 if (TemplateParamLists.size() > 0)
6720 // For source fidelity, store all the template param lists.
6721 NewFD->setTemplateParameterListsInfo(Context,
6722 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006723 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006724 }
6725
6726 if (Invalid) {
6727 NewFD->setInvalidDecl();
6728 if (FunctionTemplate)
6729 FunctionTemplate->setInvalidDecl();
6730 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006731
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006732 // C++ [dcl.fct.spec]p5:
6733 // The virtual specifier shall only be used in declarations of
6734 // nonstatic class member functions that appear within a
6735 // member-specification of a class declaration; see 10.3.
6736 //
6737 if (isVirtual && !NewFD->isInvalidDecl()) {
6738 if (!isVirtualOkay) {
6739 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6740 diag::err_virtual_non_function);
6741 } else if (!CurContext->isRecord()) {
6742 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006743 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6744 diag::err_virtual_out_of_class)
6745 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6746 } else if (NewFD->getDescribedFunctionTemplate()) {
6747 // C++ [temp.mem]p3:
6748 // A member function template shall not be virtual.
6749 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6750 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006751 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6752 } else {
6753 // Okay: Add virtual to the method.
6754 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006755 }
Richard Smith60e141e2013-05-04 07:00:32 +00006756
6757 if (getLangOpts().CPlusPlus1y &&
6758 NewFD->getResultType()->isUndeducedType())
6759 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006760 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006761
Richard Smith37e849a2013-08-14 20:16:31 +00006762 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6763 NewFD->getResultType()->isUndeducedType()) {
6764 // If the function template is referenced directly (for instance, as a
6765 // member of the current instantiation), pretend it has a dependent type.
6766 // This is not really justified by the standard, but is the only sane
6767 // thing to do.
6768 const FunctionProtoType *FPT =
6769 NewFD->getType()->castAs<FunctionProtoType>();
6770 QualType Result = SubstAutoType(FPT->getResultType(),
6771 Context.DependentTy);
6772 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6773 FPT->getExtProtoInfo()));
6774 }
6775
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006776 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006777 // The inline specifier shall not appear on a block scope function
6778 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006779 if (isInline && !NewFD->isInvalidDecl()) {
6780 if (CurContext->isFunctionOrMethod()) {
6781 // 'inline' is not allowed on block scope function declaration.
6782 Diag(D.getDeclSpec().getInlineSpecLoc(),
6783 diag::err_inline_declaration_block_scope) << Name
6784 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6785 }
6786 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006787
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006788 // C++ [dcl.fct.spec]p6:
6789 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006790 // constructor or conversion function within its class definition;
6791 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006792 if (isExplicit && !NewFD->isInvalidDecl()) {
6793 if (!CurContext->isRecord()) {
6794 // 'explicit' was specified outside of the class.
6795 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6796 diag::err_explicit_out_of_class)
6797 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6798 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6799 !isa<CXXConversionDecl>(NewFD)) {
6800 // 'explicit' was specified on a function that wasn't a constructor
6801 // or conversion function.
6802 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6803 diag::err_explicit_non_ctor_or_conv_function)
6804 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6805 }
6806 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006807
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006808 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006809 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006810 // are implicitly inline.
6811 NewFD->setImplicitlyInline();
6812
Richard Smith21c8fa82013-01-14 05:37:29 +00006813 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006814 // be either constructors or to return a literal type. Therefore,
6815 // destructors cannot be declared constexpr.
6816 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006817 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006818 }
6819
Douglas Gregor8d267c52011-09-09 02:06:17 +00006820 // If __module_private__ was specified, mark the function accordingly.
6821 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006822 if (isFunctionTemplateSpecialization) {
6823 SourceLocation ModulePrivateLoc
6824 = D.getDeclSpec().getModulePrivateSpecLoc();
6825 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6826 << 0
6827 << FixItHint::CreateRemoval(ModulePrivateLoc);
6828 } else {
6829 NewFD->setModulePrivate();
6830 if (FunctionTemplate)
6831 FunctionTemplate->setModulePrivate();
6832 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006833 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006834
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006835 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006836 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006837 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006838 FunctionTemplate->setAccess(AS_public);
6839 }
Richard Smith22050f22013-07-17 23:53:16 +00006840 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006841 NewFD->setAccess(AS_public);
6842 }
6843
Douglas Gregor45fa5602011-11-07 20:56:01 +00006844 // If a function is defined as defaulted or deleted, mark it as such now.
6845 switch (D.getFunctionDefinitionKind()) {
6846 case FDK_Declaration:
6847 case FDK_Definition:
6848 break;
6849
6850 case FDK_Defaulted:
6851 NewFD->setDefaulted();
6852 break;
6853
6854 case FDK_Deleted:
6855 NewFD->setDeletedAsWritten();
6856 break;
6857 }
6858
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006859 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6860 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006861 // C++ [class.mfct]p2:
6862 // A member function may be defined (8.4) in its class definition, in
6863 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006864 NewFD->setImplicitlyInline();
6865 }
6866
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006867 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6868 !CurContext->isRecord()) {
6869 // C++ [class.static]p1:
6870 // A data or function member of a class may be declared static
6871 // in a class definition, in which case it is a static member of
6872 // the class.
6873
6874 // Complain about the 'static' specifier if it's on an out-of-line
6875 // member function definition.
6876 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6877 diag::err_static_out_of_line)
6878 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6879 }
Richard Smith444d3842012-10-20 08:26:51 +00006880
6881 // C++11 [except.spec]p15:
6882 // A deallocation function with no exception-specification is treated
6883 // as if it were specified with noexcept(true).
6884 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6885 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6886 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006887 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006888 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6889 EPI.ExceptionSpecType = EST_BasicNoexcept;
6890 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006891 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006892 }
David Majnemerd2b0cf32013-10-20 05:40:29 +00006893
6894 // C++11 [replacement.functions]p3:
6895 // The program's definitions shall not be specified as inline.
David Majnemer3abf5f62013-10-21 00:25:32 +00006896 //
6897 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
David Majnemerd2b0cf32013-10-20 05:40:29 +00006898 if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6899 Diag(D.getDeclSpec().getInlineSpecLoc(),
6900 diag::err_operator_new_delete_declared_inline)
6901 << NewFD->getDeclName();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006902 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006903
6904 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006905 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006906 isExplicitSpecialization ||
6907 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006908
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006909 // Handle GNU asm-label extension (encoded as an attribute).
6910 if (Expr *E = (Expr*) D.getAsmLabel()) {
6911 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006912 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006913 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6914 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006915 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6916 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6917 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6918 if (I != ExtnameUndeclaredIdentifiers.end()) {
6919 NewFD->addAttr(I->second);
6920 ExtnameUndeclaredIdentifiers.erase(I);
6921 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006922 }
6923
Chris Lattner2dbd2852009-04-25 06:12:16 +00006924 // Copy the parameter declarations from the declarator D to the function
6925 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006926 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006927 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006928 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006929
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006930 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6931 // function that takes no arguments, not a function that takes a
6932 // single void argument.
6933 // We let through "const void" here because Sema::GetTypeForDeclarator
6934 // already checks for that case.
6935 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6936 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006937 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006938 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006939 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006940 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006941 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006942 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006943 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6944 Param->setDeclContext(NewFD);
6945 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006946
6947 if (Param->isInvalidDecl())
6948 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006949 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006950 }
Mike Stump1eb44332009-09-09 15:08:12 +00006951
John McCall183700f2009-09-21 23:43:11 +00006952 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006953 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006954 // following example, we'll need to synthesize (unnamed)
6955 // parameters for use in the declaration.
6956 //
6957 // @code
6958 // typedef void fn(int);
6959 // fn f;
6960 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006961
Chris Lattner1ad9b282009-04-25 06:03:53 +00006962 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006963 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6964 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006965 ParmVarDecl *Param =
6966 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006967 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006968 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006969 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006970 } else {
6971 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6972 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006973 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006974
Chris Lattner2dbd2852009-04-25 06:12:16 +00006975 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006976 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006977
James Molloy16f1f712012-02-29 10:24:19 +00006978 // Find all anonymous symbols defined during the declaration of this function
6979 // and add to NewFD. This lets us track decls such 'enum Y' in:
6980 //
6981 // void f(enum Y {AA} x) {}
6982 //
6983 // which would otherwise incorrectly end up in the translation unit scope.
6984 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6985 DeclsInPrototypeScope.clear();
6986
Richard Smith7586a6e2013-01-30 05:45:05 +00006987 if (D.getDeclSpec().isNoreturnSpecified())
6988 NewFD->addAttr(
6989 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6990 Context));
6991
Richard Smithb03a9df2012-03-13 05:56:40 +00006992 // Functions returning a variably modified type violate C99 6.7.5.2p2
6993 // because all functions have linkage.
6994 if (!NewFD->isInvalidDecl() &&
6995 NewFD->getResultType()->isVariablyModifiedType()) {
6996 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6997 NewFD->setInvalidDecl();
6998 }
6999
Rafael Espindola98ae8342012-05-10 02:50:16 +00007000 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00007001 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00007002
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00007003 QualType RetType = NewFD->getResultType();
7004 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7005 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7006 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7007 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00007008 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00007009 // Attach the attribute to the new decl. Don't apply the attribute if it
7010 // returns an instance of the class (e.g. assignment operators).
7011 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00007012 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
7013 Context));
7014 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00007015 }
7016
David Blaikie4e4d0842012-03-11 07:00:24 +00007017 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007018 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00007019 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00007020 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7021 CheckMain(NewFD, D.getDeclSpec());
7022
David Majnemere9f6f332013-09-16 22:44:20 +00007023 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7024 CheckMSVCRTEntryPoint(NewFD);
7025
David Majnemerc371db62013-07-06 02:13:46 +00007026 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00007027 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7028 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00007029 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00007030 // Make graceful recovery from an invalid redeclaration.
7031 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007032 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007033 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7034 "previous declaration set still overloaded");
7035 } else {
7036 // If the declarator is a template-id, translate the parser's template
7037 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007038 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7039 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7040 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7041 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007042 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007043 TemplateId->NumArgs);
7044 translateTemplateArguments(TemplateArgsPtr,
7045 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007046
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007047 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007048
Douglas Gregor89b9f102011-06-06 15:22:55 +00007049 if (NewFD->isInvalidDecl()) {
7050 HasExplicitTemplateArgs = false;
7051 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007052 // Function template with explicit template arguments.
7053 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7054 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7055
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007056 HasExplicitTemplateArgs = false;
7057 } else if (!isFunctionTemplateSpecialization &&
7058 !D.getDeclSpec().isFriendSpecified()) {
7059 // We have encountered something that the user meant to be a
7060 // specialization (because it has explicitly-specified template
7061 // arguments) but that was not introduced with a "template<>" (or had
7062 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007063 // FIXME: Differentiate between attempts for explicit instantiations
7064 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007065 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7066 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7067 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007068 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007069 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007070 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007071 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007072 // "friend void foo<>(int);" is an implicit specialization decl.
7073 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007074 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007075 } else if (isFriend && isFunctionTemplateSpecialization) {
7076 // This combination is only possible in a recovery case; the user
7077 // wrote something like:
7078 // template <> friend void foo(int);
7079 // which we're recovering from as if the user had written:
7080 // friend void foo<>(int);
7081 // Go ahead and fake up a template id.
7082 HasExplicitTemplateArgs = true;
7083 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7084 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007085 }
John McCall29ae6e52010-10-13 05:45:15 +00007086
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007087 // If it's a friend (and only if it's a friend), it's possible
7088 // that either the specialized function type or the specialized
7089 // template is dependent, and therefore matching will fail. In
7090 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007091 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007092 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007093 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7094 TemplateSpecializationType::anyDependentTemplateArguments(
7095 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7096 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007097 assert(HasExplicitTemplateArgs &&
7098 "friend function specialization without template args");
7099 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7100 Previous))
7101 NewFD->setInvalidDecl();
7102 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007103 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007104 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007105 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007106 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007107 diag::ext_function_specialization_in_class :
7108 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007109 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007110 } else if (CheckFunctionTemplateSpecialization(NewFD,
7111 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7112 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007113 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007114
7115 // C++ [dcl.stc]p1:
7116 // A storage-class-specifier shall not be specified in an explicit
7117 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007118 FunctionTemplateSpecializationInfo *Info =
7119 NewFD->getTemplateSpecializationInfo();
7120 if (Info && SC != SC_None) {
7121 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007122 Diag(NewFD->getLocation(),
7123 diag::err_explicit_specialization_inconsistent_storage_class)
7124 << SC
7125 << FixItHint::CreateRemoval(
7126 D.getDeclSpec().getStorageClassSpecLoc());
7127
7128 else
7129 Diag(NewFD->getLocation(),
7130 diag::ext_explicit_specialization_storage_class)
7131 << FixItHint::CreateRemoval(
7132 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007133 }
7134
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007135 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7136 if (CheckMemberSpecialization(NewFD, Previous))
7137 NewFD->setInvalidDecl();
7138 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007139
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007140 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007141 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007142 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7143 CheckMain(NewFD, D.getDeclSpec());
7144
David Majnemere9f6f332013-09-16 22:44:20 +00007145 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7146 CheckMSVCRTEntryPoint(NewFD);
7147
David Blaikie14068e82011-09-08 06:33:04 +00007148 if (NewFD->isInvalidDecl()) {
7149 // If this is a class member, mark the class invalid immediately.
7150 // This avoids some consistency errors later.
7151 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7152 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007153 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007154 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7155 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007156 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007157
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007158 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007159 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7160 "previous declaration set still overloaded");
7161
7162 NamedDecl *PrincipalDecl = (FunctionTemplate
7163 ? cast<NamedDecl>(FunctionTemplate)
7164 : NewFD);
7165
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007166 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007167 AccessSpecifier Access = AS_public;
7168 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007169 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007170
7171 NewFD->setAccess(Access);
7172 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007173 }
7174
7175 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7176 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7177 PrincipalDecl->setNonMemberOperator();
7178
7179 // If we have a function template, check the template parameter
7180 // list. This will check and merge default template arguments.
7181 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007182 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007183 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007184 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007185 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007186 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007187 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007188 ? TPC_FriendFunctionTemplateDefinition
7189 : TPC_FriendFunctionTemplate)
7190 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007191 DC && DC->isRecord() &&
7192 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007193 ? TPC_ClassTemplateMember
7194 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007195 }
7196
7197 if (NewFD->isInvalidDecl()) {
7198 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007199 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007200 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007201 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007202 // Fake up an access specifier if it's supposed to be a class member.
7203 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7204 NewFD->setAccess(AS_public);
7205
7206 // Qualified decls generally require a previous declaration.
7207 if (D.getCXXScopeSpec().isSet()) {
7208 // ...with the major exception of templated-scope or
7209 // dependent-scope friend declarations.
7210
7211 // TODO: we currently also suppress this check in dependent
7212 // contexts because (1) the parameter depth will be off when
7213 // matching friend templates and (2) we might actually be
7214 // selecting a friend based on a dependent factor. But there
7215 // are situations where these conditions don't apply and we
7216 // can actually do this check immediately.
7217 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007218 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007219 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7220 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007221 // ignore these
7222 } else {
7223 // The user tried to provide an out-of-line definition for a
7224 // function that is a member of a class or namespace, but there
7225 // was no such member function declared (C++ [class.mfct]p2,
7226 // C++ [namespace.memdef]p2). For example:
7227 //
7228 // class X {
7229 // void f() const;
7230 // };
7231 //
7232 // void X::f() { } // ill-formed
7233 //
7234 // Complain about this problem, and attempt to suggest close
7235 // matches (e.g., those that differ only in cv-qualifiers and
7236 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007237
Richard Smith4e9686b2013-08-09 04:35:01 +00007238 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7239 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007240 AddToScope = ExtraArgs.AddToScope;
7241 return Result;
7242 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007243 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007244
7245 // Unqualified local friend declarations are required to resolve
7246 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007247 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007248 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7249 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007250 AddToScope = ExtraArgs.AddToScope;
7251 return Result;
7252 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007253 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007254
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007255 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007256 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007257 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007258 // An out-of-line member function declaration must also be a
7259 // definition (C++ [dcl.meaning]p1).
7260 // Note that this is not the case for explicit specializations of
7261 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007262 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7263 // extension for compatibility with old SWIG code which likes to
7264 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007265 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7266 << D.getCXXScopeSpec().getRange();
7267 }
7268 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007269
Rafael Espindola65611bf2013-03-02 21:41:48 +00007270 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007271 checkAttributesAfterMerging(*this, *NewFD);
7272
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007273 AddKnownFunctionAttributes(NewFD);
7274
Douglas Gregord9455382010-08-06 13:50:58 +00007275 if (NewFD->hasAttr<OverloadableAttr>() &&
7276 !NewFD->getType()->getAs<FunctionProtoType>()) {
7277 Diag(NewFD->getLocation(),
7278 diag::err_attribute_overloadable_no_prototype)
7279 << NewFD;
7280
7281 // Turn this into a variadic function with no parameters.
7282 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007283 FunctionProtoType::ExtProtoInfo EPI(
7284 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007285 EPI.Variadic = true;
7286 EPI.ExtInfo = FT->getExtInfo();
7287
Dmitri Gribenko55431692013-05-05 00:41:58 +00007288 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007289 NewFD->setType(R);
7290 }
7291
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007292 // If there's a #pragma GCC visibility in scope, and this isn't a class
7293 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007294 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007295 AddPushedVisibilityAttribute(NewFD);
7296
John McCall8dfac0b2011-09-30 05:12:12 +00007297 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7298 // marking the function.
7299 AddCFAuditedAttribute(NewFD);
7300
Richard Smithaa4bc182013-06-30 09:48:50 +00007301 // If this is the first declaration of an extern C variable, update
7302 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007303 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007304 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007305 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007306
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007307 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007308 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007309
David Blaikie4e4d0842012-03-11 07:00:24 +00007310 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007311 if (FunctionTemplate) {
7312 if (NewFD->isInvalidDecl())
7313 FunctionTemplate->setInvalidDecl();
7314 return FunctionTemplate;
7315 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007316 }
Mike Stump1eb44332009-09-09 15:08:12 +00007317
Guy Benyeie6b9d802013-01-20 12:31:11 +00007318 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007319 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7320 if ((getLangOpts().OpenCLVersion >= 120)
7321 && (SC == SC_Static)) {
7322 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7323 D.setInvalidType();
7324 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007325
7326 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7327 if (!NewFD->getResultType()->isVoidType()) {
7328 Diag(D.getIdentifierLoc(),
7329 diag::err_expected_kernel_void_return_type);
7330 D.setInvalidType();
7331 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007332
7333 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007334 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7335 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007336 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007337 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007338 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007339 }
7340
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007341 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007342
David Blaikie4e4d0842012-03-11 07:00:24 +00007343 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007344 if (IdentifierInfo *II = NewFD->getIdentifier())
7345 if (!NewFD->isInvalidDecl() &&
7346 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7347 if (II->isStr("cudaConfigureCall")) {
7348 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7349 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7350
7351 Context.setcudaConfigureCallDecl(NewFD);
7352 }
7353 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007354
7355 // Here we have an function template explicit specialization at class scope.
7356 // The actually specialization will be postponed to template instatiation
7357 // time via the ClassScopeFunctionSpecializationDecl node.
7358 if (isDependentClassScopeExplicitSpecialization) {
7359 ClassScopeFunctionSpecializationDecl *NewSpec =
7360 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007361 Context, CurContext, SourceLocation(),
7362 cast<CXXMethodDecl>(NewFD),
7363 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007364 CurContext->addDecl(NewSpec);
7365 AddToScope = false;
7366 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007367
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007368 return NewFD;
7369}
7370
7371/// \brief Perform semantic checking of a new function declaration.
7372///
7373/// Performs semantic analysis of the new function declaration
7374/// NewFD. This routine performs all semantic checking that does not
7375/// require the actual declarator involved in the declaration, and is
7376/// used both for the declaration of functions as they are parsed
7377/// (called via ActOnDeclarator) and for the declaration of functions
7378/// that have been instantiated via C++ template instantiation (called
7379/// via InstantiateDecl).
7380///
James Dennettefce31f2012-06-22 08:10:18 +00007381/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007382/// an explicit specialization of the previous declaration.
7383///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007384/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007385///
James Dennettefce31f2012-06-22 08:10:18 +00007386/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007387bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007388 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007389 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007390 assert(!NewFD->getResultType()->isVariablyModifiedType()
7391 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007392
Richard Smithdd9459f2013-08-13 18:18:50 +00007393 // Determine whether the type of this function should be merged with
7394 // a previous visible declaration. This never happens for functions in C++,
7395 // and always happens in C if the previous declaration was visible.
7396 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7397 !Previous.isShadowed();
7398
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007399 // Filter out any non-conflicting previous declarations.
7400 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7401
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007402 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007403 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007404
Douglas Gregor04495c82009-02-24 01:23:02 +00007405 // Merge or overload the declaration with an existing declaration of
7406 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007407 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007408 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007409 // a declaration that requires merging. If it's an overload,
7410 // there's no more work to do here; we'll just add the new
7411 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007412 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007413 NamedDecl *Candidate = Previous.getFoundDecl();
7414 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7415 Redeclaration = true;
7416 OldDecl = Candidate;
7417 }
John McCall871b2e72009-12-09 03:35:25 +00007418 } else {
John McCallad00b772010-06-16 08:42:20 +00007419 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7420 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007421 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007422 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007423 break;
7424
7425 case Ovl_NonFunction:
7426 Redeclaration = true;
7427 break;
7428
7429 case Ovl_Overload:
7430 Redeclaration = false;
7431 break;
John McCall68263142009-11-18 22:49:29 +00007432 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007433
David Blaikie4e4d0842012-03-11 07:00:24 +00007434 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007435 // If a function name is overloadable in C, then every function
7436 // with that name must be marked "overloadable".
7437 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7438 << Redeclaration << NewFD;
7439 NamedDecl *OverloadedDecl = 0;
7440 if (Redeclaration)
7441 OverloadedDecl = OldDecl;
7442 else if (!Previous.empty())
7443 OverloadedDecl = Previous.getRepresentativeDecl();
7444 if (OverloadedDecl)
7445 Diag(OverloadedDecl->getLocation(),
7446 diag::note_attribute_overloadable_prev_overload);
7447 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7448 Context));
7449 }
John McCall68263142009-11-18 22:49:29 +00007450 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007451 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007452
Richard Smithaa4bc182013-06-30 09:48:50 +00007453 // Check for a previous extern "C" declaration with this name.
7454 if (!Redeclaration &&
7455 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7456 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7457 if (!Previous.empty()) {
7458 // This is an extern "C" declaration with the same name as a previous
7459 // declaration, and thus redeclares that entity...
7460 Redeclaration = true;
7461 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007462 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007463
7464 // ... except in the presence of __attribute__((overloadable)).
7465 if (OldDecl->hasAttr<OverloadableAttr>()) {
7466 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7467 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7468 << Redeclaration << NewFD;
7469 Diag(Previous.getFoundDecl()->getLocation(),
7470 diag::note_attribute_overloadable_prev_overload);
7471 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7472 Context));
7473 }
7474 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7475 Redeclaration = false;
7476 OldDecl = 0;
7477 }
7478 }
7479 }
7480 }
7481
Richard Smith21c8fa82013-01-14 05:37:29 +00007482 // C++11 [dcl.constexpr]p8:
7483 // A constexpr specifier for a non-static member function that is not
7484 // a constructor declares that member function to be const.
7485 //
7486 // This needs to be delayed until we know whether this is an out-of-line
7487 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007488 //
7489 // This rule is not present in C++1y, so we produce a backwards
7490 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007491 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007492 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7493 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007494 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7495 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7496 if (FunctionTemplateDecl *OldTD =
7497 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7498 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7499 if (!OldMD || !OldMD->isStatic()) {
7500 const FunctionProtoType *FPT =
7501 MD->getType()->castAs<FunctionProtoType>();
7502 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7503 EPI.TypeQuals |= Qualifiers::Const;
7504 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007505 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007506
7507 // Warn that we did this, if we're not performing template instantiation.
7508 // In that case, we'll have warned already when the template was defined.
7509 if (ActiveTemplateInstantiations.empty()) {
7510 SourceLocation AddConstLoc;
7511 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7512 .IgnoreParens().getAs<FunctionTypeLoc>())
7513 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7514
7515 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7516 << FixItHint::CreateInsertion(AddConstLoc, " const");
7517 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007518 }
7519 }
7520
7521 if (Redeclaration) {
7522 // NewFD and OldDecl represent declarations that need to be
7523 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007524 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007525 NewFD->setInvalidDecl();
7526 return Redeclaration;
7527 }
7528
7529 Previous.clear();
7530 Previous.addDecl(OldDecl);
7531
7532 if (FunctionTemplateDecl *OldTemplateDecl
7533 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7534 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7535 FunctionTemplateDecl *NewTemplateDecl
7536 = NewFD->getDescribedFunctionTemplate();
7537 assert(NewTemplateDecl && "Template/non-template mismatch");
7538 if (CXXMethodDecl *Method
7539 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7540 Method->setAccess(OldTemplateDecl->getAccess());
7541 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007542 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007543
7544 // If this is an explicit specialization of a member that is a function
7545 // template, mark it as a member specialization.
7546 if (IsExplicitSpecialization &&
7547 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7548 NewTemplateDecl->setMemberSpecialization();
7549 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007550 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007551
7552 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007553 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007554 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007555
7556 if (isa<CXXMethodDecl>(NewFD)) {
7557 // A valid redeclaration of a C++ method must be out-of-line,
7558 // but (unfortunately) it's not necessarily a definition
7559 // because of templates, which means that the previous
7560 // declaration is not necessarily from the class definition.
7561
7562 // For just setting the access, that doesn't matter.
7563 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7564 NewFD->setAccess(oldMethod->getAccess());
7565
7566 // Update the key-function state if necessary for this ABI.
7567 if (NewFD->isInlined() &&
7568 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7569 // setNonKeyFunction needs to work with the original
7570 // declaration from the class definition, and isVirtual() is
7571 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007572 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007573 if (oldMethod->isVirtual()) {
7574 Context.setNonKeyFunction(oldMethod);
7575 }
7576 }
7577 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007578 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007579 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007580
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007581 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007582 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007583 // C++-specific checks.
7584 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7585 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007586 } else if (CXXDestructorDecl *Destructor =
7587 dyn_cast<CXXDestructorDecl>(NewFD)) {
7588 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007589 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007590
Douglas Gregor4923aa22010-07-02 20:37:36 +00007591 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007592 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007593 if (!ClassType->isDependentType()) {
7594 DeclarationName Name
7595 = Context.DeclarationNames.getCXXDestructorName(
7596 Context.getCanonicalType(ClassType));
7597 if (NewFD->getDeclName() != Name) {
7598 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007599 NewFD->setInvalidDecl();
7600 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007601 }
7602 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007603 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007604 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007605 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007606 }
7607
7608 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7610 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007611 !Method->getDescribedFunctionTemplate() &&
7612 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007613 if (AddOverriddenMethods(Method->getParent(), Method)) {
7614 // If the function was marked as "static", we have a problem.
7615 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007616 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007617 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007618 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007619 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007620
7621 if (Method->isStatic())
7622 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007623 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007624
7625 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7626 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007627 CheckOverloadedOperatorDeclaration(NewFD)) {
7628 NewFD->setInvalidDecl();
7629 return Redeclaration;
7630 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007631
7632 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7633 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007634 CheckLiteralOperatorDeclaration(NewFD)) {
7635 NewFD->setInvalidDecl();
7636 return Redeclaration;
7637 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007638
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007639 // In C++, check default arguments now that we have merged decls. Unless
7640 // the lexical context is the class, because in this case this is done
7641 // during delayed parsing anyway.
7642 if (!CurContext->isRecord())
7643 CheckCXXDefaultArguments(NewFD);
Warren Hunt2d023ec2013-11-01 23:46:51 +00007644
Douglas Gregorb68e3992010-12-21 19:47:46 +00007645 // If this function declares a builtin function, check the type of this
7646 // declaration against the expected type for the builtin.
7647 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7648 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007649 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007650 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7651 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7652 // The type of this function differs from the type of the builtin,
7653 // so forget about the builtin entirely.
7654 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7655 }
7656 }
Warren Hunt2d023ec2013-11-01 23:46:51 +00007657
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007658 // If this function is declared as being extern "C", then check to see if
7659 // the function returns a UDT (class, struct, or union type) that is not C
7660 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007661 // But, issue any diagnostic on the first declaration only.
7662 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007663 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007664 if (R->isIncompleteType() && !R->isVoidType())
7665 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7666 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007667 else if (!R.isPODType(Context) && !R->isVoidType() &&
7668 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007669 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007670 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007671 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007672 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007673}
7674
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007675static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7676 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7677 if (!TSI)
7678 return SourceRange();
7679
7680 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007681 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007682 if (!FunctionTL)
7683 return SourceRange();
7684
David Blaikie39e6ab42013-02-18 22:06:02 +00007685 TypeLoc ResultTL = FunctionTL.getResultLoc();
7686 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007687 return ResultTL.getSourceRange();
7688
7689 return SourceRange();
7690}
7691
David Blaikie14068e82011-09-08 06:33:04 +00007692void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007693 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7694 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007695 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7696 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007697 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007698 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007699 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007700 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007701 ? diag::err_static_main : diag::warn_static_main)
7702 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7703 if (FD->isInlineSpecified())
7704 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7705 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007706 if (DS.isNoreturnSpecified()) {
7707 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7708 SourceRange NoreturnRange(NoreturnLoc,
7709 PP.getLocForEndOfToken(NoreturnLoc));
7710 Diag(NoreturnLoc, diag::ext_noreturn_main);
7711 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7712 << FixItHint::CreateRemoval(NoreturnRange);
7713 }
Richard Smitha5065862012-02-04 06:10:17 +00007714 if (FD->isConstexpr()) {
7715 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7716 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7717 FD->setConstexpr(false);
7718 }
John McCall13591ed2009-07-25 04:36:53 +00007719
Joey Goulyc879fe52013-11-05 12:30:39 +00007720 if (getLangOpts().OpenCL) {
7721 Diag(FD->getLocation(), diag::err_opencl_no_main)
7722 << FD->hasAttr<OpenCLKernelAttr>();
7723 FD->setInvalidDecl();
7724 return;
7725 }
7726
John McCall13591ed2009-07-25 04:36:53 +00007727 QualType T = FD->getType();
7728 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007729 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007730
John McCall75d8ba32012-02-14 19:50:52 +00007731 // All the standards say that main() should should return 'int'.
7732 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7733 // In C and C++, main magically returns 0 if you fall off the end;
7734 // set the flag which tells us that.
7735 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7736 FD->setHasImplicitReturnZero(true);
7737
7738 // In C with GNU extensions we allow main() to have non-integer return
7739 // type, but we should warn about the extension, and we disable the
7740 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007741 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007742 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7743
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007744 SourceRange ResultRange = getResultSourceRange(FD);
7745 if (ResultRange.isValid())
7746 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7747 << FixItHint::CreateReplacement(ResultRange, "int");
7748
John McCall75d8ba32012-02-14 19:50:52 +00007749 // Otherwise, this is just a flat-out error.
7750 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007751 SourceRange ResultRange = getResultSourceRange(FD);
7752 if (ResultRange.isValid())
7753 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7754 << FixItHint::CreateReplacement(ResultRange, "int");
7755 else
7756 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7757
John McCall13591ed2009-07-25 04:36:53 +00007758 FD->setInvalidDecl(true);
7759 }
7760
7761 // Treat protoless main() as nullary.
7762 if (isa<FunctionNoProtoType>(FT)) return;
7763
7764 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7765 unsigned nparams = FTP->getNumArgs();
7766 assert(FD->getNumParams() == nparams);
7767
John McCall66755862009-12-24 09:58:38 +00007768 bool HasExtraParameters = (nparams > 3);
7769
7770 // Darwin passes an undocumented fourth argument of type char**. If
7771 // other platforms start sprouting these, the logic below will start
7772 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007773 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007774 HasExtraParameters = false;
7775
7776 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007777 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7778 FD->setInvalidDecl(true);
7779 nparams = 3;
7780 }
7781
7782 // FIXME: a lot of the following diagnostics would be improved
7783 // if we had some location information about types.
7784
7785 QualType CharPP =
7786 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007787 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007788
7789 for (unsigned i = 0; i < nparams; ++i) {
7790 QualType AT = FTP->getArgType(i);
7791
7792 bool mismatch = true;
7793
7794 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7795 mismatch = false;
7796 else if (Expected[i] == CharPP) {
7797 // As an extension, the following forms are okay:
7798 // char const **
7799 // char const * const *
7800 // char * const *
7801
John McCall0953e762009-09-24 19:53:00 +00007802 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007803 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007804 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7805 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007806 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7807 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007808 qs.removeConst();
7809 mismatch = !qs.empty();
7810 }
7811 }
7812
7813 if (mismatch) {
7814 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7815 // TODO: suggest replacing given type with expected type
7816 FD->setInvalidDecl(true);
7817 }
7818 }
7819
7820 if (nparams == 1 && !FD->isInvalidDecl()) {
7821 Diag(FD->getLocation(), diag::warn_main_one_arg);
7822 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007823
7824 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007825 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7826 FD->setInvalidDecl();
7827 }
7828}
7829
7830void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7831 QualType T = FD->getType();
7832 assert(T->isFunctionType() && "function decl is not of function type");
7833 const FunctionType *FT = T->castAs<FunctionType>();
7834
7835 // Set an implicit return of 'zero' if the function can return some integral,
7836 // enumeration, pointer or nullptr type.
7837 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7838 FT->getResultType()->isAnyPointerType() ||
7839 FT->getResultType()->isNullPtrType())
7840 // DllMain is exempt because a return value of zero means it failed.
7841 if (FD->getName() != "DllMain")
7842 FD->setHasImplicitReturnZero(true);
7843
7844 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7845 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007846 FD->setInvalidDecl();
7847 }
John McCall8c4859a2009-07-24 03:03:21 +00007848}
7849
Eli Friedmanc594b322008-05-20 13:48:25 +00007850bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007851 // FIXME: Need strict checking. In C89, we need to check for
7852 // any assignment, increment, decrement, function-calls, or
7853 // commas outside of a sizeof. In C99, it's the same list,
7854 // except that the aforementioned are allowed in unevaluated
7855 // expressions. Everything else falls under the
7856 // "may accept other forms of constant expressions" exception.
7857 // (We never end up here for C++, so the constant expression
7858 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007859 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007860 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007861 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7862 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007863 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007864}
7865
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007866namespace {
7867 // Visits an initialization expression to see if OrigDecl is evaluated in
7868 // its own initialization and throws a warning if it does.
7869 class SelfReferenceChecker
7870 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7871 Sema &S;
7872 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007873 bool isRecordType;
7874 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007875 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007876
7877 public:
7878 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7879
7880 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007881 S(S), OrigDecl(OrigDecl) {
7882 isPODType = false;
7883 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007884 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007885 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7886 isPODType = VD->getType().isPODType(S.Context);
7887 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007888 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007889 }
7890 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007891
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007892 // For most expressions, the cast is directly above the DeclRefExpr.
7893 // For conditional operators, the cast can be outside the conditional
7894 // operator if both expressions are DeclRefExpr's.
7895 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007896 if (isReferenceType)
7897 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007898 E = E->IgnoreParenImpCasts();
7899 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7900 HandleDeclRefExpr(DRE);
7901 return;
7902 }
7903
7904 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7905 HandleValue(CO->getTrueExpr());
7906 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007907 return;
7908 }
7909
7910 if (isa<MemberExpr>(E)) {
7911 Expr *Base = E->IgnoreParenImpCasts();
7912 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7913 // Check for static member variables and don't warn on them.
7914 if (!isa<FieldDecl>(ME->getMemberDecl()))
7915 return;
7916 Base = ME->getBase()->IgnoreParenImpCasts();
7917 }
7918 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7919 HandleDeclRefExpr(DRE);
7920 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007921 }
7922 }
7923
Richard Trieu568f7852012-10-01 17:39:51 +00007924 // Reference types are handled here since all uses of references are
7925 // bad, not just r-value uses.
7926 void VisitDeclRefExpr(DeclRefExpr *E) {
7927 if (isReferenceType)
7928 HandleDeclRefExpr(E);
7929 }
7930
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007931 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007932 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007933 (isRecordType && E->getCastKind() == CK_NoOp))
7934 HandleValue(E->getSubExpr());
7935
7936 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007937 }
7938
Richard Trieu898267f2011-09-01 21:44:13 +00007939 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007940 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007941 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007942
Richard Trieu6b2cc422012-10-03 00:41:36 +00007943 // Warn when a non-static method call is followed by non-static member
7944 // field accesses, which is followed by a DeclRefExpr.
7945 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7946 bool Warn = (MD && !MD->isStatic());
7947 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7948 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7949 if (!isa<FieldDecl>(ME->getMemberDecl()))
7950 Warn = false;
7951 Base = ME->getBase()->IgnoreParenImpCasts();
7952 }
Richard Trieu898267f2011-09-01 21:44:13 +00007953
Richard Trieu6b2cc422012-10-03 00:41:36 +00007954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7955 if (Warn)
7956 HandleDeclRefExpr(DRE);
7957 return;
7958 }
7959
7960 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7961 // Visit that expression.
7962 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007963 }
7964
Richard Trieu8af742a2013-03-26 03:41:40 +00007965 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7966 if (E->getNumArgs() > 0)
7967 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7968 HandleDeclRefExpr(DRE);
7969
7970 Inherited::VisitCXXOperatorCallExpr(E);
7971 }
7972
Richard Trieu898267f2011-09-01 21:44:13 +00007973 void VisitUnaryOperator(UnaryOperator *E) {
7974 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007975 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7976 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7977 if (!isPODType)
7978 HandleValue(E->getSubExpr());
7979 return;
7980 }
Richard Trieu898267f2011-09-01 21:44:13 +00007981 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007982 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007983
7984 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7985
Richard Trieu898267f2011-09-01 21:44:13 +00007986 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007987 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007988 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007989 unsigned diag;
7990 if (isReferenceType) {
7991 diag = diag::warn_uninit_self_reference_in_reference_init;
7992 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7993 diag = diag::warn_static_self_reference_in_init;
7994 } else {
7995 diag = diag::warn_uninit_self_reference_in_init;
7996 }
7997
Richard Trieu898267f2011-09-01 21:44:13 +00007998 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007999 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00008000 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00008001 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00008002 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00008003 }
8004 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00008005
Richard Trieu568f7852012-10-01 17:39:51 +00008006 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8007 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8008 bool DirectInit) {
8009 // Parameters arguments are occassionially constructed with itself,
8010 // for instance, in recursive functions. Skip them.
8011 if (isa<ParmVarDecl>(OrigDecl))
8012 return;
8013
8014 E = E->IgnoreParens();
8015
8016 // Skip checking T a = a where T is not a record or reference type.
8017 // Doing so is a way to silence uninitialized warnings.
8018 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8019 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8020 if (ICE->getCastKind() == CK_LValueToRValue)
8021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8022 if (DRE->getDecl() == OrigDecl)
8023 return;
8024
8025 SelfReferenceChecker(S, OrigDecl).Visit(E);
8026 }
Richard Trieu898267f2011-09-01 21:44:13 +00008027}
8028
Douglas Gregor09f41cf2009-01-14 15:45:31 +00008029/// AddInitializerToDecl - Adds the initializer Init to the
8030/// declaration dcl. If DirectInit is true, this is C++ direct
8031/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00008032void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8033 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008034 // If there is no declaration, there was an error parsing it. Just ignore
8035 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00008036 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008037 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008038
Douglas Gregor021c3b32009-03-11 23:00:04 +00008039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8040 // With declarators parsed the way they are, the parser cannot
8041 // distinguish between a normal initializer and a pure-specifier.
8042 // Thus this grotesque test.
8043 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008044 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008045 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8046 CheckPureMethod(Method, Init->getSourceRange());
8047 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008048 Diag(Method->getLocation(), diag::err_member_function_initialization)
8049 << Method->getDeclName() << Init->getSourceRange();
8050 Method->setInvalidDecl();
8051 }
8052 return;
8053 }
8054
Steve Naroff410e3e22007-09-12 20:13:48 +00008055 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8056 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008057 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8058 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008059 RealDecl->setInvalidDecl();
8060 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008061 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008062 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8063
Richard Smith01888722011-12-15 19:20:59 +00008064 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008065 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008066 Expr *DeduceInit = Init;
8067 // Initializer could be a C++ direct-initializer. Deduction only works if it
8068 // contains exactly one expression.
8069 if (CXXDirectInit) {
8070 if (CXXDirectInit->getNumExprs() == 0) {
8071 // It isn't possible to write this directly, but it is possible to
8072 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008073 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008074 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8075 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008076 << VDecl->getDeclName() << VDecl->getType()
8077 << VDecl->getSourceRange();
8078 RealDecl->setInvalidDecl();
8079 return;
8080 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008081 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008082 VDecl->isInitCapture()
8083 ? diag::err_init_capture_multiple_expressions
8084 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008085 << VDecl->getDeclName() << VDecl->getType()
8086 << VDecl->getSourceRange();
8087 RealDecl->setInvalidDecl();
8088 return;
8089 } else {
8090 DeduceInit = CXXDirectInit->getExpr(0);
8091 }
8092 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008093
8094 // Expressions default to 'id' when we're in a debugger.
8095 bool DefaultedToAuto = false;
8096 if (getLangOpts().DebuggerCastResultToId &&
8097 Init->getType() == Context.UnknownAnyTy) {
8098 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8099 if (Result.isInvalid()) {
8100 VDecl->setInvalidDecl();
8101 return;
8102 }
8103 Init = Result.take();
8104 DefaultedToAuto = true;
8105 }
Richard Smith9b131752013-04-30 21:23:01 +00008106
8107 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008108 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008109 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008110 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008111 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008112 RealDecl->setInvalidDecl();
8113 return;
8114 }
Richard Smith9b131752013-04-30 21:23:01 +00008115 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008116 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008117
John McCallf85e1932011-06-15 23:02:42 +00008118 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008119 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008120 VDecl->setInvalidDecl();
8121
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008122 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8123 // 'id' instead of a specific object type prevents most of our usual checks.
8124 // We only want to warn outside of template instantiations, though:
8125 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008126 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008127 DeducedType->isObjCIdType()) {
8128 SourceLocation Loc =
8129 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008130 Diag(Loc, diag::warn_auto_var_is_id)
8131 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8132 }
8133
Richard Smith34b41d92011-02-20 03:19:35 +00008134 // If this is a redeclaration, check that the type we just deduced matches
8135 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008136 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8137 // We never need to merge the type, because we cannot form an incomplete
8138 // array of auto, nor deduce such a type.
8139 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8140 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008141
8142 // Check the deduced type is valid for a variable declaration.
8143 CheckVariableDeclarationType(VDecl);
8144 if (VDecl->isInvalidDecl())
8145 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008146 }
Richard Smith01888722011-12-15 19:20:59 +00008147
8148 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8149 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8150 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8151 VDecl->setInvalidDecl();
8152 return;
8153 }
8154
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008155 if (!VDecl->getType()->isDependentType()) {
8156 // A definition must end up with a complete type, which means it must be
8157 // complete with the restriction that an array type might be completed by
8158 // the initializer; note that later code assumes this restriction.
8159 QualType BaseDeclType = VDecl->getType();
8160 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8161 BaseDeclType = Array->getElementType();
8162 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8163 diag::err_typecheck_decl_incomplete_type)) {
8164 RealDecl->setInvalidDecl();
8165 return;
8166 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008167
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008168 // The variable can not have an abstract class type.
8169 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8170 diag::err_abstract_type_in_decl,
8171 AbstractVariableType))
8172 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008173 }
8174
Sebastian Redl31310a22010-02-01 20:16:42 +00008175 const VarDecl *Def;
8176 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008177 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008178 << VDecl->getDeclName();
8179 Diag(Def->getLocation(), diag::note_previous_definition);
8180 VDecl->setInvalidDecl();
8181 return;
8182 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008183
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008184 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008185 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008186 // C++ [class.static.data]p4
8187 // If a static data member is of const integral or const
8188 // enumeration type, its declaration in the class definition can
8189 // specify a constant-initializer which shall be an integral
8190 // constant expression (5.19). In that case, the member can appear
8191 // in integral constant expressions. The member shall still be
8192 // defined in a namespace scope if it is used in the program and the
8193 // namespace scope definition shall not contain an initializer.
8194 //
8195 // We already performed a redefinition check above, but for static
8196 // data members we also need to check whether there was an in-class
8197 // declaration with an initializer.
8198 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008199 Diag(VDecl->getLocation(), diag::err_redefinition)
8200 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008201 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8202 return;
8203 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008204
Douglas Gregora31040f2010-12-16 01:31:22 +00008205 if (VDecl->hasLocalStorage())
8206 getCurFunction()->setHasBranchProtectedScope();
8207
8208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8209 VDecl->setInvalidDecl();
8210 return;
8211 }
8212 }
John McCalle46f62c2010-08-01 01:24:59 +00008213
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008214 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8215 // a kernel function cannot be initialized."
8216 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8217 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8218 VDecl->setInvalidDecl();
8219 return;
8220 }
8221
Steve Naroffbb204692007-09-12 14:07:44 +00008222 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008223 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008224 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008225
Douglas Gregor1344e942013-03-07 22:57:58 +00008226 // Expressions default to 'id' when we're in a debugger
8227 // and we are assigning it to a variable of Objective-C pointer type.
8228 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8229 Init->getType() == Context.UnknownAnyTy) {
8230 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8231 if (Result.isInvalid()) {
8232 VDecl->setInvalidDecl();
8233 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008234 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008235 Init = Result.take();
8236 }
Richard Smith01888722011-12-15 19:20:59 +00008237
8238 // Perform the initialization.
8239 if (!VDecl->isInvalidDecl()) {
8240 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8241 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008242 = DirectInit ?
8243 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8244 Init->getLocStart(),
8245 Init->getLocEnd())
8246 : InitializationKind::CreateDirectList(
8247 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008248 : InitializationKind::CreateCopy(VDecl->getLocation(),
8249 Init->getLocStart());
8250
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008251 MultiExprArg Args = Init;
8252 if (CXXDirectInit)
8253 Args = MultiExprArg(CXXDirectInit->getExprs(),
8254 CXXDirectInit->getNumExprs());
8255
8256 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8257 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008258 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008259 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008260 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008261 }
Richard Smith01888722011-12-15 19:20:59 +00008262
8263 Init = Result.takeAs<Expr>();
8264 }
8265
Richard Trieu568f7852012-10-01 17:39:51 +00008266 // Check for self-references within variable initializers.
8267 // Variables declared within a function/method body (except for references)
8268 // are handled by a dataflow analysis.
8269 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8270 VDecl->getType()->isReferenceType()) {
8271 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8272 }
8273
Richard Smith01888722011-12-15 19:20:59 +00008274 // If the type changed, it means we had an incomplete type that was
8275 // completed by the initializer. For example:
8276 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008277 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008278 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008279 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008280
Jordan Rosee10f4d32012-09-15 02:48:31 +00008281 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008282 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8283
Jordan Rosee10f4d32012-09-15 02:48:31 +00008284 if (VDecl->hasAttr<BlocksAttr>())
8285 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008286
8287 // It is safe to assign a weak reference into a strong variable.
8288 // Although this code can still have problems:
8289 // id x = self.weakProp;
8290 // id y = self.weakProp;
8291 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8292 // paths through the function. This should be revisited if
8293 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008294 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008295 DiagnosticsEngine::Level Level =
8296 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8297 Init->getLocStart());
8298 if (Level != DiagnosticsEngine::Ignored)
8299 getCurFunction()->markSafeWeakUse(Init);
8300 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008301 }
8302
Richard Smith41956372013-01-14 22:39:08 +00008303 // The initialization is usually a full-expression.
8304 //
8305 // FIXME: If this is a braced initialization of an aggregate, it is not
8306 // an expression, and each individual field initializer is a separate
8307 // full-expression. For instance, in:
8308 //
8309 // struct Temp { ~Temp(); };
8310 // struct S { S(Temp); };
8311 // struct T { S a, b; } t = { Temp(), Temp() }
8312 //
8313 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008314 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8315 false,
8316 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008317 if (Result.isInvalid()) {
8318 VDecl->setInvalidDecl();
8319 return;
8320 }
8321 Init = Result.take();
8322
Richard Smith01888722011-12-15 19:20:59 +00008323 // Attach the initializer to the decl.
8324 VDecl->setInit(Init);
8325
8326 if (VDecl->isLocalVarDecl()) {
8327 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8328 // static storage duration shall be constant expressions or string literals.
8329 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008330 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8331 if (VDecl->getStorageClass() == SC_Static)
8332 CheckForConstantInitializer(Init, DclT);
8333 // C89 is stricter than C99 for non-static aggregate types.
8334 // C89 6.5.7p3: All the expressions [...] in an initializer list
8335 // for an object that has aggregate or union type shall be
8336 // constant expressions.
8337 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008338 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008339 !Init->isConstantInitializer(Context, false))
8340 Diag(Init->getExprLoc(),
8341 diag::ext_aggregate_init_not_constant)
8342 << Init->getSourceRange();
8343 }
Mike Stump1eb44332009-09-09 15:08:12 +00008344 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008345 VDecl->getLexicalDeclContext()->isRecord()) {
8346 // This is an in-class initialization for a static data member, e.g.,
8347 //
8348 // struct S {
8349 // static const int value = 17;
8350 // };
8351
Douglas Gregor021c3b32009-03-11 23:00:04 +00008352 // C++ [class.mem]p4:
8353 // A member-declarator can contain a constant-initializer only
8354 // if it declares a static member (9.4) of const integral or
8355 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008356 //
Richard Smith01888722011-12-15 19:20:59 +00008357 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008358 // If a non-volatile const static data member is of integral or
8359 // enumeration type, its declaration in the class definition can
8360 // specify a brace-or-equal-initializer in which every initalizer-clause
8361 // that is an assignment-expression is a constant expression. A static
8362 // data member of literal type can be declared in the class definition
8363 // with the constexpr specifier; if so, its declaration shall specify a
8364 // brace-or-equal-initializer in which every initializer-clause that is
8365 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008366
8367 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008368 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008369
Richard Smithc6d990a2011-09-29 19:11:37 +00008370 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008371 // type. We separately check that every constexpr variable is of literal
8372 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008373 } else if (VDecl->isConstexpr()) {
8374
John McCall4e635642010-09-10 23:21:22 +00008375 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008376 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008377 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8378 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008379 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008380
8381 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008382 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008383 // Check whether the expression is a constant expression.
8384 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008385 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008386 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008387 // in-class initializer cannot be volatile.
8388 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8389 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008390 ; // Nothing to check.
8391 else if (Init->isIntegerConstantExpr(Context, &Loc))
8392 ; // Ok, it's an ICE!
8393 else if (Init->isEvaluatable(Context)) {
8394 // If we can constant fold the initializer through heroics, accept it,
8395 // but report this as a use of an extension for -pedantic.
8396 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8397 << Init->getSourceRange();
8398 } else {
8399 // Otherwise, this is some crazy unknown case. Report the issue at the
8400 // location provided by the isIntegerConstantExpr failed check.
8401 Diag(Loc, diag::err_in_class_initializer_non_constant)
8402 << Init->getSourceRange();
8403 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008404 }
8405
Richard Smith01888722011-12-15 19:20:59 +00008406 // We allow foldable floating-point constants as an extension.
8407 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008408 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8409 // it anyway and provide a fixit to add the 'constexpr'.
8410 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008411 Diag(VDecl->getLocation(),
8412 diag::ext_in_class_initializer_float_type_cxx11)
8413 << DclT << Init->getSourceRange();
8414 Diag(VDecl->getLocStart(),
8415 diag::note_in_class_initializer_float_type_cxx11)
8416 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008417 } else {
8418 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8419 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008420
Richard Smithb4b1d692013-01-25 04:22:16 +00008421 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8422 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8423 << Init->getSourceRange();
8424 VDecl->setInvalidDecl();
8425 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008426 }
Richard Smith947be192011-09-29 23:18:34 +00008427
Richard Smith01888722011-12-15 19:20:59 +00008428 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008429 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008430 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008431 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008432 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8433 VDecl->setConstexpr(true);
8434
Richard Smithc6d990a2011-09-29 19:11:37 +00008435 } else {
8436 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008437 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008438 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008439 }
Steve Naroff248a7532008-04-15 22:42:06 +00008440 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008441 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008442 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008443 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008444 VDecl->isExternC())) &&
8445 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008446 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008447
Richard Smith01888722011-12-15 19:20:59 +00008448 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008449 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008450 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008451 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8452 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8453 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008454 !Init->isConstantInitializer(
8455 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008456 // GNU C++98 edits for __thread, [basic.start.init]p4:
8457 // An object of thread storage duration shall not require dynamic
8458 // initialization.
8459 // FIXME: Need strict checking here.
8460 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8461 if (getLangOpts().CPlusPlus11)
8462 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8463 }
Steve Naroffbb204692007-09-12 14:07:44 +00008464 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008465
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008466 // We will represent direct-initialization similarly to copy-initialization:
8467 // int x(1); -as-> int x = 1;
8468 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8469 //
8470 // Clients that want to distinguish between the two forms, can check for
8471 // direct initializer using VarDecl::getInitStyle().
8472 // A major benefit is that clients that don't particularly care about which
8473 // exactly form was it (like the CodeGen) can handle both cases without
8474 // special case code.
8475
8476 // C++ 8.5p11:
8477 // The form of initialization (using parentheses or '=') is generally
8478 // insignificant, but does matter when the entity being initialized has a
8479 // class type.
8480 if (CXXDirectInit) {
8481 assert(DirectInit && "Call-style initializer must be direct init.");
8482 VDecl->setInitStyle(VarDecl::CallInit);
8483 } else if (DirectInit) {
8484 // This must be list-initialization. No other way is direct-initialization.
8485 VDecl->setInitStyle(VarDecl::ListInit);
8486 }
8487
John McCall2998d6b2011-01-19 11:48:09 +00008488 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008489}
8490
John McCall7727acf2010-03-31 02:13:20 +00008491/// ActOnInitializerError - Given that there was an error parsing an
8492/// initializer for the given declaration, try to return to some form
8493/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008494void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008495 // Our main concern here is re-establishing invariants like "a
8496 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008497 if (!D || D->isInvalidDecl()) return;
8498
8499 VarDecl *VD = dyn_cast<VarDecl>(D);
8500 if (!VD) return;
8501
Richard Smith34b41d92011-02-20 03:19:35 +00008502 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008503 if (ParsingInitForAutoVars.count(D)) {
8504 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008505 return;
8506 }
8507
John McCall7727acf2010-03-31 02:13:20 +00008508 QualType Ty = VD->getType();
8509 if (Ty->isDependentType()) return;
8510
8511 // Require a complete type.
8512 if (RequireCompleteType(VD->getLocation(),
8513 Context.getBaseElementType(Ty),
8514 diag::err_typecheck_decl_incomplete_type)) {
8515 VD->setInvalidDecl();
8516 return;
8517 }
8518
8519 // Require an abstract type.
8520 if (RequireNonAbstractType(VD->getLocation(), Ty,
8521 diag::err_abstract_type_in_decl,
8522 AbstractVariableType)) {
8523 VD->setInvalidDecl();
8524 return;
8525 }
8526
8527 // Don't bother complaining about constructors or destructors,
8528 // though.
8529}
8530
John McCalld226f652010-08-21 09:40:31 +00008531void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008532 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008533 // If there is no declaration, there was an error parsing it. Just ignore it.
8534 if (RealDecl == 0)
8535 return;
8536
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008537 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8538 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008539
Richard Smithdd4b3502011-12-25 21:17:58 +00008540 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008541 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008542 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8543 << Var->getDeclName() << Type;
8544 Var->setInvalidDecl();
8545 return;
8546 }
Mike Stump1eb44332009-09-09 15:08:12 +00008547
Richard Smithdd4b3502011-12-25 21:17:58 +00008548 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008549 // the constexpr specifier; if so, its declaration shall specify
8550 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008551 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8552 // the definition of a variable [...] or the declaration of a static data
8553 // member.
8554 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8555 if (Var->isStaticDataMember())
8556 Diag(Var->getLocation(),
8557 diag::err_constexpr_static_mem_var_requires_init)
8558 << Var->getDeclName();
8559 else
8560 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008561 Var->setInvalidDecl();
8562 return;
8563 }
8564
Douglas Gregor60c93c92010-02-09 07:26:29 +00008565 switch (Var->isThisDeclarationADefinition()) {
8566 case VarDecl::Definition:
8567 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8568 break;
8569
8570 // We have an out-of-line definition of a static data member
8571 // that has an in-class initializer, so we type-check this like
8572 // a declaration.
8573 //
8574 // Fall through
8575
8576 case VarDecl::DeclarationOnly:
8577 // It's only a declaration.
8578
8579 // Block scope. C99 6.7p7: If an identifier for an object is
8580 // declared with no linkage (C99 6.2.2p6), the type for the
8581 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008582 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008583 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008584 RequireCompleteType(Var->getLocation(), Type,
8585 diag::err_typecheck_decl_incomplete_type))
8586 Var->setInvalidDecl();
8587
8588 // Make sure that the type is not abstract.
8589 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8590 RequireNonAbstractType(Var->getLocation(), Type,
8591 diag::err_abstract_type_in_decl,
8592 AbstractVariableType))
8593 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008594 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008595 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008596 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008597 Diag(Var->getLocation(), diag::note_private_extern);
8598 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008599
Douglas Gregor60c93c92010-02-09 07:26:29 +00008600 return;
8601
8602 case VarDecl::TentativeDefinition:
8603 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8604 // object that has file scope without an initializer, and without a
8605 // storage-class specifier or with the storage-class specifier "static",
8606 // constitutes a tentative definition. Note: A tentative definition with
8607 // external linkage is valid (C99 6.2.2p5).
8608 if (!Var->isInvalidDecl()) {
8609 if (const IncompleteArrayType *ArrayT
8610 = Context.getAsIncompleteArrayType(Type)) {
8611 if (RequireCompleteType(Var->getLocation(),
8612 ArrayT->getElementType(),
8613 diag::err_illegal_decl_array_incomplete_type))
8614 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008615 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008616 // C99 6.9.2p3: If the declaration of an identifier for an object is
8617 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8618 // declared type shall not be an incomplete type.
8619 // NOTE: code such as the following
8620 // static struct s;
8621 // struct s { int a; };
8622 // is accepted by gcc. Hence here we issue a warning instead of
8623 // an error and we do not invalidate the static declaration.
8624 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008625 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008626 RequireCompleteType(Var->getLocation(), Type,
8627 diag::ext_typecheck_decl_incomplete_type);
8628 }
8629 }
8630
8631 // Record the tentative definition; we're done.
8632 if (!Var->isInvalidDecl())
8633 TentativeDefinitions.push_back(Var);
8634 return;
8635 }
8636
8637 // Provide a specific diagnostic for uninitialized variable
8638 // definitions with incomplete array type.
8639 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008640 Diag(Var->getLocation(),
8641 diag::err_typecheck_incomplete_array_needs_initializer);
8642 Var->setInvalidDecl();
8643 return;
8644 }
8645
John McCallb567a8b2010-08-01 01:25:24 +00008646 // Provide a specific diagnostic for uninitialized variable
8647 // definitions with reference type.
8648 if (Type->isReferenceType()) {
8649 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8650 << Var->getDeclName()
8651 << SourceRange(Var->getLocation(), Var->getLocation());
8652 Var->setInvalidDecl();
8653 return;
8654 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008655
8656 // Do not attempt to type-check the default initializer for a
8657 // variable with dependent type.
8658 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008659 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008660
Douglas Gregor60c93c92010-02-09 07:26:29 +00008661 if (Var->isInvalidDecl())
8662 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008663
Douglas Gregor60c93c92010-02-09 07:26:29 +00008664 if (RequireCompleteType(Var->getLocation(),
8665 Context.getBaseElementType(Type),
8666 diag::err_typecheck_decl_incomplete_type)) {
8667 Var->setInvalidDecl();
8668 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008669 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008670
Douglas Gregor60c93c92010-02-09 07:26:29 +00008671 // The variable can not have an abstract class type.
8672 if (RequireNonAbstractType(Var->getLocation(), Type,
8673 diag::err_abstract_type_in_decl,
8674 AbstractVariableType)) {
8675 Var->setInvalidDecl();
8676 return;
8677 }
8678
Douglas Gregor4337dc72011-05-21 17:52:48 +00008679 // Check for jumps past the implicit initializer. C++0x
8680 // clarifies that this applies to a "variable with automatic
8681 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008682 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008683 // A program that jumps from a point where a variable with automatic
8684 // storage duration is not in scope to a point where it is in scope is
8685 // ill-formed unless the variable has scalar type, class type with a
8686 // trivial default constructor and a trivial destructor, a cv-qualified
8687 // version of one of these types, or an array of one of the preceding
8688 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008689 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008690 if (const RecordType *Record
8691 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008692 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008693 // Mark the function for further checking even if the looser rules of
8694 // C++11 do not require such checks, so that we can diagnose
8695 // incompatibilities with C++98.
8696 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008697 getCurFunction()->setHasBranchProtectedScope();
8698 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008699 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008700
8701 // C++03 [dcl.init]p9:
8702 // If no initializer is specified for an object, and the
8703 // object is of (possibly cv-qualified) non-POD class type (or
8704 // array thereof), the object shall be default-initialized; if
8705 // the object is of const-qualified type, the underlying class
8706 // type shall have a user-declared default
8707 // constructor. Otherwise, if no initializer is specified for
8708 // a non- static object, the object and its subobjects, if
8709 // any, have an indeterminate initial value); if the object
8710 // or any of its subobjects are of const-qualified type, the
8711 // program is ill-formed.
8712 // C++0x [dcl.init]p11:
8713 // If no initializer is specified for an object, the object is
8714 // default-initialized; [...].
8715 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8716 InitializationKind Kind
8717 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008718
8719 InitializationSequence InitSeq(*this, Entity, Kind, None);
8720 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008721 if (Init.isInvalid())
8722 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008723 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008724 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008725 // This is important for template substitution.
8726 Var->setInitStyle(VarDecl::CallInit);
8727 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008728
John McCall2998d6b2011-01-19 11:48:09 +00008729 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008730 }
8731}
8732
Richard Smithad762fc2011-04-14 22:09:26 +00008733void Sema::ActOnCXXForRangeDecl(Decl *D) {
8734 VarDecl *VD = dyn_cast<VarDecl>(D);
8735 if (!VD) {
8736 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8737 D->setInvalidDecl();
8738 return;
8739 }
8740
8741 VD->setCXXForRangeDecl(true);
8742
8743 // for-range-declaration cannot be given a storage class specifier.
8744 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008745 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008746 case SC_None:
8747 break;
8748 case SC_Extern:
8749 Error = 0;
8750 break;
8751 case SC_Static:
8752 Error = 1;
8753 break;
8754 case SC_PrivateExtern:
8755 Error = 2;
8756 break;
8757 case SC_Auto:
8758 Error = 3;
8759 break;
8760 case SC_Register:
8761 Error = 4;
8762 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008763 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008764 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008765 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008766 if (VD->isConstexpr())
8767 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008768 if (Error != -1) {
8769 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8770 << VD->getDeclName() << Error;
8771 D->setInvalidDecl();
8772 }
8773}
8774
John McCall2998d6b2011-01-19 11:48:09 +00008775void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8776 if (var->isInvalidDecl()) return;
8777
John McCallf85e1932011-06-15 23:02:42 +00008778 // In ARC, don't allow jumps past the implicit initialization of a
8779 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008780 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008781 var->hasLocalStorage()) {
8782 switch (var->getType().getObjCLifetime()) {
8783 case Qualifiers::OCL_None:
8784 case Qualifiers::OCL_ExplicitNone:
8785 case Qualifiers::OCL_Autoreleasing:
8786 break;
8787
8788 case Qualifiers::OCL_Weak:
8789 case Qualifiers::OCL_Strong:
8790 getCurFunction()->setHasBranchProtectedScope();
8791 break;
8792 }
8793 }
8794
Eli Friedmane4851f22012-10-23 20:19:32 +00008795 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008796 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008797 getDiagnostics().getDiagnosticLevel(
8798 diag::warn_missing_variable_declarations,
8799 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008800 // Find a previous declaration that's not a definition.
8801 VarDecl *prev = var->getPreviousDecl();
8802 while (prev && prev->isThisDeclarationADefinition())
8803 prev = prev->getPreviousDecl();
8804
8805 if (!prev)
8806 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8807 }
8808
Richard Smith6a570f62013-04-14 20:11:31 +00008809 if (var->getTLSKind() == VarDecl::TLS_Static &&
8810 var->getType().isDestructedType()) {
8811 // GNU C++98 edits for __thread, [basic.start.term]p3:
8812 // The type of an object with thread storage duration shall not
8813 // have a non-trivial destructor.
8814 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8815 if (getLangOpts().CPlusPlus11)
8816 Diag(var->getLocation(), diag::note_use_thread_local);
8817 }
8818
John McCall2998d6b2011-01-19 11:48:09 +00008819 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008820 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008821
Richard Smitha67d5032012-11-09 23:03:14 +00008822 QualType type = var->getType();
8823 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008824
8825 // __block variables might require us to capture a copy-initializer.
8826 if (var->hasAttr<BlocksAttr>()) {
8827 // It's currently invalid to ever have a __block variable with an
8828 // array type; should we diagnose that here?
8829
8830 // Regardless, we don't want to ignore array nesting when
8831 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008832 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008833 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008834 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008835 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008836 ExprResult result
8837 = PerformMoveOrCopyInitialization(
8838 InitializedEntity::InitializeBlock(poi, type, false),
8839 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008840 if (!result.isInvalid()) {
8841 result = MaybeCreateExprWithCleanups(result);
8842 Expr *init = result.takeAs<Expr>();
8843 Context.setBlockVarCopyInits(var, init);
8844 }
8845 }
8846 }
8847
Richard Smith66f85712011-11-07 22:16:17 +00008848 Expr *Init = var->getInit();
8849 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008850 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008851
Richard Smith9568f0c2012-10-29 18:26:47 +00008852 if (!var->getDeclContext()->isDependentContext() &&
8853 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008854 if (IsGlobal && !var->isConstexpr() &&
8855 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8856 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008857 != DiagnosticsEngine::Ignored) {
8858 // Warn about globals which don't have a constant initializer. Don't
8859 // warn about globals with a non-trivial destructor because we already
8860 // warned about them.
8861 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8862 if (!(RD && !RD->hasTrivialDestructor()) &&
8863 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8864 Diag(var->getLocation(), diag::warn_global_constructor)
8865 << Init->getSourceRange();
8866 }
Richard Smith099e7f62011-12-19 06:19:21 +00008867
Richard Smith099e7f62011-12-19 06:19:21 +00008868 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008869 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008870 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8871 SourceLocation DiagLoc = var->getLocation();
8872 // If the note doesn't add any useful information other than a source
8873 // location, fold it into the primary diagnostic.
8874 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8875 diag::note_invalid_subexpr_in_const_expr) {
8876 DiagLoc = Notes[0].first;
8877 Notes.clear();
8878 }
8879 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8880 << var << Init->getSourceRange();
8881 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8882 Diag(Notes[I].first, Notes[I].second);
8883 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008884 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008885 // Check whether the initializer of a const variable of integral or
8886 // enumeration type is an ICE now, since we can't tell whether it was
8887 // initialized by a constant expression if we check later.
8888 var->checkInitIsICE();
8889 }
Richard Smith66f85712011-11-07 22:16:17 +00008890 }
John McCall2998d6b2011-01-19 11:48:09 +00008891
8892 // Require the destructor.
8893 if (const RecordType *recordType = baseType->getAs<RecordType>())
8894 FinalizeVarWithDestructor(var, recordType);
8895}
8896
Richard Smith483b9f32011-02-21 20:05:19 +00008897/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8898/// any semantic actions necessary after any initializer has been attached.
8899void
8900Sema::FinalizeDeclaration(Decl *ThisDecl) {
8901 // Note that we are no longer parsing the initializer for this declaration.
8902 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008903
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008904 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008905 if (!VD)
8906 return;
8907
Rafael Espindola29535ba2013-08-16 23:18:50 +00008908 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8909 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8910 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8911 VD->dropAttr<UsedAttr>();
8912 }
8913 }
8914
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008915 if (!VD->isInvalidDecl() &&
8916 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8917 if (const VarDecl *Def = VD->getDefinition()) {
8918 if (Def->hasAttr<AliasAttr>()) {
8919 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8920 << VD->getDeclName();
8921 Diag(Def->getLocation(), diag::note_previous_definition);
8922 VD->setInvalidDecl();
8923 }
8924 }
8925 }
8926
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008927 const DeclContext *DC = VD->getDeclContext();
8928 // If there's a #pragma GCC visibility in scope, and this isn't a class
8929 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008930 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008931 AddPushedVisibilityAttribute(VD);
8932
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008933 if (VD->isFileVarDecl())
8934 MarkUnusedFileScopedDecl(VD);
8935
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008936 // Now we have parsed the initializer and can update the table of magic
8937 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008938 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8939 !VD->getType()->isIntegralOrEnumerationType())
8940 return;
8941
8942 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8943 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8944 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8945 I != E; ++I) {
8946 const Expr *MagicValueExpr = VD->getInit();
8947 if (!MagicValueExpr) {
8948 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008949 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008950 llvm::APSInt MagicValueInt;
8951 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8952 Diag(I->getRange().getBegin(),
8953 diag::err_type_tag_for_datatype_not_ice)
8954 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8955 continue;
8956 }
8957 if (MagicValueInt.getActiveBits() > 64) {
8958 Diag(I->getRange().getBegin(),
8959 diag::err_type_tag_for_datatype_too_large)
8960 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8961 continue;
8962 }
8963 uint64_t MagicValue = MagicValueInt.getZExtValue();
8964 RegisterTypeTagForDatatype(I->getArgumentKind(),
8965 MagicValue,
8966 I->getMatchingCType(),
8967 I->getLayoutCompatible(),
8968 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008969 }
Richard Smith483b9f32011-02-21 20:05:19 +00008970}
8971
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008972Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8973 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008974 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008975
8976 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008977 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008978
David Majnemeraa824612013-09-17 23:57:10 +00008979 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008980 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008981 if (Decl *D = Group[i]) {
8982 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8983 if (!FirstDeclaratorInGroup)
8984 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008985 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008986 }
Richard Smith406c38e2011-02-23 00:37:57 +00008987
Eli Friedman5e867c82013-07-10 00:30:46 +00008988 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008989 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008990 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008991 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8992 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8993 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008994 }
David Blaikie66cff722012-11-14 01:52:05 +00008995
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008996 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008997}
8998
8999/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9000/// group, performing any necessary semantic checking.
9001Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009002Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00009003 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00009004 // C++0x [dcl.spec.auto]p7:
9005 // If the type deduced for the template parameter U is not the same in each
9006 // deduction, the program is ill-formed.
9007 // FIXME: When initializer-list support is added, a distinction is needed
9008 // between the deduced type U and the deduced type which 'auto' stands for.
9009 // auto a = 0, b = { 1, 2, 3 };
9010 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009011 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00009012 QualType Deduced;
9013 CanQualType DeducedCanon;
9014 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009015 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00009016 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9017 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00009018 // Don't reissue diagnostics when instantiating a template.
9019 if (AT && D->isInvalidDecl())
9020 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00009021 QualType U = AT ? AT->getDeducedType() : QualType();
9022 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009023 CanQualType UCanon = Context.getCanonicalType(U);
9024 if (Deduced.isNull()) {
9025 Deduced = U;
9026 DeducedCanon = UCanon;
9027 DeducedDecl = D;
9028 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00009029 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9030 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00009031 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00009032 << Deduced << DeducedDecl->getDeclName()
9033 << U << D->getDeclName()
9034 << DeducedDecl->getInit()->getSourceRange()
9035 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00009036 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00009037 break;
9038 }
9039 }
9040 }
9041 }
9042 }
9043
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009044 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009045
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009046 return DeclGroupPtrTy::make(
9047 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009048}
Steve Naroffe1223f72007-08-28 03:03:08 +00009049
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009050void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009051 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009052}
9053
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009054void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009055 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009056 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009057 return;
9058
9059 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9060 Group[0]->getLocation())
9061 == DiagnosticsEngine::Ignored)
9062 return;
9063
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009064 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009065 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009066 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009067 // additional declaration references:
9068 // 'typedef struct S {} S;'
9069 // 'typedef struct S *S;'
9070 // 'struct S *pS;'
9071 // FinalizeDeclaratorGroup adds these as separate declarations.
9072 Decl *MaybeTagDecl = Group[0];
9073 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009074 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009075 }
9076 }
9077
9078 // See if there are any new comments that are not attached to a decl.
9079 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9080 if (!Comments.empty() &&
9081 !Comments.back()->isAttached()) {
9082 // There is at least one comment that not attached to a decl.
9083 // Maybe it should be attached to one of these decls?
9084 //
9085 // Note that this way we pick up not only comments that precede the
9086 // declaration, but also comments that *follow* the declaration -- thanks to
9087 // the lookahead in the lexer: we've consumed the semicolon and looked
9088 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009089 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009090 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009091 }
9092}
Chris Lattner682bf922009-03-29 16:50:03 +00009093
Chris Lattner04421082008-04-08 04:40:51 +00009094/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9095/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009096Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009097 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009098
Chris Lattner04421082008-04-08 04:40:51 +00009099 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009100
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009101 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009102 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009103 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009104 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009105 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009106 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9107 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009108 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009109 Diag(DS.getStorageClassSpecLoc(),
9110 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009111 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009112 }
Eli Friedman63054b32009-04-19 20:27:55 +00009113
Richard Smithec642442013-04-12 22:46:28 +00009114 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9115 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9116 << DeclSpec::getSpecifierName(TSCS);
9117 if (DS.isConstexprSpecified())
9118 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009119 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009120
Richard Smithec642442013-04-12 22:46:28 +00009121 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009122
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009123 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009124 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009125
David Blaikie4e4d0842012-03-11 07:00:24 +00009126 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009127 // Check that there are no default arguments inside the type of this
9128 // parameter.
9129 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009130
9131 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9132 if (D.getCXXScopeSpec().isSet()) {
9133 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9134 << D.getCXXScopeSpec().getRange();
9135 D.getCXXScopeSpec().clear();
9136 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009137 }
9138
Sean Hunt7533a5b2010-11-03 01:07:06 +00009139 // Ensure we have a valid name
9140 IdentifierInfo *II = 0;
9141 if (D.hasName()) {
9142 II = D.getIdentifier();
9143 if (!II) {
9144 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9145 << GetNameForDeclarator(D).getName().getAsString();
9146 D.setInvalidType(true);
9147 }
9148 }
9149
Chris Lattnerd84aac12010-02-22 00:40:25 +00009150 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009151 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009152 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9153 ForRedeclaration);
9154 LookupName(R, S);
9155 if (R.isSingleResult()) {
9156 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009157 if (PrevDecl->isTemplateParameter()) {
9158 // Maybe we will complain about the shadowed template parameter.
9159 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9160 // Just pretend that we didn't see the previous declaration.
9161 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009162 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009163 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009164 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009165
Chris Lattnercf79b012009-01-21 02:38:50 +00009166 // Recover by removing the name
9167 II = 0;
9168 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009169 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009170 }
Chris Lattner04421082008-04-08 04:40:51 +00009171 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009172 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009173
John McCall7a9813c2010-01-22 00:28:27 +00009174 // Temporarily put parameter variables in the translation unit, not
9175 // the enclosing context. This prevents them from accidentally
9176 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009177 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009178 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009179 D.getIdentifierLoc(), II,
9180 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009181 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009182
Chris Lattnereaaebc72009-04-25 08:06:05 +00009183 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009184 New->setInvalidDecl();
9185
9186 assert(S->isFunctionPrototypeScope());
9187 assert(S->getFunctionPrototypeDepth() >= 1);
9188 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9189 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009190
Douglas Gregor44b43212008-12-11 16:49:14 +00009191 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009192 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009193 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009194 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009195
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009196 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009197
Douglas Gregore3895852011-09-12 18:37:38 +00009198 if (D.getDeclSpec().isModulePrivateSpecified())
9199 Diag(New->getLocation(), diag::err_module_private_local)
9200 << 1 << New->getDeclName()
9201 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9202 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9203
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009204 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009205 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9206 }
John McCalld226f652010-08-21 09:40:31 +00009207 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009208}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009209
John McCall82dc0092010-06-04 11:21:44 +00009210/// \brief Synthesizes a variable for a parameter arising from a
9211/// typedef.
9212ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9213 SourceLocation Loc,
9214 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009215 /* FIXME: setting StartLoc == Loc.
9216 Would it be worth to modify callers so as to provide proper source
9217 location for the unnamed parameters, embedding the parameter's type? */
9218 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009219 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009220 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009221 Param->setImplicit();
9222 return Param;
9223}
9224
John McCallfbce0e12010-08-24 09:05:15 +00009225void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9226 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009227 // Don't diagnose unused-parameter errors in template instantiations; we
9228 // will already have done so in the template itself.
9229 if (!ActiveTemplateInstantiations.empty())
9230 return;
9231
9232 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009233 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009234 !(*Param)->hasAttr<UnusedAttr>()) {
9235 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9236 << (*Param)->getDeclName();
9237 }
9238 }
9239}
9240
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009241void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9242 ParmVarDecl * const *ParamEnd,
9243 QualType ReturnTy,
9244 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009245 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009246 return;
9247
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009248 // Warn if the return value is pass-by-value and larger than the specified
9249 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009250 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009251 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009252 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009253 Diag(D->getLocation(), diag::warn_return_value_size)
9254 << D->getDeclName() << Size;
9255 }
9256
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009257 // Warn if any parameter is pass-by-value and larger than the specified
9258 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009259 for (; Param != ParamEnd; ++Param) {
9260 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009261 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009262 continue;
9263 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009264 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009265 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9266 << (*Param)->getDeclName() << Size;
9267 }
9268}
9269
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009270ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9271 SourceLocation NameLoc, IdentifierInfo *Name,
9272 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009273 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009274 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009275 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009276 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009277 T->isObjCLifetimeType()) {
9278
9279 Qualifiers::ObjCLifetime lifetime;
9280
9281 // Special cases for arrays:
9282 // - if it's const, use __unsafe_unretained
9283 // - otherwise, it's an error
9284 if (T->isArrayType()) {
9285 if (!T.isConstQualified()) {
9286 DelayedDiagnostics.add(
9287 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009288 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009289 }
9290 lifetime = Qualifiers::OCL_ExplicitNone;
9291 } else {
9292 lifetime = T->getObjCARCImplicitLifetime();
9293 }
9294 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009295 }
9296
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009297 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009298 Context.getAdjustedParameterType(T),
9299 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009300 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009301
9302 // Parameters can not be abstract class types.
9303 // For record types, this is done by the AbstractClassUsageDiagnoser once
9304 // the class has been completely parsed.
9305 if (!CurContext->isRecord() &&
9306 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9307 AbstractParamType))
9308 New->setInvalidDecl();
9309
9310 // Parameter declarators cannot be interface types. All ObjC objects are
9311 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009312 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009313 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009314 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009315 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009316 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009317 T = Context.getObjCObjectPointerType(T);
9318 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009319 }
9320
9321 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9322 // duration shall not be qualified by an address-space qualifier."
9323 // Since all parameters have automatic store duration, they can not have
9324 // an address space.
9325 if (T.getAddressSpace() != 0) {
9326 Diag(NameLoc, diag::err_arg_with_address_space);
9327 New->setInvalidDecl();
9328 }
9329
9330 return New;
9331}
9332
Douglas Gregora3a83512009-04-01 23:51:29 +00009333void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9334 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009335 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009336
Reid Spencer5f016e22007-07-11 17:01:13 +00009337 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9338 // for a K&R function.
9339 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009340 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9341 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009342 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009343 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009344 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009345 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009346 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009347 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009348 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009349 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009350
Reid Spencer5f016e22007-07-11 17:01:13 +00009351 // Implicitly declare the argument as type 'int' for lack of a better
9352 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009353 AttributeFactory attrs;
9354 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009355 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009356 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009357 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009358 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009359 // Use the identifier location for the type source range.
9360 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9361 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009362 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9363 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009364 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009365 }
9366 }
Mike Stump1eb44332009-09-09 15:08:12 +00009367 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009368}
9369
Richard Smith87162c22012-04-17 22:30:01 +00009370Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009371 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009372 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009373 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009374
Douglas Gregor45fa5602011-11-07 20:56:01 +00009375 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009376 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009377 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009378}
9379
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009380static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9381 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009382 // Don't warn about invalid declarations.
9383 if (FD->isInvalidDecl())
9384 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009385
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009386 // Or declarations that aren't global.
9387 if (!FD->isGlobal())
9388 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009389
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009390 // Don't warn about C++ member functions.
9391 if (isa<CXXMethodDecl>(FD))
9392 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009393
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009394 // Don't warn about 'main'.
9395 if (FD->isMain())
9396 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009397
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009398 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009399 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009400 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009401
9402 // Don't warn about function templates.
9403 if (FD->getDescribedFunctionTemplate())
9404 return false;
9405
9406 // Don't warn about function template specializations.
9407 if (FD->isFunctionTemplateSpecialization())
9408 return false;
9409
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009410 // Don't warn for OpenCL kernels.
9411 if (FD->hasAttr<OpenCLKernelAttr>())
9412 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009413
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009414 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009415 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9416 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009417 // Ignore any declarations that occur in function or method
9418 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009419 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009420 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009421
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009422 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009423 if (FD->getNumParams() == 0)
9424 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009425 break;
9426 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009427
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009428 return MissingPrototype;
9429}
9430
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009431void
9432Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9433 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009434 // Don't complain if we're in GNU89 mode and the previous definition
9435 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009436 const FunctionDecl *Definition = EffectiveDefinition;
9437 if (!Definition)
9438 if (!FD->isDefined(Definition))
9439 return;
9440
9441 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009442 return;
9443
9444 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9445 Definition->getStorageClass() == SC_Extern)
9446 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009447 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009448 else
9449 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9450
9451 Diag(Definition->getLocation(), diag::note_previous_definition);
9452 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009453}
Faisal Valic00e4192013-11-07 05:17:06 +00009454
9455
Faisal Valibef582b2013-10-23 16:10:50 +00009456static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9457 Sema &S) {
9458 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Valid78d6592013-11-12 01:40:44 +00009459
9460 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valibef582b2013-10-23 16:10:50 +00009461 LSI->CallOperator = CallOperator;
9462 LSI->Lambda = LambdaClass;
9463 LSI->ReturnType = CallOperator->getResultType();
9464 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9465
9466 if (LCD == LCD_None)
9467 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9468 else if (LCD == LCD_ByCopy)
9469 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9470 else if (LCD == LCD_ByRef)
9471 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9472 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9473
9474 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9475 LSI->Mutable = !CallOperator->isConst();
9476
Faisal Valic00e4192013-11-07 05:17:06 +00009477 // Add the captures to the LSI so they can be noted as already
9478 // captured within tryCaptureVar.
9479 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9480 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9481 if (C->capturesVariable()) {
9482 VarDecl *VD = C->getCapturedVar();
9483 if (VD->isInitCapture())
9484 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9485 QualType CaptureType = VD->getType();
9486 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9487 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9488 /*RefersToEnclosingLocal*/true, C->getLocation(),
9489 /*EllipsisLoc*/C->isPackExpansion()
9490 ? C->getEllipsisLoc() : SourceLocation(),
9491 CaptureType, /*Expr*/ 0);
9492
9493 } else if (C->capturesThis()) {
9494 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9495 S.getCurrentThisType(), /*Expr*/ 0);
9496 }
9497 }
Faisal Valibef582b2013-10-23 16:10:50 +00009498}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009499
John McCalld226f652010-08-21 09:40:31 +00009500Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009501 // Clear the last template instantiation error context.
9502 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9503
Douglas Gregor52591bf2009-06-24 00:54:41 +00009504 if (!D)
9505 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009506 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009507
John McCalld226f652010-08-21 09:40:31 +00009508 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009509 FD = FunTmpl->getTemplatedDecl();
9510 else
John McCalld226f652010-08-21 09:40:31 +00009511 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009512 // If we are instantiating a generic lambda call operator, push
9513 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009514 // that's already been calculated (ActOnLambdaExpr) to prime the current
9515 // LambdaScopeInfo.
9516 // When the template operator is being specialized, the LambdaScopeInfo,
9517 // has to be properly restored so that tryCaptureVariable doesn't try
9518 // and capture any new variables. In addition when calculating potential
9519 // captures during transformation of nested lambdas, it is necessary to
9520 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009521 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009522 assert(ActiveTemplateInstantiations.size() &&
9523 "There should be an active template instantiation on the stack "
9524 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009525 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009526 }
9527 else
9528 // Enter a new function scope
9529 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009530
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009531 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009532 if (!FD->isLateTemplateParsed())
9533 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009534
Douglas Gregorcda9c672009-02-16 17:45:42 +00009535 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009536 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009537 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9538 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009539 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009540 FD->setInvalidDecl();
9541 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009542 }
9543
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009544 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009545 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9546 QualType ResultType = FD->getResultType();
9547 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009548 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009549 RequireCompleteType(FD->getLocation(), ResultType,
9550 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009551 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009552
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009553 // GNU warning -Wmissing-prototypes:
9554 // Warn if a global function is defined without a previous
9555 // prototype declaration. This warning is issued even if the
9556 // definition itself provides a prototype. The aim is to detect
9557 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009558 const FunctionDecl *PossibleZeroParamPrototype = 0;
9559 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009560 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009561
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009562 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009563 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009564 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009565 if (TypeSourceInfo *TI =
9566 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9567 TypeLoc TL = TI->getTypeLoc();
9568 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9569 Diag(PossibleZeroParamPrototype->getLocation(),
9570 diag::note_declaration_not_a_prototype)
9571 << PossibleZeroParamPrototype
9572 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9573 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009574 }
9575 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009576
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009577 if (FnBodyScope)
9578 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009579
Chris Lattner04421082008-04-08 04:40:51 +00009580 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009581 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9582 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009583
9584 // Introduce our parameters into the function scope
9585 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9586 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009587 Param->setOwningFunction(FD);
9588
Chris Lattner04421082008-04-08 04:40:51 +00009589 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009590 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009591 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009592
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009593 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009594 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009595 }
Chris Lattner04421082008-04-08 04:40:51 +00009596
James Molloy16f1f712012-02-29 10:24:19 +00009597 // If we had any tags defined in the function prototype,
9598 // introduce them into the function scope.
9599 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009600 for (ArrayRef<NamedDecl *>::iterator
9601 I = FD->getDeclsInPrototypeScope().begin(),
9602 E = FD->getDeclsInPrototypeScope().end();
9603 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009604 NamedDecl *D = *I;
9605
9606 // Some of these decls (like enums) may have been pinned to the translation unit
9607 // for lack of a real context earlier. If so, remove from the translation unit
9608 // and reattach to the current context.
9609 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9610 // Is the decl actually in the context?
9611 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9612 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9613 if (*DI == D) {
9614 Context.getTranslationUnitDecl()->removeDecl(D);
9615 break;
9616 }
9617 }
9618 // Either way, reassign the lexical decl context to our FunctionDecl.
9619 D->setLexicalDeclContext(CurContext);
9620 }
9621
9622 // If the decl has a non-null name, make accessible in the current scope.
9623 if (!D->getName().empty())
9624 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9625
9626 // Similarly, dive into enums and fish their constants out, making them
9627 // accessible in this scope.
9628 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9629 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9630 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009631 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009632 }
9633 }
9634 }
9635
Richard Smith87162c22012-04-17 22:30:01 +00009636 // Ensure that the function's exception specification is instantiated.
9637 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9638 ResolveExceptionSpec(D->getLocation(), FPT);
9639
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009640 // Checking attributes of current function definition
9641 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009642 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9643 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9644 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009645 // Microsoft accepts dllimport for functions defined within class scope.
9646 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009647 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009648 Diag(FD->getLocation(),
9649 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9650 << "dllimport";
9651 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009652 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009653 }
9654
9655 // Visual C++ appears to not think this is an issue, so only issue
9656 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009657 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009658 // If a symbol previously declared dllimport is later defined, the
9659 // attribute is ignored in subsequent references, and a warning is
9660 // emitted.
9661 Diag(FD->getLocation(),
9662 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009663 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009664 }
9665 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009666 // We want to attach documentation to original Decl (which might be
9667 // a function template).
9668 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009669 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009670}
9671
Douglas Gregor5077c382010-05-15 06:01:05 +00009672/// \brief Given the set of return statements within a function body,
9673/// compute the variables that are subject to the named return value
9674/// optimization.
9675///
9676/// Each of the variables that is subject to the named return value
9677/// optimization will be marked as NRVO variables in the AST, and any
9678/// return statement that has a marked NRVO variable as its NRVO candidate can
9679/// use the named return value optimization.
9680///
9681/// This function applies a very simplistic algorithm for NRVO: if every return
9682/// statement in the function has the same NRVO candidate, that candidate is
9683/// the NRVO variable.
9684///
9685/// FIXME: Employ a smarter algorithm that accounts for multiple return
9686/// statements and the lifetimes of the NRVO candidates. We should be able to
9687/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009688void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009689 ReturnStmt **Returns = Scope->Returns.data();
9690
Douglas Gregor5077c382010-05-15 06:01:05 +00009691 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009692 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009693 if (!Returns[I]->getNRVOCandidate())
9694 return;
9695
9696 if (!NRVOCandidate)
9697 NRVOCandidate = Returns[I]->getNRVOCandidate();
9698 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9699 return;
9700 }
9701
9702 if (NRVOCandidate)
9703 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9704}
9705
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009706bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009707 if (!Consumer.shouldSkipFunctionBody(D))
9708 return false;
9709
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009710 if (isa<ObjCMethodDecl>(D))
9711 return true;
9712
9713 FunctionDecl *FD = 0;
9714 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9715 FD = FTD->getTemplatedDecl();
9716 else
9717 FD = cast<FunctionDecl>(D);
9718
9719 // We cannot skip the body of a function (or function template) which is
9720 // constexpr, since we may need to evaluate its body in order to parse the
9721 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009722 // We cannot skip the body of a function with an undeduced return type,
9723 // because any callers of that function need to know the type.
9724 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009725}
9726
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009727Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009728 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009729 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009730 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009731 MD->setHasSkippedBody();
9732 return ActOnFinishFunctionBody(Decl, 0);
9733}
9734
John McCallf312b1e2010-08-26 23:41:50 +00009735Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009736 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009737}
9738
John McCall9ae2f072010-08-23 23:25:46 +00009739Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9740 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009741 FunctionDecl *FD = 0;
9742 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9743 if (FunTmpl)
9744 FD = FunTmpl->getTemplatedDecl();
9745 else
9746 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9747
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009748 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009749 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009750
Douglas Gregord83d0402009-08-22 00:34:47 +00009751 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009752 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009753
Richard Smith25d8c852013-05-10 04:31:10 +00009754 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9755 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9756 // If the function has a deduced result type but contains no 'return'
9757 // statements, the result type as written must be exactly 'auto', and
9758 // the deduced result type is 'void'.
9759 if (!FD->getResultType()->getAs<AutoType>()) {
9760 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9761 << FD->getResultType();
9762 FD->setInvalidDecl();
9763 } else {
9764 // Substitute 'void' for the 'auto' in the type.
9765 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9766 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9767 Context.adjustDeducedFunctionResultType(
9768 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009769 }
9770 }
9771
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009772 // The only way to be included in UndefinedButUsed is if there is an
9773 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009774 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009775 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009776 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009777 UndefinedButUsed.erase(FD);
9778 else if (FD->isInlined() &&
9779 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9780 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9781 UndefinedButUsed.erase(FD);
9782 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009783
John McCall75d8ba32012-02-14 19:50:52 +00009784 // If the function implicitly returns zero (like 'main') or is naked,
9785 // don't complain about missing return statements.
9786 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009787 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009788
Francois Pichet6a247472011-05-11 02:14:46 +00009789 // MSVC permits the use of pure specifier (=0) on function definition,
9790 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009791 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009792 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9793
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009794 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009795 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009796 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9797 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009798
9799 // If this is a constructor, we need a vtable.
9800 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9801 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009802
Jordan Rose7dd900e2012-07-02 21:19:23 +00009803 // Try to apply the named return value optimization. We have to check
9804 // if we can do this here because lambdas keep return statements around
9805 // to deduce an implicit return type.
9806 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9807 !FD->isDependentContext())
9808 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009809 }
9810
Douglas Gregor76e3da52012-02-08 20:17:14 +00009811 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9812 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009813 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009814 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009815 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009816 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009817 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009818 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9819 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009820
9821 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009822 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009823 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009824 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009825 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9826 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009827 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009828 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009829 } else {
John McCalld226f652010-08-21 09:40:31 +00009830 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009831 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009832
Jordan Rose535a5d02012-10-19 16:05:26 +00009833 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009834 "This should only be set for ObjC methods, which should have been "
9835 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009836
Reid Spencer5f016e22007-07-11 17:01:13 +00009837 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009838 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009839 // C++ constructors that have function-try-blocks can't have return
9840 // statements in the handlers of that block. (C++ [except.handle]p14)
9841 // Verify this.
9842 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9843 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9844
Richard Smith37bee672011-08-12 18:44:32 +00009845 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009846 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009847 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009848 !hasAnyUnrecoverableErrorsInThisFunction() &&
9849 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009850 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009851
John McCall15442822010-08-04 01:04:25 +00009852 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9853 if (!Destructor->getParent()->isDependentType())
9854 CheckDestructor(Destructor);
9855
John McCallef027fe2010-03-16 21:39:52 +00009856 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9857 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009858 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009859
9860 // If any errors have occurred, clear out any temporaries that may have
9861 // been leftover. This ensures that these temporaries won't be picked up for
9862 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009863 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009864 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009865 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009866 }
9867 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9868 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009869 // Since the body is valid, issue any analysis-based warnings that are
9870 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009871 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009872 }
9873
Richard Smith86c3ae42012-02-13 03:54:03 +00009874 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9875 (!CheckConstexprFunctionDecl(FD) ||
9876 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009877 FD->setInvalidDecl();
9878
John McCall80ee6e82011-11-10 05:35:25 +00009879 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009880 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009881 assert(MaybeODRUseExprs.empty() &&
9882 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009883 }
9884
John McCall90f97892010-03-25 22:08:03 +00009885 if (!IsInstantiation)
9886 PopDeclContext();
9887
Eli Friedmanec9ea722012-01-05 03:35:19 +00009888 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009889 // If any errors have occurred, clear out any temporaries that may have
9890 // been leftover. This ensures that these temporaries won't be picked up for
9891 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009892 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009893 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009894 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009895
John McCalld226f652010-08-21 09:40:31 +00009896 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009897}
9898
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009899
9900/// When we finish delayed parsing of an attribute, we must attach it to the
9901/// relevant Decl.
9902void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9903 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009904 // Always attach attributes to the underlying decl.
9905 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9906 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009907 ProcessDeclAttributeList(S, D, Attrs.getList());
9908
9909 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9910 if (Method->isStatic())
9911 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009912}
9913
9914
Reid Spencer5f016e22007-07-11 17:01:13 +00009915/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9916/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009917NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009918 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009919 // Before we produce a declaration for an implicitly defined
9920 // function, see whether there was a locally-scoped declaration of
9921 // this name as a function or variable. If so, use that
9922 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009923 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9924 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9925 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9926 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009927 }
9928
Chris Lattner37d10842008-05-05 21:18:06 +00009929 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009930 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009931 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009932 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009933 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009934 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009935 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009936 diag_id = diag::warn_implicit_function_decl;
9937 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009938
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009939 // Because typo correction is expensive, only do it if the implicit
9940 // function declaration is going to be treated as an error.
9941 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9942 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009943 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009944 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009945 LookupOrdinaryName, S, 0, Validator)))
9946 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9947 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009948 }
9949
Reid Spencer5f016e22007-07-11 17:01:13 +00009950 // Set a Declarator for the implicit definition: int foo();
9951 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009952 AttributeFactory attrFactory;
9953 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009954 unsigned DiagID;
9955 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009956 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009957 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009958 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009959 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009960 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9961 /*IsAmbiguous=*/false,
9962 /*RParenLoc=*/NoLoc,
9963 /*ArgInfo=*/0,
9964 /*NumArgs=*/0,
9965 /*EllipsisLoc=*/NoLoc,
9966 /*RParenLoc=*/NoLoc,
9967 /*TypeQuals=*/0,
9968 /*RefQualifierIsLvalueRef=*/true,
9969 /*RefQualifierLoc=*/NoLoc,
9970 /*ConstQualifierLoc=*/NoLoc,
9971 /*VolatileQualifierLoc=*/NoLoc,
9972 /*MutableLoc=*/NoLoc,
9973 EST_None,
9974 /*ESpecLoc=*/NoLoc,
9975 /*Exceptions=*/0,
9976 /*ExceptionRanges=*/0,
9977 /*NumExceptions=*/0,
9978 /*NoexceptExpr=*/0,
9979 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009980 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009981 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009982 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009983
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009984 // Insert this function into translation-unit scope.
9985
9986 DeclContext *PrevDC = CurContext;
9987 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009988
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009989 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009990 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009991
9992 CurContext = PrevDC;
9993
Douglas Gregor3c385e52009-02-14 18:57:46 +00009994 AddKnownFunctionAttributes(FD);
9995
Steve Naroffe2ef8152008-04-04 14:32:09 +00009996 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009997}
9998
Douglas Gregor3c385e52009-02-14 18:57:46 +00009999/// \brief Adds any function attributes that we know a priori based on
10000/// the declaration of this function.
10001///
10002/// These attributes can apply both to implicitly-declared builtins
10003/// (like __builtin___printf_chk) or to library-declared functions
10004/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010005///
10006/// We need to check for duplicate attributes both here and where user-written
10007/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +000010008void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10009 if (FD->isInvalidDecl())
10010 return;
10011
10012 // If this is a built-in function, map its builtin attributes to
10013 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +000010014 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +000010015 // Handle printf-formatting attributes.
10016 unsigned FormatIdx;
10017 bool HasVAListArg;
10018 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010019 if (!FD->getAttr<FormatAttr>()) {
10020 const char *fmt = "printf";
10021 unsigned int NumParams = FD->getNumParams();
10022 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10023 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10024 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +000010025 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010026 &Context.Idents.get(fmt),
10027 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +000010028 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010029 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010030 }
Ted Kremenekbee05c12010-07-16 02:11:15 +000010031 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10032 HasVAListArg)) {
10033 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010034 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010035 &Context.Idents.get("scanf"),
10036 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +000010037 HasVAListArg ? 0 : FormatIdx+2));
10038 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010039
10040 // Mark const if we don't care about errno and that is the only
10041 // thing preventing the function from being const. This allows
10042 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +000010043 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010044 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010045 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010046 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010047 }
Mike Stump0feecbb2009-07-27 19:14:18 +000010048
Rafael Espindola67004152011-10-12 19:51:18 +000010049 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10050 !FD->getAttr<ReturnsTwiceAttr>())
10051 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010052 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010053 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010054 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010055 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +000010056 }
10057
10058 IdentifierInfo *Name = FD->getIdentifier();
10059 if (!Name)
10060 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010061 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010062 FD->getDeclContext()->isTranslationUnit()) ||
10063 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010064 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010065 LinkageSpecDecl::lang_c)) {
10066 // Okay: this could be a libc/libm/Objective-C function we know
10067 // about.
10068 } else
10069 return;
10070
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010071 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010072 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010073 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010074 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010075 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010076 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010077 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010078 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010079
10080 if (Name->isStr("__CFStringMakeConstantString")) {
10081 // We already have a __builtin___CFStringMakeConstantString,
10082 // but builds that use -fno-constant-cfstrings don't go through that.
10083 if (!FD->getAttr<FormatArgAttr>())
10084 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10085 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010086}
Reid Spencer5f016e22007-07-11 17:01:13 +000010087
John McCallba6a9bd2009-10-24 08:00:42 +000010088TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010089 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010090 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010091 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010092
John McCalla93c9342009-12-07 02:54:59 +000010093 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010094 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010095 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010096 }
10097
Reid Spencer5f016e22007-07-11 17:01:13 +000010098 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010099 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010100 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010101 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010102 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010103 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010104
John McCallcde5a402011-02-01 08:20:08 +000010105 // Bail out immediately if we have an invalid declaration.
10106 if (D.isInvalidType()) {
10107 NewTD->setInvalidDecl();
10108 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010109 }
10110
Douglas Gregore3895852011-09-12 18:37:38 +000010111 if (D.getDeclSpec().isModulePrivateSpecified()) {
10112 if (CurContext->isFunctionOrMethod())
10113 Diag(NewTD->getLocation(), diag::err_module_private_local)
10114 << 2 << NewTD->getDeclName()
10115 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10116 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10117 else
10118 NewTD->setModulePrivate();
10119 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010120
John McCallcde5a402011-02-01 08:20:08 +000010121 // C++ [dcl.typedef]p8:
10122 // If the typedef declaration defines an unnamed class (or
10123 // enum), the first typedef-name declared by the declaration
10124 // to be that class type (or enum type) is used to denote the
10125 // class type (or enum type) for linkage purposes only.
10126 // We need to check whether the type was declared in the declaration.
10127 switch (D.getDeclSpec().getTypeSpecType()) {
10128 case TST_enum:
10129 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010130 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010131 case TST_union:
10132 case TST_class: {
10133 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10134
10135 // Do nothing if the tag is not anonymous or already has an
10136 // associated typedef (from an earlier typedef in this decl group).
10137 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010138 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010139
10140 // A well-formed anonymous tag must always be a TUK_Definition.
10141 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10142
10143 // The type must match the tag exactly; no qualifiers allowed.
10144 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10145 break;
10146
10147 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010148 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010149 break;
10150 }
10151
10152 default:
10153 break;
10154 }
10155
Steve Naroff5912a352007-08-28 20:14:24 +000010156 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010157}
10158
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010159
Richard Smithf1c66b42012-03-14 23:13:10 +000010160/// \brief Check that this is a valid underlying type for an enum declaration.
10161bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10162 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10163 QualType T = TI->getType();
10164
Eli Friedman2fcff832012-12-18 02:37:32 +000010165 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010166 return false;
10167
Eli Friedman2fcff832012-12-18 02:37:32 +000010168 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10169 if (BT->isInteger())
10170 return false;
10171
Richard Smithf1c66b42012-03-14 23:13:10 +000010172 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10173 return true;
10174}
10175
10176/// Check whether this is a valid redeclaration of a previous enumeration.
10177/// \return true if the redeclaration was invalid.
10178bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10179 QualType EnumUnderlyingTy,
10180 const EnumDecl *Prev) {
10181 bool IsFixed = !EnumUnderlyingTy.isNull();
10182
10183 if (IsScoped != Prev->isScoped()) {
10184 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10185 << Prev->isScoped();
10186 Diag(Prev->getLocation(), diag::note_previous_use);
10187 return true;
10188 }
10189
10190 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010191 if (!EnumUnderlyingTy->isDependentType() &&
10192 !Prev->getIntegerType()->isDependentType() &&
10193 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010194 Prev->getIntegerType())) {
10195 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10196 << EnumUnderlyingTy << Prev->getIntegerType();
10197 Diag(Prev->getLocation(), diag::note_previous_use);
10198 return true;
10199 }
10200 } else if (IsFixed != Prev->isFixed()) {
10201 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10202 << Prev->isFixed();
10203 Diag(Prev->getLocation(), diag::note_previous_use);
10204 return true;
10205 }
10206
10207 return false;
10208}
10209
Joao Matos6666ed42012-08-31 18:45:21 +000010210/// \brief Get diagnostic %select index for tag kind for
10211/// redeclaration diagnostic message.
10212/// WARNING: Indexes apply to particular diagnostics only!
10213///
10214/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010215static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010216 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010217 case TTK_Struct: return 0;
10218 case TTK_Interface: return 1;
10219 case TTK_Class: return 2;
10220 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010221 }
Joao Matos6666ed42012-08-31 18:45:21 +000010222}
10223
10224/// \brief Determine if tag kind is a class-key compatible with
10225/// class for redeclaration (class, struct, or __interface).
10226///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010227/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010228static bool isClassCompatTagKind(TagTypeKind Tag)
10229{
10230 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10231}
10232
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010233/// \brief Determine whether a tag with a given kind is acceptable
10234/// as a redeclaration of the given tag declaration.
10235///
10236/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010237bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010238 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010239 SourceLocation NewTagLoc,
10240 const IdentifierInfo &Name) {
10241 // C++ [dcl.type.elab]p3:
10242 // The class-key or enum keyword present in the
10243 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010244 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010245 // refers. This rule also applies to the form of
10246 // elaborated-type-specifier that declares a class-name or
10247 // friend class since it can be construed as referring to the
10248 // definition of the class. Thus, in any
10249 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010250 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010251 // used to refer to a union (clause 9), and either the class or
10252 // struct class-key shall be used to refer to a class (clause 9)
10253 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010254 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010255 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010256 if (OldTag == NewTag)
10257 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010258
Joao Matos6666ed42012-08-31 18:45:21 +000010259 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010260 // Warn about the struct/class tag mismatch.
10261 bool isTemplate = false;
10262 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10263 isTemplate = Record->getDescribedClassTemplate();
10264
Richard Trieubbf34c02011-06-10 03:11:26 +000010265 if (!ActiveTemplateInstantiations.empty()) {
10266 // In a template instantiation, do not offer fix-its for tag mismatches
10267 // since they usually mess up the template instead of fixing the problem.
10268 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010269 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10270 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010271 return true;
10272 }
10273
10274 if (isDefinition) {
10275 // On definitions, check previous tags and issue a fix-it for each
10276 // one that doesn't match the current tag.
10277 if (Previous->getDefinition()) {
10278 // Don't suggest fix-its for redefinitions.
10279 return true;
10280 }
10281
10282 bool previousMismatch = false;
10283 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10284 E(Previous->redecls_end()); I != E; ++I) {
10285 if (I->getTagKind() != NewTag) {
10286 if (!previousMismatch) {
10287 previousMismatch = true;
10288 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010289 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10290 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010291 }
10292 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010293 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010294 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010295 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010296 }
10297 }
10298 return true;
10299 }
10300
10301 // Check for a previous definition. If current tag and definition
10302 // are same type, do nothing. If no definition, but disagree with
10303 // with previous tag type, give a warning, but no fix-it.
10304 const TagDecl *Redecl = Previous->getDefinition() ?
10305 Previous->getDefinition() : Previous;
10306 if (Redecl->getTagKind() == NewTag) {
10307 return true;
10308 }
10309
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010310 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010311 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10312 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010313 Diag(Redecl->getLocation(), diag::note_previous_use);
10314
10315 // If there is a previous defintion, suggest a fix-it.
10316 if (Previous->getDefinition()) {
10317 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010318 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010319 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010320 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010321 }
10322
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010323 return true;
10324 }
10325 return false;
10326}
10327
Steve Naroff08d92e42007-09-15 18:49:24 +000010328/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010329/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010330/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010331/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010332Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010333 SourceLocation KWLoc, CXXScopeSpec &SS,
10334 IdentifierInfo *Name, SourceLocation NameLoc,
10335 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010336 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010337 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010338 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010339 SourceLocation ScopedEnumKWLoc,
10340 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010341 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010342 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010343 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010344 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010345 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010346 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010347
Douglas Gregor402abb52009-05-28 23:31:59 +000010348 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010349 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010350 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010351
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010352 // FIXME: Check explicit specializations more carefully.
10353 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010354 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010355
10356 // We only need to do this matching if we have template parameters
10357 // or a scope specifier, which also conveniently avoids this work
10358 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010359 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010360 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010361 if (TemplateParameterList *TemplateParams =
10362 MatchTemplateParametersToScopeSpecifier(
10363 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10364 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010365 if (Kind == TTK_Enum) {
10366 Diag(KWLoc, diag::err_enum_template);
10367 return 0;
10368 }
10369
Douglas Gregord85bea22009-09-26 06:47:28 +000010370 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010371 // This is a declaration or definition of a class template (which may
10372 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010373
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010374 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010375 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010376
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010377 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010378 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010379 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010380 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010381 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010382 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010383 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010384 return Result.get();
10385 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010386 // The "template<>" header is extraneous.
10387 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010388 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010389 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010390 }
Mike Stump1eb44332009-09-09 15:08:12 +000010391 }
10392 }
10393
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010394 // Figure out the underlying type if this a enum declaration. We need to do
10395 // this early, because it's needed to detect if this is an incompatible
10396 // redeclaration.
10397 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10398
10399 if (Kind == TTK_Enum) {
10400 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10401 // No underlying type explicitly specified, or we failed to parse the
10402 // type, default to int.
10403 EnumUnderlying = Context.IntTy.getTypePtr();
10404 else if (UnderlyingType.get()) {
10405 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10406 // integral type; any cv-qualification is ignored.
10407 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010408 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010409 EnumUnderlying = TI;
10410
Richard Smithf1c66b42012-03-14 23:13:10 +000010411 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010412 // Recover by falling back to int.
10413 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010414
Richard Smithf1c66b42012-03-14 23:13:10 +000010415 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010416 UPPC_FixedUnderlyingType))
10417 EnumUnderlying = Context.IntTy.getTypePtr();
10418
David Blaikie4e4d0842012-03-11 07:00:24 +000010419 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010420 // Microsoft enums are always of int type.
10421 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010422 }
10423
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010424 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010425 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010426 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010427
Chandler Carruth7bf36002010-03-01 21:17:36 +000010428 RedeclarationKind Redecl = ForRedeclaration;
10429 if (TUK == TUK_Friend || TUK == TUK_Reference)
10430 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010431
10432 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010433 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010434 if (Name && SS.isNotEmpty()) {
10435 // We have a nested-name tag ('struct foo::bar').
10436
10437 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010438 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010439 Name = 0;
10440 goto CreateNewDecl;
10441 }
10442
John McCallc4e70192009-09-11 04:59:25 +000010443 // If this is a friend or a reference to a class in a dependent
10444 // context, don't try to make a decl for it.
10445 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10446 DC = computeDeclContext(SS, false);
10447 if (!DC) {
10448 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010449 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010450 }
John McCall77bb1aa2010-05-01 00:40:08 +000010451 } else {
10452 DC = computeDeclContext(SS, true);
10453 if (!DC) {
10454 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10455 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010456 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010457 }
John McCallc4e70192009-09-11 04:59:25 +000010458 }
10459
John McCall77bb1aa2010-05-01 00:40:08 +000010460 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010461 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010462
Douglas Gregor1931b442009-02-03 00:34:39 +000010463 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010464 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010465 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010466
John McCall68263142009-11-18 22:49:29 +000010467 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010468 return 0;
John McCall6e247262009-10-10 05:48:19 +000010469
John McCall68263142009-11-18 22:49:29 +000010470 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010471 // Name lookup did not find anything. However, if the
10472 // nested-name-specifier refers to the current instantiation,
10473 // and that current instantiation has any dependent base
10474 // classes, we might find something at instantiation time: treat
10475 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010476 // But this only makes any sense for reference-like lookups.
10477 if (Previous.wasNotFoundInCurrentInstantiation() &&
10478 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010479 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010480 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010481 }
10482
10483 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010484 Diag(NameLoc, diag::err_not_tag_in_scope)
10485 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010486 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010487 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010488 goto CreateNewDecl;
10489 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010490 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010491 // If this is a named struct, check to see if there was a previous forward
10492 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010493 // FIXME: We're looking into outer scopes here, even when we
10494 // shouldn't be. Doing so can result in ambiguities that we
10495 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010496 LookupName(Previous, S);
10497
John McCallc96cd7a2013-03-20 01:53:00 +000010498 // When declaring or defining a tag, ignore ambiguities introduced
10499 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010500 if (Previous.isAmbiguous() &&
10501 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010502 LookupResult::Filter F = Previous.makeFilter();
10503 while (F.hasNext()) {
10504 NamedDecl *ND = F.next();
10505 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10506 F.erase();
10507 }
10508 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010509 }
John McCallc96cd7a2013-03-20 01:53:00 +000010510
10511 // C++11 [namespace.memdef]p3:
10512 // If the name in a friend declaration is neither qualified nor
10513 // a template-id and the declaration is a function or an
10514 // elaborated-type-specifier, the lookup to determine whether
10515 // the entity has been previously declared shall not consider
10516 // any scopes outside the innermost enclosing namespace.
10517 //
10518 // Does it matter that this should be by scope instead of by
10519 // semantic context?
10520 if (!Previous.empty() && TUK == TUK_Friend) {
10521 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10522 LookupResult::Filter F = Previous.makeFilter();
10523 while (F.hasNext()) {
10524 NamedDecl *ND = F.next();
10525 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010526 if (DC->isFileContext() &&
10527 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010528 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010529 FriendSawTagOutsideEnclosingNamespace = true;
10530 }
John McCallc96cd7a2013-03-20 01:53:00 +000010531 }
10532 F.done();
10533 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010534
John McCall68263142009-11-18 22:49:29 +000010535 // Note: there used to be some attempt at recovery here.
10536 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010537 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010538
David Blaikie4e4d0842012-03-11 07:00:24 +000010539 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010540 // FIXME: This makes sure that we ignore the contexts associated
10541 // with C structs, unions, and enums when looking for a matching
10542 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010543 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010544 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10545 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010546 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010547 } else if (S->isFunctionPrototypeScope()) {
10548 // If this is an enum declaration in function prototype scope, set its
10549 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010550 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010551 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010552 }
10553
John McCall68263142009-11-18 22:49:29 +000010554 if (Previous.isSingleResult() &&
10555 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010556 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010557 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010558 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010559 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010560 }
10561
David Blaikie4e4d0842012-03-11 07:00:24 +000010562 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010563 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010564 // This is a declaration of or a reference to "std::bad_alloc".
10565 isStdBadAlloc = true;
10566
John McCall68263142009-11-18 22:49:29 +000010567 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010568 // std::bad_alloc has been implicitly declared (but made invisible to
10569 // name lookup). Fill in this implicit declaration as the previous
10570 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010571 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010572 }
10573 }
John McCall68263142009-11-18 22:49:29 +000010574
John McCall9c86b512010-03-25 21:28:06 +000010575 // If we didn't find a previous declaration, and this is a reference
10576 // (or friend reference), move to the correct scope. In C++, we
10577 // also need to do a redeclaration lookup there, just in case
10578 // there's a shadow friend decl.
10579 if (Name && Previous.empty() &&
10580 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10581 if (Invalid) goto CreateNewDecl;
10582 assert(SS.isEmpty());
10583
10584 if (TUK == TUK_Reference) {
10585 // C++ [basic.scope.pdecl]p5:
10586 // -- for an elaborated-type-specifier of the form
10587 //
10588 // class-key identifier
10589 //
10590 // if the elaborated-type-specifier is used in the
10591 // decl-specifier-seq or parameter-declaration-clause of a
10592 // function defined in namespace scope, the identifier is
10593 // declared as a class-name in the namespace that contains
10594 // the declaration; otherwise, except as a friend
10595 // declaration, the identifier is declared in the smallest
10596 // non-class, non-function-prototype scope that contains the
10597 // declaration.
10598 //
10599 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10600 // C structs and unions.
10601 //
10602 // It is an error in C++ to declare (rather than define) an enum
10603 // type, including via an elaborated type specifier. We'll
10604 // diagnose that later; for now, declare the enum in the same
10605 // scope as we would have picked for any other tag type.
10606 //
10607 // GNU C also supports this behavior as part of its incomplete
10608 // enum types extension, while GNU C++ does not.
10609 //
10610 // Find the context where we'll be declaring the tag.
10611 // FIXME: We would like to maintain the current DeclContext as the
10612 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010613 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010614 SearchDC = SearchDC->getParent();
10615
10616 // Find the scope where we'll be declaring the tag.
10617 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010618 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010619 S->isFunctionPrototypeScope()) ||
10620 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010621 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010622 S = S->getParent();
10623 } else {
10624 assert(TUK == TUK_Friend);
10625 // C++ [namespace.memdef]p3:
10626 // If a friend declaration in a non-local class first declares a
10627 // class or function, the friend class or function is a member of
10628 // the innermost enclosing namespace.
10629 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010630 }
10631
John McCall0d6b1642010-04-23 18:46:30 +000010632 // In C++, we need to do a redeclaration lookup to properly
10633 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010634 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010635 Previous.setRedeclarationKind(ForRedeclaration);
10636 LookupQualifiedName(Previous, SearchDC);
10637 }
10638 }
10639
John McCall68263142009-11-18 22:49:29 +000010640 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010641 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010642
10643 // It's okay to have a tag decl in the same scope as a typedef
10644 // which hides a tag decl in the same scope. Finding this
10645 // insanity with a redeclaration lookup can only actually happen
10646 // in C++.
10647 //
10648 // This is also okay for elaborated-type-specifiers, which is
10649 // technically forbidden by the current standard but which is
10650 // okay according to the likely resolution of an open issue;
10651 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010652 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010653 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010654 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10655 TagDecl *Tag = TT->getDecl();
10656 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010657 Tag->getDeclContext()->getRedeclContext()
10658 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010659 PrevDecl = Tag;
10660 Previous.clear();
10661 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010662 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010663 }
10664 }
10665 }
10666 }
10667
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010668 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010669 // If this is a use of a previous tag, or if the tag is already declared
10670 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010671 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010672 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010673 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010674 // Make sure that this wasn't declared as an enum and now used as a
10675 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010676 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10677 TUK == TUK_Definition, KWLoc,
10678 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010679 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010680 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10681 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010682 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010683 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010684 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010685 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10686 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010687 else
10688 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010689 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010690
Mike Stump1eb44332009-09-09 15:08:12 +000010691 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010692 Kind = PrevTagDecl->getTagKind();
10693 else {
10694 // Recover by making this an anonymous redefinition.
10695 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010696 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010697 Invalid = true;
10698 }
10699 }
10700
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010701 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10702 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10703
Richard Smithbdad7a22012-01-10 01:33:14 +000010704 // If this is an elaborated-type-specifier for a scoped enumeration,
10705 // the 'class' keyword is not necessary and not permitted.
10706 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10707 if (ScopedEnum)
10708 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10709 << PrevEnum->isScoped()
10710 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10711 return PrevTagDecl;
10712 }
10713
Richard Smithf1c66b42012-03-14 23:13:10 +000010714 QualType EnumUnderlyingTy;
10715 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10716 EnumUnderlyingTy = TI->getType();
10717 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10718 EnumUnderlyingTy = QualType(T, 0);
10719
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010720 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010721 // returning the previous declaration, unless this is a definition,
10722 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010723 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10724 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010725 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010726 }
10727
David Majnemer2ec2b842013-06-11 03:51:23 +000010728 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010729 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010730 // except that a nested class or member class template can be declared
10731 // and then later defined.
10732 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10733 S->isDeclScope(PrevDecl)) {
10734 Diag(NameLoc, diag::ext_member_redeclared);
10735 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10736 }
10737
Douglas Gregora3a83512009-04-01 23:51:29 +000010738 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010739 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010740
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010741 // FIXME: In the future, return a variant or some other clue
10742 // for the consumer of this Decl to know it doesn't own it.
10743 // For our current ASTs this shouldn't be a problem, but will
10744 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010745 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010746 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010747 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010748
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010749 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010750 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010751 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010752 // If we're defining a specialization and the previous definition
10753 // is from an implicit instantiation, don't emit an error
10754 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010755 bool IsExplicitSpecializationAfterInstantiation = false;
10756 if (isExplicitSpecialization) {
10757 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10758 IsExplicitSpecializationAfterInstantiation =
10759 RD->getTemplateSpecializationKind() !=
10760 TSK_ExplicitSpecialization;
10761 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10762 IsExplicitSpecializationAfterInstantiation =
10763 ED->getTemplateSpecializationKind() !=
10764 TSK_ExplicitSpecialization;
10765 }
10766
10767 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010768 // A redeclaration in function prototype scope in C isn't
10769 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010770 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010771 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10772 else
10773 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010774 Diag(Def->getLocation(), diag::note_previous_definition);
10775 // If this is a redefinition, recover by making this
10776 // struct be anonymous, which will make any later
10777 // references get the previous definition.
10778 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010779 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010780 Invalid = true;
10781 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010782 } else {
10783 // If the type is currently being defined, complain
10784 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010785 const TagType *Tag
10786 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010787 if (Tag->isBeingDefined()) {
10788 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010789 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010790 diag::note_previous_definition);
10791 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010792 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010793 Invalid = true;
10794 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010795 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010796
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010797 // Okay, this is definition of a previously declared or referenced
10798 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010799 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010800 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010801 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010802 // have a definition. Just create a new decl.
10803
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010804 } else {
10805 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010806 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010807 // new decl/type. We set PrevDecl to NULL so that the entities
10808 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010809 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010810 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010811 // If we get here, we're going to create a new Decl. If PrevDecl
10812 // is non-NULL, it's a definition of the tag declared by
10813 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010814
10815
10816 // Otherwise, PrevDecl is not a tag, but was found with tag
10817 // lookup. This is only actually possible in C++, where a few
10818 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010819 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010820 // Use a better diagnostic if an elaborated-type-specifier
10821 // found the wrong kind of type on the first
10822 // (non-redeclaration) lookup.
10823 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10824 !Previous.isForRedeclaration()) {
10825 unsigned Kind = 0;
10826 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010827 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10828 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010829 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10830 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10831 Invalid = true;
10832
10833 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010834 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10835 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010836 // do nothing
10837
10838 // Diagnose implicit declarations introduced by elaborated types.
10839 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10840 unsigned Kind = 0;
10841 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010842 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10843 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010844 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10845 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10846 Invalid = true;
10847
10848 // Otherwise it's a declaration. Call out a particularly common
10849 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010850 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10851 unsigned Kind = 0;
10852 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010853 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010854 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010855 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10856 Invalid = true;
10857
10858 // Otherwise, diagnose.
10859 } else {
10860 // The tag name clashes with something else in the target scope,
10861 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010862 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010863 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010864 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010865 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010866 }
John McCall0d6b1642010-04-23 18:46:30 +000010867
10868 // The existing declaration isn't relevant to us; we're in a
10869 // new scope, so clear out the previous declaration.
10870 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010871 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010872 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010873
Chris Lattnercc98eac2008-12-17 07:13:27 +000010874CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010875
John McCall68263142009-11-18 22:49:29 +000010876 TagDecl *PrevDecl = 0;
10877 if (Previous.isSingleResult())
10878 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10879
Reid Spencer5f016e22007-07-11 17:01:13 +000010880 // If there is an identifier, use the location of the identifier as the
10881 // location of the decl, otherwise use the location of the struct/union
10882 // keyword.
10883 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010884
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010885 // Otherwise, create a new declaration. If there is a previous
10886 // declaration of the same entity, the two will be linked via
10887 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010888 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010889
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010890 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010891 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010892 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10893 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010894 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010895 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010896 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010897 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010898 if (TUK != TUK_Definition && !Invalid) {
10899 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010900 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10901 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010902 // C++0x: 7.2p2: opaque-enum-declaration.
10903 // Conflicts are diagnosed above. Do nothing.
10904 }
10905 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010906 Diag(Loc, diag::ext_forward_ref_enum_def)
10907 << New;
10908 Diag(Def->getLocation(), diag::note_previous_definition);
10909 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010910 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010911 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010912 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010913 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010914 DiagID = diag::err_forward_ref_enum;
10915 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010916
10917 // If this is a forward-declared reference to an enumeration, make a
10918 // note of it; we won't actually be introducing the declaration into
10919 // the declaration context.
10920 if (TUK == TUK_Reference)
10921 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010922 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010923 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010924
10925 if (EnumUnderlying) {
10926 EnumDecl *ED = cast<EnumDecl>(New);
10927 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10928 ED->setIntegerTypeSourceInfo(TI);
10929 else
10930 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10931 ED->setPromotionType(ED->getIntegerType());
10932 }
10933
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010934 } else {
10935 // struct/union/class
10936
Reid Spencer5f016e22007-07-11 17:01:13 +000010937 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10938 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010939 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010940 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010941 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010942 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010943
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010944 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010945 StdBadAlloc = cast<CXXRecordDecl>(New);
10946 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010947 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010948 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010949 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010950
John McCallb6217662010-03-15 10:12:16 +000010951 // Maybe add qualifier info.
10952 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010953 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010954 // If this is either a declaration or a definition, check the
10955 // nested-name-specifier against the current context. We don't do this
10956 // for explicit specializations, because they have similar checking
10957 // (with more specific diagnostics) in the call to
10958 // CheckMemberSpecialization, below.
10959 if (!isExplicitSpecialization &&
10960 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10961 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10962 Invalid = true;
10963
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010964 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010965 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010966 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010967 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010968 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010969 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010970 }
10971 else
10972 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010973 }
10974
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010975 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10976 // Add alignment attributes if necessary; these attributes are checked when
10977 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010978 //
10979 // It is important for implementing the correct semantics that this
10980 // happen here (in act on tag decl). The #pragma pack stack is
10981 // maintained as a result of parser callbacks which can occur at
10982 // many points during the parsing of a struct declaration (because
10983 // the #pragma tokens are effectively skipped over during the
10984 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010985 if (TUK == TUK_Definition) {
10986 AddAlignmentAttributesForRecord(RD);
10987 AddMsStructLayoutForRecord(RD);
10988 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010989 }
10990
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010991 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010992 if (isExplicitSpecialization)
10993 Diag(New->getLocation(), diag::err_module_private_specialization)
10994 << 2
10995 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010996 // __module_private__ does not apply to local classes. However, we only
10997 // diagnose this as an error when the declaration specifiers are
10998 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010999 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000011000 New->setModulePrivate();
11001 }
11002
Douglas Gregorf6b11852009-10-08 15:14:33 +000011003 // If this is a specialization of a member class (of a class template),
11004 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000011005 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000011006 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000011007
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011008 if (Invalid)
11009 New->setInvalidDecl();
11010
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011011 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011012 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011013
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011014 // If we're declaring or defining a tag in function prototype scope
11015 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000011016 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000011017 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11018
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011019 // Set the lexical context. If the tag has a C++ scope specifier, the
11020 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000011021 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011022
John McCall02cace72009-08-28 07:59:38 +000011023 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000011024 // In Microsoft mode, a friend declaration also acts as a forward
11025 // declaration so we always pass true to setObjectOfFriendDecl to make
11026 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000011027 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000011028 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11029 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000011030
Anders Carlsson0cf88302009-03-26 01:19:02 +000011031 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000011032 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000011033 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000011034
John McCall0f434ec2009-07-31 02:45:11 +000011035 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011036 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000011037
Reid Spencer5f016e22007-07-11 17:01:13 +000011038 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000011039 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000011040 // We might be replacing an existing declaration in the lookup tables;
11041 // if so, borrow its access specifier.
11042 if (PrevDecl)
11043 New->setAccess(PrevDecl->getAccess());
11044
Sebastian Redl7a126a42010-08-31 00:36:30 +000011045 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011046 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000011047 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000011048 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11049 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000011050 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000011051 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011052 PushOnScopeChains(New, S, !IsForwardReference);
11053 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011054 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011055
Douglas Gregor4920f1f2009-01-12 22:49:06 +000011056 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011057 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000011058 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000011059
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011060 // If this is the C FILE type, notify the AST context.
11061 if (IdentifierInfo *II = New->getIdentifier())
11062 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011063 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011064 II->isStr("FILE"))
11065 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011066
James Molloy16f1f712012-02-29 10:24:19 +000011067 // If we were in function prototype scope (and not in C++ mode), add this
11068 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011069 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011070 InFunctionDeclarator && Name)
11071 DeclsInPrototypeScope.push_back(New);
11072
Rafael Espindola98ae8342012-05-10 02:50:16 +000011073 if (PrevDecl)
11074 mergeDeclAttributes(New, PrevDecl);
11075
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011076 // If there's a #pragma GCC visibility in scope, set the visibility of this
11077 // record.
11078 AddPushedVisibilityAttribute(New);
11079
Douglas Gregor402abb52009-05-28 23:31:59 +000011080 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011081 // In C++, don't return an invalid declaration. We can't recover well from
11082 // the cases where we make the type anonymous.
11083 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011084}
11085
John McCalld226f652010-08-21 09:40:31 +000011086void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011087 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011088 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011089
Douglas Gregor72de6672009-01-08 20:45:30 +000011090 // Enter the tag context.
11091 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011092
11093 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011094
11095 // If there's a #pragma GCC visibility in scope, set the visibility of this
11096 // record.
11097 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011098}
Douglas Gregor72de6672009-01-08 20:45:30 +000011099
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011100Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011101 assert(isa<ObjCContainerDecl>(IDecl) &&
11102 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11103 DeclContext *OCD = cast<DeclContext>(IDecl);
11104 assert(getContainingDC(OCD) == CurContext &&
11105 "The next DeclContext should be lexically contained in the current one.");
11106 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011107 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011108}
11109
John McCalld226f652010-08-21 09:40:31 +000011110void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011111 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011112 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011113 SourceLocation LBraceLoc) {
11114 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011115 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011116
John McCallf9368152009-12-20 07:58:13 +000011117 FieldCollector->StartClass();
11118
11119 if (!Record->getIdentifier())
11120 return;
11121
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011122 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011123 Record->addAttr(new (Context)
11124 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11125
John McCallf9368152009-12-20 07:58:13 +000011126 // C++ [class]p2:
11127 // [...] The class-name is also inserted into the scope of the
11128 // class itself; this is known as the injected-class-name. For
11129 // purposes of access checking, the injected-class-name is treated
11130 // as if it were a public member name.
11131 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011132 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11133 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011134 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011135 /*PrevDecl=*/0,
11136 /*DelayTypeCreation=*/true);
11137 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011138 InjectedClassName->setImplicit();
11139 InjectedClassName->setAccess(AS_public);
11140 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11141 InjectedClassName->setDescribedClassTemplate(Template);
11142 PushOnScopeChains(InjectedClassName, S);
11143 assert(InjectedClassName->isInjectedClassName() &&
11144 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011145}
11146
John McCalld226f652010-08-21 09:40:31 +000011147void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011148 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011149 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011150 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011151 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011152
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011153 // Make sure we "complete" the definition even it is invalid.
11154 if (Tag->isBeingDefined()) {
11155 assert(Tag->isInvalidDecl() && "We should already have completed it");
11156 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11157 RD->completeDefinition();
11158 }
11159
Douglas Gregor72de6672009-01-08 20:45:30 +000011160 if (isa<CXXRecordDecl>(Tag))
11161 FieldCollector->FinishClass();
11162
11163 // Exit this scope of this tag's definition.
11164 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011165
11166 if (getCurLexicalContext()->isObjCContainer() &&
11167 Tag->getDeclContext()->isFileContext())
11168 Tag->setTopLevelDeclInObjCContainer();
11169
Douglas Gregor72de6672009-01-08 20:45:30 +000011170 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011171 if (!Tag->isInvalidDecl())
11172 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011173}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011174
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011175void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011176 // Exit this scope of this interface definition.
11177 PopDeclContext();
11178}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011179
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011180void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011181 assert(DC == CurContext && "Mismatch of container contexts");
11182 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011183 ActOnObjCContainerFinishDefinition();
11184}
11185
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011186void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11187 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011188 OriginalLexicalContext = 0;
11189}
11190
John McCalld226f652010-08-21 09:40:31 +000011191void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011192 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011193 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011194 Tag->setInvalidDecl();
11195
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011196 // Make sure we "complete" the definition even it is invalid.
11197 if (Tag->isBeingDefined()) {
11198 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11199 RD->completeDefinition();
11200 }
11201
John McCalla8cab012010-03-17 19:25:57 +000011202 // We're undoing ActOnTagStartDefinition here, not
11203 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11204 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011205
11206 PopDeclContext();
11207}
11208
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011209// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011210ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11211 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011212 QualType FieldTy, bool IsMsStruct,
11213 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011214 // Default to true; that shouldn't confuse checks for emptiness
11215 if (ZeroWidth)
11216 *ZeroWidth = true;
11217
Chris Lattner24793662009-03-05 22:45:59 +000011218 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011219 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011220 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011221 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011222 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011223 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011224 if (FieldName)
11225 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11226 << FieldName << FieldTy << BitWidth->getSourceRange();
11227 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11228 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011229 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11230 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011231 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011232
11233 // If the bit-width is type- or value-dependent, don't try to check
11234 // it now.
11235 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011236 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011237
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011238 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011239 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11240 if (ICE.isInvalid())
11241 return ICE;
11242 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011243
Eli Friedman1d954f62009-08-15 21:55:26 +000011244 if (Value != 0 && ZeroWidth)
11245 *ZeroWidth = false;
11246
Chris Lattnercd087072008-12-12 04:56:04 +000011247 // Zero-width bitfield is ok for anonymous field.
11248 if (Value == 0 && FieldName)
11249 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011250
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011251 if (Value.isSigned() && Value.isNegative()) {
11252 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011253 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011254 << FieldName << Value.toString(10);
11255 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11256 << Value.toString(10);
11257 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011258
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011259 if (!FieldTy->isDependentType()) {
11260 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011261 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011262 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011263 if (FieldName)
11264 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11265 << FieldName << (unsigned)Value.getZExtValue()
11266 << (unsigned)TypeSize;
11267
11268 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11269 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11270 }
11271
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011272 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011273 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11274 << FieldName << (unsigned)Value.getZExtValue()
11275 << (unsigned)TypeSize;
11276 else
11277 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11278 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011279 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011280 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011281
Richard Smith282e7e62012-02-04 09:53:13 +000011282 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011283}
11284
Richard Smith7a614d82011-06-11 17:19:42 +000011285/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011286/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011287Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011288 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011289 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011290 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011291 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011292 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011293}
11294
11295/// HandleField - Analyze a field of a C struct or a C++ data member.
11296///
11297FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11298 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011299 Declarator &D, Expr *BitWidth,
11300 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011301 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011302 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011303 SourceLocation Loc = DeclStart;
11304 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011305
John McCallbf1a0282010-06-04 23:28:52 +000011306 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11307 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011308 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011309 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011310
Douglas Gregore1862692010-12-15 23:18:36 +000011311 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11312 UPPC_DataMemberType)) {
11313 D.setInvalidType();
11314 T = Context.IntTy;
11315 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11316 }
11317 }
11318
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011319 // TR 18037 does not allow fields to be declared with address spaces.
11320 if (T.getQualifiers().hasAddressSpace()) {
11321 Diag(Loc, diag::err_field_with_address_space);
11322 D.setInvalidType();
11323 }
11324
Guy Benyeie6b9d802013-01-20 12:31:11 +000011325 // OpenCL 1.2 spec, s6.9 r:
11326 // The event type cannot be used to declare a structure or union field.
11327 if (LangOpts.OpenCL && T->isEventT()) {
11328 Diag(Loc, diag::err_event_t_struct_field);
11329 D.setInvalidType();
11330 }
11331
Richard Smithc7f81162013-03-18 22:52:47 +000011332 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011333
Richard Smithec642442013-04-12 22:46:28 +000011334 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11335 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11336 diag::err_invalid_thread)
11337 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011338
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011339 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011340 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011341 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11342 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011343 switch (Previous.getResultKind()) {
11344 case LookupResult::Found:
11345 case LookupResult::FoundUnresolvedValue:
11346 PrevDecl = Previous.getAsSingle<NamedDecl>();
11347 break;
11348
11349 case LookupResult::FoundOverloaded:
11350 PrevDecl = Previous.getRepresentativeDecl();
11351 break;
11352
11353 case LookupResult::NotFound:
11354 case LookupResult::NotFoundInCurrentInstantiation:
11355 case LookupResult::Ambiguous:
11356 break;
11357 }
11358 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011359
11360 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11361 // Maybe we will complain about the shadowed template parameter.
11362 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11363 // Just pretend that we didn't see the previous declaration.
11364 PrevDecl = 0;
11365 }
11366
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011367 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11368 PrevDecl = 0;
11369
Steve Naroffea218b82009-07-14 14:58:18 +000011370 bool Mutable
11371 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011372 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011373 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011374 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011375 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011376
11377 if (NewFD->isInvalidDecl())
11378 Record->setInvalidDecl();
11379
Douglas Gregor591dc842011-09-12 16:11:24 +000011380 if (D.getDeclSpec().isModulePrivateSpecified())
11381 NewFD->setModulePrivate();
11382
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011383 if (NewFD->isInvalidDecl() && PrevDecl) {
11384 // Don't introduce NewFD into scope; there's already something
11385 // with the same name in the same scope.
11386 } else if (II) {
11387 PushOnScopeChains(NewFD, S);
11388 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011389 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011390
11391 return NewFD;
11392}
11393
11394/// \brief Build a new FieldDecl and check its well-formedness.
11395///
11396/// This routine builds a new FieldDecl given the fields name, type,
11397/// record, etc. \p PrevDecl should refer to any previous declaration
11398/// with the same name and in the same scope as the field to be
11399/// created.
11400///
11401/// \returns a new FieldDecl.
11402///
Mike Stump1eb44332009-09-09 15:08:12 +000011403/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011404FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011405 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011406 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011407 bool Mutable, Expr *BitWidth,
11408 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011409 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011410 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011411 Declarator *D) {
11412 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011413 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011414 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011415
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011416 // If we receive a broken type, recover by assuming 'int' and
11417 // marking this declaration as invalid.
11418 if (T.isNull()) {
11419 InvalidDecl = true;
11420 T = Context.IntTy;
11421 }
11422
Eli Friedman721e77d2009-12-07 00:22:08 +000011423 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011424 if (!EltTy->isDependentType()) {
11425 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11426 // Fields of incomplete type force their record to be invalid.
11427 Record->setInvalidDecl();
11428 InvalidDecl = true;
11429 } else {
11430 NamedDecl *Def;
11431 EltTy->isIncompleteType(&Def);
11432 if (Def && Def->isInvalidDecl()) {
11433 Record->setInvalidDecl();
11434 InvalidDecl = true;
11435 }
11436 }
John McCall2d7d2d92010-08-16 23:42:35 +000011437 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011438
Joey Gouly617bb312013-01-17 17:35:00 +000011439 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11440 if (BitWidth && getLangOpts().OpenCL) {
11441 Diag(Loc, diag::err_opencl_bitfields);
11442 InvalidDecl = true;
11443 }
11444
Reid Spencer5f016e22007-07-11 17:01:13 +000011445 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11446 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011447 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011448 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011449 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011450
11451 TypeSourceInfo *FixedTInfo =
11452 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11453 SizeIsNegative,
11454 Oversized);
11455 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011456 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011457 TInfo = FixedTInfo;
11458 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011459 } else {
11460 if (SizeIsNegative)
11461 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011462 else if (Oversized.getBoolValue())
11463 Diag(Loc, diag::err_array_too_large)
11464 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011465 else
11466 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011467 InvalidDecl = true;
11468 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011469 }
Mike Stump1eb44332009-09-09 15:08:12 +000011470
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011471 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011472 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11473 diag::err_abstract_type_in_decl,
11474 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011475 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011476
Eli Friedman1d954f62009-08-15 21:55:26 +000011477 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011478 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011479 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011480 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11481 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011482 if (!BitWidth) {
11483 InvalidDecl = true;
11484 BitWidth = 0;
11485 ZeroWidth = false;
11486 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011487 }
Mike Stump1eb44332009-09-09 15:08:12 +000011488
John McCall4bde1e12010-06-04 08:34:12 +000011489 // Check that 'mutable' is consistent with the type of the declaration.
11490 if (!InvalidDecl && Mutable) {
11491 unsigned DiagID = 0;
11492 if (T->isReferenceType())
11493 DiagID = diag::err_mutable_reference;
11494 else if (T.isConstQualified())
11495 DiagID = diag::err_mutable_const;
11496
11497 if (DiagID) {
11498 SourceLocation ErrLoc = Loc;
11499 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11500 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11501 Diag(ErrLoc, DiagID);
11502 Mutable = false;
11503 InvalidDecl = true;
11504 }
11505 }
11506
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011507 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011508 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011509 if (InvalidDecl)
11510 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011511
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011512 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11513 Diag(Loc, diag::err_duplicate_member) << II;
11514 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11515 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011516 }
11517
David Blaikie4e4d0842012-03-11 07:00:24 +000011518 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011519 if (Record->isUnion()) {
11520 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11521 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11522 if (RDecl->getDefinition()) {
11523 // C++ [class.union]p1: An object of a class with a non-trivial
11524 // constructor, a non-trivial copy constructor, a non-trivial
11525 // destructor, or a non-trivial copy assignment operator
11526 // cannot be a member of a union, nor can an array of such
11527 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011528 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011529 NewFD->setInvalidDecl();
11530 }
11531 }
11532
11533 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011534 // the program is ill-formed, except when compiling with MSVC extensions
11535 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011536 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011537 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11538 diag::ext_union_member_of_reference_type :
11539 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011540 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011541 if (!getLangOpts().MicrosoftExt)
11542 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011543 }
11544 }
11545 }
11546
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011547 // FIXME: We need to pass in the attributes given an AST
11548 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011549 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011550 // FIXME: The current scope is almost... but not entirely... correct here.
11551 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011552
Richard Smithbe507b62013-02-01 08:12:08 +000011553 if (NewFD->hasAttrs())
11554 CheckAlignasUnderalignment(NewFD);
11555 }
11556
John McCallf85e1932011-06-15 23:02:42 +000011557 // In auto-retain/release, infer strong retension for fields of
11558 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011559 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011560 NewFD->setInvalidDecl();
11561
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011562 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011563 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011564
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011565 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011566 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011567}
11568
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011569bool Sema::CheckNontrivialField(FieldDecl *FD) {
11570 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011571 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011572
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011573 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11574 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011575
11576 QualType EltTy = Context.getBaseElementType(FD->getType());
11577 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011578 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011579 if (RDecl->getDefinition()) {
11580 // We check for copy constructors before constructors
11581 // because otherwise we'll never get complaints about
11582 // copy constructors.
11583
11584 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011585 // We're required to check for any non-trivial constructors. Since the
11586 // implicit default constructor is suppressed if there are any
11587 // user-declared constructors, we just need to check that there is a
11588 // trivial default constructor and a trivial copy constructor. (We don't
11589 // worry about move constructors here, since this is a C++98 check.)
11590 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011591 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011592 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011593 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011594 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011595 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011596 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011597 member = CXXDestructor;
11598
11599 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011600 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011601 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011602 // Objective-C++ ARC: it is an error to have a non-trivial field of
11603 // a union. However, system headers in Objective-C programs
11604 // occasionally have Objective-C lifetime objects within unions,
11605 // and rather than cause the program to fail, we make those
11606 // members unavailable.
11607 SourceLocation Loc = FD->getLocation();
11608 if (getSourceManager().isInSystemHeader(Loc)) {
11609 if (!FD->hasAttr<UnavailableAttr>())
11610 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011611 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011612 return false;
11613 }
11614 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011615
Richard Smith80ad52f2013-01-02 11:42:31 +000011616 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011617 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11618 diag::err_illegal_union_or_anon_struct_member)
11619 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011620 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011621 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011622 }
11623 }
11624 }
Richard Smithac713512012-12-08 02:53:02 +000011625
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011626 return false;
11627}
11628
Mike Stump1eb44332009-09-09 15:08:12 +000011629/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011630/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011631static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011632TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011633 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011634 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011635 case tok::objc_private: return ObjCIvarDecl::Private;
11636 case tok::objc_public: return ObjCIvarDecl::Public;
11637 case tok::objc_protected: return ObjCIvarDecl::Protected;
11638 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011639 }
11640}
11641
Mike Stump1eb44332009-09-09 15:08:12 +000011642/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011643/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011644Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011645 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011646 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011647 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011648
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011649 IdentifierInfo *II = D.getIdentifier();
11650 Expr *BitWidth = (Expr*)BitfieldWidth;
11651 SourceLocation Loc = DeclStart;
11652 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011653
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011654 // FIXME: Unnamed fields can be handled in various different ways, for
11655 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011656
John McCallbf1a0282010-06-04 23:28:52 +000011657 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11658 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011659
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011660 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011661 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011662 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011663 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011664 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011665 } else {
11666 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011667
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011668 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011669
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011670 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011671 if (T->isReferenceType()) {
11672 Diag(Loc, diag::err_ivar_reference_type);
11673 D.setInvalidType();
11674 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011675 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11676 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011677 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011678 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011679 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011680 }
Mike Stump1eb44332009-09-09 15:08:12 +000011681
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011682 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011683 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011684 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11685 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011686 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011687 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011688 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11689 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011690 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011691 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011692 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011693 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011694 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011695 EnclosingContext = IMPDecl->getClassInterface();
11696 assert(EnclosingContext && "Implementation has no class interface!");
11697 }
11698 else
11699 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011700 } else {
11701 if (ObjCCategoryDecl *CDecl =
11702 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011703 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011704 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011705 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011706 }
11707 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011708 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011709 }
Mike Stump1eb44332009-09-09 15:08:12 +000011710
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011711 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011712 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11713 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011714 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011715
Douglas Gregor72de6672009-01-08 20:45:30 +000011716 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011717 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011718 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011719 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011720 && !isa<TagDecl>(PrevDecl)) {
11721 Diag(Loc, diag::err_duplicate_member) << II;
11722 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11723 NewID->setInvalidDecl();
11724 }
11725 }
11726
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011727 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011728 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011729
Chris Lattnereaaebc72009-04-25 08:06:05 +000011730 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011731 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011732
John McCallf85e1932011-06-15 23:02:42 +000011733 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011734 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011735 NewID->setInvalidDecl();
11736
Douglas Gregor591dc842011-09-12 16:11:24 +000011737 if (D.getDeclSpec().isModulePrivateSpecified())
11738 NewID->setModulePrivate();
11739
Douglas Gregor72de6672009-01-08 20:45:30 +000011740 if (II) {
11741 // FIXME: When interfaces are DeclContexts, we'll need to add
11742 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011743 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011744 IdResolver.AddDecl(NewID);
11745 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011746
John McCall260611a2012-06-20 06:18:46 +000011747 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011748 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011749 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011750
John McCalld226f652010-08-21 09:40:31 +000011751 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011752}
11753
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011754/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011755/// class and class extensions. For every class \@interface and class
11756/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011757/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011758void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011759 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011760 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011761 return;
11762
11763 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11764 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11765
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011766 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011767 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011768 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011769 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011770 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011771 if (!CD->IsClassExtension())
11772 return;
11773 }
11774 // No need to add this to end of @implementation.
11775 else
11776 return;
11777 }
11778 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011779 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11780 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011781
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011782 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011783 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011784 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011785 Context.getTrivialTypeSourceInfo(Context.CharTy,
11786 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011787 ObjCIvarDecl::Private, BW,
11788 true);
11789 AllIvarDecls.push_back(Ivar);
11790}
11791
Robert Wilhelm834c0582013-08-09 18:02:13 +000011792void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11793 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11794 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011795 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011796
Eric Christopher6dba4a12012-07-19 22:22:51 +000011797 // If this is an Objective-C @implementation or category and we have
11798 // new fields here we should reset the layout of the interface since
11799 // it will now change.
11800 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11801 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11802 switch (DC->getKind()) {
11803 default: break;
11804 case Decl::ObjCCategory:
11805 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11806 break;
11807 case Decl::ObjCImplementation:
11808 Context.
11809 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11810 break;
11811 }
11812 }
11813
Eli Friedman11e70d72012-02-07 05:00:47 +000011814 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11815
11816 // Start counting up the number of named members; make sure to include
11817 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011818 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011819 if (Record) {
11820 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11821 e = Record->decls_end(); i != e; i++) {
11822 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11823 if (IFD->getDeclName())
11824 ++NumNamedMembers;
11825 }
11826 }
11827
11828 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011829 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011830
John McCallf85e1932011-06-15 23:02:42 +000011831 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011832 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011833 i != end; ++i) {
11834 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011835
Reid Spencer5f016e22007-07-11 17:01:13 +000011836 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011837 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011838
Douglas Gregor72de6672009-01-08 20:45:30 +000011839 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011840 // Remember all fields written by the user.
11841 RecFields.push_back(FD);
11842 }
Mike Stump1eb44332009-09-09 15:08:12 +000011843
Chris Lattner24793662009-03-05 22:45:59 +000011844 // If the field is already invalid for some reason, don't emit more
11845 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011846 if (FD->isInvalidDecl()) {
11847 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011848 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011849 }
Mike Stump1eb44332009-09-09 15:08:12 +000011850
Douglas Gregore7450f52009-03-24 19:52:54 +000011851 // C99 6.7.2.1p2:
11852 // A structure or union shall not contain a member with
11853 // incomplete or function type (hence, a structure shall not
11854 // contain an instance of itself, but may contain a pointer to
11855 // an instance of itself), except that the last member of a
11856 // structure with more than one named member may have incomplete
11857 // array type; such a structure (and any union containing,
11858 // possibly recursively, a member that is such a structure)
11859 // shall not be a member of a structure or an element of an
11860 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011861 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011862 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011863 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011864 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011865 FD->setInvalidDecl();
11866 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011867 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011868 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011869 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011870 ((getLangOpts().MicrosoftExt ||
11871 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011872 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011873 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011874 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011875 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011876 // as the sole element of a struct/class.
David Majnemer633c0c22013-11-02 10:38:05 +000011877 unsigned DiagID = 0;
11878 if (Record->isUnion())
11879 DiagID = getLangOpts().MicrosoftExt
11880 ? diag::ext_flexible_array_union_ms
11881 : getLangOpts().CPlusPlus
11882 ? diag::ext_flexible_array_union_gnu
11883 : diag::err_flexible_array_union;
11884 else if (Fields.size() == 1)
11885 DiagID = getLangOpts().MicrosoftExt
11886 ? diag::ext_flexible_array_empty_aggregate_ms
11887 : getLangOpts().CPlusPlus
11888 ? diag::ext_flexible_array_empty_aggregate_gnu
11889 : NumNamedMembers < 1
11890 ? diag::err_flexible_array_empty_aggregate
11891 : 0;
11892
11893 if (DiagID)
11894 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11895 << Record->getTagKind();
David Majnemer3a665572013-11-02 11:19:13 +000011896 // While the layout of types that contain virtual bases is not specified
11897 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11898 // virtual bases after the derived members. This would make a flexible
11899 // array member declared at the end of an object not adjacent to the end
11900 // of the type.
11901 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11902 if (RD->getNumVBases() != 0)
11903 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11904 << FD->getDeclName() << Record->getTagKind();
David Majnemer633c0c22013-11-02 10:38:05 +000011905 if (!getLangOpts().C99)
11906 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11907 << FD->getDeclName() << Record->getTagKind();
11908
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011909 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011910 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011911 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011912 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011913 FD->setInvalidDecl();
11914 EnclosingDecl->setInvalidDecl();
11915 continue;
11916 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011917 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011918 if (Record)
11919 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011920 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011921 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011922 diag::err_field_incomplete)) {
11923 // Incomplete type
11924 FD->setInvalidDecl();
11925 EnclosingDecl->setInvalidDecl();
11926 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011927 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011928 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11929 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011930 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011931 Record->setHasFlexibleArrayMember(true);
11932 } else {
11933 // If this is a struct/class and this is not the last element, reject
11934 // it. Note that GCC supports variable sized arrays in the middle of
11935 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011936 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011937 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011938 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011939 else {
11940 // We support flexible arrays at the end of structs in
11941 // other structs as an extension.
11942 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11943 << FD->getDeclName();
11944 if (Record)
11945 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011946 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011947 }
11948 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011949 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11950 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11951 diag::err_abstract_type_in_decl,
11952 AbstractIvarType)) {
11953 // Ivars can not have abstract class types
11954 FD->setInvalidDecl();
11955 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011956 if (Record && FDTTy->getDecl()->hasObjectMember())
11957 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011958 if (Record && FDTTy->getDecl()->hasVolatileMember())
11959 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011960 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011961 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011962 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11963 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11964 QualType T = Context.getObjCObjectPointerType(FD->getType());
11965 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011966 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11967 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11968 // It's an error in ARC if a field has lifetime.
11969 // We don't want to report this in a system header, though,
11970 // so we just make the field unavailable.
11971 // FIXME: that's really not sufficient; we need to make the type
11972 // itself invalid to, say, initialize or copy.
11973 QualType T = FD->getType();
11974 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11975 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11976 SourceLocation loc = FD->getLocation();
11977 if (getSourceManager().isInSystemHeader(loc)) {
11978 if (!FD->hasAttr<UnavailableAttr>()) {
11979 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11980 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011981 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011982 } else {
11983 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011984 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011985 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011986 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011987 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011988 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011989 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011990 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011991 if (FD->getType()->isObjCObjectPointerType() ||
11992 FD->getType().isObjCGCStrong())
11993 Record->setHasObjectMember(true);
11994 else if (Context.getAsArrayType(FD->getType())) {
11995 QualType BaseType = Context.getBaseElementType(FD->getType());
11996 if (BaseType->isRecordType() &&
11997 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011998 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011999 else if (BaseType->isObjCObjectPointerType() ||
12000 BaseType.isObjCGCStrong())
12001 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000012002 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000012003 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000012004 if (Record && FD->getType().isVolatileQualified())
12005 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000012006 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000012007 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000012008 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000012009 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000012010
Reid Spencer5f016e22007-07-11 17:01:13 +000012011 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000012012 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012013 bool Completed = false;
12014 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12015 if (!CXXRecord->isInvalidDecl()) {
12016 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000012017 for (CXXRecordDecl::conversion_iterator
12018 I = CXXRecord->conversion_begin(),
12019 E = CXXRecord->conversion_end(); I != E; ++I)
12020 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012021
12022 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000012023 if (CXXRecord->hasUserDeclaredDestructor()) {
12024 // Adjust user-defined destructor exception spec.
12025 if (getLangOpts().CPlusPlus11)
12026 AdjustDestructorExceptionSpec(CXXRecord,
12027 CXXRecord->getDestructor());
12028
12029 // The Microsoft ABI requires that we perform the destructor body
12030 // checks (i.e. operator delete() lookup) at every declaration, as
12031 // any translation unit may need to emit a deleting destructor.
12032 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12033 CheckDestructor(CXXRecord->getDestructor());
12034 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000012035
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012036 // Add any implicitly-declared members to this class.
12037 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12038
12039 // If we have virtual base classes, we may end up finding multiple
12040 // final overriders for a given virtual function. Check for this
12041 // problem now.
12042 if (CXXRecord->getNumVBases()) {
12043 CXXFinalOverriderMap FinalOverriders;
12044 CXXRecord->getFinalOverriders(FinalOverriders);
12045
12046 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12047 MEnd = FinalOverriders.end();
12048 M != MEnd; ++M) {
12049 for (OverridingMethods::iterator SO = M->second.begin(),
12050 SOEnd = M->second.end();
12051 SO != SOEnd; ++SO) {
12052 assert(SO->second.size() > 0 &&
12053 "Virtual function without overridding functions?");
12054 if (SO->second.size() == 1)
12055 continue;
12056
12057 // C++ [class.virtual]p2:
12058 // In a derived class, if a virtual member function of a base
12059 // class subobject has more than one final overrider the
12060 // program is ill-formed.
12061 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000012062 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012063 Diag(M->first->getLocation(),
12064 diag::note_overridden_virtual_function);
12065 for (OverridingMethods::overriding_iterator
12066 OM = SO->second.begin(),
12067 OMEnd = SO->second.end();
12068 OM != OMEnd; ++OM)
12069 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012070 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012071
12072 Record->setInvalidDecl();
12073 }
12074 }
12075 CXXRecord->completeDefinition(&FinalOverriders);
12076 Completed = true;
12077 }
12078 }
12079 }
12080 }
12081
12082 if (!Completed)
12083 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012084
Richard Smithbe507b62013-02-01 08:12:08 +000012085 if (Record->hasAttrs())
12086 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012087
Serge Pavlov142ab062013-11-14 02:13:03 +000012088 // Check if the structure/union declaration is a type that can have zero
12089 // size in C. For C this is a language extension, for C++ it may cause
12090 // compatibility problems.
12091 bool CheckForZeroSize;
Serge Pavlov122e6012013-06-08 13:29:58 +000012092 if (!getLangOpts().CPlusPlus) {
Serge Pavlov142ab062013-11-14 02:13:03 +000012093 CheckForZeroSize = true;
12094 } else {
12095 // For C++ filter out types that cannot be referenced in C code.
12096 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12097 CheckForZeroSize =
12098 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12099 !CXXRecord->isDependentType() &&
12100 CXXRecord->isCLike();
12101 }
12102 if (CheckForZeroSize) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012103 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012104 bool IsEmpty = true;
12105 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012106 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012107 E = Record->field_end();
12108 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12109 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012110 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012111 if (I->getBitWidthValue(Context) > 0)
12112 ZeroSize = false;
12113 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012114 ++NonBitFields;
12115 QualType FieldType = I->getType();
12116 if (FieldType->isIncompleteType() ||
12117 !Context.getTypeSizeInChars(FieldType).isZero())
12118 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012119 }
12120 }
12121
Serge Pavlov142ab062013-11-14 02:13:03 +000012122 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12123 // allowed in C++, but warn if its declaration is inside
12124 // extern "C" block.
12125 if (ZeroSize) {
12126 Diag(RecLoc, getLangOpts().CPlusPlus ?
12127 diag::warn_zero_size_struct_union_in_extern_c :
12128 diag::warn_zero_size_struct_union_compat)
12129 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12130 }
Serge Pavlov122e6012013-06-08 13:29:58 +000012131
Serge Pavlov142ab062013-11-14 02:13:03 +000012132 // Structs without named members are extension in C (C99 6.7.2.1p7),
12133 // but are accepted by GCC.
12134 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12135 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12136 diag::ext_no_named_members_in_struct_union)
12137 << Record->isUnion();
Serge Pavlov122e6012013-06-08 13:29:58 +000012138 }
12139 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012140 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012141 ObjCIvarDecl **ClsFields =
12142 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012143 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012144 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012145 // Add ivar's to class's DeclContext.
12146 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12147 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012148 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012149 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012150 // Must enforce the rule that ivars in the base classes may not be
12151 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012152 if (ID->getSuperClass())
12153 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012154 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012155 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012156 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012157 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12158 // Ivar declared in @implementation never belongs to the implementation.
12159 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012160 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012161 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012162 IMPDecl->setIvarLBraceLoc(LBrac);
12163 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012164 } else if (ObjCCategoryDecl *CDecl =
12165 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012166 // case of ivars in class extension; all other cases have been
12167 // reported as errors elsewhere.
12168 // FIXME. Class extension does not have a LocEnd field.
12169 // CDecl->setLocEnd(RBrac);
12170 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012171 // Diagnose redeclaration of private ivars.
12172 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012173 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012174 if (IDecl) {
12175 if (const ObjCIvarDecl *ClsIvar =
12176 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12177 Diag(ClsFields[i]->getLocation(),
12178 diag::err_duplicate_ivar_declaration);
12179 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12180 continue;
12181 }
Douglas Gregord3297242013-01-16 23:00:23 +000012182 for (ObjCInterfaceDecl::known_extensions_iterator
12183 Ext = IDecl->known_extensions_begin(),
12184 ExtEnd = IDecl->known_extensions_end();
12185 Ext != ExtEnd; ++Ext) {
12186 if (const ObjCIvarDecl *ClsExtIvar
12187 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012188 Diag(ClsFields[i]->getLocation(),
12189 diag::err_duplicate_ivar_declaration);
12190 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12191 continue;
12192 }
12193 }
12194 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012195 ClsFields[i]->setLexicalDeclContext(CDecl);
12196 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012197 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012198 CDecl->setIvarLBraceLoc(LBrac);
12199 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012200 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012201 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012202
12203 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012204 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012205}
12206
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012207/// \brief Determine whether the given integral value is representable within
12208/// the given type T.
12209static bool isRepresentableIntegerValue(ASTContext &Context,
12210 llvm::APSInt &Value,
12211 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012212 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012213 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012214
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012215 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012216 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012217 --BitWidth;
12218 return Value.getActiveBits() <= BitWidth;
12219 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012220 return Value.getMinSignedBits() <= BitWidth;
12221}
12222
12223// \brief Given an integral type, return the next larger integral type
12224// (or a NULL type of no such type exists).
12225static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12226 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12227 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012228 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012229 const unsigned NumTypes = 4;
12230 QualType SignedIntegralTypes[NumTypes] = {
12231 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12232 };
12233 QualType UnsignedIntegralTypes[NumTypes] = {
12234 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12235 Context.UnsignedLongLongTy
12236 };
12237
12238 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012239 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12240 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012241 for (unsigned I = 0; I != NumTypes; ++I)
12242 if (Context.getTypeSize(Types[I]) > BitWidth)
12243 return Types[I];
12244
12245 return QualType();
12246}
12247
Douglas Gregor879fd492009-03-17 19:05:46 +000012248EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12249 EnumConstantDecl *LastEnumConst,
12250 SourceLocation IdLoc,
12251 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012252 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012253 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012254 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012255 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012256
12257 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12258 Val = 0;
12259
Eli Friedman19efa3e2011-12-06 00:10:34 +000012260 if (Val)
12261 Val = DefaultLvalueConversion(Val).take();
12262
Douglas Gregor4912c342009-11-06 00:03:12 +000012263 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012264 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012265 EltTy = Context.DependentTy;
12266 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012267 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012268 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012269 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012270 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12271 // constant-expression in the enumerator-definition shall be a converted
12272 // constant expression of the underlying type.
12273 EltTy = Enum->getIntegerType();
12274 ExprResult Converted =
12275 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12276 CCEK_Enumerator);
12277 if (Converted.isInvalid())
12278 Val = 0;
12279 else
12280 Val = Converted.take();
12281 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012282 !(Val = VerifyIntegerConstantExpression(Val,
12283 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012284 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012285 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012286 if (Enum->isFixed()) {
12287 EltTy = Enum->getIntegerType();
12288
Richard Smith8ef7b202012-01-18 23:55:52 +000012289 // In Obj-C and Microsoft mode, require the enumeration value to be
12290 // representable in the underlying type of the enumeration. In C++11,
12291 // we perform a non-narrowing conversion as part of converted constant
12292 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012293 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012294 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012295 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012296 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012297 } else
12298 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012299 } else
John Wiegley429bb272011-04-08 18:41:53 +000012300 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012301 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012302 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012303 // If the underlying type is not fixed, the type of each enumerator
12304 // is the type of its initializing value:
12305 // - If an initializer is specified for an enumerator, the
12306 // initializing value has the same type as the expression.
12307 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012308 } else {
12309 // C99 6.7.2.2p2:
12310 // The expression that defines the value of an enumeration constant
12311 // shall be an integer constant expression that has a value
12312 // representable as an int.
12313
12314 // Complain if the value is not representable in an int.
12315 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12316 Diag(IdLoc, diag::ext_enum_value_not_int)
12317 << EnumVal.toString(10) << Val->getSourceRange()
12318 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12319 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12320 // Force the type of the expression to 'int'.
12321 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12322 }
12323 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012324 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012325 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012326 }
12327 }
Mike Stump1eb44332009-09-09 15:08:12 +000012328
Douglas Gregor879fd492009-03-17 19:05:46 +000012329 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012330 if (Enum->isDependentType())
12331 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012332 else if (!LastEnumConst) {
12333 // C++0x [dcl.enum]p5:
12334 // If the underlying type is not fixed, the type of each enumerator
12335 // is the type of its initializing value:
12336 // - If no initializer is specified for the first enumerator, the
12337 // initializing value has an unspecified integral type.
12338 //
12339 // GCC uses 'int' for its unspecified integral type, as does
12340 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012341 if (Enum->isFixed()) {
12342 EltTy = Enum->getIntegerType();
12343 }
12344 else {
12345 EltTy = Context.IntTy;
12346 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012347 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012348 // Assign the last value + 1.
12349 EnumVal = LastEnumConst->getInitVal();
12350 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012351 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012352
12353 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012354 if (EnumVal < LastEnumConst->getInitVal()) {
12355 // C++0x [dcl.enum]p5:
12356 // If the underlying type is not fixed, the type of each enumerator
12357 // is the type of its initializing value:
12358 //
12359 // - Otherwise the type of the initializing value is the same as
12360 // the type of the initializing value of the preceding enumerator
12361 // unless the incremented value is not representable in that type,
12362 // in which case the type is an unspecified integral type
12363 // sufficient to contain the incremented value. If no such type
12364 // exists, the program is ill-formed.
12365 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012366 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012367 // There is no integral type larger enough to represent this
12368 // value. Complain, then allow the value to wrap around.
12369 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012370 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012371 ++EnumVal;
12372 if (Enum->isFixed())
12373 // When the underlying type is fixed, this is ill-formed.
12374 Diag(IdLoc, diag::err_enumerator_wrapped)
12375 << EnumVal.toString(10)
12376 << EltTy;
12377 else
12378 Diag(IdLoc, diag::warn_enumerator_too_large)
12379 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012380 } else {
12381 EltTy = T;
12382 }
12383
12384 // Retrieve the last enumerator's value, extent that type to the
12385 // type that is supposed to be large enough to represent the incremented
12386 // value, then increment.
12387 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012388 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012389 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012390 ++EnumVal;
12391
12392 // If we're not in C++, diagnose the overflow of enumerator values,
12393 // which in C99 means that the enumerator value is not representable in
12394 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12395 // permits enumerator values that are representable in some larger
12396 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012397 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012398 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012399 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012400 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12401 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12402 Diag(IdLoc, diag::ext_enum_value_not_int)
12403 << EnumVal.toString(10) << 1;
12404 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012405 }
12406 }
Mike Stump1eb44332009-09-09 15:08:12 +000012407
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012408 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012409 // Make the enumerator value match the signedness and size of the
12410 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012411 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012412 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012413 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012414
Douglas Gregor879fd492009-03-17 19:05:46 +000012415 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012416 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012417}
12418
12419
John McCall5b629aa2010-10-22 23:36:17 +000012420Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12421 SourceLocation IdLoc, IdentifierInfo *Id,
12422 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012423 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012424 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012425 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012426 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012427
Chris Lattner31e05722007-08-26 06:24:45 +000012428 // The scope passed in may not be a decl scope. Zip up the scope tree until
12429 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012430 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012431
Reid Spencer5f016e22007-07-11 17:01:13 +000012432 // Verify that there isn't already something declared with this name in this
12433 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012434 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012435 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012436 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012437 // Maybe we will complain about the shadowed template parameter.
12438 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12439 // Just pretend that we didn't see the previous declaration.
12440 PrevDecl = 0;
12441 }
12442
12443 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012444 // When in C++, we may get a TagDecl with the same name; in this case the
12445 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012446 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012447 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012448 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012449 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012450 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012451 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012452 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012453 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012454 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012455 }
12456 }
12457
Aaron Ballmanf8167872012-07-19 03:12:23 +000012458 // C++ [class.mem]p15:
12459 // If T is the name of a class, then each of the following shall have a name
12460 // different from T:
12461 // - every enumerator of every member of class T that is an unscoped
12462 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012463 if (CXXRecordDecl *Record
12464 = dyn_cast<CXXRecordDecl>(
12465 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012466 if (!TheEnumDecl->isScoped() &&
12467 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012468 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12469
John McCall5b629aa2010-10-22 23:36:17 +000012470 EnumConstantDecl *New =
12471 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012472
John McCall92f88312010-01-23 00:46:32 +000012473 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012474 // Process attributes.
12475 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12476
12477 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012478 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012479 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012480 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012481
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012482 ActOnDocumentableDecl(New);
12483
John McCalld226f652010-08-21 09:40:31 +000012484 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012485}
12486
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012487// Returns true when the enum initial expression does not trigger the
12488// duplicate enum warning. A few common cases are exempted as follows:
12489// Element2 = Element1
12490// Element2 = Element1 + 1
12491// Element2 = Element1 - 1
12492// Where Element2 and Element1 are from the same enum.
12493static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12494 Expr *InitExpr = ECD->getInitExpr();
12495 if (!InitExpr)
12496 return true;
12497 InitExpr = InitExpr->IgnoreImpCasts();
12498
12499 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12500 if (!BO->isAdditiveOp())
12501 return true;
12502 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12503 if (!IL)
12504 return true;
12505 if (IL->getValue() != 1)
12506 return true;
12507
12508 InitExpr = BO->getLHS();
12509 }
12510
12511 // This checks if the elements are from the same enum.
12512 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12513 if (!DRE)
12514 return true;
12515
12516 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12517 if (!EnumConstant)
12518 return true;
12519
12520 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12521 Enum)
12522 return true;
12523
12524 return false;
12525}
12526
12527struct DupKey {
12528 int64_t val;
12529 bool isTombstoneOrEmptyKey;
12530 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12531 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12532};
12533
12534static DupKey GetDupKey(const llvm::APSInt& Val) {
12535 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12536 false);
12537}
12538
12539struct DenseMapInfoDupKey {
12540 static DupKey getEmptyKey() { return DupKey(0, true); }
12541 static DupKey getTombstoneKey() { return DupKey(1, true); }
12542 static unsigned getHashValue(const DupKey Key) {
12543 return (unsigned)(Key.val * 37);
12544 }
12545 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12546 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12547 LHS.val == RHS.val;
12548 }
12549};
12550
12551// Emits a warning when an element is implicitly set a value that
12552// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012553static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12554 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012555 QualType EnumType) {
12556 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12557 Enum->getLocation()) ==
12558 DiagnosticsEngine::Ignored)
12559 return;
12560 // Avoid anonymous enums
12561 if (!Enum->getIdentifier())
12562 return;
12563
12564 // Only check for small enums.
12565 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12566 return;
12567
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012568 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12569 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012570
12571 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12572 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12573 ValueToVectorMap;
12574
12575 DuplicatesVector DupVector;
12576 ValueToVectorMap EnumMap;
12577
12578 // Populate the EnumMap with all values represented by enum constants without
12579 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012580 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012581 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012582
12583 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12584 // this constant. Skip this enum since it may be ill-formed.
12585 if (!ECD) {
12586 return;
12587 }
12588
12589 if (ECD->getInitExpr())
12590 continue;
12591
12592 DupKey Key = GetDupKey(ECD->getInitVal());
12593 DeclOrVector &Entry = EnumMap[Key];
12594
12595 // First time encountering this value.
12596 if (Entry.isNull())
12597 Entry = ECD;
12598 }
12599
12600 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012601 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012602 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12603 if (!ValidDuplicateEnum(ECD, Enum))
12604 continue;
12605
12606 DupKey Key = GetDupKey(ECD->getInitVal());
12607
12608 DeclOrVector& Entry = EnumMap[Key];
12609 if (Entry.isNull())
12610 continue;
12611
12612 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12613 // Ensure constants are different.
12614 if (D == ECD)
12615 continue;
12616
12617 // Create new vector and push values onto it.
12618 ECDVector *Vec = new ECDVector();
12619 Vec->push_back(D);
12620 Vec->push_back(ECD);
12621
12622 // Update entry to point to the duplicates vector.
12623 Entry = Vec;
12624
12625 // Store the vector somewhere we can consult later for quick emission of
12626 // diagnostics.
12627 DupVector.push_back(Vec);
12628 continue;
12629 }
12630
12631 ECDVector *Vec = Entry.get<ECDVector*>();
12632 // Make sure constants are not added more than once.
12633 if (*Vec->begin() == ECD)
12634 continue;
12635
12636 Vec->push_back(ECD);
12637 }
12638
12639 // Emit diagnostics.
12640 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12641 DupVectorEnd = DupVector.end();
12642 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12643 ECDVector *Vec = *DupVectorIter;
12644 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12645
12646 // Emit warning for one enum constant.
12647 ECDVector::iterator I = Vec->begin();
12648 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12649 << (*I)->getName() << (*I)->getInitVal().toString(10)
12650 << (*I)->getSourceRange();
12651 ++I;
12652
12653 // Emit one note for each of the remaining enum constants with
12654 // the same value.
12655 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12656 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12657 << (*I)->getName() << (*I)->getInitVal().toString(10)
12658 << (*I)->getSourceRange();
12659 delete Vec;
12660 }
12661}
12662
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012663void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012664 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012665 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012666 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012667 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012668 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012669
12670 if (Attr)
12671 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012672
Eli Friedmaned0716b2009-12-11 01:34:50 +000012673 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012674 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012675 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012676 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012677 if (!ECD) continue;
12678
12679 ECD->setType(EnumType);
12680 }
12681
John McCall1b5a6182010-05-06 08:49:23 +000012682 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012683 return;
12684 }
12685
Chris Lattnere37f0be2007-08-28 05:10:31 +000012686 // TODO: If the result value doesn't fit in an int, it must be a long or long
12687 // long value. ISO C does not support this, but GCC does as an extension,
12688 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012689 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12690 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12691 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012692
Chris Lattnerac609682007-08-28 06:15:15 +000012693 // Verify that all the values are okay, compute the size of the values, and
12694 // reverse the list.
12695 unsigned NumNegativeBits = 0;
12696 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012697
Chris Lattnerac609682007-08-28 06:15:15 +000012698 // Keep track of whether all elements have type int.
12699 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012700
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012701 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012702 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012703 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012704 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012705
Chris Lattner211a30e2007-08-28 05:27:00 +000012706 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012707
Chris Lattnerac609682007-08-28 06:15:15 +000012708 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012709 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012710 NumPositiveBits = std::max(NumPositiveBits,
12711 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012712 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012713 NumNegativeBits = std::max(NumNegativeBits,
12714 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012715
Chris Lattnerac609682007-08-28 06:15:15 +000012716 // Keep track of whether every enum element has type int (very commmon).
12717 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012718 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012719 }
Mike Stump1eb44332009-09-09 15:08:12 +000012720
Chris Lattnerac609682007-08-28 06:15:15 +000012721 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012722 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012723 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012724
John McCall842aef82009-12-09 09:09:27 +000012725 // C++0x N3000 [conv.prom]p3:
12726 // An rvalue of an unscoped enumeration type whose underlying
12727 // type is not fixed can be converted to an rvalue of the first
12728 // of the following types that can represent all the values of
12729 // the enumeration: int, unsigned int, long int, unsigned long
12730 // int, long long int, or unsigned long long int.
12731 // C99 6.4.4.3p2:
12732 // An identifier declared as an enumeration constant has type int.
12733 // The C99 rule is modified by a gcc extension
12734 QualType BestPromotionType;
12735
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012736 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012737 // -fshort-enums is the equivalent to specifying the packed attribute on all
12738 // enum definitions.
12739 if (LangOpts.ShortEnums)
12740 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012741
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012742 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012743 BestType = Enum->getIntegerType();
12744 if (BestType->isPromotableIntegerType())
12745 BestPromotionType = Context.getPromotedIntegerType(BestType);
12746 else
12747 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012748 // We don't need to set BestWidth, because BestType is going to be the type
12749 // of the enumerators, but we do anyway because otherwise some compilers
12750 // warn that it might be used uninitialized.
12751 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012752 }
12753 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012754 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012755 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012756 // If it's packed, check also if it fits a char or a short.
12757 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012758 BestType = Context.SignedCharTy;
12759 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012760 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012761 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012762 BestType = Context.ShortTy;
12763 BestWidth = ShortWidth;
12764 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012765 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012766 BestWidth = IntWidth;
12767 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012768 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012769
John McCall842aef82009-12-09 09:09:27 +000012770 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012771 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012772 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012773 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012774
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012775 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012776 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12777 BestType = Context.LongLongTy;
12778 }
12779 }
John McCall842aef82009-12-09 09:09:27 +000012780 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012781 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012782 // If there is no negative value, figure out the smallest type that fits
12783 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012784 // If it's packed, check also if it fits a char or a short.
12785 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012786 BestType = Context.UnsignedCharTy;
12787 BestPromotionType = Context.IntTy;
12788 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012789 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012790 BestType = Context.UnsignedShortTy;
12791 BestPromotionType = Context.IntTy;
12792 BestWidth = ShortWidth;
12793 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012794 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012795 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012796 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012797 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012798 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012799 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012800 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012801 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012802 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012803 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012804 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012805 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012806 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012807 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012808 "How could an initializer get larger than ULL?");
12809 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012810 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012811 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012812 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012813 }
12814 }
Mike Stump1eb44332009-09-09 15:08:12 +000012815
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012816 // Loop over all of the enumerator constants, changing their types to match
12817 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012818 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012819 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012820 if (!ECD) continue; // Already issued a diagnostic.
12821
12822 // Standard C says the enumerators have int type, but we allow, as an
12823 // extension, the enumerators to be larger than int size. If each
12824 // enumerator value fits in an int, type it as an int, otherwise type it the
12825 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12826 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012827
12828 // Determine whether the value fits into an int.
12829 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012830
12831 // If it fits into an integer type, force it. Otherwise force it to match
12832 // the enum decl type.
12833 QualType NewTy;
12834 unsigned NewWidth;
12835 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012836 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012837 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012838 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012839 NewTy = Context.IntTy;
12840 NewWidth = IntWidth;
12841 NewSign = true;
12842 } else if (ECD->getType() == BestType) {
12843 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012844 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012845 // C++ [dcl.enum]p4: Following the closing brace of an
12846 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012847 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012848 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012849 continue;
12850 } else {
12851 NewTy = BestType;
12852 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012853 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012854 }
12855
12856 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012857 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012858 InitVal.setIsSigned(NewSign);
12859 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012860
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012861 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012862 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012863 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012864 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012865 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012866 ECD->getInitExpr(),
12867 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012868 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012869 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012870 // C++ [dcl.enum]p4: Following the closing brace of an
12871 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012872 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012873 ECD->setType(EnumType);
12874 else
12875 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012876 }
Mike Stump1eb44332009-09-09 15:08:12 +000012877
John McCall1b5a6182010-05-06 08:49:23 +000012878 Enum->completeDefinition(BestType, BestPromotionType,
12879 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012880
12881 // If we're declaring a function, ensure this decl isn't forgotten about -
12882 // it needs to go into the function scope.
12883 if (InFunctionDeclarator)
12884 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012885
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012886 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012887
12888 // Now that the enum type is defined, ensure it's not been underaligned.
12889 if (Enum->hasAttrs())
12890 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012891}
12892
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012893Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12894 SourceLocation StartLoc,
12895 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012896 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012897
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012898 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012899 AsmString, StartLoc,
12900 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012901 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012902 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012903}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012904
Douglas Gregor5948ae12012-01-03 18:04:46 +000012905DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12906 SourceLocation ImportLoc,
12907 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012908 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012909 Module::AllVisible,
12910 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012911 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012912 return true;
12913
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012914 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012915 Module *ModCheck = Mod;
12916 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12917 // If we've run out of module parents, just drop the remaining identifiers.
12918 // We need the length to be consistent.
12919 if (!ModCheck)
12920 break;
12921 ModCheck = ModCheck->Parent;
12922
12923 IdentifierLocs.push_back(Path[I].second);
12924 }
12925
12926 ImportDecl *Import = ImportDecl::Create(Context,
12927 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012928 AtLoc.isValid()? AtLoc : ImportLoc,
12929 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012930 Context.getTranslationUnitDecl()->addDecl(Import);
12931 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012932}
12933
Douglas Gregorca2ab452013-01-12 01:29:50 +000012934void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12935 // Create the implicit import declaration.
12936 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12937 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12938 Loc, Mod, Loc);
12939 TU->addDecl(ImportD);
12940 Consumer.HandleImplicitImportDecl(ImportD);
12941
12942 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012943 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12944 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012945}
12946
David Chisnall5f3c1632012-02-18 16:12:34 +000012947void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12948 IdentifierInfo* AliasName,
12949 SourceLocation PragmaLoc,
12950 SourceLocation NameLoc,
12951 SourceLocation AliasNameLoc) {
12952 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12953 LookupOrdinaryName);
12954 AsmLabelAttr *Attr =
12955 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012956
12957 if (PrevDecl)
12958 PrevDecl->addAttr(Attr);
12959 else
12960 (void)ExtnameUndeclaredIdentifiers.insert(
12961 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12962}
12963
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012964void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12965 SourceLocation PragmaLoc,
12966 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012967 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012968
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012969 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012970 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012971 } else {
12972 (void)WeakUndeclaredIdentifiers.insert(
12973 std::pair<IdentifierInfo*,WeakInfo>
12974 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012975 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012976}
12977
12978void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12979 IdentifierInfo* AliasName,
12980 SourceLocation PragmaLoc,
12981 SourceLocation NameLoc,
12982 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012983 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12984 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012985 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012986
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012987 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012988 if (!PrevDecl->hasAttr<AliasAttr>())
12989 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012990 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012991 } else {
12992 (void)WeakUndeclaredIdentifiers.insert(
12993 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012994 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012995}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012996
12997Decl *Sema::getObjCDeclContext() const {
12998 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12999}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000013000
13001AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000013002 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000013003 return D->getAvailability();
13004}