blob: 328ce7059631765d5a6815f38c3990cff2c684e3 [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.
Bill Wendlingb7accd02013-12-05 05:24:30 +0000873 // A Lambda call operator whose parent is a class must not be treated
874 // as an inline member function. A Lambda can be used legally
875 // either as an in-class member initializer or a default argument. These
876 // are parsed once the class has been marked complete and so the containing
877 // context would be the nested class (when the lambda is defined in one);
878 // If the class is not complete, then the lambda is being used in an
879 // ill-formed fashion (such as to specify the width of a bit-field, or
880 // in an array-bound) - in which case we still want to return the
881 // lexically containing DC (which could be a nested class).
882 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall88232aa2009-08-18 00:00:49 +0000883 DC = DC->getLexicalParent();
884
885 // A function not defined within a class will always return to its
886 // lexical context.
887 if (!isa<CXXRecordDecl>(DC))
888 return DC;
889
890 // A C++ inline method/friend is parsed *after* the topmost class
891 // it was declared in is fully parsed ("complete"); the topmost
892 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000893 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000894 DC = RD;
895
896 // Return the declaration context of the topmost class the inline method is
897 // declared in.
898 return DC;
899 }
900
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000901 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000902}
903
Douglas Gregor44b43212008-12-11 16:49:14 +0000904void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000905 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000906 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000907 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000908 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000909}
910
Chris Lattnerb048c982008-04-06 04:47:34 +0000911void Sema::PopDeclContext() {
912 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000913
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000914 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000915 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000916}
917
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000918/// EnterDeclaratorContext - Used when we must lookup names in the context
919/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000920///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000921void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000922 // C++0x [basic.lookup.unqual]p13:
923 // A name used in the definition of a static data member of class
924 // X (after the qualified-id of the static member) is looked up as
925 // if the name was used in a member function of X.
926 // C++0x [basic.lookup.unqual]p14:
927 // If a variable member of a namespace is defined outside of the
928 // scope of its namespace then any name used in the definition of
929 // the variable member (after the declarator-id) is looked up as
930 // if the definition of the variable member occurred in its
931 // namespace.
932 // Both of these imply that we should push a scope whose context
933 // is the semantic context of the declaration. We can't use
934 // PushDeclContext here because that context is not necessarily
935 // lexically contained in the current context. Fortunately,
936 // the containing scope should have the appropriate information.
937
938 assert(!S->getEntity() && "scope already has entity");
939
940#ifndef NDEBUG
941 Scope *Ancestor = S->getParent();
942 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
943 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
944#endif
945
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000946 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000947 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000948}
949
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000950void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000951 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000952
John McCall7a1dc562009-12-19 10:49:29 +0000953 // Switch back to the lexical context. The safety of this is
954 // enforced by an assert in EnterDeclaratorContext.
955 Scope *Ancestor = S->getParent();
956 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekf0d58612013-10-08 17:08:03 +0000957 CurContext = Ancestor->getEntity();
John McCall7a1dc562009-12-19 10:49:29 +0000958
959 // We don't need to do anything with the scope, which is going to
960 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000961}
962
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000963
964void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
965 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
966 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
967 // We assume that the caller has already called
968 // ActOnReenterTemplateScope
969 FD = TFD->getTemplatedDecl();
970 }
971 if (!FD)
972 return;
973
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000974 // Same implementation as PushDeclContext, but enters the context
975 // from the lexical parent, rather than the top-level class.
976 assert(CurContext == FD->getLexicalParent() &&
977 "The next DeclContext should be lexically contained in the current one.");
978 CurContext = FD;
979 S->setEntity(CurContext);
980
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000981 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
982 ParmVarDecl *Param = FD->getParamDecl(P);
983 // If the parameter has an identifier, then add it to the scope
984 if (Param->getIdentifier()) {
985 S->AddDecl(Param);
986 IdResolver.AddDecl(Param);
987 }
988 }
989}
990
991
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000992void Sema::ActOnExitFunctionContext() {
993 // Same implementation as PopDeclContext, but returns to the lexical parent,
994 // rather than the top-level class.
995 assert(CurContext && "DeclContext imbalance!");
996 CurContext = CurContext->getLexicalParent();
997 assert(CurContext && "Popped translation unit!");
998}
999
1000
Douglas Gregorf9201e02009-02-11 23:02:49 +00001001/// \brief Determine whether we allow overloading of the function
1002/// PrevDecl with another declaration.
1003///
1004/// This routine determines whether overloading is possible, not
1005/// whether some new function is actually an overload. It will return
1006/// true in C++ (where we can always provide overloads) or, as an
1007/// extension, in C when the previous function is already an
1008/// overloaded function declaration or has the "overloadable"
1009/// attribute.
John McCall68263142009-11-18 22:49:29 +00001010static bool AllowOverloadingOfFunction(LookupResult &Previous,
1011 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001012 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001013 return true;
1014
John McCall68263142009-11-18 22:49:29 +00001015 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001016 return true;
1017
John McCall68263142009-11-18 22:49:29 +00001018 return (Previous.getResultKind() == LookupResult::Found
1019 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +00001020}
1021
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001022/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +00001023void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +00001024 // Move up the scope chain until we find the nearest enclosing
1025 // non-transparent context. The declaration will be introduced into this
1026 // scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00001027 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor074149e2009-01-05 19:45:36 +00001028 S = S->getParent();
1029
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001030 // Add scoped declarations into their context, so that they can be
1031 // found later. Declarations without a context won't be inserted
1032 // into any context.
John McCallab88d972009-08-31 22:39:49 +00001033 if (AddToContext)
1034 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001035
Richard Smitha41c97a2013-09-20 01:15:31 +00001036 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1037 // are function-local declarations.
1038 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +00001039 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smitha41c97a2013-09-20 01:15:31 +00001040 D->getLexicalDeclContext()->getRedeclContext()) &&
1041 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruth8761d682010-02-21 07:08:09 +00001042 return;
1043
1044 // Template instantiations should also not be pushed into scope.
1045 if (isa<FunctionDecl>(D) &&
1046 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +00001047 return;
1048
John McCallf36e02d2009-10-09 21:13:30 +00001049 // If this replaces anything in the current scope,
1050 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1051 IEnd = IdResolver.end();
1052 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001053 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1054 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +00001055 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001056
John McCallf36e02d2009-10-09 21:13:30 +00001057 // Should only need to replace one decl.
1058 break;
Douglas Gregor516ff432009-04-24 02:57:34 +00001059 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001060 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001061
John McCalld226f652010-08-21 09:40:31 +00001062 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001063
1064 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1065 // Implicitly-generated labels may end up getting generated in an order that
1066 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1067 // the label at the appropriate place in the identifier chain.
1068 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +00001069 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +00001070 if (IDC == CurContext) {
1071 if (!S->isDeclScope(*I))
1072 continue;
1073 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001074 break;
1075 }
1076
Douglas Gregor250e7a72011-03-16 16:39:03 +00001077 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001078 } else {
1079 IdResolver.AddDecl(D);
1080 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001081}
1082
Douglas Gregoreee242f2011-10-27 09:33:13 +00001083void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1084 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1085 TUScope->AddDecl(D);
1086}
1087
Richard Smithdd9459f2013-08-13 18:18:50 +00001088bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001089 bool ExplicitInstantiationOrSpecialization) {
Nico Weber355a1662012-12-17 03:51:09 +00001090 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001091 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001092}
1093
John McCall5f1e0942010-08-24 08:50:51 +00001094Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1095 DeclContext *TargetDC = DC->getPrimaryContext();
1096 do {
Ted Kremenekf0d58612013-10-08 17:08:03 +00001097 if (DeclContext *ScopeDC = S->getEntity())
John McCall5f1e0942010-08-24 08:50:51 +00001098 if (ScopeDC->getPrimaryContext() == TargetDC)
1099 return S;
1100 } while ((S = S->getParent()));
1101
1102 return 0;
1103}
1104
John McCall68263142009-11-18 22:49:29 +00001105static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1106 DeclContext*,
1107 ASTContext&);
1108
1109/// Filters out lookup results that don't fall within the given scope
1110/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001111void Sema::FilterLookupForScope(LookupResult &R,
1112 DeclContext *Ctx, Scope *S,
1113 bool ConsiderLinkage,
1114 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001115 LookupResult::Filter F = R.makeFilter();
1116 while (F.hasNext()) {
1117 NamedDecl *D = F.next();
1118
Richard Smith3e4c6c42011-05-05 21:57:07 +00001119 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001120 continue;
1121
1122 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001123 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001124 continue;
1125
1126 F.erase();
1127 }
1128
1129 F.done();
1130}
1131
1132static bool isUsingDecl(NamedDecl *D) {
1133 return isa<UsingShadowDecl>(D) ||
1134 isa<UnresolvedUsingTypenameDecl>(D) ||
1135 isa<UnresolvedUsingValueDecl>(D);
1136}
1137
1138/// Removes using shadow declarations from the lookup results.
1139static void RemoveUsingDecls(LookupResult &R) {
1140 LookupResult::Filter F = R.makeFilter();
1141 while (F.hasNext())
1142 if (isUsingDecl(F.next()))
1143 F.erase();
1144
1145 F.done();
1146}
1147
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001148/// \brief Check for this common pattern:
1149/// @code
1150/// class S {
1151/// S(const S&); // DO NOT IMPLEMENT
1152/// void operator=(const S&); // DO NOT IMPLEMENT
1153/// };
1154/// @endcode
1155static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1156 // FIXME: Should check for private access too but access is set after we get
1157 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001158 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001159 return false;
1160
1161 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1162 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1164 return Method->isCopyAssignmentOperator();
1165 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001166}
1167
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001168// We need this to handle
1169//
1170// typedef struct {
1171// void *foo() { return 0; }
1172// } A;
1173//
1174// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1175// for example. If 'A', foo will have external linkage. If we have '*A',
1176// foo will have no linkage. Since we can't know untill we get to the end
1177// of the typedef, this function finds out if D might have non external linkage.
1178// Callers should verify at the end of the TU if it D has external linkage or
1179// not.
1180bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1181 const DeclContext *DC = D->getDeclContext();
1182 while (!DC->isTranslationUnit()) {
1183 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1184 if (!RD->hasNameForLinkage())
1185 return true;
1186 }
1187 DC = DC->getParent();
1188 }
1189
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001190 return !D->isExternallyVisible();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001191}
1192
Eli Friedman39bd3712013-09-10 03:05:56 +00001193// FIXME: This needs to be refactored; some other isInMainFile users want
1194// these semantics.
1195static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1196 if (S.TUKind != TU_Complete)
1197 return false;
1198 return S.SourceMgr.isInMainFile(Loc);
1199}
1200
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001201bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1202 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001203
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001204 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1205 return false;
1206
1207 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001208 if (D->getDeclContext()->isDependentContext() ||
1209 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001210 return false;
1211
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001212 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001213 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1214 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001215
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1217 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1218 return false;
1219 } else {
Eli Friedman39bd3712013-09-10 03:05:56 +00001220 // 'static inline' functions are defined in headers; don't warn.
1221 if (FD->isInlineSpecified() &&
1222 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001223 return false;
1224 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001225
Sean Hunt10620eb2011-05-06 20:44:56 +00001226 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001227 Context.DeclMustBeEmitted(FD))
1228 return false;
John McCall82b96592010-10-27 01:41:35 +00001229 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman39bd3712013-09-10 03:05:56 +00001230 // Constants and utility variables are defined in headers with internal
1231 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1232 // like "inline".)
1233 if (!isMainFileLoc(*this, VD->getLocation()))
1234 return false;
1235
Eli Friedman39bd3712013-09-10 03:05:56 +00001236 if (Context.DeclMustBeEmitted(VD))
John McCall82b96592010-10-27 01:41:35 +00001237 return false;
1238
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001239 if (VD->isStaticDataMember() &&
1240 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1241 return false;
John McCall82b96592010-10-27 01:41:35 +00001242 } else {
1243 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001244 }
1245
John McCall82b96592010-10-27 01:41:35 +00001246 // Only warn for unused decls internal to the translation unit.
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001247 return mightHaveNonExternalLinkage(D);
John McCall82b96592010-10-27 01:41:35 +00001248}
1249
1250void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001251 if (!D)
1252 return;
1253
1254 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001255 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001256 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1257 return; // First should already be in the vector.
1258 }
1259
1260 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001261 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001262 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1263 return; // First should already be in the vector.
1264 }
1265
David Blaikie7f7c42b2012-05-26 05:35:39 +00001266 if (ShouldWarnIfUnusedFileScopedDecl(D))
1267 UnusedFileScopedDecls.push_back(D);
1268}
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001269
Anders Carlsson99a000e2009-11-07 07:18:14 +00001270static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001271 if (D->isInvalidDecl())
1272 return false;
1273
Eli Friedmandd9d6452012-01-13 23:41:25 +00001274 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001275 return false;
John McCall86ff3082010-02-04 22:26:26 +00001276
Chris Lattner57ad3782011-02-17 20:34:02 +00001277 if (isa<LabelDecl>(D))
1278 return true;
1279
John McCall86ff3082010-02-04 22:26:26 +00001280 // White-list anything that isn't a local variable.
1281 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1282 !D->getDeclContext()->isFunctionOrMethod())
1283 return false;
1284
1285 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001286 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001287
1288 // White-list anything with an __attribute__((unused)) type.
1289 QualType Ty = VD->getType();
1290
1291 // Only look at the outermost level of typedef.
Douglas Gregor2c8e81e2012-09-14 05:10:40 +00001292 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallaec58602010-03-31 02:47:45 +00001293 if (TT->getDecl()->hasAttr<UnusedAttr>())
1294 return false;
1295 }
1296
Douglas Gregor5764f612010-05-08 23:05:03 +00001297 // If we failed to complete the type for some reason, or if the type is
1298 // dependent, don't diagnose the variable.
1299 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001300 return false;
1301
John McCallaec58602010-03-31 02:47:45 +00001302 if (const TagType *TT = Ty->getAs<TagType>()) {
1303 const TagDecl *Tag = TT->getDecl();
1304 if (Tag->hasAttr<UnusedAttr>())
1305 return false;
1306
1307 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001308 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001309 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001310
1311 if (const Expr *Init = VD->getInit()) {
David Blaikie39e17762012-10-24 21:29:06 +00001312 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1313 Init = Cleanups->getSubExpr();
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001314 const CXXConstructExpr *Construct =
1315 dyn_cast<CXXConstructExpr>(Init);
1316 if (Construct && !Construct->isElidable()) {
1317 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001318 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001319 return false;
1320 }
1321 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001322 }
1323 }
John McCallaec58602010-03-31 02:47:45 +00001324
1325 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001326 }
1327
John McCall86ff3082010-02-04 22:26:26 +00001328 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001329}
1330
Anna Zaksd5612a22011-07-28 20:52:06 +00001331static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1332 FixItHint &Hint) {
1333 if (isa<LabelDecl>(D)) {
1334 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001335 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001336 if (AfterColon.isInvalid())
1337 return;
1338 Hint = FixItHint::CreateRemoval(CharSourceRange::
1339 getCharRange(D->getLocStart(), AfterColon));
1340 }
1341 return;
1342}
1343
Chris Lattner337e5502011-02-18 01:27:55 +00001344/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1345/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001346void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001347 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001348 if (!ShouldDiagnoseUnusedDecl(D))
1349 return;
1350
Anna Zaksd5612a22011-07-28 20:52:06 +00001351 GenerateFixForUnusedDecl(D, Context, Hint);
1352
Chris Lattner57ad3782011-02-17 20:34:02 +00001353 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001354 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001355 DiagID = diag::warn_unused_exception_param;
1356 else if (isa<LabelDecl>(D))
1357 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001358 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001359 DiagID = diag::warn_unused_variable;
1360
Anna Zaksd5612a22011-07-28 20:52:06 +00001361 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001362}
1363
Chris Lattner337e5502011-02-18 01:27:55 +00001364static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1365 // Verify that we have no forward references left. If so, there was a goto
1366 // or address of a label taken, but no definition of it. Label fwd
1367 // definitions are indicated with a null substmt.
1368 if (L->getStmt() == 0)
1369 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1370}
1371
Steve Naroffb216c882007-10-09 22:01:59 +00001372void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001373 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001374 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001375 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1378 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001379 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001380 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001381
Douglas Gregor44b43212008-12-11 16:49:14 +00001382 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1383 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001384
Douglas Gregor44b43212008-12-11 16:49:14 +00001385 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001386
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001387 // Diagnose unused variables in this scope.
Matt Beaumont-Gay59d8ccb2013-03-28 21:46:45 +00001388 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001389 DiagnoseUnusedDecl(D);
1390
Chris Lattner337e5502011-02-18 01:27:55 +00001391 // If this was a forward reference to a label, verify it was defined.
1392 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1393 CheckPoppedLabel(LD, *this);
1394
Douglas Gregor44b43212008-12-11 16:49:14 +00001395 // Remove this name from our lexical scope.
1396 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 }
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00001398 DiagnoseUnusedBackingIvarInAccessor(S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001399}
1400
James Molloy16f1f712012-02-29 10:24:19 +00001401void Sema::ActOnStartFunctionDeclarator() {
1402 ++InFunctionDeclarator;
1403}
1404
1405void Sema::ActOnEndFunctionDeclarator() {
1406 assert(InFunctionDeclarator);
1407 --InFunctionDeclarator;
1408}
1409
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001410/// \brief Look for an Objective-C class in the translation unit.
1411///
1412/// \param Id The name of the Objective-C class we're looking for. If
1413/// typo-correction fixes this name, the Id will be updated
1414/// to the fixed name.
1415///
1416/// \param IdLoc The location of the name in the translation unit.
1417///
James Dennett16ae9de2012-06-22 10:16:05 +00001418/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001419/// if there is no class with the given name.
1420///
1421/// \returns The declaration of the named Objective-C class, or NULL if the
1422/// class could not be found.
1423ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1424 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001425 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001426 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1427 // creation from this context.
1428 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1429
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001430 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001431 // Perform typo correction at the given location, but only if we
1432 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001433 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1434 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1435 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001436 Validator)) {
Richard Smith2d670972013-08-17 00:46:16 +00001437 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001438 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001439 Id = IDecl->getIdentifier();
1440 }
1441 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001442 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1443 // This routine must always return a class definition, if any.
1444 if (Def && Def->getDefinition())
1445 Def = Def->getDefinition();
1446 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001447}
1448
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001449/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1450/// from S, where a non-field would be declared. This routine copes
1451/// with the difference between C and C++ scoping rules in structs and
1452/// unions. For example, the following code is well-formed in C but
1453/// ill-formed in C++:
1454/// @code
1455/// struct S6 {
1456/// enum { BAR } e;
1457/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001458///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001459/// void test_S6() {
1460/// struct S6 a;
1461/// a.e = BAR;
1462/// }
1463/// @endcode
1464/// For the declaration of BAR, this routine will return a different
1465/// scope. The scope S will be the scope of the unnamed enumeration
1466/// within S6. In C++, this routine will return the scope associated
1467/// with S6, because the enumeration's scope is a transparent
1468/// context but structures can contain non-field names. In C, this
1469/// routine will return the translation unit scope, since the
1470/// enumeration's scope is a transparent context and structures cannot
1471/// contain non-field names.
1472Scope *Sema::getNonFieldDeclScope(Scope *S) {
1473 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001474 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001476 S = S->getParent();
1477 return S;
1478}
1479
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001480/// \brief Looks up the declaration of "struct objc_super" and
1481/// saves it for later use in building builtin declaration of
1482/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1483/// pre-existing declaration exists no action takes place.
1484static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1485 IdentifierInfo *II) {
1486 if (!II->isStr("objc_msgSendSuper"))
1487 return;
1488 ASTContext &Context = ThisSema.Context;
1489
1490 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1491 SourceLocation(), Sema::LookupTagName);
1492 ThisSema.LookupName(Result, S);
1493 if (Result.getResultKind() == LookupResult::Found)
1494 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1495 Context.setObjCSuperType(Context.getTagDeclType(TD));
1496}
1497
Douglas Gregor3e41d602009-02-13 23:20:09 +00001498/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1499/// file scope. lazily create a decl for it. ForRedeclaration is true
1500/// if we're creating this built-in in anticipation of redeclaring the
1501/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001502NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001503 Scope *S, bool ForRedeclaration,
1504 SourceLocation Loc) {
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001505 LookupPredefedObjCSuperType(*this, S, II);
1506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 Builtin::ID BID = (Builtin::ID)bid;
1508
Chris Lattner86df27b2009-06-14 00:45:47 +00001509 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001510 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001511 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001512 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001513 // Okay
1514 break;
1515
Mike Stumpf711c412009-07-28 23:57:15 +00001516 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001517 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001518 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001519 << Context.BuiltinInfo.GetName(BID);
1520 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001521
Mike Stumpf711c412009-07-28 23:57:15 +00001522 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001523 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001524 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001525 << Context.BuiltinInfo.GetName(BID);
1526 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001527
1528 case ASTContext::GE_Missing_ucontext:
1529 if (ForRedeclaration)
1530 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1531 << Context.BuiltinInfo.GetName(BID);
1532 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001533 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001534
1535 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1536 Diag(Loc, diag::ext_implicit_lib_function_decl)
1537 << Context.BuiltinInfo.GetName(BID)
1538 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001539 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001540 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001541 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001542 Diag(Loc, diag::note_please_include_header)
1543 << Context.BuiltinInfo.getHeaderName(BID)
1544 << Context.BuiltinInfo.GetName(BID);
1545 }
1546
Warren Hunt2d023ec2013-11-01 23:46:51 +00001547 DeclContext *Parent = Context.getTranslationUnitDecl();
1548 if (getLangOpts().CPlusPlus) {
1549 LinkageSpecDecl *CLinkageDecl =
1550 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1551 LinkageSpecDecl::lang_c, false);
1552 Parent->addDecl(CLinkageDecl);
1553 Parent = CLinkageDecl;
1554 }
1555
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001556 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt2d023ec2013-11-01 23:46:51 +00001557 Parent,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001558 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001559 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001560 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001561 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001562 New->setImplicit();
1563
Chris Lattner95e2c712008-05-05 22:18:14 +00001564 // Create Decl objects for each parameter, adding them to the
1565 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001566 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001567 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001568 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1569 ParmVarDecl *parm =
1570 ParmVarDecl::Create(Context, New, SourceLocation(),
1571 SourceLocation(), 0,
1572 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001573 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001574 parm->setScopeInfo(0, i);
1575 Params.push_back(parm);
1576 }
David Blaikie4278c652011-09-21 18:16:56 +00001577 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001578 }
Mike Stump1eb44332009-09-09 15:08:12 +00001579
1580 AddKnownFunctionAttributes(New);
Warren Hunt2d023ec2013-11-01 23:46:51 +00001581 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Chris Lattner7f925cc2008-04-11 07:00:53 +00001583 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001584 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1585 // relate Scopes to DeclContexts, and probably eliminate CurContext
1586 // entirely, but we're not there yet.
1587 DeclContext *SavedContext = CurContext;
Warren Hunt2d023ec2013-11-01 23:46:51 +00001588 CurContext = Parent;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001589 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001590 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 return New;
1592}
1593
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001594/// \brief Filter out any previous declarations that the given declaration
1595/// should not consider because they are not permitted to conflict, e.g.,
1596/// because they come from hidden sub-modules and do not refer to the same
1597/// entity.
1598static void filterNonConflictingPreviousDecls(ASTContext &context,
1599 NamedDecl *decl,
1600 LookupResult &previous){
1601 // This is only interesting when modules are enabled.
1602 if (!context.getLangOpts().Modules)
1603 return;
1604
1605 // Empty sets are uninteresting.
1606 if (previous.empty())
1607 return;
1608
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001609 LookupResult::Filter filter = previous.makeFilter();
1610 while (filter.hasNext()) {
1611 NamedDecl *old = filter.next();
1612
1613 // Non-hidden declarations are never ignored.
1614 if (!old->isHidden())
1615 continue;
1616
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001617 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001618 filter.erase();
1619 }
1620
1621 filter.done();
1622}
1623
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001624bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1625 QualType OldType;
1626 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1627 OldType = OldTypedef->getUnderlyingType();
1628 else
1629 OldType = Context.getTypeDeclType(Old);
1630 QualType NewType = New->getUnderlyingType();
1631
Douglas Gregorec3bd722012-01-11 22:33:48 +00001632 if (NewType->isVariablyModifiedType()) {
1633 // Must not redefine a typedef with a variably-modified type.
1634 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1635 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1636 << Kind << NewType;
1637 if (Old->getLocation().isValid())
1638 Diag(Old->getLocation(), diag::note_previous_definition);
1639 New->setInvalidDecl();
1640 return true;
1641 }
1642
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001643 if (OldType != NewType &&
1644 !OldType->isDependentType() &&
1645 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001646 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001647 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1648 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1649 << Kind << NewType << OldType;
1650 if (Old->getLocation().isValid())
1651 Diag(Old->getLocation(), diag::note_previous_definition);
1652 New->setInvalidDecl();
1653 return true;
1654 }
1655 return false;
1656}
1657
Richard Smith162e1c12011-04-15 14:24:37 +00001658/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001659/// same name and scope as a previous declaration 'Old'. Figure out
1660/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001661/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001662///
Richard Smith162e1c12011-04-15 14:24:37 +00001663void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001664 // If the new decl is known invalid already, don't bother doing any
1665 // merging checks.
1666 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Steve Naroff2b255c42008-09-09 14:32:20 +00001668 // Allow multiple definitions for ObjC built-in typedefs.
1669 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001670 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001671 const IdentifierInfo *TypeID = New->getIdentifier();
1672 switch (TypeID->getLength()) {
1673 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001674 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001675 {
1676 if (!TypeID->isStr("id"))
1677 break;
1678 QualType T = New->getUnderlyingType();
1679 if (!T->isPointerType())
1680 break;
1681 if (!T->isVoidPointerType()) {
1682 QualType PT = T->getAs<PointerType>()->getPointeeType();
1683 if (!PT->isStructureType())
1684 break;
1685 }
1686 Context.setObjCIdRedefinitionType(T);
1687 // Install the built-in type for 'id', ignoring the current definition.
1688 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1689 return;
1690 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001691 case 5:
1692 if (!TypeID->isStr("Class"))
1693 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001694 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001695 // Install the built-in type for 'Class', ignoring the current definition.
1696 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001697 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001698 case 3:
1699 if (!TypeID->isStr("SEL"))
1700 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001701 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001702 // Install the built-in type for 'SEL', ignoring the current definition.
1703 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001704 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001705 }
1706 // Fall through - the typedef name was not a builtin type.
1707 }
John McCall68263142009-11-18 22:49:29 +00001708
Douglas Gregor66973122009-01-28 17:15:10 +00001709 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001710 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1711 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001712 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001713 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001714
1715 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001716 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001717 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001718
Chris Lattnereaaebc72009-04-25 08:06:05 +00001719 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 }
Douglas Gregor66973122009-01-28 17:15:10 +00001721
John McCall68263142009-11-18 22:49:29 +00001722 // If the old declaration is invalid, just give up here.
1723 if (Old->isInvalidDecl())
1724 return New->setInvalidDecl();
1725
Chris Lattner99cb9972008-07-25 18:44:27 +00001726 // If the typedef types are not identical, reject them in all languages and
1727 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001728 if (isIncompatibleTypedef(Old, New))
1729 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Justin Bogner2dd68de2013-10-08 00:19:09 +00001731 // The types match. Link up the redeclaration chain and merge attributes if
1732 // the old declaration was a typedef.
1733 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001734 New->setPreviousDecl(Typedef);
Justin Bogner2dd68de2013-10-08 00:19:09 +00001735 mergeDeclAttributes(New, Old);
1736 }
Eli Friedman9ec40992013-07-16 02:07:49 +00001737
David Blaikie4e4d0842012-03-11 07:00:24 +00001738 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001739 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001740
David Blaikie4e4d0842012-03-11 07:00:24 +00001741 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001742 // C++ [dcl.typedef]p2:
1743 // In a given non-class scope, a typedef specifier can be used to
1744 // redefine the name of any type declared in that scope to refer
1745 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001746 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001747 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001748
1749 // C++0x [dcl.typedef]p4:
1750 // In a given class scope, a typedef specifier can be used to redefine
1751 // any class-name declared in that scope that is not also a typedef-name
1752 // to refer to the type to which it already refers.
1753 //
1754 // This wording came in via DR424, which was a correction to the
1755 // wording in DR56, which accidentally banned code like:
1756 //
1757 // struct S {
1758 // typedef struct A { } A;
1759 // };
1760 //
1761 // in the C++03 standard. We implement the C++0x semantics, which
1762 // allow the above but disallow
1763 //
1764 // struct S {
1765 // typedef int I;
1766 // typedef int I;
1767 // };
1768 //
1769 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001770 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001771 return;
1772
Chris Lattner32b06752009-04-17 22:04:20 +00001773 Diag(New->getLocation(), diag::err_redefinition)
1774 << New->getDeclName();
1775 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001776 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001777 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001778
Douglas Gregorc0004df2012-01-11 04:25:01 +00001779 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001780 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001781 return;
1782
Chris Lattner32b06752009-04-17 22:04:20 +00001783 // If we have a redefinition of a typedef in C, emit a warning. This warning
1784 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001785 // -Wtypedef-redefinition. If either the original or the redefinition is
1786 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001787 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001788 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1789 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001790 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Chris Lattner32b06752009-04-17 22:04:20 +00001792 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1793 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001794 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001795 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001796}
1797
Chris Lattner6b6b5372008-06-26 18:38:35 +00001798/// DeclhasAttr - returns true if decl Declaration already has the target
1799/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001800static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001801DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001802 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1803 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1804 // responsible for making sure they are consistent.
1805 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1806 if (AA)
1807 return false;
1808
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001809 // The following thread safety attributes can also be duplicated.
1810 switch (A->getKind()) {
1811 case attr::ExclusiveLocksRequired:
1812 case attr::SharedLocksRequired:
1813 case attr::LocksExcluded:
1814 case attr::ExclusiveLockFunction:
1815 case attr::SharedLockFunction:
1816 case attr::UnlockFunction:
1817 case attr::ExclusiveTrylockFunction:
1818 case attr::SharedTrylockFunction:
1819 case attr::GuardedBy:
1820 case attr::PtGuardedBy:
1821 case attr::AcquiredBefore:
1822 case attr::AcquiredAfter:
1823 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001824 default:
1825 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001826 }
1827
Sean Huntcf807c42010-08-18 23:23:40 +00001828 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001829 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001830 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1831 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001832 if (Ann) {
1833 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1834 return true;
1835 continue;
1836 }
Sean Huntcf807c42010-08-18 23:23:40 +00001837 // FIXME: Don't hardcode this check
1838 if (OA && isa<OwnershipAttr>(*i))
1839 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001840 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001841 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001842
1843 return false;
1844}
1845
Richard Smith671b3212013-02-22 04:55:39 +00001846static bool isAttributeTargetADefinition(Decl *D) {
1847 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1848 return VD->isThisDeclarationADefinition();
1849 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1850 return TD->isCompleteDefinition() || TD->isBeingDefined();
1851 return true;
1852}
1853
1854/// Merge alignment attributes from \p Old to \p New, taking into account the
1855/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1856///
1857/// \return \c true if any attributes were added to \p New.
1858static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1859 // Look for alignas attributes on Old, and pick out whichever attribute
1860 // specifies the strictest alignment requirement.
1861 AlignedAttr *OldAlignasAttr = 0;
1862 AlignedAttr *OldStrictestAlignAttr = 0;
1863 unsigned OldAlign = 0;
1864 for (specific_attr_iterator<AlignedAttr>
1865 I = Old->specific_attr_begin<AlignedAttr>(),
1866 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1867 // FIXME: We have no way of representing inherited dependent alignments
1868 // in a case like:
1869 // template<int A, int B> struct alignas(A) X;
1870 // template<int A, int B> struct alignas(B) X {};
1871 // For now, we just ignore any alignas attributes which are not on the
1872 // definition in such a case.
1873 if (I->isAlignmentDependent())
1874 return false;
1875
1876 if (I->isAlignas())
1877 OldAlignasAttr = *I;
1878
1879 unsigned Align = I->getAlignment(S.Context);
1880 if (Align > OldAlign) {
1881 OldAlign = Align;
1882 OldStrictestAlignAttr = *I;
1883 }
1884 }
1885
1886 // Look for alignas attributes on New.
1887 AlignedAttr *NewAlignasAttr = 0;
1888 unsigned NewAlign = 0;
1889 for (specific_attr_iterator<AlignedAttr>
1890 I = New->specific_attr_begin<AlignedAttr>(),
1891 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1892 if (I->isAlignmentDependent())
1893 return false;
1894
1895 if (I->isAlignas())
1896 NewAlignasAttr = *I;
1897
1898 unsigned Align = I->getAlignment(S.Context);
1899 if (Align > NewAlign)
1900 NewAlign = Align;
1901 }
1902
1903 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1904 // Both declarations have 'alignas' attributes. We require them to match.
1905 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1906 // fall short. (If two declarations both have alignas, they must both match
1907 // every definition, and so must match each other if there is a definition.)
1908
1909 // If either declaration only contains 'alignas(0)' specifiers, then it
1910 // specifies the natural alignment for the type.
1911 if (OldAlign == 0 || NewAlign == 0) {
1912 QualType Ty;
1913 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1914 Ty = VD->getType();
1915 else
1916 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1917
1918 if (OldAlign == 0)
1919 OldAlign = S.Context.getTypeAlign(Ty);
1920 if (NewAlign == 0)
1921 NewAlign = S.Context.getTypeAlign(Ty);
1922 }
1923
1924 if (OldAlign != NewAlign) {
1925 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1926 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1927 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1928 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1929 }
1930 }
1931
1932 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1933 // C++11 [dcl.align]p6:
1934 // if any declaration of an entity has an alignment-specifier,
1935 // every defining declaration of that entity shall specify an
1936 // equivalent alignment.
1937 // C11 6.7.5/7:
1938 // If the definition of an object does not have an alignment
1939 // specifier, any other declaration of that object shall also
1940 // have no alignment specifier.
1941 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1942 << OldAlignasAttr->isC11();
1943 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1944 << OldAlignasAttr->isC11();
1945 }
1946
1947 bool AnyAdded = false;
1948
1949 // Ensure we have an attribute representing the strictest alignment.
1950 if (OldAlign > NewAlign) {
1951 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1952 Clone->setInherited(true);
1953 New->addAttr(Clone);
1954 AnyAdded = true;
1955 }
1956
1957 // Ensure we have an alignas attribute if the old declaration had one.
1958 if (OldAlignasAttr && !NewAlignasAttr &&
1959 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1960 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1961 Clone->setInherited(true);
1962 New->addAttr(Clone);
1963 AnyAdded = true;
1964 }
1965
1966 return AnyAdded;
1967}
1968
1969static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1970 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001971 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001972 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001973 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001974 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1975 AA->getIntroduced(), AA->getDeprecated(),
1976 AA->getObsoleted(), AA->getUnavailable(),
1977 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001978 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001979 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1980 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1981 AttrSpellingListIndex);
1982 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1983 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1984 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001985 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001986 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1987 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001988 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001989 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1990 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001991 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001992 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1993 FA->getFormatIdx(), FA->getFirstArg(),
1994 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001995 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001996 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1997 AttrSpellingListIndex);
1998 else if (isa<AlignedAttr>(Attr))
1999 // AlignedAttrs are handled separately, because we need to handle all
2000 // such attributes on a declaration at the same time.
2001 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00002002 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00002003 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00002004
Rafael Espindola599f1b72012-05-13 03:25:18 +00002005 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00002006 NewAttr->setInherited(true);
2007 D->addAttr(NewAttr);
2008 return true;
2009 }
2010
2011 return false;
2012}
2013
Rafael Espindola4b044c62012-07-15 01:05:36 +00002014static const Decl *getDefinition(const Decl *D) {
2015 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00002016 return TD->getDefinition();
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002017 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2018 const VarDecl *Def = VD->getDefinition();
2019 if (Def)
2020 return Def;
2021 return VD->getActingDefinition();
2022 }
Rafael Espindola4b044c62012-07-15 01:05:36 +00002023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00002024 const FunctionDecl* Def;
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002025 if (FD->isDefined(Def))
Rafael Espindola3f664062012-05-18 01:47:00 +00002026 return Def;
2027 }
2028 return NULL;
2029}
2030
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002031static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2032 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2033 I != E; ++I) {
2034 Attr *Attribute = *I;
2035 if (Attribute->getKind() == Kind)
2036 return true;
2037 }
2038 return false;
2039}
2040
2041/// checkNewAttributesAfterDef - If we already have a definition, check that
2042/// there are no new attributes in this declaration.
2043static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2044 if (!New->hasAttrs())
2045 return;
2046
2047 const Decl *Def = getDefinition(Old);
2048 if (!Def || Def == New)
2049 return;
2050
2051 AttrVec &NewAttributes = New->getAttrs();
2052 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2053 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002054
2055 if (isa<AliasAttr>(NewAttribute)) {
2056 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2057 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2058 else {
2059 VarDecl *VD = cast<VarDecl>(New);
2060 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2061 VarDecl::TentativeDefinition
2062 ? diag::err_alias_after_tentative
2063 : diag::err_redefinition;
2064 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2065 S.Diag(Def->getLocation(), diag::note_previous_definition);
2066 VD->setInvalidDecl();
2067 }
2068 ++I;
2069 continue;
2070 }
2071
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2073 // Tentative definitions are only interesting for the alias check above.
2074 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2075 ++I;
2076 continue;
2077 }
2078 }
2079
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002080 if (hasAttribute(Def, NewAttribute->getKind())) {
2081 ++I;
2082 continue; // regular attr merging will take care of validating this.
2083 }
Richard Smith671b3212013-02-22 04:55:39 +00002084
Richard Smith7586a6e2013-01-30 05:45:05 +00002085 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002086 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002087 ++I;
2088 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002089 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2090 if (AA->isAlignas()) {
2091 // C++11 [dcl.align]p6:
2092 // if any declaration of an entity has an alignment-specifier,
2093 // every defining declaration of that entity shall specify an
2094 // equivalent alignment.
2095 // C11 6.7.5/7:
2096 // If the definition of an object does not have an alignment
2097 // specifier, any other declaration of that object shall also
2098 // have no alignment specifier.
2099 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2100 << AA->isC11();
2101 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2102 << AA->isC11();
2103 NewAttributes.erase(NewAttributes.begin() + I);
2104 --E;
2105 continue;
2106 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002107 }
Richard Smith671b3212013-02-22 04:55:39 +00002108
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002109 S.Diag(NewAttribute->getLocation(),
2110 diag::warn_attribute_precede_definition);
2111 S.Diag(Def->getLocation(), diag::note_previous_definition);
2112 NewAttributes.erase(NewAttributes.begin() + I);
2113 --E;
2114 }
2115}
2116
John McCalleca5d222011-03-02 04:00:57 +00002117/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002118void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002119 AvailabilityMergeKind AMK) {
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002120 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2121 UsedAttr *NewAttr = OldAttr->clone(Context);
2122 NewAttr->setInherited(true);
2123 New->addAttr(NewAttr);
2124 }
2125
Richard Smith3a2b7a12013-01-28 22:42:45 +00002126 if (!Old->hasAttrs() && !New->hasAttrs())
2127 return;
2128
Rafael Espindola3f664062012-05-18 01:47:00 +00002129 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002130 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002131
Douglas Gregor27c6da22012-01-01 20:30:41 +00002132 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002133 return;
John McCalleca5d222011-03-02 04:00:57 +00002134
Douglas Gregor27c6da22012-01-01 20:30:41 +00002135 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002136
Sean Huntcf807c42010-08-18 23:23:40 +00002137 // Ensure that any moving of objects within the allocated map is done before
2138 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002139 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002140
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002141 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002142 i = Old->specific_attr_begin<InheritableAttr>(),
2143 e = Old->specific_attr_end<InheritableAttr>();
2144 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002145 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002146 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002147 if (isa<DeprecatedAttr>(*i) ||
2148 isa<UnavailableAttr>(*i) ||
2149 isa<AvailabilityAttr>(*i)) {
2150 switch (AMK) {
2151 case AMK_None:
2152 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002153
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002154 case AMK_Redeclaration:
2155 break;
2156
2157 case AMK_Override:
2158 Override = true;
2159 break;
2160 }
2161 }
2162
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002163 // Already handled.
2164 if (isa<UsedAttr>(*i))
2165 continue;
2166
Richard Smith671b3212013-02-22 04:55:39 +00002167 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002168 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002169 }
John McCalleca5d222011-03-02 04:00:57 +00002170
Richard Smith671b3212013-02-22 04:55:39 +00002171 if (mergeAlignedAttrs(*this, New, Old))
2172 foundAny = true;
2173
Douglas Gregor27c6da22012-01-01 20:30:41 +00002174 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002175}
2176
2177/// mergeParamDeclAttributes - Copy attributes from the old parameter
2178/// to the new one.
2179static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2180 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002181 Sema &S) {
2182 // C++11 [dcl.attr.depend]p2:
2183 // The first declaration of a function shall specify the
2184 // carries_dependency attribute for its declarator-id if any declaration
2185 // of the function specifies the carries_dependency attribute.
2186 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2187 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2188 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2189 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2190 // Find the first declaration of the parameter.
2191 // FIXME: Should we build redeclaration chains for function parameters?
2192 const FunctionDecl *FirstFD =
Rafael Espindolabc650912013-10-17 15:37:26 +00002193 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smith3a2b7a12013-01-28 22:42:45 +00002194 const ParmVarDecl *FirstVD =
2195 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2196 S.Diag(FirstVD->getLocation(),
2197 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2198 }
2199
John McCalleca5d222011-03-02 04:00:57 +00002200 if (!oldDecl->hasAttrs())
2201 return;
2202
2203 bool foundAny = newDecl->hasAttrs();
2204
2205 // Ensure that any moving of objects within the allocated map is
2206 // done before we process them.
2207 if (!foundAny) newDecl->setAttrs(AttrVec());
2208
2209 for (specific_attr_iterator<InheritableParamAttr>
2210 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2211 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2212 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002213 InheritableAttr *newAttr =
2214 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002215 newAttr->setInherited(true);
2216 newDecl->addAttr(newAttr);
2217 foundAny = true;
2218 }
2219 }
2220
2221 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002222}
2223
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002224namespace {
2225
Douglas Gregorc8376562009-03-06 22:43:54 +00002226/// Used in MergeFunctionDecl to keep track of function parameters in
2227/// C.
2228struct GNUCompatibleParamWarning {
2229 ParmVarDecl *OldParm;
2230 ParmVarDecl *NewParm;
2231 QualType PromotedType;
2232};
2233
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002234}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002235
2236/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002237Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002238 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002239 if (Ctor->isDefaultConstructor())
2240 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002241
2242 if (Ctor->isCopyConstructor())
2243 return Sema::CXXCopyConstructor;
2244
2245 if (Ctor->isMoveConstructor())
2246 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002247 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002248 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002249 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002250 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002251 } else if (MD->isMoveAssignmentOperator()) {
2252 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002253 }
Sean Huntf961ea52011-05-10 19:08:14 +00002254
Sean Huntf961ea52011-05-10 19:08:14 +00002255 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002256}
2257
Sebastian Redl515ddd82010-06-09 21:17:41 +00002258/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002259/// only extern inline functions can be redefined, and even then only in
2260/// GNU89 mode.
2261static bool canRedefineFunction(const FunctionDecl *FD,
2262 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002263 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2264 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002265 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002266 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002267}
2268
Reid Kleckneref072032013-08-27 23:08:25 +00002269const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2270 const AttributedType *AT = T->getAs<AttributedType>();
2271 while (AT && !AT->isCallingConv())
2272 AT = AT->getModifiedType()->getAs<AttributedType>();
2273 return AT;
John McCallfb609142012-08-25 02:00:03 +00002274}
2275
Benjamin Kramera574c892013-02-15 12:30:38 +00002276template <typename T>
2277static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002278 const DeclContext *DC = Old->getDeclContext();
2279 if (DC->isRecord())
2280 return false;
2281
2282 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002283 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002284 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002285 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002286 return true;
2287 return false;
2288}
2289
Chris Lattner04421082008-04-08 04:40:51 +00002290/// MergeFunctionDecl - We just parsed a function 'New' from
2291/// declarator D which has the same name and scope as a previous
2292/// declaration 'Old'. Figure out how to resolve this situation,
2293/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002294///
2295/// In C++, New and Old must be declarations that are not
2296/// overloaded. Use IsOverload to determine whether New and Old are
2297/// overloaded, and to select the Old declaration that New should be
2298/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002299///
2300/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002301bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2302 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002303 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002304 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002305 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002306 = dyn_cast<FunctionTemplateDecl>(OldD))
2307 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002308 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002309 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002311 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002312 if (New->getFriendObjectKind()) {
2313 Diag(New->getLocation(), diag::err_using_decl_friend);
2314 Diag(Shadow->getTargetDecl()->getLocation(),
2315 diag::note_using_decl_target);
2316 Diag(Shadow->getUsingDecl()->getLocation(),
2317 diag::note_using_decl) << 0;
2318 return true;
2319 }
2320
John McCall41ce66f2009-12-10 19:51:03 +00002321 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2322 Diag(Shadow->getTargetDecl()->getLocation(),
2323 diag::note_using_decl_target);
2324 Diag(Shadow->getUsingDecl()->getLocation(),
2325 diag::note_using_decl) << 0;
2326 return true;
2327 }
2328
Chris Lattner5dc266a2008-11-20 06:13:02 +00002329 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002330 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002331 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002332 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002334
David Majnemerbcd06502013-07-07 23:49:50 +00002335 // If the old declaration is invalid, just give up here.
2336 if (Old->isInvalidDecl())
2337 return true;
2338
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002339 // Determine whether the previous declaration was a definition,
2340 // implicit declaration, or a declaration.
2341 diag::kind PrevDiag;
2342 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002343 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002344 else if (Old->isImplicit())
2345 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002346 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002347 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002349 // Don't complain about this if we're in GNU89 mode and the old function
2350 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002351 // Don't complain about specializations. They are not supposed to have
2352 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002353 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002354 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002355 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002356 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002357 !canRedefineFunction(Old, getLangOpts())) {
2358 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002359 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2360 Diag(Old->getLocation(), PrevDiag);
2361 } else {
2362 Diag(New->getLocation(), diag::err_static_non_static) << New;
2363 Diag(Old->getLocation(), PrevDiag);
2364 return true;
2365 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002366 }
2367
Reid Kleckneref072032013-08-27 23:08:25 +00002368
2369 // If a function is first declared with a calling convention, but is later
2370 // declared or defined without one, all following decls assume the calling
2371 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002372 //
John McCallfb609142012-08-25 02:00:03 +00002373 // It's OK if a function is first declared without a calling convention,
2374 // but is later declared or defined with the default calling convention.
2375 //
Reid Kleckneref072032013-08-27 23:08:25 +00002376 // To test if either decl has an explicit calling convention, we look for
2377 // AttributedType sugar nodes on the type as written. If they are missing or
2378 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002379 //
2380 // Note also that we DO NOT return at this point, because we still have
2381 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002382 QualType OldQType = Context.getCanonicalType(Old->getType());
2383 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002384 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002385 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002386 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2387 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2388 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002389
Reid Kleckneref072032013-08-27 23:08:25 +00002390 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002391 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckneref072032013-08-27 23:08:25 +00002392 const FunctionType *FT =
2393 First->getType().getCanonicalType()->castAs<FunctionType>();
2394 FunctionType::ExtInfo FI = FT->getExtInfo();
2395 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2396 if (!NewCCExplicit) {
2397 // Inherit the CC from the previous declaration if it was specified
2398 // there but not here.
2399 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2400 RequiresAdjustment = true;
2401 } else {
2402 // Calling conventions aren't compatible, so complain.
2403 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2404 Diag(New->getLocation(), diag::err_cconv_change)
2405 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2406 << !FirstCCExplicit
2407 << (!FirstCCExplicit ? "" :
2408 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002409
Reid Kleckneref072032013-08-27 23:08:25 +00002410 // Put the note on the first decl, since it is the one that matters.
2411 Diag(First->getLocation(), diag::note_previous_declaration);
2412 return true;
2413 }
John McCallf82b4e82010-02-04 05:44:44 +00002414 }
2415
John McCall04a67a62010-02-05 21:31:56 +00002416 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002417 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2418 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2419 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002420 }
2421
Douglas Gregord2c64902010-06-18 21:30:25 +00002422 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002423 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2424 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2425 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002426 Diag(New->getLocation(), diag::err_regparm_mismatch)
2427 << NewType->getRegParmType()
2428 << OldType->getRegParmType();
2429 Diag(Old->getLocation(), diag::note_previous_declaration);
2430 return true;
2431 }
John McCalle6a365d2010-12-19 02:44:49 +00002432
2433 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2434 RequiresAdjustment = true;
2435 }
2436
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002437 // Merge ns_returns_retained attribute.
2438 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2439 if (NewTypeInfo.getProducesResult()) {
2440 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2441 Diag(Old->getLocation(), diag::note_previous_declaration);
2442 return true;
2443 }
2444
2445 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2446 RequiresAdjustment = true;
2447 }
2448
John McCalle6a365d2010-12-19 02:44:49 +00002449 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002450 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2451 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2452 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002453 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002454 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002455 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002456
2457 // If this redeclaration makes the function inline, we may need to add it to
2458 // UndefinedButUsed.
2459 if (!Old->isInlined() && New->isInlined() &&
2460 !New->hasAttr<GNUInlineAttr>() &&
2461 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2462 Old->isUsed(false) &&
2463 !Old->isDefined() && !New->isThisDeclarationADefinition())
2464 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2465 SourceLocation()));
2466
2467 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2468 // about it.
2469 if (New->hasAttr<GNUInlineAttr>() &&
2470 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2471 UndefinedButUsed.erase(Old->getCanonicalDecl());
2472 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002473
David Blaikie4e4d0842012-03-11 07:00:24 +00002474 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002475 // (C++98 13.1p2):
2476 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002477 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002478 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002479
2480 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002481 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002482 // Redeclarations or specializations of a function or function template
2483 // with a declared return type that uses a placeholder type shall also
2484 // use that placeholder, not a deduced type.
2485 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2486 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2487 : OldType)->getResultType();
2488 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2489 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2490 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002491 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002492 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2493 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2494 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002495 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2496 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002497 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2498 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002499 if (New->isCXXClassMember() && New->isOutOfLine())
2500 Diag(New->getLocation(),
2501 diag::err_member_def_does_not_match_ret_type) << New;
2502 else
2503 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002504 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2505 return true;
2506 }
2507 else
2508 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002509 }
2510
Richard Smith60e141e2013-05-04 07:00:32 +00002511 QualType OldReturnType = OldType->getResultType();
2512 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2513 if (OldReturnType != NewReturnType) {
2514 // If this function has a deduced return type and has already been
2515 // defined, copy the deduced value from the old declaration.
2516 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2517 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002518 New->setType(
2519 SubstAutoType(New->getType(),
2520 OldAT->isDependentType() ? Context.DependentTy
2521 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002522 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002523 SubstAutoType(NewQType,
2524 OldAT->isDependentType() ? Context.DependentTy
2525 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002526 }
2527 }
2528
2529 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2530 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002531 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002532 // Preserve triviality.
2533 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002534
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002535 // MSVC allows explicit template specialization at class scope:
2536 // 2 CXMethodDecls referring to the same function will be injected.
2537 // We don't want a redeclartion error.
2538 bool IsClassScopeExplicitSpecialization =
2539 OldMethod->isFunctionTemplateSpecialization() &&
2540 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002541 bool isFriend = NewMethod->getFriendObjectKind();
2542
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002543 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2544 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002545 // -- Member function declarations with the same name and the
2546 // same parameter types cannot be overloaded if any of them
2547 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002548 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002549 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2550 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2551 return true;
2552 }
Richard Smith838925d2012-07-13 04:12:04 +00002553
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002554 // C++ [class.mem]p1:
2555 // [...] A member shall not be declared twice in the
2556 // member-specification, except that a nested class or member
2557 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002558 if (ActiveTemplateInstantiations.empty()) {
2559 unsigned NewDiag;
2560 if (isa<CXXConstructorDecl>(OldMethod))
2561 NewDiag = diag::err_constructor_redeclared;
2562 else if (isa<CXXDestructorDecl>(NewMethod))
2563 NewDiag = diag::err_destructor_redeclared;
2564 else if (isa<CXXConversionDecl>(NewMethod))
2565 NewDiag = diag::err_conv_function_redeclared;
2566 else
2567 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002568
Richard Smith838925d2012-07-13 04:12:04 +00002569 Diag(New->getLocation(), NewDiag);
2570 } else {
2571 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2572 << New << New->getType();
2573 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002574 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002575
2576 // Complain if this is an explicit declaration of a special
2577 // member that was initially declared implicitly.
2578 //
2579 // As an exception, it's okay to befriend such methods in order
2580 // to permit the implicit constructor/destructor/operator calls.
2581 } else if (OldMethod->isImplicit()) {
2582 if (isFriend) {
2583 NewMethod->setImplicit();
2584 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002585 Diag(NewMethod->getLocation(),
2586 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002587 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002588 return true;
2589 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002590 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002591 Diag(NewMethod->getLocation(),
2592 diag::err_definition_of_explicitly_defaulted_member)
2593 << getSpecialMember(OldMethod);
2594 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002595 }
2596 }
2597
Richard Smithcd8ab512013-01-17 01:30:42 +00002598 // C++11 [dcl.attr.noreturn]p1:
2599 // The first declaration of a function shall specify the noreturn
2600 // attribute if any declaration of that function specifies the noreturn
2601 // attribute.
2602 if (New->hasAttr<CXX11NoReturnAttr>() &&
2603 !Old->hasAttr<CXX11NoReturnAttr>()) {
2604 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2605 diag::err_noreturn_missing_on_first_decl);
Rafael Espindolabc650912013-10-17 15:37:26 +00002606 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithcd8ab512013-01-17 01:30:42 +00002607 diag::note_noreturn_missing_first_decl);
2608 }
2609
Richard Smith3a2b7a12013-01-28 22:42:45 +00002610 // C++11 [dcl.attr.depend]p2:
2611 // The first declaration of a function shall specify the
2612 // carries_dependency attribute for its declarator-id if any declaration
2613 // of the function specifies the carries_dependency attribute.
2614 if (New->hasAttr<CarriesDependencyAttr>() &&
2615 !Old->hasAttr<CarriesDependencyAttr>()) {
2616 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2617 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindolabc650912013-10-17 15:37:26 +00002618 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002619 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2620 }
2621
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002622 // (C++98 8.3.5p3):
2623 // All declarations for a function shall agree exactly in both the
2624 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002625 // We also want to respect all the extended bits except noreturn.
2626
2627 // noreturn should now match unless the old type info didn't have it.
2628 QualType OldQTypeForComparison = OldQType;
2629 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2630 assert(OldQType == QualType(OldType, 0));
2631 const FunctionType *OldTypeForComparison
2632 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2633 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2634 assert(OldQTypeForComparison.isCanonical());
2635 }
2636
Rafael Espindola950fee22013-02-14 01:18:37 +00002637 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokera8a2ebe2013-10-22 22:53:01 +00002638 // As a special case, retain the language linkage from previous
2639 // declarations of a friend function as an extension.
2640 //
2641 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2642 // and is useful because there's otherwise no way to specify language
2643 // linkage within class scope.
2644 //
2645 // Check cautiously as the friend object kind isn't yet complete.
2646 if (New->getFriendObjectKind() != Decl::FOK_None) {
2647 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2648 Diag(Old->getLocation(), PrevDiag);
2649 } else {
2650 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2651 Diag(Old->getLocation(), PrevDiag);
2652 return true;
2653 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002654 }
2655
John McCalle6a365d2010-12-19 02:44:49 +00002656 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002657 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002658
Richard Smitha41c97a2013-09-20 01:15:31 +00002659 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2660 New->isLocalExternDecl()) {
2661 // It's OK if we couldn't merge types for a local function declaraton
2662 // if either the old or new type is dependent. We'll merge the types
2663 // when we instantiate the function.
2664 return false;
2665 }
2666
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002667 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002668 }
Chris Lattner04421082008-04-08 04:40:51 +00002669
2670 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002671 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002672 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002673 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002674 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2675 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002676 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002677 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002678 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002679 // The old declaration provided a function prototype, but the
2680 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002681 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002682 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002683 OldProto->arg_type_end());
2684 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002685 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002686 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002687 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002688 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002689
2690 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002692 for (FunctionProtoType::arg_type_iterator
2693 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002694 ParamEnd = OldProto->arg_type_end();
2695 ParamType != ParamEnd; ++ParamType) {
2696 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002697 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002698 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002699 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002700 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002701 0);
John McCallfb44de92011-05-01 22:35:37 +00002702 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002703 Param->setImplicit();
2704 Params.push_back(Param);
2705 }
2706
David Blaikie4278c652011-09-21 18:16:56 +00002707 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002708 }
Douglas Gregor68719812009-02-16 18:20:44 +00002709
Richard Smithdd9459f2013-08-13 18:18:50 +00002710 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002711 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002712
Douglas Gregorc8376562009-03-06 22:43:54 +00002713 // GNU C permits a K&R definition to follow a prototype declaration
2714 // if the declared types of the parameters in the K&R definition
2715 // match the types in the prototype declaration, even when the
2716 // promoted types of the parameters from the K&R definition differ
2717 // from the types in the prototype. GCC then keeps the types from
2718 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002719 //
2720 // If a variadic prototype is followed by a non-variadic K&R definition,
2721 // the K&R definition becomes variadic. This is sort of an edge case, but
2722 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2723 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002724 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002725 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002726 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002727 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002728 SmallVector<QualType, 16> ArgTypes;
2729 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002730 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002731 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002732 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002733 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Douglas Gregorc8376562009-03-06 22:43:54 +00002735 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002736 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2737 NewProto->getResultType());
2738 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002739 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002740 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002741 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2742 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002743 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002744 NewProto->getArgType(Idx))) {
2745 ArgTypes.push_back(NewParm->getType());
2746 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002747 NewParm->getType(),
2748 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002749 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002750 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2751 Warnings.push_back(Warn);
2752 ArgTypes.push_back(NewParm->getType());
2753 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002754 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002755 }
2756
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002757 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002758 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2759 Diag(Warnings[Warn].NewParm->getLocation(),
2760 diag::ext_param_promoted_not_compatible_with_prototype)
2761 << Warnings[Warn].PromotedType
2762 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002763 if (Warnings[Warn].OldParm->getLocation().isValid())
2764 Diag(Warnings[Warn].OldParm->getLocation(),
2765 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002766 }
2767
Richard Smithdd9459f2013-08-13 18:18:50 +00002768 if (MergeTypeWithOld)
2769 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2770 OldProto->getExtProtoInfo()));
2771 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002772 }
2773
2774 // Fall through to diagnose conflicting types.
2775 }
2776
John McCall088831d2013-04-14 08:50:55 +00002777 // A function that has already been declared has been redeclared or
2778 // defined with a different type; show an appropriate diagnostic.
2779
2780 // If the previous declaration was an implicitly-generated builtin
2781 // declaration, then at the very least we should use a specialized note.
2782 unsigned BuiltinID;
2783 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2784 // If it's actually a library-defined builtin function like 'malloc'
2785 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002786 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002787 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2788 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2789 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002790
2791 // If this is a global redeclaration, just forget hereafter
2792 // about the "builtin-ness" of the function.
2793 //
2794 // Doing this for local extern declarations is problematic. If
2795 // the builtin declaration remains visible, a second invalid
2796 // local declaration will produce a hard error; if it doesn't
2797 // remain visible, a single bogus local redeclaration (which is
2798 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002799 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002800 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2801
Douglas Gregor374e1562009-03-23 17:47:24 +00002802 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002803 }
Steve Naroff837618c2008-01-16 15:01:34 +00002804
Douglas Gregorcda9c672009-02-16 17:45:42 +00002805 PrevDiag = diag::note_previous_builtin_declaration;
2806 }
2807
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002808 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002809 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002810 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811}
2812
Douglas Gregor04495c82009-02-24 01:23:02 +00002813/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002814/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002815///
2816/// This routine handles the merging of attributes and other
Alp Toker89673e02013-10-22 09:00:49 +00002817/// properties of function declarations from the old declaration to
Douglas Gregor04495c82009-02-24 01:23:02 +00002818/// the new declaration, once we know that New is in fact a
2819/// redeclaration of Old.
2820///
2821/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002822bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002823 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002824 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002825 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002826
Douglas Gregor04495c82009-02-24 01:23:02 +00002827 // Merge "pure" flag.
2828 if (Old->isPure())
2829 New->setPure();
2830
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002831 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00002832 if (Old->getMostRecentDecl()->isUsed(false))
2833 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002834
John McCalleca5d222011-03-02 04:00:57 +00002835 // Merge attributes from the parameters. These can mismatch with K&R
2836 // declarations.
2837 if (New->getNumParams() == Old->getNumParams())
2838 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2839 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002840 *this);
John McCalleca5d222011-03-02 04:00:57 +00002841
David Blaikie4e4d0842012-03-11 07:00:24 +00002842 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002843 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002844
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002845 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002846 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2847 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002848 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002849 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002850 New->setType(Merged);
2851
Douglas Gregor04495c82009-02-24 01:23:02 +00002852 return false;
2853}
2854
John McCallf85e1932011-06-15 23:02:42 +00002855
John McCalleca5d222011-03-02 04:00:57 +00002856void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002857 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002858
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002859 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002860 AvailabilityMergeKind MergeKind =
2861 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2862 : AMK_Override;
2863 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002864
2865 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002866 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2867 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002868 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002869 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002870 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002871 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002872
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002873 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002874}
2875
Sebastian Redl60618fa2011-03-12 11:50:43 +00002876/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2877/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002878/// emitting diagnostics as appropriate.
2879///
2880/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002881/// to here in AddInitializerToDecl. We can't check them before the initializer
2882/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002883void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2884 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002885 if (New->isInvalidDecl() || Old->isInvalidDecl())
2886 return;
2887
2888 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002889 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002890 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002891 // We don't know what the new type is until the initializer is attached.
2892 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002893 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2894 // These could still be something that needs exception specs checked.
2895 return MergeVarDeclExceptionSpecs(New, Old);
2896 }
Richard Smith34b41d92011-02-20 03:19:35 +00002897 // C++ [basic.link]p10:
2898 // [...] the types specified by all declarations referring to a given
2899 // object or function shall be identical, except that declarations for an
2900 // array object can specify array types that differ by the presence or
2901 // absence of a major array bound (8.3.4).
2902 else if (Old->getType()->isIncompleteArrayType() &&
2903 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002904 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2905 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2906 if (Context.hasSameType(OldArray->getElementType(),
2907 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002908 MergedT = New->getType();
2909 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002910 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002911 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2912 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2913 if (Context.hasSameType(OldArray->getElementType(),
2914 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002915 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002916 } else if (New->getType()->isObjCObjectPointerType() &&
2917 Old->getType()->isObjCObjectPointerType()) {
2918 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2919 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002920 }
2921 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002922 // C 6.2.7p2:
2923 // All declarations that refer to the same object or function shall have
2924 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002925 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2926 }
2927 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002928 // It's OK if we couldn't merge types if either type is dependent, for a
2929 // block-scope variable. In other cases (static data members of class
2930 // templates, variable templates, ...), we require the types to be
2931 // equivalent.
2932 // FIXME: The C++ standard doesn't say anything about this.
2933 if ((New->getType()->isDependentType() ||
2934 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2935 // If the old type was dependent, we can't merge with it, so the new type
2936 // becomes dependent for now. We'll reproduce the original type when we
2937 // instantiate the TypeSourceInfo for the variable.
2938 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2939 New->setType(Context.DependentTy);
2940 return;
2941 }
2942
2943 // FIXME: Even if this merging succeeds, some other non-visible declaration
2944 // of this variable might have an incompatible type. For instance:
2945 //
2946 // extern int arr[];
2947 // void f() { extern int arr[2]; }
2948 // void g() { extern int arr[3]; }
2949 //
2950 // Neither C nor C++ requires a diagnostic for this, but we should still try
2951 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002952 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002953 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002954 Diag(Old->getLocation(), diag::note_previous_definition);
2955 return New->setInvalidDecl();
2956 }
John McCall5b8740f2013-04-01 18:34:28 +00002957
2958 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002959 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002960 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002961 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002962}
2963
Richard Smith99a72382013-09-03 21:00:58 +00002964static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2965 LookupResult &Previous) {
2966 // C11 6.2.7p4:
2967 // For an identifier with internal or external linkage declared
2968 // in a scope in which a prior declaration of that identifier is
2969 // visible, if the prior declaration specifies internal or
2970 // external linkage, the type of the identifier at the later
2971 // declaration becomes the composite type.
2972 //
2973 // If the variable isn't visible, we do not merge with its type.
2974 if (Previous.isShadowed())
2975 return false;
2976
2977 if (S.getLangOpts().CPlusPlus) {
2978 // C++11 [dcl.array]p3:
2979 // If there is a preceding declaration of the entity in the same
2980 // scope in which the bound was specified, an omitted array bound
2981 // is taken to be the same as in that earlier declaration.
2982 return NewVD->isPreviousDeclInSameBlockScope() ||
2983 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2984 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2985 } else {
2986 // If the old declaration was function-local, don't merge with its
2987 // type unless we're in the same function.
2988 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2989 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2990 }
2991}
2992
Reid Spencer5f016e22007-07-11 17:01:13 +00002993/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2994/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2995/// situation, merging decls or emitting diagnostics as appropriate.
2996///
Mike Stump1eb44332009-09-09 15:08:12 +00002997/// Tentative definition rules (C99 6.9.2p2) are checked by
2998/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002999/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00003000///
Richard Smith99a72382013-09-03 21:00:58 +00003001void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00003002 // If the new decl is already invalid, don't do any other checking.
3003 if (New->isInvalidDecl())
3004 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Larisse Voufo4a919892013-08-14 03:09:19 +00003006 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00003007 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00003008 if (Previous.isSingleResult() &&
3009 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00003010 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00003011 Old = Old->getDescribedVarTemplate() ? Old : 0;
3012 else
3013 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3014 }
3015 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003016 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00003017 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00003018 Diag(Previous.getRepresentativeDecl()->getLocation(),
3019 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003020 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003022
Rafael Espindola90cc3902013-04-15 12:49:13 +00003023 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3024 return;
3025
Douglas Gregor7f6ff022010-08-30 14:32:14 +00003026 // C++ [class.mem]p1:
3027 // A member shall not be declared twice in the member-specification [...]
3028 //
3029 // Here, we need only consider static data members.
3030 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3031 Diag(New->getLocation(), diag::err_duplicate_member)
3032 << New->getIdentifier();
3033 Diag(Old->getLocation(), diag::note_previous_declaration);
3034 New->setInvalidDecl();
3035 }
3036
Douglas Gregor27c6da22012-01-01 20:30:41 +00003037 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00003038 // Warn if an already-declared variable is made a weak_import in a subsequent
3039 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00003040 if (New->getAttr<WeakImportAttr>() &&
3041 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003042 !Old->getAttr<WeakImportAttr>()) {
3043 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3044 Diag(Old->getLocation(), diag::note_previous_definition);
3045 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00003046 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003047 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003048
Richard Smith34b41d92011-02-20 03:19:35 +00003049 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00003050 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3051
Richard Smith34b41d92011-02-20 03:19:35 +00003052 if (New->isInvalidDecl())
3053 return;
Douglas Gregor656de632009-03-11 23:52:16 +00003054
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003055 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00003056 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003057 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00003058 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003059 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003060 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003061 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003062 }
Mike Stump1eb44332009-09-09 15:08:12 +00003063 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003064 // For an identifier declared with the storage-class specifier
3065 // extern in a scope in which a prior declaration of that
3066 // identifier is visible,23) if the prior declaration specifies
3067 // internal or external linkage, the linkage of the identifier at
3068 // the later declaration is the same as the linkage specified at
3069 // the prior declaration. If no prior declaration is visible, or
3070 // if the prior declaration specifies no linkage, then the
3071 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00003072 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003073 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003074 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003075 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003076 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003077 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003078 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003079 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003080 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003081
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003082 // Check if extern is followed by non-extern and vice-versa.
3083 if (New->hasExternalStorage() &&
3084 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3085 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3086 Diag(Old->getLocation(), diag::note_previous_definition);
3087 return New->setInvalidDecl();
3088 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003089 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3090 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003091 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3092 Diag(Old->getLocation(), diag::note_previous_definition);
3093 return New->setInvalidDecl();
3094 }
3095
Steve Naroff094cefb2008-09-17 14:05:40 +00003096 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003098 // FIXME: The test for external storage here seems wrong? We still
3099 // need to check for mismatches.
3100 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003101 // Don't complain about out-of-line definitions of static members.
3102 !(Old->getLexicalDeclContext()->isRecord() &&
3103 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003104 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003105 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003106 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003107 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003108
Richard Smith38afbc72013-04-13 02:43:54 +00003109 if (New->getTLSKind() != Old->getTLSKind()) {
3110 if (!Old->getTLSKind()) {
3111 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3112 Diag(Old->getLocation(), diag::note_previous_declaration);
3113 } else if (!New->getTLSKind()) {
3114 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3115 Diag(Old->getLocation(), diag::note_previous_declaration);
3116 } else {
3117 // Do not allow redeclaration to change the variable between requiring
3118 // static and dynamic initialization.
3119 // FIXME: GCC allows this, but uses the TLS keyword on the first
3120 // declaration to determine the kind. Do we need to be compatible here?
3121 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3122 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3123 Diag(Old->getLocation(), diag::note_previous_declaration);
3124 }
Eli Friedman63054b32009-04-19 20:27:55 +00003125 }
3126
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003127 // C++ doesn't have tentative definitions, so go right ahead and check here.
3128 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003129 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003130 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003131 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003132 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003133 Diag(Def->getLocation(), diag::note_previous_definition);
3134 New->setInvalidDecl();
3135 return;
3136 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003137
Rafael Espindola950fee22013-02-14 01:18:37 +00003138 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003139 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3140 Diag(Old->getLocation(), diag::note_previous_definition);
3141 New->setInvalidDecl();
3142 return;
3143 }
3144
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003145 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00003146 if (Old->getMostRecentDecl()->isUsed(false))
3147 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003148
Douglas Gregor275a3692009-03-10 23:43:53 +00003149 // Keep a chain of previous declarations.
Rafael Espindolabc650912013-10-17 15:37:26 +00003150 New->setPreviousDecl(Old);
John McCall46460a62010-01-20 21:53:11 +00003151
3152 // Inherit access appropriately.
3153 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003154
3155 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3156 if (New->isStaticDataMember() && New->isOutOfLine())
3157 VTD->setAccess(New->getAccess());
3158 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003159}
3160
3161/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3162/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003163Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003164 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003165 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003166}
3167
Eli Friedman5e867c82013-07-10 00:30:46 +00003168static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003169 if (!S.Context.getLangOpts().CPlusPlus)
3170 return;
3171
Eli Friedman5e867c82013-07-10 00:30:46 +00003172 if (isa<CXXRecordDecl>(Tag->getParent())) {
3173 // If this tag is the direct child of a class, number it if
3174 // it is anonymous.
3175 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3176 return;
3177 MangleNumberingContext &MCtx =
3178 S.Context.getManglingNumberContext(Tag->getParent());
3179 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3180 return;
3181 }
3182
3183 // If this tag isn't a direct child of a class, number it if it is local.
3184 Decl *ManglingContextDecl;
3185 if (MangleNumberingContext *MCtx =
3186 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3187 ManglingContextDecl)) {
3188 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3189 }
3190}
3191
Chandler Carruth0f4be742011-05-03 18:35:10 +00003192/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003193/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003194/// parameters to cope with template friend declarations.
3195Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3196 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003197 MultiTemplateParamsArg TemplateParams,
3198 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003199 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003200 TagDecl *Tag = 0;
3201 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3202 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003203 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003204 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003205 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003206 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003207
3208 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003209 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003210
John McCall67d1a672009-08-06 02:15:43 +00003211 // Note that the above type specs guarantee that the
3212 // type rep is a Decl, whereas in many of the others
3213 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003214 if (isa<TagDecl>(TagD))
3215 Tag = cast<TagDecl>(TagD);
3216 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3217 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003218 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003219
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003220 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003221 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003222 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003223 if (Tag->isInvalidDecl())
3224 return Tag;
3225 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003226
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003227 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3228 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3229 // or incomplete types shall not be restrict-qualified."
3230 if (TypeQuals & DeclSpec::TQ_restrict)
3231 Diag(DS.getRestrictSpecLoc(),
3232 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3233 << DS.getSourceRange();
3234 }
3235
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003236 if (DS.isConstexprSpecified()) {
3237 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3238 // and definitions of functions and variables.
3239 if (Tag)
3240 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3241 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3242 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003243 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3244 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003245 else
3246 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3247 // Don't emit warnings after this error.
3248 return TagD;
3249 }
3250
Richard Smithc7f81162013-03-18 22:52:47 +00003251 DiagnoseFunctionSpecifiers(DS);
3252
Douglas Gregord85bea22009-09-26 06:47:28 +00003253 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003254 // If we're dealing with a decl but not a TagDecl, assume that
3255 // whatever routines created it handled the friendship aspect.
3256 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003257 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003258 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003259 }
John McCallac4df242011-03-22 23:00:04 +00003260
Richard Smithc7f81162013-03-18 22:52:47 +00003261 CXXScopeSpec &SS = DS.getTypeSpecScope();
3262 bool IsExplicitSpecialization =
3263 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3264 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3265 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3266 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3267 // nested-name-specifier unless it is an explicit instantiation
3268 // or an explicit specialization.
3269 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3270 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3271 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3272 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3273 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3274 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3275 << SS.getRange();
3276 return 0;
3277 }
3278
3279 // Track whether this decl-specifier declares anything.
3280 bool DeclaresAnything = true;
3281
3282 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003283 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003284 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003285 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003286 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003287 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003288 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003289
Richard Smithc7f81162013-03-18 22:52:47 +00003290 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003291 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003292 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003293
Richard Smithc7f81162013-03-18 22:52:47 +00003294 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003295 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003296 CurContext->isRecord() &&
3297 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3298 // Handle 2 kinds of anonymous struct:
3299 // struct STRUCT;
3300 // and
3301 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3302 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003303 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003304 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3305 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003306 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003307 << DS.getSourceRange();
3308 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3309 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003310 }
Richard Smithc7f81162013-03-18 22:52:47 +00003311
3312 // Skip all the checks below if we have a type error.
3313 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3314 (TagD && TagD->isInvalidDecl()))
3315 return TagD;
3316
3317 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003318 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3319 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3320 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003321 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3322 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003323
John McCallac4df242011-03-22 23:00:04 +00003324 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003325 // Customize diagnostic for a typedef missing a name.
3326 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003327 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003328 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003329 else
3330 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003331 }
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Richard Smithc7f81162013-03-18 22:52:47 +00003333 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003334 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3335 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3336 << Tag->getTagKind()
3337 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3338
Richard Smithc7f81162013-03-18 22:52:47 +00003339 ActOnDocumentableDecl(TagD);
3340
3341 // C 6.7/2:
3342 // A declaration [...] shall declare at least a declarator [...], a tag,
3343 // or the members of an enumeration.
3344 // C++ [dcl.dcl]p3:
3345 // [If there are no declarators], and except for the declaration of an
3346 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3347 // names into the program, or shall redeclare a name introduced by a
3348 // previous declaration.
3349 if (!DeclaresAnything) {
3350 // In C, we allow this as a (popular) extension / bug. Don't bother
3351 // producing further diagnostics for redundant qualifiers after this.
3352 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3353 return TagD;
3354 }
3355
3356 // C++ [dcl.stc]p1:
3357 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3358 // init-declarator-list of the declaration shall not be empty.
3359 // C++ [dcl.fct.spec]p1:
3360 // If a cv-qualifier appears in a decl-specifier-seq, the
3361 // init-declarator-list of the declaration shall not be empty.
3362 //
3363 // Spurious qualifiers here appear to be valid in C.
3364 unsigned DiagID = diag::warn_standalone_specifier;
3365 if (getLangOpts().CPlusPlus)
3366 DiagID = diag::ext_standalone_specifier;
3367
3368 // Note that a linkage-specification sets a storage class, but
3369 // 'extern "C" struct foo;' is actually valid and not theoretically
3370 // useless.
3371 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3372 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3373 Diag(DS.getStorageClassSpecLoc(), DiagID)
3374 << DeclSpec::getSpecifierName(SCS);
3375
Richard Smithec642442013-04-12 22:46:28 +00003376 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3377 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3378 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003379 if (DS.getTypeQualifiers()) {
3380 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3381 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3382 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3383 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3384 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003385 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3386 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003387 }
3388
Eli Friedmanfc038e92011-12-17 00:36:09 +00003389 // Warn about ignored type attributes, for example:
3390 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003391 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003392 if (!DS.getAttributes().empty()) {
3393 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3394 if (TypeSpecType == DeclSpec::TST_class ||
3395 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003396 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003397 TypeSpecType == DeclSpec::TST_union ||
3398 TypeSpecType == DeclSpec::TST_enum) {
3399 AttributeList* attrs = DS.getAttributes().getList();
3400 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003401 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003402 << attrs->getName()
3403 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3404 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003405 TypeSpecType == DeclSpec::TST_union ? 2 :
3406 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003407 attrs = attrs->getNext();
3408 }
3409 }
3410 }
John McCallac4df242011-03-22 23:00:04 +00003411
John McCalld226f652010-08-21 09:40:31 +00003412 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003413}
3414
John McCall1d7c5282009-12-18 10:40:03 +00003415/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003416/// check if there's an existing declaration that can't be overloaded.
3417///
3418/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003419static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3420 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003421 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003422 DeclarationName Name,
3423 SourceLocation NameLoc,
3424 unsigned diagnostic) {
3425 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3426 Sema::ForRedeclaration);
3427 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003428
John McCall1d7c5282009-12-18 10:40:03 +00003429 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003430 return false;
3431
3432 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003433 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003434 assert(PrevDecl && "Expected a non-null Decl");
3435
3436 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3437 return false;
John McCall68263142009-11-18 22:49:29 +00003438
John McCall1d7c5282009-12-18 10:40:03 +00003439 SemaRef.Diag(NameLoc, diagnostic) << Name;
3440 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003441
3442 return true;
3443}
3444
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003445/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3446/// anonymous struct or union AnonRecord into the owning context Owner
3447/// and scope S. This routine will be invoked just after we realize
3448/// that an unnamed union or struct is actually an anonymous union or
3449/// struct, e.g.,
3450///
3451/// @code
3452/// union {
3453/// int i;
3454/// float f;
3455/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3456/// // f into the surrounding scope.x
3457/// @endcode
3458///
3459/// This routine is recursive, injecting the names of nested anonymous
3460/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003461static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003462 DeclContext *Owner,
3463 RecordDecl *AnonRecord,
3464 AccessSpecifier AS,
3465 SmallVectorImpl<NamedDecl *> &Chaining,
3466 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003467 unsigned diagKind
3468 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3469 : diag::err_anonymous_struct_member_redecl;
3470
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003471 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003472
3473 // Look every FieldDecl and IndirectFieldDecl with a name.
3474 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3475 DEnd = AnonRecord->decls_end();
3476 D != DEnd; ++D) {
3477 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3478 cast<NamedDecl>(*D)->getDeclName()) {
3479 ValueDecl *VD = cast<ValueDecl>(*D);
3480 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3481 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003482 // C++ [class.union]p2:
3483 // The names of the members of an anonymous union shall be
3484 // distinct from the names of any other entity in the
3485 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003486 Invalid = true;
3487 } else {
3488 // C++ [class.union]p2:
3489 // For the purpose of name lookup, after the anonymous union
3490 // definition, the members of the anonymous union are
3491 // considered to have been defined in the scope in which the
3492 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003493 unsigned OldChainingSize = Chaining.size();
3494 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3495 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3496 PE = IF->chain_end(); PI != PE; ++PI)
3497 Chaining.push_back(*PI);
3498 else
3499 Chaining.push_back(VD);
3500
Francois Pichet87c2e122010-11-21 06:08:52 +00003501 assert(Chaining.size() >= 2);
3502 NamedDecl **NamedChain =
3503 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3504 for (unsigned i = 0; i < Chaining.size(); i++)
3505 NamedChain[i] = Chaining[i];
3506
3507 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003508 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3509 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003510 NamedChain, Chaining.size());
3511
3512 IndirectField->setAccess(AS);
3513 IndirectField->setImplicit();
3514 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003515
3516 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003517 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003518
Francois Pichet8e161ed2010-11-23 06:07:27 +00003519 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003520 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003521 }
3522 }
3523
3524 return Invalid;
3525}
3526
Douglas Gregor16573fa2010-04-19 22:54:31 +00003527/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3528/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003529/// illegal input values are mapped to SC_None.
3530static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003531StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3532 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3533 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3534 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003535 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003536 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003537 case DeclSpec::SCS_extern:
3538 if (DS.isExternInLinkageSpec())
3539 return SC_None;
3540 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003541 case DeclSpec::SCS_static: return SC_Static;
3542 case DeclSpec::SCS_auto: return SC_Auto;
3543 case DeclSpec::SCS_register: return SC_Register;
3544 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003545 // Illegal SCSs map to None: error reporting is up to the caller.
3546 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003547 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003548 }
3549 llvm_unreachable("unknown storage class specifier");
3550}
3551
Francois Pichet8e161ed2010-11-23 06:07:27 +00003552/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003553/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003554/// (C++ [class.union]) and a C11 feature; anonymous structures
3555/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003556Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3557 AccessSpecifier AS,
3558 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003559 DeclContext *Owner = Record->getDeclContext();
3560
3561 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003562 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003563 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003564 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003565 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003566 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003567 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003569 // C and C++ require different kinds of checks for anonymous
3570 // structs/unions.
3571 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003572 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003573 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003574 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003575 if (Record->isUnion()) {
3576 // C++ [class.union]p6:
3577 // Anonymous unions declared in a named namespace or in the
3578 // global namespace shall be declared static.
3579 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3580 (isa<TranslationUnitDecl>(Owner) ||
3581 (isa<NamespaceDecl>(Owner) &&
3582 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003583 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3584 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003585
3586 // Recover by adding 'static'.
3587 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3588 PrevSpec, DiagID);
3589 }
3590 // C++ [class.union]p6:
3591 // A storage class is not allowed in a declaration of an
3592 // anonymous union in a class scope.
3593 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3594 isa<RecordDecl>(Owner)) {
3595 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003596 diag::err_anonymous_union_with_storage_spec)
3597 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003598
3599 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003600 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3601 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003602 PrevSpec, DiagID);
3603 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003604 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003605
Douglas Gregor7604f642011-05-09 23:05:33 +00003606 // Ignore const/volatile/restrict qualifiers.
3607 if (DS.getTypeQualifiers()) {
3608 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3609 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003610 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003611 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3612 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003613 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003614 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003615 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003616 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3617 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003618 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003619 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003620 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003621 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003622 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3623 Diag(DS.getAtomicSpecLoc(),
3624 diag::ext_anonymous_struct_union_qualified)
3625 << Record->isUnion() << "_Atomic"
3626 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003627
3628 DS.ClearTypeQualifiers();
3629 }
3630
Mike Stump1eb44332009-09-09 15:08:12 +00003631 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003632 // The member-specification of an anonymous union shall only
3633 // define non-static data members. [Note: nested types and
3634 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003635 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3636 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003637 Mem != MemEnd; ++Mem) {
3638 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3639 // C++ [class.union]p3:
3640 // An anonymous union shall not have private or protected
3641 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003642 assert(FD->getAccess() != AS_none);
3643 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003644 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3645 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3646 Invalid = true;
3647 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003648
Sean Huntcf34e752011-05-16 22:41:40 +00003649 // C++ [class.union]p1
3650 // An object of a class with a non-trivial constructor, a non-trivial
3651 // copy constructor, a non-trivial destructor, or a non-trivial copy
3652 // assignment operator cannot be a member of a union, nor can an
3653 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003654 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003655 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003656 } else if ((*Mem)->isImplicit()) {
3657 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003658 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3659 // This is a type that showed up in an
3660 // elaborated-type-specifier inside the anonymous struct or
3661 // union, but which actually declares a type outside of the
3662 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003663 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3664 if (!MemRecord->isAnonymousStructOrUnion() &&
3665 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003666 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003667 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00003668 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3669 << (int)Record->isUnion();
3670 else {
3671 // This is a nested type declaration.
3672 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3673 << (int)Record->isUnion();
3674 Invalid = true;
3675 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003676 } else {
3677 // This is an anonymous type definition within another anonymous type.
3678 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3679 // not part of standard C++.
3680 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003681 diag::ext_anonymous_record_with_anonymous_type)
3682 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003683 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003684 } else if (isa<AccessSpecDecl>(*Mem)) {
3685 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003686 } else {
3687 // We have something that isn't a non-static data
3688 // member. Complain about it.
3689 unsigned DK = diag::err_anonymous_record_bad_member;
3690 if (isa<TypeDecl>(*Mem))
3691 DK = diag::err_anonymous_record_with_type;
3692 else if (isa<FunctionDecl>(*Mem))
3693 DK = diag::err_anonymous_record_with_function;
3694 else if (isa<VarDecl>(*Mem))
3695 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003696
3697 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003698 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003699 DK == diag::err_anonymous_record_with_type)
3700 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003701 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003702 else {
3703 Diag((*Mem)->getLocation(), DK)
3704 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003705 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003706 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003707 }
3708 }
Mike Stump1eb44332009-09-09 15:08:12 +00003709 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003710
3711 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003712 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003713 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003714 Invalid = true;
3715 }
3716
John McCalleb692e02009-10-22 23:31:08 +00003717 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003718 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003719 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003720 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003721
Mike Stump1eb44332009-09-09 15:08:12 +00003722 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003723 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003724 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003725 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003726 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003727 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003728 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003729 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003730 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003731 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003732 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003733 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003734 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003735 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003736 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003737 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003738 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003739 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003740 // mutable can only appear on non-static class members, so it's always
3741 // an error here
3742 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3743 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003744 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003745 }
3746
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003747 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003748 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003749 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003750 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003751 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003752
3753 // Default-initialize the implicit variable. This initialization will be
3754 // trivial in almost all cases, except if a union member has an in-class
3755 // initializer:
3756 // union { int n = 0; };
3757 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003758 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003759 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003760
3761 // Add the anonymous struct/union object to the current
3762 // context. We'll be referencing this object when we refer to one of
3763 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003764 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003765
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003766 // Inject the members of the anonymous struct/union into the owning
3767 // context and into the identifier resolver chain for name lookup
3768 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003769 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003770 Chain.push_back(Anon);
3771
Francois Pichet8e161ed2010-11-23 06:07:27 +00003772 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3773 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003774 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003775
3776 // Mark this as an anonymous struct/union type. Note that we do not
3777 // do this until after we have already checked and injected the
3778 // members of this anonymous struct/union type, because otherwise
3779 // the members could be injected twice: once by DeclContext when it
3780 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003781 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003782 Record->setAnonymousStructOrUnion(true);
3783
3784 if (Invalid)
3785 Anon->setInvalidDecl();
3786
John McCalld226f652010-08-21 09:40:31 +00003787 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003788}
3789
Francois Pichet8e161ed2010-11-23 06:07:27 +00003790/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3791/// Microsoft C anonymous structure.
3792/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3793/// Example:
3794///
3795/// struct A { int a; };
3796/// struct B { struct A; int b; };
3797///
3798/// void foo() {
3799/// B var;
3800/// var.a = 3;
3801/// }
3802///
3803Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3804 RecordDecl *Record) {
3805
3806 // If there is no Record, get the record via the typedef.
3807 if (!Record)
3808 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3809
3810 // Mock up a declarator.
3811 Declarator Dc(DS, Declarator::TypeNameContext);
3812 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3813 assert(TInfo && "couldn't build declarator info for anonymous struct");
3814
3815 // Create a declaration for this anonymous struct.
3816 NamedDecl* Anon = FieldDecl::Create(Context,
3817 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003818 DS.getLocStart(),
3819 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003820 /*IdentifierInfo=*/0,
3821 Context.getTypeDeclType(Record),
3822 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003823 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003824 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003825 Anon->setImplicit();
3826
3827 // Add the anonymous struct object to the current context.
3828 CurContext->addDecl(Anon);
3829
3830 // Inject the members of the anonymous struct into the current
3831 // context and into the identifier resolver chain for name lookup
3832 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003833 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003834 Chain.push_back(Anon);
3835
Nico Weberee625af2012-02-01 00:41:00 +00003836 RecordDecl *RecordDef = Record->getDefinition();
3837 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3838 RecordDef, AS_none,
3839 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003840 Anon->setInvalidDecl();
3841
3842 return Anon;
3843}
Steve Narofff0090632007-09-02 02:04:30 +00003844
Douglas Gregor10bd3682008-11-17 22:58:34 +00003845/// GetNameForDeclarator - Determine the full declaration name for the
3846/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003847DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003848 return GetNameFromUnqualifiedId(D.getName());
3849}
3850
Abramo Bagnara25777432010-08-11 22:01:17 +00003851/// \brief Retrieves the declaration name from a parsed unqualified-id.
3852DeclarationNameInfo
3853Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3854 DeclarationNameInfo NameInfo;
3855 NameInfo.setLoc(Name.StartLocation);
3856
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003857 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003858
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003859 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003860 case UnqualifiedId::IK_Identifier:
3861 NameInfo.setName(Name.Identifier);
3862 NameInfo.setLoc(Name.StartLocation);
3863 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003864
Abramo Bagnara25777432010-08-11 22:01:17 +00003865 case UnqualifiedId::IK_OperatorFunctionId:
3866 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3867 Name.OperatorFunctionId.Operator));
3868 NameInfo.setLoc(Name.StartLocation);
3869 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3870 = Name.OperatorFunctionId.SymbolLocations[0];
3871 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3872 = Name.EndLocation.getRawEncoding();
3873 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003874
Abramo Bagnara25777432010-08-11 22:01:17 +00003875 case UnqualifiedId::IK_LiteralOperatorId:
3876 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3877 Name.Identifier));
3878 NameInfo.setLoc(Name.StartLocation);
3879 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3880 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003881
Abramo Bagnara25777432010-08-11 22:01:17 +00003882 case UnqualifiedId::IK_ConversionFunctionId: {
3883 TypeSourceInfo *TInfo;
3884 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3885 if (Ty.isNull())
3886 return DeclarationNameInfo();
3887 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3888 Context.getCanonicalType(Ty)));
3889 NameInfo.setLoc(Name.StartLocation);
3890 NameInfo.setNamedTypeInfo(TInfo);
3891 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003892 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003893
3894 case UnqualifiedId::IK_ConstructorName: {
3895 TypeSourceInfo *TInfo;
3896 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3897 if (Ty.isNull())
3898 return DeclarationNameInfo();
3899 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3900 Context.getCanonicalType(Ty)));
3901 NameInfo.setLoc(Name.StartLocation);
3902 NameInfo.setNamedTypeInfo(TInfo);
3903 return NameInfo;
3904 }
3905
3906 case UnqualifiedId::IK_ConstructorTemplateId: {
3907 // In well-formed code, we can only have a constructor
3908 // template-id that refers to the current context, so go there
3909 // to find the actual type being constructed.
3910 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3911 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3912 return DeclarationNameInfo();
3913
3914 // Determine the type of the class being constructed.
3915 QualType CurClassType = Context.getTypeDeclType(CurClass);
3916
3917 // FIXME: Check two things: that the template-id names the same type as
3918 // CurClassType, and that the template-id does not occur when the name
3919 // was qualified.
3920
3921 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3922 Context.getCanonicalType(CurClassType)));
3923 NameInfo.setLoc(Name.StartLocation);
3924 // FIXME: should we retrieve TypeSourceInfo?
3925 NameInfo.setNamedTypeInfo(0);
3926 return NameInfo;
3927 }
3928
3929 case UnqualifiedId::IK_DestructorName: {
3930 TypeSourceInfo *TInfo;
3931 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3932 if (Ty.isNull())
3933 return DeclarationNameInfo();
3934 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3935 Context.getCanonicalType(Ty)));
3936 NameInfo.setLoc(Name.StartLocation);
3937 NameInfo.setNamedTypeInfo(TInfo);
3938 return NameInfo;
3939 }
3940
3941 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003942 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003943 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3944 return Context.getNameForTemplate(TName, TNameLoc);
3945 }
3946
3947 } // switch (Name.getKind())
3948
David Blaikieb219cfc2011-09-23 05:06:16 +00003949 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003950}
3951
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003952static QualType getCoreType(QualType Ty) {
3953 do {
3954 if (Ty->isPointerType() || Ty->isReferenceType())
3955 Ty = Ty->getPointeeType();
3956 else if (Ty->isArrayType())
3957 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3958 else
3959 return Ty.withoutLocalFastQualifiers();
3960 } while (true);
3961}
3962
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003963/// hasSimilarParameters - Determine whether the C++ functions Declaration
3964/// and Definition have "nearly" matching parameters. This heuristic is
3965/// used to improve diagnostics in the case where an out-of-line function
3966/// definition doesn't match any declaration within the class or namespace.
3967/// Also sets Params to the list of indices to the parameters that differ
3968/// between the declaration and the definition. If hasSimilarParameters
3969/// returns true and Params is empty, then all of the parameters match.
3970static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003971 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003972 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003973 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003974 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003975 if (Declaration->param_size() != Definition->param_size())
3976 return false;
3977 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3978 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3979 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3980
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003981 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003982 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003983 continue;
3984
3985 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3986 QualType DefParamBaseTy = getCoreType(DefParamTy);
3987 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3988 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3989
3990 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3991 (DeclTyName && DeclTyName == DefTyName))
3992 Params.push_back(Idx);
3993 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003994 return false;
3995 }
3996
3997 return true;
3998}
3999
John McCall63b43852010-04-29 23:50:39 +00004000/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4001/// declarator needs to be rebuilt in the current instantiation.
4002/// Any bits of declarator which appear before the name are valid for
4003/// consideration here. That's specifically the type in the decl spec
4004/// and the base type in any member-pointer chunks.
4005static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4006 DeclarationName Name) {
4007 // The types we specifically need to rebuild are:
4008 // - typenames, typeofs, and decltypes
4009 // - types which will become injected class names
4010 // Of course, we also need to rebuild any type referencing such a
4011 // type. It's safest to just say "dependent", but we call out a
4012 // few cases here.
4013
4014 DeclSpec &DS = D.getMutableDeclSpec();
4015 switch (DS.getTypeSpecType()) {
4016 case DeclSpec::TST_typename:
4017 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00004018 case DeclSpec::TST_underlyingType:
4019 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00004020 // Grab the type from the parser.
4021 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00004022 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00004023 if (T.isNull() || !T->isDependentType()) break;
4024
4025 // Make sure there's a type source info. This isn't really much
4026 // of a waste; most dependent types should have type source info
4027 // attached already.
4028 if (!TSI)
4029 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4030
4031 // Rebuild the type in the current instantiation.
4032 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4033 if (!TSI) return true;
4034
4035 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00004036 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4037 DS.UpdateTypeRep(LocType);
4038 break;
4039 }
4040
Richard Smithc4a83912012-10-01 20:35:07 +00004041 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00004042 case DeclSpec::TST_typeofExpr: {
4043 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00004044 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00004045 if (Result.isInvalid()) return true;
4046 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00004047 break;
4048 }
4049
4050 default:
4051 // Nothing to do for these decl specs.
4052 break;
4053 }
4054
4055 // It doesn't matter what order we do this in.
4056 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4057 DeclaratorChunk &Chunk = D.getTypeObject(I);
4058
4059 // The only type information in the declarator which can come
4060 // before the declaration name is the base type of a member
4061 // pointer.
4062 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4063 continue;
4064
4065 // Rebuild the scope specifier in-place.
4066 CXXScopeSpec &SS = Chunk.Mem.Scope();
4067 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4068 return true;
4069 }
4070
4071 return false;
4072}
4073
Anders Carlsson3242ee02011-07-04 16:28:17 +00004074Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00004075 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004076 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004077
4078 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004079 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004080 Dcl->setTopLevelDeclInObjCContainer();
4081
4082 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004083}
4084
Richard Smith162e1c12011-04-15 14:24:37 +00004085/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4086/// If T is the name of a class, then each of the following shall have a
4087/// name different from T:
4088/// - every static data member of class T;
4089/// - every member function of class T
4090/// - every member of class T that is itself a type;
4091/// \returns true if the declaration name violates these rules.
4092bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4093 DeclarationNameInfo NameInfo) {
4094 DeclarationName Name = NameInfo.getName();
4095
4096 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4097 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4098 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4099 return true;
4100 }
4101
4102 return false;
4103}
Douglas Gregor42acead2012-03-17 23:06:31 +00004104
Douglas Gregor69605872012-03-28 16:01:27 +00004105/// \brief Diagnose a declaration whose declarator-id has the given
4106/// nested-name-specifier.
4107///
4108/// \param SS The nested-name-specifier of the declarator-id.
4109///
4110/// \param DC The declaration context to which the nested-name-specifier
4111/// resolves.
4112///
4113/// \param Name The name of the entity being declared.
4114///
4115/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004116///
4117/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004118bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004119 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004120 SourceLocation Loc) {
4121 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004122 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004123 Cur = Cur->getParent();
4124
4125 // C++ [dcl.meaning]p1:
4126 // A declarator-id shall not be qualified except for the definition
4127 // of a member function (9.3) or static data member (9.4) outside of
4128 // its class, the definition or explicit instantiation of a function
4129 // or variable member of a namespace outside of its namespace, or the
4130 // definition of an explicit specialization outside of its namespace,
4131 // or the declaration of a friend function that is a member of
4132 // another class or namespace (11.3). [...]
4133
4134 // The user provided a superfluous scope specifier that refers back to the
4135 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004136 //
4137 // class X {
4138 // void X::f();
4139 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004140 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004141 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4142 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004143 << Name << FixItHint::CreateRemoval(SS.getRange());
4144 SS.clear();
4145 return false;
4146 }
Douglas Gregor69605872012-03-28 16:01:27 +00004147
4148 // Check whether the qualifying scope encloses the scope of the original
4149 // declaration.
4150 if (!Cur->Encloses(DC)) {
4151 if (Cur->isRecord())
4152 Diag(Loc, diag::err_member_qualification)
4153 << Name << SS.getRange();
4154 else if (isa<TranslationUnitDecl>(DC))
4155 Diag(Loc, diag::err_invalid_declarator_global_scope)
4156 << Name << SS.getRange();
4157 else if (isa<FunctionDecl>(Cur))
4158 Diag(Loc, diag::err_invalid_declarator_in_function)
4159 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004160 else if (isa<BlockDecl>(Cur))
4161 Diag(Loc, diag::err_invalid_declarator_in_block)
4162 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004163 else
4164 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004165 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004166
Douglas Gregor42acead2012-03-17 23:06:31 +00004167 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004168 }
4169
4170 if (Cur->isRecord()) {
4171 // Cannot qualify members within a class.
4172 Diag(Loc, diag::err_member_qualification)
4173 << Name << SS.getRange();
4174 SS.clear();
4175
4176 // C++ constructors and destructors with incorrect scopes can break
4177 // our AST invariants by having the wrong underlying types. If
4178 // that's the case, then drop this declaration entirely.
4179 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4180 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4181 !Context.hasSameType(Name.getCXXNameType(),
4182 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4183 return true;
4184
4185 return false;
4186 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004187
Douglas Gregor69605872012-03-28 16:01:27 +00004188 // C++11 [dcl.meaning]p1:
4189 // [...] "The nested-name-specifier of the qualified declarator-id shall
4190 // not begin with a decltype-specifer"
4191 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4192 while (SpecLoc.getPrefix())
4193 SpecLoc = SpecLoc.getPrefix();
4194 if (dyn_cast_or_null<DecltypeType>(
4195 SpecLoc.getNestedNameSpecifier()->getAsType()))
4196 Diag(Loc, diag::err_decltype_in_declarator)
4197 << SpecLoc.getTypeLoc().getSourceRange();
4198
Douglas Gregor42acead2012-03-17 23:06:31 +00004199 return false;
4200}
4201
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004202NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4203 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004204 // TODO: consider using NameInfo for diagnostic.
4205 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4206 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004207
Chris Lattnere80a59c2007-07-25 00:24:17 +00004208 // All of these full declarators require an identifier. If it doesn't have
4209 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004210 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004211 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004212 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004213 diag::err_declarator_need_ident)
4214 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004215 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004216 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4217 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Chris Lattner31e05722007-08-26 06:24:45 +00004219 // The scope passed in may not be a decl scope. Zip up the scope tree until
4220 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004221 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004222 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004223 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004224
John McCall63b43852010-04-29 23:50:39 +00004225 DeclContext *DC = CurContext;
4226 if (D.getCXXScopeSpec().isInvalid())
4227 D.setInvalidType();
4228 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004229 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4230 UPPC_DeclarationQualifier))
4231 return 0;
4232
John McCall63b43852010-04-29 23:50:39 +00004233 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4234 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Bill Wendling13303b92013-11-26 04:09:45 +00004235 if (!DC || isa<EnumDecl>(DC)) {
John McCall63b43852010-04-29 23:50:39 +00004236 // If we could not compute the declaration context, it's because the
4237 // declaration context is dependent but does not refer to a class,
4238 // class template, or class template partial specialization. Complain
4239 // and return early, to avoid the coming semantic disaster.
4240 Diag(D.getIdentifierLoc(),
4241 diag::err_template_qualified_declarator_no_match)
4242 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4243 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004244 return 0;
John McCall63b43852010-04-29 23:50:39 +00004245 }
John McCall63b43852010-04-29 23:50:39 +00004246 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004247
John McCall63b43852010-04-29 23:50:39 +00004248 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004249 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004250 return 0;
John McCall63b43852010-04-29 23:50:39 +00004251
Douglas Gregor69605872012-03-28 16:01:27 +00004252 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4253 Diag(D.getIdentifierLoc(),
4254 diag::err_member_def_undefined_record)
4255 << Name << DC << D.getCXXScopeSpec().getRange();
4256 D.setInvalidType();
4257 } else if (!D.getDeclSpec().isFriendSpecified()) {
4258 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4259 Name, D.getIdentifierLoc())) {
4260 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004261 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004262
4263 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004264 }
John McCall63b43852010-04-29 23:50:39 +00004265 }
4266
4267 // Check whether we need to rebuild the type of the given
4268 // declaration in the current instantiation.
4269 if (EnteringContext && IsDependentContext &&
4270 TemplateParamLists.size() != 0) {
4271 ContextRAII SavedContext(*this, DC);
4272 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4273 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004274 }
4275 }
Richard Smith162e1c12011-04-15 14:24:37 +00004276
4277 if (DiagnoseClassNameShadow(DC, NameInfo))
4278 // If this is a typedef, we'll end up spewing multiple diagnostics.
4279 // Just return early; it's safer.
4280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4281 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004282
John McCallbf1a0282010-06-04 23:28:52 +00004283 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4284 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004285
Douglas Gregord0937222010-12-13 22:49:22 +00004286 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4287 UPPC_DeclarationType))
4288 D.setInvalidType();
4289
Abramo Bagnara25777432010-08-11 22:01:17 +00004290 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004291 ForRedeclaration);
4292
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004293 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004294 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004295 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004296 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004297
4298 // If the declaration we're planning to build will be a function
4299 // or object with linkage, then look for another declaration with
4300 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004301 //
4302 // If the declaration we're planning to build will be declared with
4303 // external linkage in the translation unit, create any builtin with
4304 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004305 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4306 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004307 else if (CurContext->isFunctionOrMethod() &&
4308 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4309 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004310 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004311 CreateBuiltins =
4312 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4313 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4314 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4315 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004316
4317 if (IsLinkageLookup)
4318 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004319
Richard Smithdd9459f2013-08-13 18:18:50 +00004320 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004321 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004322 LookupQualifiedName(Previous, DC);
4323
Douglas Gregor69605872012-03-28 16:01:27 +00004324 // C++ [dcl.meaning]p1:
4325 // When the declarator-id is qualified, the declaration shall refer to a
4326 // previously declared member of the class or namespace to which the
4327 // qualifier refers (or, in the case of a namespace, of an element of the
4328 // inline namespace set of that namespace (7.3.1)) or to a specialization
4329 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004330 //
Douglas Gregor69605872012-03-28 16:01:27 +00004331 // Note that we already checked the context above, and that we do not have
4332 // enough information to make sure that Previous contains the declaration
4333 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004334 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004335 // class X {
4336 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004337 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004338 // };
4339 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004340 // void X::f(int) { } // ill-formed
4341 //
Douglas Gregor69605872012-03-28 16:01:27 +00004342 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004343 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004344 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004345
4346 // C++ [dcl.meaning]p1:
4347 // [...] the member shall not merely have been introduced by a
4348 // using-declaration in the scope of the class or namespace nominated by
4349 // the nested-name-specifier of the declarator-id.
4350 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004351 }
4352
John McCall68263142009-11-18 22:49:29 +00004353 if (Previous.isSingleResult() &&
4354 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004355 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004356 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004357 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4358 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Douglas Gregor72c3f312008-12-05 18:15:24 +00004360 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004361 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004362 }
4363
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004364 // In C++, the previous declaration we find might be a tag type
4365 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004366 // tag type. Note that this does does not apply if we're declaring a
4367 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004368 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004369 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004370 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004371
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004372 // Check that there are no default arguments other than in the parameters
4373 // of a function declaration (C++ only).
4374 if (getLangOpts().CPlusPlus)
4375 CheckExtraCXXDefaultArguments(D);
4376
Nico Webere6bb76c2012-12-23 00:40:46 +00004377 NamedDecl *New;
4378
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004379 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004380 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004381 if (TemplateParamLists.size()) {
4382 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004383 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004384 }
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004386 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004387 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004388 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004389 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004390 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004391 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004392 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4393 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004394 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004395
4396 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004397 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004398
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004399 // If this has an identifier and is not an invalid redeclaration or
4400 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004401 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004402 !(D.isRedeclaration() && New->isInvalidDecl())) {
4403 // Only make a locally-scoped extern declaration visible if it is the first
4404 // declaration of this entity. Qualified lookup for such an entity should
4405 // only find this declaration if there is no visible declaration of it.
4406 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4407 PushOnScopeChains(New, S, AddToContext);
4408 if (!AddToContext)
4409 CurContext->addHiddenDecl(New);
4410 }
Mike Stump1eb44332009-09-09 15:08:12 +00004411
John McCalld226f652010-08-21 09:40:31 +00004412 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004413}
4414
Abramo Bagnara88adb982012-11-08 16:27:30 +00004415/// Helper method to turn variable array types into constant array
4416/// types in certain situations which would otherwise be errors (for
4417/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004418static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4419 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004420 bool &SizeIsNegative,
4421 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004422 // This method tries to turn a variable array into a constant
4423 // array even when the size isn't an ICE. This is necessary
4424 // for compatibility with code that depends on gcc's buggy
4425 // constant expression folding, like struct {char x[(int)(char*)2];}
4426 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004427 Oversized = 0;
4428
4429 if (T->isDependentType())
4430 return QualType();
4431
John McCall0953e762009-09-24 19:53:00 +00004432 QualifierCollector Qs;
4433 const Type *Ty = Qs.strip(T);
4434
4435 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004436 QualType Pointee = PTy->getPointeeType();
4437 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004438 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4439 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004440 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004441 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004442 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004443 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004444 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4445 QualType Inner = PTy->getInnerType();
4446 QualType FixedType =
4447 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4448 Oversized);
4449 if (FixedType.isNull()) return FixedType;
4450 FixedType = Context.getParenType(FixedType);
4451 return Qs.apply(Context, FixedType);
4452 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004453
4454 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004455 if (!VLATy)
4456 return QualType();
4457 // FIXME: We should probably handle this case
4458 if (VLATy->getElementType()->isVariablyModifiedType())
4459 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004460
Richard Smithaa9c3502011-12-07 00:43:50 +00004461 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004462 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004463 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004464 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004465
Douglas Gregor2767ce22010-08-18 00:39:00 +00004466 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004467 if (Res.isSigned() && Res.isNegative()) {
4468 SizeIsNegative = true;
4469 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004470 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004471
Douglas Gregor2767ce22010-08-18 00:39:00 +00004472 // Check whether the array is too large to be addressed.
4473 unsigned ActiveSizeBits
4474 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4475 Res);
4476 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4477 Oversized = Res;
4478 return QualType();
4479 }
4480
4481 return Context.getConstantArrayType(VLATy->getElementType(),
4482 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004483}
4484
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004485static void
4486FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004487 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4488 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4489 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4490 DstPTL.getPointeeLoc());
4491 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004492 return;
4493 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004494 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4495 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4496 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4497 DstPTL.getInnerLoc());
4498 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4499 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004500 return;
4501 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004502 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4503 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4504 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4505 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004506 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004507 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4508 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4509 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004510}
4511
Abramo Bagnara88adb982012-11-08 16:27:30 +00004512/// Helper method to turn variable array types into constant array
4513/// types in certain situations which would otherwise be errors (for
4514/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004515static TypeSourceInfo*
4516TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4517 ASTContext &Context,
4518 bool &SizeIsNegative,
4519 llvm::APSInt &Oversized) {
4520 QualType FixedTy
4521 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4522 SizeIsNegative, Oversized);
4523 if (FixedTy.isNull())
4524 return 0;
4525 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4526 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4527 FixedTInfo->getTypeLoc());
4528 return FixedTInfo;
4529}
4530
Richard Smith5ea6ef42013-01-10 23:43:47 +00004531/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004532/// that it can be found later for redeclarations. We include any extern "C"
4533/// declaration that is not visible in the translation unit here, not just
4534/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004535void
Richard Smith662f41b2013-06-18 20:15:12 +00004536Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004537 if (!getLangOpts().CPlusPlus &&
4538 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4539 // Don't need to track declarations in the TU in C.
4540 return;
4541
Douglas Gregor63935192009-03-02 00:19:53 +00004542 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004543 // FIXME: There can be multiple such declarations if they are functions marked
4544 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004545 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004546}
4547
Richard Smith662f41b2013-06-18 20:15:12 +00004548NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004549 if (ExternalSource) {
4550 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004551 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004552 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004553 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004554 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4555 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004556 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4557 if (Pos == LocallyScopedExternCDecls.end())
4558 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004559 }
4560 }
Richard Smith662f41b2013-06-18 20:15:12 +00004561
4562 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola87bcee82013-10-19 16:55:03 +00004563 return D ? D->getMostRecentDecl() : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004564}
4565
Eli Friedman85a53192009-04-07 19:37:57 +00004566/// \brief Diagnose function specifiers on a declaration of an identifier that
4567/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004568void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004569 // FIXME: We should probably indicate the identifier in question to avoid
4570 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004571 if (DS.isInlineSpecified())
4572 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004573 diag::err_inline_non_function);
4574
Richard Smithc7f81162013-03-18 22:52:47 +00004575 if (DS.isVirtualSpecified())
4576 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004577 diag::err_virtual_non_function);
4578
Richard Smithc7f81162013-03-18 22:52:47 +00004579 if (DS.isExplicitSpecified())
4580 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004581 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004582
Richard Smithc7f81162013-03-18 22:52:47 +00004583 if (DS.isNoreturnSpecified())
4584 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004585 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004586}
4587
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004588NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004589Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004590 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004591 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4592 if (D.getCXXScopeSpec().isSet()) {
4593 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4594 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004595 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004596 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004597 DC = CurContext;
4598 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004599 }
4600
Richard Smithc7f81162013-03-18 22:52:47 +00004601 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004602
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004603 if (D.getDeclSpec().isConstexprSpecified())
4604 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4605 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004606
Douglas Gregoraef01992010-07-13 06:37:01 +00004607 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4608 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4609 << D.getName().getSourceRange();
4610 return 0;
4611 }
4612
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004613 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004614 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004616 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004617 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004618
Richard Smith3e4c6c42011-05-05 21:57:07 +00004619 CheckTypedefForVariablyModifiedType(S, NewTD);
4620
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004621 bool Redeclaration = D.isRedeclaration();
4622 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4623 D.setRedeclaration(Redeclaration);
4624 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004625}
4626
Richard Smith3e4c6c42011-05-05 21:57:07 +00004627void
4628Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004629 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4630 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004631 // Note that variably modified types must be fixed before merging the decl so
4632 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004633 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4634 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004635 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004636 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004638 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004639 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004640 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004641 TypeSourceInfo *FixedTInfo =
4642 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4643 SizeIsNegative,
4644 Oversized);
4645 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004646 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004647 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004648 } else {
4649 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004650 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004651 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004652 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004653 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004654 Diag(NewTD->getLocation(), diag::err_array_too_large)
4655 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004656 else
Richard Smith162e1c12011-04-15 14:24:37 +00004657 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004658 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004659 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004660 }
4661 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004662}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004663
Richard Smith3e4c6c42011-05-05 21:57:07 +00004664
4665/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4666/// declares a typedef-name, either using the 'typedef' type specifier or via
4667/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4668NamedDecl*
4669Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4670 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004671 // Merge the decl with the existing one if appropriate. If the decl is
4672 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004673 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004674 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004675 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004676 if (!Previous.empty()) {
4677 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004678 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004679 }
4680
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004681 // If this is the C FILE type, notify the AST context.
4682 if (IdentifierInfo *II = NewTD->getIdentifier())
4683 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004684 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004685 if (II->isStr("FILE"))
4686 Context.setFILEDecl(NewTD);
4687 else if (II->isStr("jmp_buf"))
4688 Context.setjmp_bufDecl(NewTD);
4689 else if (II->isStr("sigjmp_buf"))
4690 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004691 else if (II->isStr("ucontext_t"))
4692 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004693 }
4694
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004695 return NewTD;
4696}
4697
Douglas Gregor8f301052009-02-24 19:23:27 +00004698/// \brief Determines whether the given declaration is an out-of-scope
4699/// previous declaration.
4700///
4701/// This routine should be invoked when name lookup has found a
4702/// previous declaration (PrevDecl) that is not in the scope where a
4703/// new declaration by the same name is being introduced. If the new
4704/// declaration occurs in a local scope, previous declarations with
4705/// linkage may still be considered previous declarations (C99
4706/// 6.2.2p4-5, C++ [basic.link]p6).
4707///
4708/// \param PrevDecl the previous declaration found by name
4709/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004710///
Douglas Gregor8f301052009-02-24 19:23:27 +00004711/// \param DC the context in which the new declaration is being
4712/// declared.
4713///
4714/// \returns true if PrevDecl is an out-of-scope previous declaration
4715/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004716static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004717isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4718 ASTContext &Context) {
4719 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004720 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004721
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004722 if (!PrevDecl->hasLinkage())
4723 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004724
David Blaikie4e4d0842012-03-11 07:00:24 +00004725 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004726 // C++ [basic.link]p6:
4727 // If there is a visible declaration of an entity with linkage
4728 // having the same name and type, ignoring entities declared
4729 // outside the innermost enclosing namespace scope, the block
4730 // scope declaration declares that same entity and receives the
4731 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004732 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004733 if (!OuterContext->isFunctionOrMethod())
4734 // This rule only applies to block-scope declarations.
4735 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004736
4737 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4738 if (PrevOuterContext->isRecord())
4739 // We found a member function: ignore it.
4740 return false;
4741
4742 // Find the innermost enclosing namespace for the new and
4743 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004744 OuterContext = OuterContext->getEnclosingNamespaceContext();
4745 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004746
Douglas Gregor757c6002010-08-27 22:55:10 +00004747 // The previous declaration is in a different namespace, so it
4748 // isn't the same function.
4749 if (!OuterContext->Equals(PrevOuterContext))
4750 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004751 }
4752
Douglas Gregor8f301052009-02-24 19:23:27 +00004753 return true;
4754}
4755
John McCallb6217662010-03-15 10:12:16 +00004756static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4757 CXXScopeSpec &SS = D.getCXXScopeSpec();
4758 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004759 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004760}
4761
John McCallf85e1932011-06-15 23:02:42 +00004762bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4763 QualType type = decl->getType();
4764 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4765 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4766 // Various kinds of declaration aren't allowed to be __autoreleasing.
4767 unsigned kind = -1U;
4768 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4769 if (var->hasAttr<BlocksAttr>())
4770 kind = 0; // __block
4771 else if (!var->hasLocalStorage())
4772 kind = 1; // global
4773 } else if (isa<ObjCIvarDecl>(decl)) {
4774 kind = 3; // ivar
4775 } else if (isa<FieldDecl>(decl)) {
4776 kind = 2; // field
4777 }
4778
4779 if (kind != -1U) {
4780 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4781 << kind;
4782 }
4783 } else if (lifetime == Qualifiers::OCL_None) {
4784 // Try to infer lifetime.
4785 if (!type->isObjCLifetimeType())
4786 return false;
4787
4788 lifetime = type->getObjCARCImplicitLifetime();
4789 type = Context.getLifetimeQualifiedType(type, lifetime);
4790 decl->setType(type);
4791 }
4792
4793 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4794 // Thread-local variables cannot have lifetime.
4795 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004796 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004797 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004798 << var->getType();
4799 return true;
4800 }
4801 }
4802
4803 return false;
4804}
4805
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004806static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4807 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004808 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004809 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004810 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4811 ND.dropAttr<WeakAttr>();
4812 }
4813 }
4814 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004815 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004816 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4817 ND.dropAttr<WeakRefAttr>();
4818 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004819 }
Reid Klecknera7225342013-05-20 14:02:37 +00004820
4821 // 'selectany' only applies to externally visible varable declarations.
4822 // It does not apply to functions.
4823 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4824 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4825 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4826 ND.dropAttr<SelectAnyAttr>();
4827 }
4828 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004829}
4830
John McCallb421d922013-04-02 02:48:58 +00004831/// Given that we are within the definition of the given function,
4832/// will that definition behave like C99's 'inline', where the
4833/// definition is discarded except for optimization purposes?
4834static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4835 // Try to avoid calling GetGVALinkageForFunction.
4836
4837 // All cases of this require the 'inline' keyword.
4838 if (!FD->isInlined()) return false;
4839
4840 // This is only possible in C++ with the gnu_inline attribute.
4841 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4842 return false;
4843
4844 // Okay, go ahead and call the relatively-more-expensive function.
4845
4846#ifndef NDEBUG
4847 // AST quite reasonably asserts that it's working on a function
4848 // definition. We don't really have a way to tell it that we're
4849 // currently defining the function, so just lie to it in +Asserts
4850 // builds. This is an awful hack.
4851 FD->setLazyBody(1);
4852#endif
4853
4854 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4855
4856#ifndef NDEBUG
4857 FD->setLazyBody(0);
4858#endif
4859
4860 return isC99Inline;
4861}
4862
Richard Smithaa4bc182013-06-30 09:48:50 +00004863/// Determine whether a variable is extern "C" prior to attaching
4864/// an initializer. We can't just call isExternC() here, because that
4865/// will also compute and cache whether the declaration is externally
4866/// visible, which might change when we attach the initializer.
4867///
4868/// This can only be used if the declaration is known to not be a
4869/// redeclaration of an internal linkage declaration.
4870///
4871/// For instance:
4872///
4873/// auto x = []{};
4874///
4875/// Attaching the initializer here makes this declaration not externally
4876/// visible, because its type has internal linkage.
4877///
4878/// FIXME: This is a hack.
4879template<typename T>
4880static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4881 if (S.getLangOpts().CPlusPlus) {
4882 // In C++, the overloadable attribute negates the effects of extern "C".
4883 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4884 return false;
4885 }
4886 return D->isExternC();
4887}
4888
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004889static bool shouldConsiderLinkage(const VarDecl *VD) {
4890 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4891 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004892 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004893 if (DC->isFileContext())
4894 return true;
4895 if (DC->isRecord())
4896 return false;
4897 llvm_unreachable("Unexpected context");
4898}
4899
4900static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4901 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4902 if (DC->isFileContext() || DC->isFunctionOrMethod())
4903 return true;
4904 if (DC->isRecord())
4905 return false;
4906 llvm_unreachable("Unexpected context");
4907}
4908
Richard Smitha41c97a2013-09-20 01:15:31 +00004909/// Adjust the \c DeclContext for a function or variable that might be a
4910/// function-local external declaration.
4911bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4912 if (!DC->isFunctionOrMethod())
4913 return false;
4914
4915 // If this is a local extern function or variable declared within a function
4916 // template, don't add it into the enclosing namespace scope until it is
4917 // instantiated; it might have a dependent type right now.
4918 if (DC->isDependentContext())
4919 return true;
4920
4921 // C++11 [basic.link]p7:
4922 // When a block scope declaration of an entity with linkage is not found to
4923 // refer to some other declaration, then that entity is a member of the
4924 // innermost enclosing namespace.
4925 //
4926 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4927 // semantically-enclosing namespace, not a lexically-enclosing one.
4928 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4929 DC = DC->getParent();
4930 return true;
4931}
4932
Larisse Voufoef4579c2013-08-06 01:03:05 +00004933NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004934Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004935 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004936 MultiTemplateParamsArg TemplateParamLists,
4937 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004938 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004939 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004940
Douglas Gregor16573fa2010-04-19 22:54:31 +00004941 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004942 VarDecl::StorageClass SC =
4943 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004944
Richard Smitha41c97a2013-09-20 01:15:31 +00004945 DeclContext *OriginalDC = DC;
4946 bool IsLocalExternDecl = SC == SC_Extern &&
4947 adjustContextForLocalExternDecl(DC);
4948
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004949 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004950 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4951 // half array type (unless the cl_khr_fp16 extension is enabled).
4952 if (Context.getBaseElementType(R)->isHalfType()) {
4953 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4954 D.setInvalidType();
4955 }
4956 }
4957
Douglas Gregor16573fa2010-04-19 22:54:31 +00004958 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004959 // mutable can only appear on non-static class members, so it's always
4960 // an error here
4961 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004962 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004963 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004964 }
John McCallb421d922013-04-02 02:48:58 +00004965
Richard Smith9109bf12013-06-17 01:34:01 +00004966 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4967 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4968 D.getDeclSpec().getStorageClassSpecLoc())) {
4969 // In C++11, the 'register' storage class specifier is deprecated.
4970 // Suppress the warning in system macros, it's used in macros in some
4971 // popular C system headers, such as in glibc's htonl() macro.
4972 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4973 diag::warn_deprecated_register)
4974 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4975 }
4976
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004977 IdentifierInfo *II = Name.getAsIdentifierInfo();
4978 if (!II) {
4979 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004980 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004981 return 0;
4982 }
4983
Richard Smithc7f81162013-03-18 22:52:47 +00004984 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004985
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004986 if (!DC->isRecord() && S->getFnParent() == 0) {
4987 // C99 6.9p2: The storage-class specifiers auto and register shall not
4988 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00004989 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004990 // If this is a register variable with an asm label specified, then this
4991 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00004992 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004993 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4994 else
4995 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004996 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004997 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004998 }
Richard Smith9109bf12013-06-17 01:34:01 +00004999
David Blaikie4e4d0842012-03-11 07:00:24 +00005000 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005001 // Set up the special work-group-local storage class for variables in the
5002 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00005003 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005004 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00005005 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005006
Guy Benyei21f18c42013-02-07 10:55:47 +00005007 // OpenCL v1.2 s6.9.b p4:
5008 // The sampler type cannot be used with the __local and __global address
5009 // space qualifiers.
5010 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5011 R.getAddressSpace() == LangAS::opencl_global)) {
5012 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5013 }
5014
Guy Benyeie6b9d802013-01-20 12:31:11 +00005015 // OpenCL 1.2 spec, p6.9 r:
5016 // The event type cannot be used to declare a program scope variable.
5017 // The event type cannot be used with the __local, __constant and __global
5018 // address space qualifiers.
5019 if (R->isEventT()) {
5020 if (S->getParent() == 0) {
5021 Diag(D.getLocStart(), diag::err_event_t_global_var);
5022 D.setInvalidType();
5023 }
5024
5025 if (R.getAddressSpace()) {
5026 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5027 D.setInvalidType();
5028 }
5029 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005030 }
5031
Larisse Voufoef4579c2013-08-06 01:03:05 +00005032 bool IsExplicitSpecialization = false;
5033 bool IsVariableTemplateSpecialization = false;
5034 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00005035 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005036 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00005037 VarDecl *NewVD = 0;
5038 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00005039 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005040 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005041 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005042 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005043
5044 if (D.isInvalidType())
5045 NewVD->setInvalidDecl();
5046 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00005047 bool Invalid = false;
5048
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005049 if (DC->isRecord() && !CurContext->isRecord()) {
5050 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00005051 switch (SC) {
5052 case SC_None:
5053 break;
5054 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005055 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5056 diag::err_static_out_of_line)
5057 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00005058 break;
5059 case SC_Auto:
5060 case SC_Register:
5061 case SC_Extern:
5062 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5063 // to names of variables declared in a block or to function parameters.
5064 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5065 // of class members
5066
5067 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5068 diag::err_storage_class_for_static_member)
5069 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5070 break;
5071 case SC_PrivateExtern:
5072 llvm_unreachable("C storage class in c++!");
5073 case SC_OpenCLWorkGroupLocal:
5074 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00005075 }
Larisse Voufo06935f32013-08-06 03:43:07 +00005076 }
5077
Richard Smithb9c64d82012-02-16 20:41:22 +00005078 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005079 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5080 if (RD->isLocalClass())
5081 Diag(D.getIdentifierLoc(),
5082 diag::err_static_data_member_not_allowed_in_local_class)
5083 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005084
Richard Smithb9c64d82012-02-16 20:41:22 +00005085 // C++98 [class.union]p1: If a union contains a static data member,
5086 // the program is ill-formed. C++11 drops this restriction.
5087 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005088 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005089 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005090 ? diag::warn_cxx98_compat_static_data_member_in_union
5091 : diag::ext_static_data_member_in_union) << Name;
5092 // We conservatively disallow static data members in anonymous structs.
5093 else if (!RD->getDeclName())
5094 Diag(D.getIdentifierLoc(),
5095 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005096 << Name << RD->isUnion();
5097 }
5098 }
5099
Larisse Voufoef4579c2013-08-06 01:03:05 +00005100 NamedDecl *PrevDecl = 0;
5101 if (Previous.begin() != Previous.end())
5102 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5103 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5104
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005105 // Match up the template parameter lists with the scope specifier, then
5106 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005107 TemplateParameterList *TemplateParams =
5108 MatchTemplateParametersToScopeSpecifier(
5109 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5110 D.getCXXScopeSpec(), TemplateParamLists,
5111 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005112 if (TemplateParams) {
5113 if (!TemplateParams->size() &&
5114 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005115 // There is an extraneous 'template<>' for this variable. Complain
5116 // about it, but allow the declaration of the variable.
5117 Diag(TemplateParams->getTemplateLoc(),
5118 diag::err_template_variable_noparams)
5119 << II
5120 << SourceRange(TemplateParams->getTemplateLoc(),
5121 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005122 } else {
5123 // Only C++1y supports variable templates (N3651).
5124 Diag(D.getIdentifierLoc(),
5125 getLangOpts().CPlusPlus1y
5126 ? diag::warn_cxx11_compat_variable_template
5127 : diag::ext_variable_template);
5128
5129 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5130 // This is an explicit specialization or a partial specialization.
5131 // Check that we can declare a specialization here
5132
5133 IsVariableTemplateSpecialization = true;
5134 IsPartialSpecialization = TemplateParams->size() > 0;
5135
5136 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005137 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005138 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005139
5140 // Check that we can declare a template here.
5141 if (CheckTemplateDeclScope(S, TemplateParams))
5142 return 0;
5143
5144 // If there is a previous declaration with the same name, check
5145 // whether this is a valid redeclaration.
5146 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5147 PrevDecl = PrevVarTemplate = 0;
5148
5149 if (PrevVarTemplate) {
5150 // Ensure that the template parameter lists are compatible.
5151 if (!TemplateParameterListsAreEqual(
5152 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5153 /*Complain=*/true, TPL_TemplateMatch))
5154 return 0;
5155 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5156 // Maybe we will complain about the shadowed template parameter.
5157 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5158
5159 // Just pretend that we didn't see the previous declaration.
5160 PrevDecl = 0;
5161 } else if (PrevDecl) {
5162 // C++ [temp]p5:
5163 // ... a template name declared in namespace scope or in class
5164 // scope shall be unique in that scope.
5165 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5166 << Name;
5167 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5168 return 0;
5169 }
5170
5171 // Check the template parameter list of this declaration, possibly
5172 // merging in the template parameter list from the previous variable
5173 // template declaration.
5174 if (CheckTemplateParameterList(
5175 TemplateParams,
5176 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5177 : 0,
5178 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5179 DC->isDependentContext())
5180 ? TPC_ClassTemplateMember
5181 : TPC_VarTemplate))
5182 Invalid = true;
5183
5184 if (D.getCXXScopeSpec().isSet()) {
5185 // If the name of the template was qualified, we must be defining
5186 // the template out-of-line.
5187 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5188 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005189 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5190 << Name << DC << /*IsDefinition*/true
5191 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005192 Invalid = true;
5193 }
5194 }
5195 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005196 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005197 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5198 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5199
5200 // We have encountered something that the user meant to be a
5201 // specialization (because it has explicitly-specified template
5202 // arguments) but that was not introduced with a "template<>" (or had
5203 // too few of them).
5204 // FIXME: Differentiate between attempts for explicit instantiations
5205 // (starting with "template") and the rest.
5206 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5207 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5208 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5209 "template<> ");
5210 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005211 }
Mike Stump1eb44332009-09-09 15:08:12 +00005212
Larisse Voufoef4579c2013-08-06 01:03:05 +00005213 if (IsVariableTemplateSpecialization) {
5214 if (!PrevVarTemplate) {
5215 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5216 << IsPartialSpecialization;
5217 return 0;
5218 }
5219
5220 SourceLocation TemplateKWLoc =
5221 TemplateParamLists.size() > 0
5222 ? TemplateParamLists[0]->getTemplateLoc()
5223 : SourceLocation();
5224 DeclResult Res = ActOnVarTemplateSpecialization(
5225 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5226 IsPartialSpecialization);
5227 if (Res.isInvalid())
5228 return 0;
5229 NewVD = cast<VarDecl>(Res.get());
5230 AddToScope = false;
5231 } else
5232 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5233 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005234
Larisse Voufo567f9172013-08-22 00:59:14 +00005235 // If this is supposed to be a variable template, create it as such.
5236 if (IsVariableTemplate) {
5237 NewTemplate =
5238 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5239 TemplateParams, NewVD, PrevVarTemplate);
5240 NewVD->setDescribedVarTemplate(NewTemplate);
5241 }
5242
Richard Smith483b9f32011-02-21 20:05:19 +00005243 // If this decl has an auto type in need of deduction, make a note of the
5244 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005245 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005246 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005247
Larisse Voufo567f9172013-08-22 00:59:14 +00005248 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005249 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005250 if (NewTemplate)
5251 NewTemplate->setInvalidDecl();
5252 }
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005254 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005255
Larisse Voufoef4579c2013-08-06 01:03:05 +00005256 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5257 if (TemplateParams && TemplateParamLists.size() > 1 &&
5258 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5259 NewVD->setTemplateParameterListsInfo(
5260 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5261 } else if (IsVariableTemplateSpecialization ||
5262 (!TemplateParams && TemplateParamLists.size() > 0 &&
5263 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005264 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005265 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005266 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005267 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005268
Richard Smith7ca48502012-02-13 22:16:19 +00005269 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005270 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005271 }
5272
Douglas Gregore3895852011-09-12 18:37:38 +00005273 // Set the lexical context. If the declarator has a C++ scope specifier, the
5274 // lexical context will be different from the semantic context.
5275 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005276 if (NewTemplate)
5277 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005278
Richard Smitha41c97a2013-09-20 01:15:31 +00005279 if (IsLocalExternDecl)
5280 NewVD->setLocalExternDecl();
5281
Richard Smithec642442013-04-12 22:46:28 +00005282 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005283 if (NewVD->hasLocalStorage()) {
5284 // C++11 [dcl.stc]p4:
5285 // When thread_local is applied to a variable of block scope the
5286 // storage-class-specifier static is implied if it does not appear
5287 // explicitly.
5288 // Core issue: 'static' is not implied if the variable is declared
5289 // 'extern'.
5290 if (SCSpec == DeclSpec::SCS_unspecified &&
5291 TSCS == DeclSpec::TSCS_thread_local &&
5292 DC->isFunctionOrMethod())
5293 NewVD->setTSCSpec(TSCS);
5294 else
5295 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5296 diag::err_thread_non_global)
5297 << DeclSpec::getSpecifierName(TSCS);
5298 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005299 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5300 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005301 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005302 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005303 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005304
John McCallb421d922013-04-02 02:48:58 +00005305 // C99 6.7.4p3
5306 // An inline definition of a function with external linkage shall
5307 // not contain a definition of a modifiable object with static or
5308 // thread storage duration...
5309 // We only apply this when the function is required to be defined
5310 // elsewhere, i.e. when the function is not 'extern inline'. Note
5311 // that a local variable with thread storage duration still has to
5312 // be marked 'static'. Also note that it's possible to get these
5313 // semantics in C++ using __attribute__((gnu_inline)).
5314 if (SC == SC_Static && S->getFnParent() != 0 &&
5315 !NewVD->getType().isConstQualified()) {
5316 FunctionDecl *CurFD = getCurFunctionDecl();
5317 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5318 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5319 diag::warn_static_local_in_extern_inline);
5320 MaybeSuggestAddingStaticToDecl(CurFD);
5321 }
5322 }
5323
Douglas Gregord023aec2011-09-09 20:53:38 +00005324 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005325 if (IsVariableTemplateSpecialization)
5326 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5327 << (IsPartialSpecialization ? 1 : 0)
5328 << FixItHint::CreateRemoval(
5329 D.getDeclSpec().getModulePrivateSpecLoc());
5330 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005331 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5332 << 2
5333 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005334 else if (NewVD->hasLocalStorage())
5335 Diag(NewVD->getLocation(), diag::err_module_private_local)
5336 << 0 << NewVD->getDeclName()
5337 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5338 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005339 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005340 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005341 if (NewTemplate)
5342 NewTemplate->setModulePrivate();
5343 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005344 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005345
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005346 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005347 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005348
Richard Smithbe507b62013-02-01 08:12:08 +00005349 if (NewVD->hasAttrs())
5350 CheckAlignasUnderalignment(NewVD);
5351
Peter Collingbournec0c00662012-08-28 20:37:50 +00005352 if (getLangOpts().CUDA) {
5353 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5354 // storage [duration]."
5355 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005356 (NewVD->hasAttr<CUDASharedAttr>() ||
5357 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005358 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005359 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005360 }
5361
John McCallf85e1932011-06-15 23:02:42 +00005362 // In auto-retain/release, infer strong retension for variables of
5363 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005364 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005365 NewVD->setInvalidDecl();
5366
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005367 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005368 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005369 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005370 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005371 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005372 if (S->getFnParent() != 0) {
5373 switch (SC) {
5374 case SC_None:
5375 case SC_Auto:
5376 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5377 break;
5378 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005379 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005380 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5381 break;
5382 case SC_Static:
5383 case SC_Extern:
5384 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005385 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005386 break;
5387 }
5388 }
5389
5390 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005391 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005392 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5393 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5394 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5395 if (I != ExtnameUndeclaredIdentifiers.end()) {
5396 NewVD->addAttr(I->second);
5397 ExtnameUndeclaredIdentifiers.erase(I);
5398 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005399 }
5400
John McCall8472af42010-03-16 21:48:18 +00005401 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005402 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005403 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005404
John McCall68263142009-11-18 22:49:29 +00005405 // Don't consider existing declarations that are in a different
5406 // scope and are out-of-semantic-context declarations (if the new
5407 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005408 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005409 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005410 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5411
Richard Smithdd9459f2013-08-13 18:18:50 +00005412 // Check whether the previous declaration is in the same block scope. This
5413 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5414 if (getLangOpts().CPlusPlus &&
5415 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5416 NewVD->setPreviousDeclInSameBlockScope(
5417 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005418 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005419
David Blaikie4e4d0842012-03-11 07:00:24 +00005420 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005421 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5422 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005423 // Merge the decl with the existing one if appropriate.
5424 if (!Previous.empty()) {
5425 if (Previous.isSingleResult() &&
5426 isa<FieldDecl>(Previous.getFoundDecl()) &&
5427 D.getCXXScopeSpec().isSet()) {
5428 // The user tried to define a non-static data member
5429 // out-of-line (C++ [dcl.meaning]p1).
5430 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5431 << D.getCXXScopeSpec().getRange();
5432 Previous.clear();
5433 NewVD->setInvalidDecl();
5434 }
5435 } else if (D.getCXXScopeSpec().isSet()) {
5436 // No previous declaration in the qualifying scope.
5437 Diag(D.getIdentifierLoc(), diag::err_no_member)
5438 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005439 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005440 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005441 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005442
Larisse Voufoef4579c2013-08-06 01:03:05 +00005443 if (!IsVariableTemplateSpecialization) {
5444 if (PrevVarTemplate) {
5445 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5446 LookupOrdinaryName, ForRedeclaration);
5447 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005448 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005449 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005450 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005451 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005452
5453 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005454 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005455 CheckMemberSpecialization(NewVD, Previous))
5456 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005457 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005458
Rafael Espindola65611bf2013-03-02 21:41:48 +00005459 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005460 checkAttributesAfterMerging(*this, *NewVD);
5461
Richard Smithaa4bc182013-06-30 09:48:50 +00005462 // If this is the first declaration of an extern C variable, update
5463 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00005464 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00005465 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005466 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005467
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005468 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005469 Decl *ManglingContextDecl;
5470 if (MangleNumberingContext *MCtx =
5471 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5472 ManglingContextDecl)) {
5473 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5474 }
5475 }
5476
Larisse Voufoef4579c2013-08-06 01:03:05 +00005477 // If we are providing an explicit specialization of a static variable
5478 // template, make a note of that.
5479 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005480 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005481
Larisse Voufo567f9172013-08-22 00:59:14 +00005482 if (NewTemplate) {
5483 ActOnDocumentableDecl(NewTemplate);
5484 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005485 }
5486
Larisse Voufo567f9172013-08-22 00:59:14 +00005487 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005488}
5489
John McCall053f4bd2010-03-22 09:20:08 +00005490/// \brief Diagnose variable or built-in function shadowing. Implements
5491/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005492///
John McCall053f4bd2010-03-22 09:20:08 +00005493/// This method is called whenever a VarDecl is added to a "useful"
5494/// scope.
John McCall8472af42010-03-16 21:48:18 +00005495///
John McCalla369a952010-03-20 04:12:52 +00005496/// \param S the scope in which the shadowing name is being declared
5497/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005498///
John McCall053f4bd2010-03-22 09:20:08 +00005499void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005500 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005501 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005502 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005503 return;
5504
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005505 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005506 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005507 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005508
5509 DeclContext *NewDC = D->getDeclContext();
5510
John McCalla369a952010-03-20 04:12:52 +00005511 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005512 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005513 return;
John McCall8472af42010-03-16 21:48:18 +00005514
John McCall8472af42010-03-16 21:48:18 +00005515 NamedDecl* ShadowedDecl = R.getFoundDecl();
5516 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5517 return;
5518
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005519 // Fields are not shadowed by variables in C++ static methods.
5520 if (isa<FieldDecl>(ShadowedDecl))
5521 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5522 if (MD->isStatic())
5523 return;
5524
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005525 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5526 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005527 // For shadowing external vars, make sure that we point to the global
5528 // declaration, not a locally scoped extern declaration.
5529 for (VarDecl::redecl_iterator
5530 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5531 I != E; ++I)
5532 if (I->isFileVarDecl()) {
5533 ShadowedDecl = *I;
5534 break;
5535 }
5536 }
5537
5538 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5539
John McCalla369a952010-03-20 04:12:52 +00005540 // Only warn about certain kinds of shadowing for class members.
5541 if (NewDC && NewDC->isRecord()) {
5542 // In particular, don't warn about shadowing non-class members.
5543 if (!OldDC->isRecord())
5544 return;
5545
5546 // TODO: should we warn about static data members shadowing
5547 // static data members from base classes?
5548
5549 // TODO: don't diagnose for inaccessible shadowed members.
5550 // This is hard to do perfectly because we might friend the
5551 // shadowing context, but that's just a false negative.
5552 }
5553
5554 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005555 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005556 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005557 if (isa<FieldDecl>(ShadowedDecl))
5558 Kind = 3; // field
5559 else
5560 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005561 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005562 Kind = 1; // global
5563 else
5564 Kind = 0; // local
5565
John McCalla369a952010-03-20 04:12:52 +00005566 DeclarationName Name = R.getLookupName();
5567
John McCall8472af42010-03-16 21:48:18 +00005568 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005569 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005570 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5571}
5572
John McCall053f4bd2010-03-22 09:20:08 +00005573/// \brief Check -Wshadow without the advantage of a previous lookup.
5574void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005575 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005576 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005577 return;
5578
John McCall053f4bd2010-03-22 09:20:08 +00005579 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5580 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5581 LookupName(R, S);
5582 CheckShadow(S, D, R);
5583}
5584
Richard Smithaa4bc182013-06-30 09:48:50 +00005585/// Check for conflict between this global or extern "C" declaration and
5586/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005587template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005588static bool checkGlobalOrExternCConflict(
5589 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5590 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5591 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005592
Richard Smithaa4bc182013-06-30 09:48:50 +00005593 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5594 // The common case: this global doesn't conflict with any extern "C"
5595 // declaration.
5596 return false;
5597 }
5598
5599 if (Prev) {
5600 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5601 // Both the old and new declarations have C language linkage. This is a
5602 // redeclaration.
5603 Previous.clear();
5604 Previous.addDecl(Prev);
5605 return true;
5606 }
5607
5608 // This is a global, non-extern "C" declaration, and there is a previous
5609 // non-global extern "C" declaration. Diagnose if this is a variable
5610 // declaration.
5611 if (!isa<VarDecl>(ND))
5612 return false;
5613 } else {
5614 // The declaration is extern "C". Check for any declaration in the
5615 // translation unit which might conflict.
5616 if (IsGlobal) {
5617 // We have already performed the lookup into the translation unit.
5618 IsGlobal = false;
5619 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5620 I != E; ++I) {
5621 if (isa<VarDecl>(*I)) {
5622 Prev = *I;
5623 break;
5624 }
5625 }
5626 } else {
5627 DeclContext::lookup_result R =
5628 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5629 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5630 I != E; ++I) {
5631 if (isa<VarDecl>(*I)) {
5632 Prev = *I;
5633 break;
5634 }
5635 // FIXME: If we have any other entity with this name in global scope,
5636 // the declaration is ill-formed, but that is a defect: it breaks the
5637 // 'stat' hack, for instance. Only variables can have mangled name
5638 // clashes with extern "C" declarations, so only they deserve a
5639 // diagnostic.
5640 }
5641 }
5642
5643 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005644 return false;
5645 }
5646
Richard Smithaa4bc182013-06-30 09:48:50 +00005647 // Use the first declaration's location to ensure we point at something which
5648 // is lexically inside an extern "C" linkage-spec.
5649 assert(Prev && "should have found a previous declaration to diagnose");
5650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindolabc650912013-10-17 15:37:26 +00005651 Prev = FD->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005652 else
Rafael Espindolabc650912013-10-17 15:37:26 +00005653 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005654
5655 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5656 << IsGlobal << ND;
5657 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5658 << IsGlobal;
5659 return false;
5660}
5661
5662/// Apply special rules for handling extern "C" declarations. Returns \c true
5663/// if we have found that this is a redeclaration of some prior entity.
5664///
5665/// Per C++ [dcl.link]p6:
5666/// Two declarations [for a function or variable] with C language linkage
5667/// with the same name that appear in different scopes refer to the same
5668/// [entity]. An entity with C language linkage shall not be declared with
5669/// the same name as an entity in global scope.
5670template<typename T>
5671static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5672 LookupResult &Previous) {
5673 if (!S.getLangOpts().CPlusPlus) {
5674 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005675 // variable declared in function scope. We don't need this in C++, because
5676 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005677 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5678 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5679 Previous.clear();
5680 Previous.addDecl(Prev);
5681 return true;
5682 }
5683 }
5684 return false;
5685 }
5686
5687 // A declaration in the translation unit can conflict with an extern "C"
5688 // declaration.
5689 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5690 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5691
5692 // An extern "C" declaration can conflict with a declaration in the
5693 // translation unit or can be a redeclaration of an extern "C" declaration
5694 // in another scope.
5695 if (isIncompleteDeclExternC(S,ND))
5696 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5697
5698 // Neither global nor extern "C": nothing to do.
5699 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005700}
5701
Richard Smithdc7a4f52013-04-30 13:56:41 +00005702void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005703 // If the decl is already known invalid, don't check it.
5704 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005705 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005706
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005707 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5708 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005709
Richard Smithdc7a4f52013-04-30 13:56:41 +00005710 // Defer checking an 'auto' type until its initializer is attached.
5711 if (T->isUndeducedType())
5712 return;
5713
John McCallc12c5bb2010-05-15 11:32:37 +00005714 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005715 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5716 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005717 T = Context.getObjCObjectPointerType(T);
5718 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005719 }
Mike Stump1eb44332009-09-09 15:08:12 +00005720
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005721 // Emit an error if an address space was applied to decl with local storage.
5722 // This includes arrays of objects with address space qualifiers, but not
5723 // automatic variables that point to other address spaces.
5724 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005725 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005726 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005727 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005728 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005729 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005730
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005731 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5732 // __constant address space.
5733 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5734 && T.getAddressSpace() != LangAS::opencl_constant
5735 && !T->isSamplerT()){
5736 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5737 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005738 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005739 }
5740
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005741 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5742 // scope.
5743 if ((getLangOpts().OpenCLVersion >= 120)
5744 && NewVD->isStaticLocal()) {
5745 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5746 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005747 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005748 }
5749
Mike Stumpf33651c2009-04-14 00:57:29 +00005750 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005751 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005752 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005753 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005754 else {
5755 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005756 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005757 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005758 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005759
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005760 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005761 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005762 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005763 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005764
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005765 if ((isVM && NewVD->hasLinkage()) ||
5766 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005767 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005768 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005769 TypeSourceInfo *FixedTInfo =
5770 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5771 SizeIsNegative, Oversized);
5772 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005773 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005774 // FIXME: This won't give the correct result for
5775 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005776 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005777
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005778 if (NewVD->isFileVarDecl())
5779 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005780 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005781 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005782 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005783 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005784 else
5785 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005786 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005787 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005788 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005789 }
5790
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005791 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005792 if (NewVD->isFileVarDecl())
5793 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5794 else
5795 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005796 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005797 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005798 }
Mike Stump1eb44332009-09-09 15:08:12 +00005799
Chris Lattnereaaebc72009-04-25 08:06:05 +00005800 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005801 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005802 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005803 }
5804
David Majnemeraa715672013-05-29 00:56:45 +00005805 if (T->isVoidType()) {
5806 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5807 // of objects and functions.
5808 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5809 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5810 << T;
5811 NewVD->setInvalidDecl();
5812 return;
5813 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005814 }
5815
5816 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5817 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5818 NewVD->setInvalidDecl();
5819 return;
5820 }
5821
5822 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5823 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5824 NewVD->setInvalidDecl();
5825 return;
5826 }
5827
5828 if (NewVD->isConstexpr() && !T->isDependentType() &&
5829 RequireLiteralType(NewVD->getLocation(), T,
5830 diag::err_constexpr_var_non_literal)) {
5831 // Can't perform this check until the type is deduced.
5832 NewVD->setInvalidDecl();
5833 return;
5834 }
5835}
5836
5837/// \brief Perform semantic checking on a newly-created variable
5838/// declaration.
5839///
5840/// This routine performs all of the type-checking required for a
5841/// variable declaration once it has been built. It is used both to
5842/// check variables after they have been parsed and their declarators
5843/// have been translated into a declaration, and to check variables
5844/// that have been instantiated from a template.
5845///
5846/// Sets NewVD->isInvalidDecl() if an error was encountered.
5847///
5848/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005849bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005850 CheckVariableDeclarationType(NewVD);
5851
5852 // If the decl is already known invalid, don't check it.
5853 if (NewVD->isInvalidDecl())
5854 return false;
5855
John McCall5b8740f2013-04-01 18:34:28 +00005856 // If we did not find anything by this name, look for a non-visible
5857 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005858 if (Previous.empty() &&
5859 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005860 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005861
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005862 // Filter out any non-conflicting previous declarations.
5863 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5864
John McCall68263142009-11-18 22:49:29 +00005865 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005866 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005867 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005868 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005869 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005870}
5871
Douglas Gregora8f32e02009-10-06 17:59:45 +00005872/// \brief Data used with FindOverriddenMethod
5873struct FindOverriddenMethodData {
5874 Sema *S;
5875 CXXMethodDecl *Method;
5876};
5877
5878/// \brief Member lookup function that determines whether a given C++
5879/// method overrides a method in a base class, to be used with
5880/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005881static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005882 CXXBasePath &Path,
5883 void *UserData) {
5884 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005885
Douglas Gregora8f32e02009-10-06 17:59:45 +00005886 FindOverriddenMethodData *Data
5887 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005888
5889 DeclarationName Name = Data->Method->getDeclName();
5890
5891 // FIXME: Do we care about other names here too?
5892 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005893 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005894 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5895 CanQualType CT = Data->S->Context.getCanonicalType(T);
5896
Anders Carlsson1a689722009-11-27 01:26:58 +00005897 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005898 }
5899
5900 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005901 !Path.Decls.empty();
5902 Path.Decls = Path.Decls.slice(1)) {
5903 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5905 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005906 return true;
5907 }
5908 }
5909
5910 return false;
5911}
5912
David Blaikie5708c182012-10-17 00:47:58 +00005913namespace {
5914 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5915}
5916/// \brief Report an error regarding overriding, along with any relevant
5917/// overriden methods.
5918///
5919/// \param DiagID the primary error to report.
5920/// \param MD the overriding method.
5921/// \param OEK which overrides to include as notes.
5922static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5923 OverrideErrorKind OEK = OEK_All) {
5924 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5925 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5926 E = MD->end_overridden_methods();
5927 I != E; ++I) {
5928 // This check (& the OEK parameter) could be replaced by a predicate, but
5929 // without lambdas that would be overkill. This is still nicer than writing
5930 // out the diag loop 3 times.
5931 if ((OEK == OEK_All) ||
5932 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5933 (OEK == OEK_Deleted && (*I)->isDeleted()))
5934 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5935 }
5936}
5937
Sebastian Redla165da02009-11-18 21:51:29 +00005938/// AddOverriddenMethods - See if a method overrides any in the base classes,
5939/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005940bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005941 // Look for virtual methods in base classes that this method might override.
5942 CXXBasePaths Paths;
5943 FindOverriddenMethodData Data;
5944 Data.Method = MD;
5945 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005946 bool hasDeletedOverridenMethods = false;
5947 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005948 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005949 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5950 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5951 E = Paths.found_decls_end(); I != E; ++I) {
5952 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005953 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005954 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005955 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005956 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005957 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005958 hasDeletedOverridenMethods |= OldMD->isDeleted();
5959 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005960 AddedAny = true;
5961 }
Sebastian Redla165da02009-11-18 21:51:29 +00005962 }
5963 }
5964 }
David Blaikie5708c182012-10-17 00:47:58 +00005965
5966 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5967 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5968 }
5969 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5970 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5971 }
5972
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005973 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005974}
5975
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005976namespace {
5977 // Struct for holding all of the extra arguments needed by
5978 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5979 struct ActOnFDArgs {
5980 Scope *S;
5981 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005982 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005983 bool AddToScope;
5984 };
5985}
5986
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005987namespace {
5988
5989// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005990// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005991class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5992 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005993 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5994 CXXRecordDecl *Parent)
5995 : Context(Context), OriginalFD(TypoFD),
5996 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005997
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005998 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005999 if (candidate.getEditDistance() == 0)
6000 return false;
6001
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006002 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006003 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6004 CDeclEnd = candidate.end();
6005 CDecl != CDeclEnd; ++CDecl) {
6006 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6007
6008 if (FD && !FD->hasBody() &&
6009 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6010 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6011 CXXRecordDecl *Parent = MD->getParent();
6012 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6013 return true;
6014 } else if (!ExpectedParent) {
6015 return true;
6016 }
6017 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006018 }
6019
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006020 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006021 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006022
6023 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006024 ASTContext &Context;
6025 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006026 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006027};
6028
6029}
6030
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006031/// \brief Generate diagnostics for an invalid function redeclaration.
6032///
6033/// This routine handles generating the diagnostic messages for an invalid
6034/// function redeclaration, including finding possible similar declarations
6035/// or performing typo correction if there are no previous declarations with
6036/// the same name.
6037///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006038/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006039/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00006040static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006041 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00006042 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006043 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006044 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006045 SmallVector<unsigned, 1> MismatchedParams;
6046 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006047 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00006048 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00006049 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6050 : diag::err_member_decl_does_not_match;
6051 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6052 IsLocalFriend ? Sema::LookupLocalFriendName
6053 : Sema::LookupOrdinaryName,
6054 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006055
6056 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00006057 if (IsLocalFriend)
6058 SemaRef.LookupName(Prev, S);
6059 else
6060 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00006061 assert(!Prev.isAmbiguous() &&
6062 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006063 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006064 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6065 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006066 if (!Prev.empty()) {
6067 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6068 Func != FuncEnd; ++Func) {
6069 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006070 if (FD &&
6071 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006072 // Add 1 to the index so that 0 can mean the mismatch didn't
6073 // involve a parameter
6074 unsigned ParamNum =
6075 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6076 NearMatches.push_back(std::make_pair(FD, ParamNum));
6077 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006078 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006079 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006080 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006081 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6082 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6083 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006084 // Set up everything for the call to ActOnFunctionDeclarator
6085 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6086 ExtraArgs.D.getIdentifierLoc());
6087 Previous.clear();
6088 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006089 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6090 CDeclEnd = Correction.end();
6091 CDecl != CDeclEnd; ++CDecl) {
6092 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006093 if (FD && !FD->hasBody() &&
6094 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006095 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006096 }
6097 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006098 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006099
6100 NamedDecl *Result;
6101 // Retry building the function declaration with the new previous
6102 // declarations, and with errors suppressed.
6103 {
6104 // Trap errors.
6105 Sema::SFINAETrap Trap(SemaRef);
6106
6107 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6108 // pieces need to verify the typo-corrected C++ declaration and hopefully
6109 // eliminate the need for the parameter pack ExtraArgs.
6110 Result = SemaRef.ActOnFunctionDeclarator(
6111 ExtraArgs.S, ExtraArgs.D,
6112 Correction.getCorrectionDecl()->getDeclContext(),
6113 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6114 ExtraArgs.AddToScope);
6115
6116 if (Trap.hasErrorOccurred())
6117 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006118 }
Richard Smith2d670972013-08-17 00:46:16 +00006119
6120 if (Result) {
6121 // Determine which correction we picked.
6122 Decl *Canonical = Result->getCanonicalDecl();
6123 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6124 I != E; ++I)
6125 if ((*I)->getCanonicalDecl() == Canonical)
6126 Correction.setCorrectionDecl(*I);
6127
6128 SemaRef.diagnoseTypo(
6129 Correction,
6130 SemaRef.PDiag(IsLocalFriend
6131 ? diag::err_no_matching_local_friend_suggest
6132 : diag::err_member_decl_does_not_match_suggest)
6133 << Name << NewDC << IsDefinition);
6134 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006135 }
Richard Smith2d670972013-08-17 00:46:16 +00006136
6137 // Pretend the typo correction never occurred
6138 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6139 ExtraArgs.D.getIdentifierLoc());
6140 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6141 Previous.clear();
6142 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006143 }
6144
Richard Smith2d670972013-08-17 00:46:16 +00006145 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6146 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006147
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006148 bool NewFDisConst = false;
6149 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006150 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006151
Craig Topper8bc99dd2013-07-04 03:15:42 +00006152 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006153 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6154 NearMatch != NearMatchEnd; ++NearMatch) {
6155 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006156 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6157 bool FDisConst = MD && MD->isConst();
6158 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006159
Richard Smitha41c97a2013-09-20 01:15:31 +00006160 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006161 if (unsigned Idx = NearMatch->second) {
6162 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006163 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6164 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006165 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6166 : diag::note_local_decl_close_param_match)
6167 << Idx << FDParam->getType()
6168 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006169 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006170 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006171 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006172 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006173 SemaRef.Diag(FD->getLocation(),
6174 IsMember ? diag::note_member_def_close_match
6175 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006176 }
Richard Smith2d670972013-08-17 00:46:16 +00006177 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006178}
6179
David Blaikied662a792011-10-19 22:56:21 +00006180static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6181 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006182 switch (D.getDeclSpec().getStorageClassSpec()) {
6183 default: llvm_unreachable("Unknown storage class!");
6184 case DeclSpec::SCS_auto:
6185 case DeclSpec::SCS_register:
6186 case DeclSpec::SCS_mutable:
6187 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6188 diag::err_typecheck_sclass_func);
6189 D.setInvalidType();
6190 break;
6191 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006192 case DeclSpec::SCS_extern:
6193 if (D.getDeclSpec().isExternInLinkageSpec())
6194 return SC_None;
6195 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006196 case DeclSpec::SCS_static: {
6197 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6198 // C99 6.7.1p5:
6199 // The declaration of an identifier for a function that has
6200 // block scope shall have no explicit storage-class specifier
6201 // other than extern
6202 // See also (C++ [dcl.stc]p4).
6203 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6204 diag::err_static_block_func);
6205 break;
6206 } else
6207 return SC_Static;
6208 }
6209 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6210 }
6211
6212 // No explicit storage class has already been returned
6213 return SC_None;
6214}
6215
6216static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6217 DeclContext *DC, QualType &R,
6218 TypeSourceInfo *TInfo,
6219 FunctionDecl::StorageClass SC,
6220 bool &IsVirtualOkay) {
6221 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6222 DeclarationName Name = NameInfo.getName();
6223
6224 FunctionDecl *NewFD = 0;
6225 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006226
David Blaikie4e4d0842012-03-11 07:00:24 +00006227 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006228 // Determine whether the function was written with a
6229 // prototype. This true when:
6230 // - there is a prototype in the declarator, or
6231 // - the type R of the function is some kind of typedef or other reference
6232 // to a type name (which eventually refers to a function type).
6233 bool HasPrototype =
6234 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6235 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6236
David Blaikied662a792011-10-19 22:56:21 +00006237 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006238 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006239 TInfo, SC, isInline,
6240 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006241 if (D.isInvalidType())
6242 NewFD->setInvalidDecl();
6243
6244 // Set the lexical context.
6245 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6246
6247 return NewFD;
6248 }
6249
6250 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6251 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6252
6253 // Check that the return type is not an abstract class type.
6254 // For record types, this is done by the AbstractClassUsageDiagnoser once
6255 // the class has been completely parsed.
6256 if (!DC->isRecord() &&
6257 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6258 R->getAs<FunctionType>()->getResultType(),
6259 diag::err_abstract_type_in_decl,
6260 SemaRef.AbstractReturnType))
6261 D.setInvalidType();
6262
6263 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6264 // This is a C++ constructor declaration.
6265 assert(DC->isRecord() &&
6266 "Constructors can only be declared in a member context");
6267
6268 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6269 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006270 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006271 R, TInfo, isExplicit, isInline,
6272 /*isImplicitlyDeclared=*/false,
6273 isConstexpr);
6274
6275 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6276 // This is a C++ destructor declaration.
6277 if (DC->isRecord()) {
6278 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6279 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6280 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6281 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006282 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006283 NameInfo, R, TInfo, isInline,
6284 /*isImplicitlyDeclared=*/false);
6285
6286 // If the class is complete, then we now create the implicit exception
6287 // specification. If the class is incomplete or dependent, we can't do
6288 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006289 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006290 Record->getDefinition() && !Record->isBeingDefined() &&
6291 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6292 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6293 }
6294
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006295 // The Microsoft ABI requires that we perform the destructor body
6296 // checks (i.e. operator delete() lookup) at every declaration, as
6297 // any translation unit may need to emit a deleting destructor.
6298 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6299 !Record->isDependentType() && Record->getDefinition() &&
6300 !Record->isBeingDefined()) {
6301 SemaRef.CheckDestructor(NewDD);
6302 }
6303
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006304 IsVirtualOkay = true;
6305 return NewDD;
6306
6307 } else {
6308 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6309 D.setInvalidType();
6310
6311 // Create a FunctionDecl to satisfy the function definition parsing
6312 // code path.
6313 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006314 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006315 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006316 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006317 /*hasPrototype=*/true, isConstexpr);
6318 }
6319
6320 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6321 if (!DC->isRecord()) {
6322 SemaRef.Diag(D.getIdentifierLoc(),
6323 diag::err_conv_function_not_member);
6324 return 0;
6325 }
6326
6327 SemaRef.CheckConversionDeclarator(D, R, SC);
6328 IsVirtualOkay = true;
6329 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006330 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006331 R, TInfo, isInline, isExplicit,
6332 isConstexpr, SourceLocation());
6333
6334 } else if (DC->isRecord()) {
6335 // If the name of the function is the same as the name of the record,
6336 // then this must be an invalid constructor that has a return type.
6337 // (The parser checks for a return type and makes the declarator a
6338 // constructor if it has no return type).
6339 if (Name.getAsIdentifierInfo() &&
6340 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6341 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6342 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6343 << SourceRange(D.getIdentifierLoc());
6344 return 0;
6345 }
6346
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006347 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006348 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6349 cast<CXXRecordDecl>(DC),
6350 D.getLocStart(), NameInfo, R,
6351 TInfo, SC, isInline,
6352 isConstexpr, SourceLocation());
6353 IsVirtualOkay = !Ret->isStatic();
6354 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006355 } else {
6356 // Determine whether the function was written with a
6357 // prototype. This true when:
6358 // - we're in C++ (where every function has a prototype),
6359 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006360 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006361 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006362 true/*HasPrototype*/, isConstexpr);
6363 }
6364}
6365
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006366void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6367 // In C++, the empty parameter-type-list must be spelled "void"; a
6368 // typedef of void is not permitted.
6369 if (getLangOpts().CPlusPlus &&
6370 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6371 bool IsTypeAlias = false;
6372 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6373 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6374 else if (const TemplateSpecializationType *TST =
6375 Param->getType()->getAs<TemplateSpecializationType>())
6376 IsTypeAlias = TST->isTypeAlias();
6377 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6378 << IsTypeAlias;
6379 }
6380}
6381
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006382enum OpenCLParamType {
6383 ValidKernelParam,
6384 PtrPtrKernelParam,
6385 PtrKernelParam,
6386 InvalidKernelParam,
6387 RecordKernelParam
6388};
6389
6390static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6391 if (PT->isPointerType()) {
6392 QualType PointeeType = PT->getPointeeType();
6393 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6394 }
6395
6396 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6397 // be used as builtin types.
6398
6399 if (PT->isImageType())
6400 return PtrKernelParam;
6401
6402 if (PT->isBooleanType())
6403 return InvalidKernelParam;
6404
6405 if (PT->isEventT())
6406 return InvalidKernelParam;
6407
6408 if (PT->isHalfType())
6409 return InvalidKernelParam;
6410
6411 if (PT->isRecordType())
6412 return RecordKernelParam;
6413
6414 return ValidKernelParam;
6415}
6416
6417static void checkIsValidOpenCLKernelParameter(
6418 Sema &S,
6419 Declarator &D,
6420 ParmVarDecl *Param,
6421 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6422 QualType PT = Param->getType();
6423
6424 // Cache the valid types we encounter to avoid rechecking structs that are
6425 // used again
6426 if (ValidTypes.count(PT.getTypePtr()))
6427 return;
6428
6429 switch (getOpenCLKernelParameterType(PT)) {
6430 case PtrPtrKernelParam:
6431 // OpenCL v1.2 s6.9.a:
6432 // A kernel function argument cannot be declared as a
6433 // pointer to a pointer type.
6434 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6435 D.setInvalidType();
6436 return;
6437
6438 // OpenCL v1.2 s6.9.k:
6439 // Arguments to kernel functions in a program cannot be declared with the
6440 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6441 // uintptr_t or a struct and/or union that contain fields declared to be
6442 // one of these built-in scalar types.
6443
6444 case InvalidKernelParam:
6445 // OpenCL v1.2 s6.8 n:
6446 // A kernel function argument cannot be declared
6447 // of event_t type.
6448 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6449 D.setInvalidType();
6450 return;
6451
6452 case PtrKernelParam:
6453 case ValidKernelParam:
6454 ValidTypes.insert(PT.getTypePtr());
6455 return;
6456
6457 case RecordKernelParam:
6458 break;
6459 }
6460
6461 // Track nested structs we will inspect
6462 SmallVector<const Decl *, 4> VisitStack;
6463
6464 // Track where we are in the nested structs. Items will migrate from
6465 // VisitStack to HistoryStack as we do the DFS for bad field.
6466 SmallVector<const FieldDecl *, 4> HistoryStack;
6467 HistoryStack.push_back((const FieldDecl *) 0);
6468
6469 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6470 VisitStack.push_back(PD);
6471
6472 assert(VisitStack.back() && "First decl null?");
6473
6474 do {
6475 const Decl *Next = VisitStack.pop_back_val();
6476 if (!Next) {
6477 assert(!HistoryStack.empty());
6478 // Found a marker, we have gone up a level
6479 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6480 ValidTypes.insert(Hist->getType().getTypePtr());
6481
6482 continue;
6483 }
6484
6485 // Adds everything except the original parameter declaration (which is not a
6486 // field itself) to the history stack.
6487 const RecordDecl *RD;
6488 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6489 HistoryStack.push_back(Field);
6490 RD = Field->getType()->castAs<RecordType>()->getDecl();
6491 } else {
6492 RD = cast<RecordDecl>(Next);
6493 }
6494
6495 // Add a null marker so we know when we've gone back up a level
6496 VisitStack.push_back((const Decl *) 0);
6497
6498 for (RecordDecl::field_iterator I = RD->field_begin(),
6499 E = RD->field_end(); I != E; ++I) {
6500 const FieldDecl *FD = *I;
6501 QualType QT = FD->getType();
6502
6503 if (ValidTypes.count(QT.getTypePtr()))
6504 continue;
6505
6506 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6507 if (ParamType == ValidKernelParam)
6508 continue;
6509
6510 if (ParamType == RecordKernelParam) {
6511 VisitStack.push_back(FD);
6512 continue;
6513 }
6514
6515 // OpenCL v1.2 s6.9.p:
6516 // Arguments to kernel functions that are declared to be a struct or union
6517 // do not allow OpenCL objects to be passed as elements of the struct or
6518 // union.
6519 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6520 S.Diag(Param->getLocation(),
6521 diag::err_record_with_pointers_kernel_param)
6522 << PT->isUnionType()
6523 << PT;
6524 } else {
6525 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6526 }
6527
6528 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6529 << PD->getDeclName();
6530
6531 // We have an error, now let's go back up through history and show where
6532 // the offending field came from
6533 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6534 E = HistoryStack.end(); I != E; ++I) {
6535 const FieldDecl *OuterField = *I;
6536 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6537 << OuterField->getType();
6538 }
6539
6540 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6541 << QT->isPointerType()
6542 << QT;
6543 D.setInvalidType();
6544 return;
6545 }
6546 } while (!VisitStack.empty());
6547}
6548
Mike Stump1eb44332009-09-09 15:08:12 +00006549NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006550Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006551 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006552 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006553 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006554 QualType R = TInfo->getType();
6555
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006556 assert(R.getTypePtr()->isFunctionType());
6557
Abramo Bagnara25777432010-08-11 22:01:17 +00006558 // TODO: consider using NameInfo for diagnostic.
6559 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6560 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006561 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006562
Richard Smithec642442013-04-12 22:46:28 +00006563 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6564 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6565 diag::err_invalid_thread)
6566 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006567
Reid Klecknerd1a32c32013-10-08 00:58:57 +00006568 if (D.isFirstDeclarationOfMember())
6569 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckneref072032013-08-27 23:08:25 +00006570
Douglas Gregor3922ed02010-12-10 19:28:19 +00006571 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006572 FunctionTemplateDecl *FunctionTemplate = 0;
6573 bool isExplicitSpecialization = false;
6574 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006575
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006576 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006577 bool HasExplicitTemplateArgs = false;
6578 TemplateArgumentListInfo TemplateArgs;
6579
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006580 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006581
Richard Smitha41c97a2013-09-20 01:15:31 +00006582 DeclContext *OriginalDC = DC;
6583 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6584
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006585 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6586 isVirtualOkay);
6587 if (!NewFD) return 0;
6588
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006589 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6590 NewFD->setTopLevelDeclInObjCContainer();
6591
Richard Smitha41c97a2013-09-20 01:15:31 +00006592 // Set the lexical context. If this is a function-scope declaration, or has a
6593 // C++ scope specifier, or is the object of a friend declaration, the lexical
6594 // context will be different from the semantic context.
6595 NewFD->setLexicalDeclContext(CurContext);
6596
6597 if (IsLocalExternDecl)
6598 NewFD->setLocalExternDecl();
6599
David Blaikie4e4d0842012-03-11 07:00:24 +00006600 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006601 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006602 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6603 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006604 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006605 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006606 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006607 // C++ [class.friend]p5
6608 // A function can be defined in a friend declaration of a
6609 // class . . . . Such a function is implicitly inline.
6610 NewFD->setImplicitlyInline();
6611 }
6612
John McCalle402e722012-09-25 07:32:39 +00006613 // If this is a method defined in an __interface, and is not a constructor
6614 // or an overloaded operator, then set the pure flag (isVirtual will already
6615 // return true).
6616 if (const CXXRecordDecl *Parent =
6617 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6618 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006619 NewFD->setPure(true);
6620 }
6621
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006622 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006623 isExplicitSpecialization = false;
6624 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006625 if (D.isInvalidType())
6626 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006627
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006628 // Match up the template parameter lists with the scope specifier, then
6629 // determine whether we have a template or a template specialization.
6630 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006631 if (TemplateParameterList *TemplateParams =
6632 MatchTemplateParametersToScopeSpecifier(
6633 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6634 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6635 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006636 if (TemplateParams->size() > 0) {
6637 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006638
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006639 // Check that we can declare a template here.
6640 if (CheckTemplateDeclScope(S, TemplateParams))
6641 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006642
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006643 // A destructor cannot be a template.
6644 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6645 Diag(NewFD->getLocation(), diag::err_destructor_template);
6646 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006647 }
Douglas Gregor20606502011-10-14 15:31:12 +00006648
6649 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006650 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006651 // now that we know what the current instantiation is.
6652 if (DC->isDependentContext()) {
6653 ContextRAII SavedContext(*this, DC);
6654 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6655 Invalid = true;
6656 }
6657
John McCall5fd378b2010-03-24 08:27:58 +00006658
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006659 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6660 NewFD->getLocation(),
6661 Name, TemplateParams,
6662 NewFD);
6663 FunctionTemplate->setLexicalDeclContext(CurContext);
6664 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6665
6666 // For source fidelity, store the other template param lists.
6667 if (TemplateParamLists.size() > 1) {
6668 NewFD->setTemplateParameterListsInfo(Context,
6669 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006670 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006671 }
6672 } else {
6673 // This is a function template specialization.
6674 isFunctionTemplateSpecialization = true;
6675 // For source fidelity, store all the template param lists.
6676 NewFD->setTemplateParameterListsInfo(Context,
6677 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006678 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006679
6680 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6681 if (isFriend) {
6682 // We want to remove the "template<>", found here.
6683 SourceRange RemoveRange = TemplateParams->getSourceRange();
6684
6685 // If we remove the template<> and the name is not a
6686 // template-id, we're actually silently creating a problem:
6687 // the friend declaration will refer to an untemplated decl,
6688 // and clearly the user wants a template specialization. So
6689 // we need to insert '<>' after the name.
6690 SourceLocation InsertLoc;
6691 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6692 InsertLoc = D.getName().getSourceRange().getEnd();
6693 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6694 }
6695
6696 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6697 << Name << RemoveRange
6698 << FixItHint::CreateRemoval(RemoveRange)
6699 << FixItHint::CreateInsertion(InsertLoc, "<>");
6700 }
6701 }
6702 }
6703 else {
6704 // All template param lists were matched against the scope specifier:
6705 // this is NOT (an explicit specialization of) a template.
6706 if (TemplateParamLists.size() > 0)
6707 // For source fidelity, store all the template param lists.
6708 NewFD->setTemplateParameterListsInfo(Context,
6709 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006710 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006711 }
6712
6713 if (Invalid) {
6714 NewFD->setInvalidDecl();
6715 if (FunctionTemplate)
6716 FunctionTemplate->setInvalidDecl();
6717 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006718
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006719 // C++ [dcl.fct.spec]p5:
6720 // The virtual specifier shall only be used in declarations of
6721 // nonstatic class member functions that appear within a
6722 // member-specification of a class declaration; see 10.3.
6723 //
6724 if (isVirtual && !NewFD->isInvalidDecl()) {
6725 if (!isVirtualOkay) {
6726 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6727 diag::err_virtual_non_function);
6728 } else if (!CurContext->isRecord()) {
6729 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006730 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6731 diag::err_virtual_out_of_class)
6732 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6733 } else if (NewFD->getDescribedFunctionTemplate()) {
6734 // C++ [temp.mem]p3:
6735 // A member function template shall not be virtual.
6736 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6737 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006738 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6739 } else {
6740 // Okay: Add virtual to the method.
6741 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006742 }
Richard Smith60e141e2013-05-04 07:00:32 +00006743
6744 if (getLangOpts().CPlusPlus1y &&
6745 NewFD->getResultType()->isUndeducedType())
6746 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006747 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006748
Richard Smithf93ec762013-11-15 02:58:23 +00006749 if (getLangOpts().CPlusPlus1y &&
6750 (NewFD->isDependentContext() ||
6751 (isFriend && CurContext->isDependentContext())) &&
Richard Smith37e849a2013-08-14 20:16:31 +00006752 NewFD->getResultType()->isUndeducedType()) {
6753 // If the function template is referenced directly (for instance, as a
6754 // member of the current instantiation), pretend it has a dependent type.
6755 // This is not really justified by the standard, but is the only sane
6756 // thing to do.
Richard Smithf93ec762013-11-15 02:58:23 +00006757 // FIXME: For a friend function, we have not marked the function as being
6758 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smith37e849a2013-08-14 20:16:31 +00006759 const FunctionProtoType *FPT =
6760 NewFD->getType()->castAs<FunctionProtoType>();
6761 QualType Result = SubstAutoType(FPT->getResultType(),
6762 Context.DependentTy);
6763 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6764 FPT->getExtProtoInfo()));
6765 }
6766
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006767 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006768 // The inline specifier shall not appear on a block scope function
6769 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006770 if (isInline && !NewFD->isInvalidDecl()) {
6771 if (CurContext->isFunctionOrMethod()) {
6772 // 'inline' is not allowed on block scope function declaration.
6773 Diag(D.getDeclSpec().getInlineSpecLoc(),
6774 diag::err_inline_declaration_block_scope) << Name
6775 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6776 }
6777 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006778
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006779 // C++ [dcl.fct.spec]p6:
6780 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006781 // constructor or conversion function within its class definition;
6782 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006783 if (isExplicit && !NewFD->isInvalidDecl()) {
6784 if (!CurContext->isRecord()) {
6785 // 'explicit' was specified outside of the class.
6786 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6787 diag::err_explicit_out_of_class)
6788 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6789 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6790 !isa<CXXConversionDecl>(NewFD)) {
6791 // 'explicit' was specified on a function that wasn't a constructor
6792 // or conversion function.
6793 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6794 diag::err_explicit_non_ctor_or_conv_function)
6795 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6796 }
6797 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006798
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006799 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006800 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006801 // are implicitly inline.
6802 NewFD->setImplicitlyInline();
6803
Richard Smith21c8fa82013-01-14 05:37:29 +00006804 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006805 // be either constructors or to return a literal type. Therefore,
6806 // destructors cannot be declared constexpr.
6807 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006808 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006809 }
6810
Douglas Gregor8d267c52011-09-09 02:06:17 +00006811 // If __module_private__ was specified, mark the function accordingly.
6812 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006813 if (isFunctionTemplateSpecialization) {
6814 SourceLocation ModulePrivateLoc
6815 = D.getDeclSpec().getModulePrivateSpecLoc();
6816 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6817 << 0
6818 << FixItHint::CreateRemoval(ModulePrivateLoc);
6819 } else {
6820 NewFD->setModulePrivate();
6821 if (FunctionTemplate)
6822 FunctionTemplate->setModulePrivate();
6823 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006824 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006825
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006826 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006827 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006828 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006829 FunctionTemplate->setAccess(AS_public);
6830 }
Richard Smith22050f22013-07-17 23:53:16 +00006831 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006832 NewFD->setAccess(AS_public);
6833 }
6834
Douglas Gregor45fa5602011-11-07 20:56:01 +00006835 // If a function is defined as defaulted or deleted, mark it as such now.
6836 switch (D.getFunctionDefinitionKind()) {
6837 case FDK_Declaration:
6838 case FDK_Definition:
6839 break;
6840
6841 case FDK_Defaulted:
6842 NewFD->setDefaulted();
6843 break;
6844
6845 case FDK_Deleted:
6846 NewFD->setDeletedAsWritten();
6847 break;
6848 }
6849
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006850 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6851 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006852 // C++ [class.mfct]p2:
6853 // A member function may be defined (8.4) in its class definition, in
6854 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006855 NewFD->setImplicitlyInline();
6856 }
6857
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006858 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6859 !CurContext->isRecord()) {
6860 // C++ [class.static]p1:
6861 // A data or function member of a class may be declared static
6862 // in a class definition, in which case it is a static member of
6863 // the class.
6864
6865 // Complain about the 'static' specifier if it's on an out-of-line
6866 // member function definition.
6867 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6868 diag::err_static_out_of_line)
6869 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6870 }
Richard Smith444d3842012-10-20 08:26:51 +00006871
6872 // C++11 [except.spec]p15:
6873 // A deallocation function with no exception-specification is treated
6874 // as if it were specified with noexcept(true).
6875 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6876 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6877 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006878 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006879 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6880 EPI.ExceptionSpecType = EST_BasicNoexcept;
6881 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006882 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006883 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006884 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006885
6886 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006887 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006888 isExplicitSpecialization ||
6889 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006890
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006891 // Handle GNU asm-label extension (encoded as an attribute).
6892 if (Expr *E = (Expr*) D.getAsmLabel()) {
6893 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006894 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006895 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6896 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006897 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6898 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6899 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6900 if (I != ExtnameUndeclaredIdentifiers.end()) {
6901 NewFD->addAttr(I->second);
6902 ExtnameUndeclaredIdentifiers.erase(I);
6903 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006904 }
6905
Chris Lattner2dbd2852009-04-25 06:12:16 +00006906 // Copy the parameter declarations from the declarator D to the function
6907 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006908 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006909 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006910 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006911
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006912 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6913 // function that takes no arguments, not a function that takes a
6914 // single void argument.
6915 // We let through "const void" here because Sema::GetTypeForDeclarator
6916 // already checks for that case.
6917 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6918 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006919 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006920 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006921 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006922 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006923 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006924 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006925 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6926 Param->setDeclContext(NewFD);
6927 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006928
6929 if (Param->isInvalidDecl())
6930 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006931 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006932 }
Mike Stump1eb44332009-09-09 15:08:12 +00006933
John McCall183700f2009-09-21 23:43:11 +00006934 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006935 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006936 // following example, we'll need to synthesize (unnamed)
6937 // parameters for use in the declaration.
6938 //
6939 // @code
6940 // typedef void fn(int);
6941 // fn f;
6942 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006943
Chris Lattner1ad9b282009-04-25 06:03:53 +00006944 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006945 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6946 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006947 ParmVarDecl *Param =
6948 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006949 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006950 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006951 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006952 } else {
6953 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6954 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006955 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006956
Chris Lattner2dbd2852009-04-25 06:12:16 +00006957 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006958 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006959
James Molloy16f1f712012-02-29 10:24:19 +00006960 // Find all anonymous symbols defined during the declaration of this function
6961 // and add to NewFD. This lets us track decls such 'enum Y' in:
6962 //
6963 // void f(enum Y {AA} x) {}
6964 //
6965 // which would otherwise incorrectly end up in the translation unit scope.
6966 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6967 DeclsInPrototypeScope.clear();
6968
Richard Smith7586a6e2013-01-30 05:45:05 +00006969 if (D.getDeclSpec().isNoreturnSpecified())
6970 NewFD->addAttr(
6971 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6972 Context));
6973
Richard Smithb03a9df2012-03-13 05:56:40 +00006974 // Functions returning a variably modified type violate C99 6.7.5.2p2
6975 // because all functions have linkage.
6976 if (!NewFD->isInvalidDecl() &&
6977 NewFD->getResultType()->isVariablyModifiedType()) {
6978 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6979 NewFD->setInvalidDecl();
6980 }
6981
Rafael Espindola98ae8342012-05-10 02:50:16 +00006982 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006983 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006984
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006985 QualType RetType = NewFD->getResultType();
6986 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6987 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6988 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6989 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006990 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006991 // Attach the attribute to the new decl. Don't apply the attribute if it
6992 // returns an instance of the class (e.g. assignment operators).
6993 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006994 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6995 Context));
6996 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006997 }
6998
David Blaikie4e4d0842012-03-11 07:00:24 +00006999 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007000 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00007001 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00007002 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7003 CheckMain(NewFD, D.getDeclSpec());
7004
David Majnemere9f6f332013-09-16 22:44:20 +00007005 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7006 CheckMSVCRTEntryPoint(NewFD);
7007
David Majnemerc371db62013-07-06 02:13:46 +00007008 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00007009 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7010 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00007011 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00007012 // Make graceful recovery from an invalid redeclaration.
7013 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007014 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007015 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7016 "previous declaration set still overloaded");
7017 } else {
Richard Smithcf19e5b2013-11-16 01:57:09 +00007018 // C++11 [replacement.functions]p3:
7019 // The program's definitions shall not be specified as inline.
7020 //
7021 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7022 //
7023 // Suppress the diagnostic if the function is __attribute__((used)), since
7024 // that forces an external definition to be emitted.
7025 if (D.getDeclSpec().isInlineSpecified() &&
7026 NewFD->isReplaceableGlobalAllocationFunction() &&
7027 !NewFD->hasAttr<UsedAttr>())
7028 Diag(D.getDeclSpec().getInlineSpecLoc(),
7029 diag::ext_operator_new_delete_declared_inline)
7030 << NewFD->getDeclName();
7031
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007032 // If the declarator is a template-id, translate the parser's template
7033 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007034 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7035 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7036 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7037 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007038 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007039 TemplateId->NumArgs);
7040 translateTemplateArguments(TemplateArgsPtr,
7041 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007042
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007043 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007044
Douglas Gregor89b9f102011-06-06 15:22:55 +00007045 if (NewFD->isInvalidDecl()) {
7046 HasExplicitTemplateArgs = false;
7047 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007048 // Function template with explicit template arguments.
7049 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7050 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7051
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007052 HasExplicitTemplateArgs = false;
7053 } else if (!isFunctionTemplateSpecialization &&
7054 !D.getDeclSpec().isFriendSpecified()) {
7055 // We have encountered something that the user meant to be a
7056 // specialization (because it has explicitly-specified template
7057 // arguments) but that was not introduced with a "template<>" (or had
7058 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007059 // FIXME: Differentiate between attempts for explicit instantiations
7060 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007061 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7062 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7063 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007064 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007065 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007066 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007067 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007068 // "friend void foo<>(int);" is an implicit specialization decl.
7069 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007070 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007071 } else if (isFriend && isFunctionTemplateSpecialization) {
7072 // This combination is only possible in a recovery case; the user
7073 // wrote something like:
7074 // template <> friend void foo(int);
7075 // which we're recovering from as if the user had written:
7076 // friend void foo<>(int);
7077 // Go ahead and fake up a template id.
7078 HasExplicitTemplateArgs = true;
7079 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7080 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007081 }
John McCall29ae6e52010-10-13 05:45:15 +00007082
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007083 // If it's a friend (and only if it's a friend), it's possible
7084 // that either the specialized function type or the specialized
7085 // template is dependent, and therefore matching will fail. In
7086 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007087 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007088 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007089 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7090 TemplateSpecializationType::anyDependentTemplateArguments(
7091 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7092 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007093 assert(HasExplicitTemplateArgs &&
7094 "friend function specialization without template args");
7095 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7096 Previous))
7097 NewFD->setInvalidDecl();
7098 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007099 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007100 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007101 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007102 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007103 diag::ext_function_specialization_in_class :
7104 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007105 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007106 } else if (CheckFunctionTemplateSpecialization(NewFD,
7107 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7108 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007109 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007110
7111 // C++ [dcl.stc]p1:
7112 // A storage-class-specifier shall not be specified in an explicit
7113 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007114 FunctionTemplateSpecializationInfo *Info =
7115 NewFD->getTemplateSpecializationInfo();
7116 if (Info && SC != SC_None) {
7117 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007118 Diag(NewFD->getLocation(),
7119 diag::err_explicit_specialization_inconsistent_storage_class)
7120 << SC
7121 << FixItHint::CreateRemoval(
7122 D.getDeclSpec().getStorageClassSpecLoc());
7123
7124 else
7125 Diag(NewFD->getLocation(),
7126 diag::ext_explicit_specialization_storage_class)
7127 << FixItHint::CreateRemoval(
7128 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007129 }
7130
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007131 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7132 if (CheckMemberSpecialization(NewFD, Previous))
7133 NewFD->setInvalidDecl();
7134 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007135
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007136 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007137 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007138 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7139 CheckMain(NewFD, D.getDeclSpec());
7140
David Majnemere9f6f332013-09-16 22:44:20 +00007141 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7142 CheckMSVCRTEntryPoint(NewFD);
7143
David Blaikie14068e82011-09-08 06:33:04 +00007144 if (NewFD->isInvalidDecl()) {
7145 // If this is a class member, mark the class invalid immediately.
7146 // This avoids some consistency errors later.
7147 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7148 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007149 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007150 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7151 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007152 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007153
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007154 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007155 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7156 "previous declaration set still overloaded");
7157
7158 NamedDecl *PrincipalDecl = (FunctionTemplate
7159 ? cast<NamedDecl>(FunctionTemplate)
7160 : NewFD);
7161
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007162 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007163 AccessSpecifier Access = AS_public;
7164 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007165 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007166
7167 NewFD->setAccess(Access);
7168 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007169 }
7170
7171 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7172 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7173 PrincipalDecl->setNonMemberOperator();
7174
7175 // If we have a function template, check the template parameter
7176 // list. This will check and merge default template arguments.
7177 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007178 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007179 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007180 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007181 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007182 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007183 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007184 ? TPC_FriendFunctionTemplateDefinition
7185 : TPC_FriendFunctionTemplate)
7186 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007187 DC && DC->isRecord() &&
7188 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007189 ? TPC_ClassTemplateMember
7190 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007191 }
7192
7193 if (NewFD->isInvalidDecl()) {
7194 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007195 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007196 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007197 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007198 // Fake up an access specifier if it's supposed to be a class member.
7199 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7200 NewFD->setAccess(AS_public);
7201
7202 // Qualified decls generally require a previous declaration.
7203 if (D.getCXXScopeSpec().isSet()) {
7204 // ...with the major exception of templated-scope or
7205 // dependent-scope friend declarations.
7206
7207 // TODO: we currently also suppress this check in dependent
7208 // contexts because (1) the parameter depth will be off when
7209 // matching friend templates and (2) we might actually be
7210 // selecting a friend based on a dependent factor. But there
7211 // are situations where these conditions don't apply and we
7212 // can actually do this check immediately.
7213 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007214 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007215 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7216 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007217 // ignore these
7218 } else {
7219 // The user tried to provide an out-of-line definition for a
7220 // function that is a member of a class or namespace, but there
7221 // was no such member function declared (C++ [class.mfct]p2,
7222 // C++ [namespace.memdef]p2). For example:
7223 //
7224 // class X {
7225 // void f() const;
7226 // };
7227 //
7228 // void X::f() { } // ill-formed
7229 //
7230 // Complain about this problem, and attempt to suggest close
7231 // matches (e.g., those that differ only in cv-qualifiers and
7232 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007233
Richard Smith4e9686b2013-08-09 04:35:01 +00007234 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7235 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007236 AddToScope = ExtraArgs.AddToScope;
7237 return Result;
7238 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007239 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007240
7241 // Unqualified local friend declarations are required to resolve
7242 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007243 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007244 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7245 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007246 AddToScope = ExtraArgs.AddToScope;
7247 return Result;
7248 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007249 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007250
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007251 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007252 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007253 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007254 // An out-of-line member function declaration must also be a
7255 // definition (C++ [dcl.meaning]p1).
7256 // Note that this is not the case for explicit specializations of
7257 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007258 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7259 // extension for compatibility with old SWIG code which likes to
7260 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007261 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7262 << D.getCXXScopeSpec().getRange();
7263 }
7264 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007265
Rafael Espindola65611bf2013-03-02 21:41:48 +00007266 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007267 checkAttributesAfterMerging(*this, *NewFD);
7268
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007269 AddKnownFunctionAttributes(NewFD);
7270
Douglas Gregord9455382010-08-06 13:50:58 +00007271 if (NewFD->hasAttr<OverloadableAttr>() &&
7272 !NewFD->getType()->getAs<FunctionProtoType>()) {
7273 Diag(NewFD->getLocation(),
7274 diag::err_attribute_overloadable_no_prototype)
7275 << NewFD;
7276
7277 // Turn this into a variadic function with no parameters.
7278 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007279 FunctionProtoType::ExtProtoInfo EPI(
7280 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007281 EPI.Variadic = true;
7282 EPI.ExtInfo = FT->getExtInfo();
7283
Dmitri Gribenko55431692013-05-05 00:41:58 +00007284 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007285 NewFD->setType(R);
7286 }
7287
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007288 // If there's a #pragma GCC visibility in scope, and this isn't a class
7289 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007290 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007291 AddPushedVisibilityAttribute(NewFD);
7292
John McCall8dfac0b2011-09-30 05:12:12 +00007293 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7294 // marking the function.
7295 AddCFAuditedAttribute(NewFD);
7296
Richard Smithaa4bc182013-06-30 09:48:50 +00007297 // If this is the first declaration of an extern C variable, update
7298 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007299 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007300 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007301 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007302
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007303 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007304 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007305
David Blaikie4e4d0842012-03-11 07:00:24 +00007306 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007307 if (FunctionTemplate) {
7308 if (NewFD->isInvalidDecl())
7309 FunctionTemplate->setInvalidDecl();
7310 return FunctionTemplate;
7311 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007312 }
Mike Stump1eb44332009-09-09 15:08:12 +00007313
Guy Benyeie6b9d802013-01-20 12:31:11 +00007314 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007315 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7316 if ((getLangOpts().OpenCLVersion >= 120)
7317 && (SC == SC_Static)) {
7318 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7319 D.setInvalidType();
7320 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007321
7322 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7323 if (!NewFD->getResultType()->isVoidType()) {
7324 Diag(D.getIdentifierLoc(),
7325 diag::err_expected_kernel_void_return_type);
7326 D.setInvalidType();
7327 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007328
7329 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007330 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7331 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007332 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007333 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007334 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007335 }
7336
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007337 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007338
David Blaikie4e4d0842012-03-11 07:00:24 +00007339 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007340 if (IdentifierInfo *II = NewFD->getIdentifier())
7341 if (!NewFD->isInvalidDecl() &&
7342 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7343 if (II->isStr("cudaConfigureCall")) {
7344 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7345 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7346
7347 Context.setcudaConfigureCallDecl(NewFD);
7348 }
7349 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007350
7351 // Here we have an function template explicit specialization at class scope.
7352 // The actually specialization will be postponed to template instatiation
7353 // time via the ClassScopeFunctionSpecializationDecl node.
7354 if (isDependentClassScopeExplicitSpecialization) {
7355 ClassScopeFunctionSpecializationDecl *NewSpec =
7356 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007357 Context, CurContext, SourceLocation(),
7358 cast<CXXMethodDecl>(NewFD),
7359 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007360 CurContext->addDecl(NewSpec);
7361 AddToScope = false;
7362 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007363
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007364 return NewFD;
7365}
7366
7367/// \brief Perform semantic checking of a new function declaration.
7368///
7369/// Performs semantic analysis of the new function declaration
7370/// NewFD. This routine performs all semantic checking that does not
7371/// require the actual declarator involved in the declaration, and is
7372/// used both for the declaration of functions as they are parsed
7373/// (called via ActOnDeclarator) and for the declaration of functions
7374/// that have been instantiated via C++ template instantiation (called
7375/// via InstantiateDecl).
7376///
James Dennettefce31f2012-06-22 08:10:18 +00007377/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007378/// an explicit specialization of the previous declaration.
7379///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007380/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007381///
James Dennettefce31f2012-06-22 08:10:18 +00007382/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007383bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007384 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007385 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007386 assert(!NewFD->getResultType()->isVariablyModifiedType()
7387 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007388
Richard Smithdd9459f2013-08-13 18:18:50 +00007389 // Determine whether the type of this function should be merged with
7390 // a previous visible declaration. This never happens for functions in C++,
7391 // and always happens in C if the previous declaration was visible.
7392 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7393 !Previous.isShadowed();
7394
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007395 // Filter out any non-conflicting previous declarations.
7396 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7397
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007398 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007399 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007400
Douglas Gregor04495c82009-02-24 01:23:02 +00007401 // Merge or overload the declaration with an existing declaration of
7402 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007403 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007404 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007405 // a declaration that requires merging. If it's an overload,
7406 // there's no more work to do here; we'll just add the new
7407 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007408 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007409 NamedDecl *Candidate = Previous.getFoundDecl();
7410 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7411 Redeclaration = true;
7412 OldDecl = Candidate;
7413 }
John McCall871b2e72009-12-09 03:35:25 +00007414 } else {
John McCallad00b772010-06-16 08:42:20 +00007415 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7416 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007417 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007418 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007419 break;
7420
7421 case Ovl_NonFunction:
7422 Redeclaration = true;
7423 break;
7424
7425 case Ovl_Overload:
7426 Redeclaration = false;
7427 break;
John McCall68263142009-11-18 22:49:29 +00007428 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007429
David Blaikie4e4d0842012-03-11 07:00:24 +00007430 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007431 // If a function name is overloadable in C, then every function
7432 // with that name must be marked "overloadable".
7433 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7434 << Redeclaration << NewFD;
7435 NamedDecl *OverloadedDecl = 0;
7436 if (Redeclaration)
7437 OverloadedDecl = OldDecl;
7438 else if (!Previous.empty())
7439 OverloadedDecl = Previous.getRepresentativeDecl();
7440 if (OverloadedDecl)
7441 Diag(OverloadedDecl->getLocation(),
7442 diag::note_attribute_overloadable_prev_overload);
7443 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7444 Context));
7445 }
John McCall68263142009-11-18 22:49:29 +00007446 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007447 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007448
Richard Smithaa4bc182013-06-30 09:48:50 +00007449 // Check for a previous extern "C" declaration with this name.
7450 if (!Redeclaration &&
7451 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7452 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7453 if (!Previous.empty()) {
7454 // This is an extern "C" declaration with the same name as a previous
7455 // declaration, and thus redeclares that entity...
7456 Redeclaration = true;
7457 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007458 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007459
7460 // ... except in the presence of __attribute__((overloadable)).
7461 if (OldDecl->hasAttr<OverloadableAttr>()) {
7462 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7463 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7464 << Redeclaration << NewFD;
7465 Diag(Previous.getFoundDecl()->getLocation(),
7466 diag::note_attribute_overloadable_prev_overload);
7467 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7468 Context));
7469 }
7470 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7471 Redeclaration = false;
7472 OldDecl = 0;
7473 }
7474 }
7475 }
7476 }
7477
Richard Smith21c8fa82013-01-14 05:37:29 +00007478 // C++11 [dcl.constexpr]p8:
7479 // A constexpr specifier for a non-static member function that is not
7480 // a constructor declares that member function to be const.
7481 //
7482 // This needs to be delayed until we know whether this is an out-of-line
7483 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007484 //
7485 // This rule is not present in C++1y, so we produce a backwards
7486 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007487 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007488 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7489 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007490 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7491 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7492 if (FunctionTemplateDecl *OldTD =
7493 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7494 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7495 if (!OldMD || !OldMD->isStatic()) {
7496 const FunctionProtoType *FPT =
7497 MD->getType()->castAs<FunctionProtoType>();
7498 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7499 EPI.TypeQuals |= Qualifiers::Const;
7500 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007501 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007502
7503 // Warn that we did this, if we're not performing template instantiation.
7504 // In that case, we'll have warned already when the template was defined.
7505 if (ActiveTemplateInstantiations.empty()) {
7506 SourceLocation AddConstLoc;
7507 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7508 .IgnoreParens().getAs<FunctionTypeLoc>())
7509 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7510
7511 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7512 << FixItHint::CreateInsertion(AddConstLoc, " const");
7513 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007514 }
7515 }
7516
7517 if (Redeclaration) {
7518 // NewFD and OldDecl represent declarations that need to be
7519 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007520 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007521 NewFD->setInvalidDecl();
7522 return Redeclaration;
7523 }
7524
7525 Previous.clear();
7526 Previous.addDecl(OldDecl);
7527
7528 if (FunctionTemplateDecl *OldTemplateDecl
7529 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7530 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7531 FunctionTemplateDecl *NewTemplateDecl
7532 = NewFD->getDescribedFunctionTemplate();
7533 assert(NewTemplateDecl && "Template/non-template mismatch");
7534 if (CXXMethodDecl *Method
7535 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7536 Method->setAccess(OldTemplateDecl->getAccess());
7537 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007538 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007539
7540 // If this is an explicit specialization of a member that is a function
7541 // template, mark it as a member specialization.
7542 if (IsExplicitSpecialization &&
7543 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7544 NewTemplateDecl->setMemberSpecialization();
7545 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007546 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007547
7548 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007549 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007550 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007551
7552 if (isa<CXXMethodDecl>(NewFD)) {
7553 // A valid redeclaration of a C++ method must be out-of-line,
7554 // but (unfortunately) it's not necessarily a definition
7555 // because of templates, which means that the previous
7556 // declaration is not necessarily from the class definition.
7557
7558 // For just setting the access, that doesn't matter.
7559 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7560 NewFD->setAccess(oldMethod->getAccess());
7561
7562 // Update the key-function state if necessary for this ABI.
7563 if (NewFD->isInlined() &&
7564 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7565 // setNonKeyFunction needs to work with the original
7566 // declaration from the class definition, and isVirtual() is
7567 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007568 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007569 if (oldMethod->isVirtual()) {
7570 Context.setNonKeyFunction(oldMethod);
7571 }
7572 }
7573 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007574 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007575 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007576
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007577 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007578 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007579 // C++-specific checks.
7580 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7581 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007582 } else if (CXXDestructorDecl *Destructor =
7583 dyn_cast<CXXDestructorDecl>(NewFD)) {
7584 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007585 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007586
Douglas Gregor4923aa22010-07-02 20:37:36 +00007587 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007588 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007589 if (!ClassType->isDependentType()) {
7590 DeclarationName Name
7591 = Context.DeclarationNames.getCXXDestructorName(
7592 Context.getCanonicalType(ClassType));
7593 if (NewFD->getDeclName() != Name) {
7594 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007595 NewFD->setInvalidDecl();
7596 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007597 }
7598 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007599 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007600 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007601 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007602 }
7603
7604 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007605 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7606 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007607 !Method->getDescribedFunctionTemplate() &&
7608 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007609 if (AddOverriddenMethods(Method->getParent(), Method)) {
7610 // If the function was marked as "static", we have a problem.
7611 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007612 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007613 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007614 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007615 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007616
7617 if (Method->isStatic())
7618 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007619 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007620
7621 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7622 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007623 CheckOverloadedOperatorDeclaration(NewFD)) {
7624 NewFD->setInvalidDecl();
7625 return Redeclaration;
7626 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007627
7628 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7629 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007630 CheckLiteralOperatorDeclaration(NewFD)) {
7631 NewFD->setInvalidDecl();
7632 return Redeclaration;
7633 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007634
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007635 // In C++, check default arguments now that we have merged decls. Unless
7636 // the lexical context is the class, because in this case this is done
7637 // during delayed parsing anyway.
7638 if (!CurContext->isRecord())
7639 CheckCXXDefaultArguments(NewFD);
Warren Hunt2d023ec2013-11-01 23:46:51 +00007640
Douglas Gregorb68e3992010-12-21 19:47:46 +00007641 // If this function declares a builtin function, check the type of this
7642 // declaration against the expected type for the builtin.
7643 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7644 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007645 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007646 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7647 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7648 // The type of this function differs from the type of the builtin,
7649 // so forget about the builtin entirely.
7650 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7651 }
7652 }
Warren Hunt2d023ec2013-11-01 23:46:51 +00007653
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007654 // If this function is declared as being extern "C", then check to see if
7655 // the function returns a UDT (class, struct, or union type) that is not C
7656 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007657 // But, issue any diagnostic on the first declaration only.
7658 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007659 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007660 if (R->isIncompleteType() && !R->isVoidType())
7661 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7662 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007663 else if (!R.isPODType(Context) && !R->isVoidType() &&
7664 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007665 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007666 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007667 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007668 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007669}
7670
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007671static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7672 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7673 if (!TSI)
7674 return SourceRange();
7675
7676 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007677 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007678 if (!FunctionTL)
7679 return SourceRange();
7680
David Blaikie39e6ab42013-02-18 22:06:02 +00007681 TypeLoc ResultTL = FunctionTL.getResultLoc();
7682 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007683 return ResultTL.getSourceRange();
7684
7685 return SourceRange();
7686}
7687
David Blaikie14068e82011-09-08 06:33:04 +00007688void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007689 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7690 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007691 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7692 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007693 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007694 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007695 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007696 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007697 ? diag::err_static_main : diag::warn_static_main)
7698 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7699 if (FD->isInlineSpecified())
7700 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7701 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007702 if (DS.isNoreturnSpecified()) {
7703 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7704 SourceRange NoreturnRange(NoreturnLoc,
7705 PP.getLocForEndOfToken(NoreturnLoc));
7706 Diag(NoreturnLoc, diag::ext_noreturn_main);
7707 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7708 << FixItHint::CreateRemoval(NoreturnRange);
7709 }
Richard Smitha5065862012-02-04 06:10:17 +00007710 if (FD->isConstexpr()) {
7711 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7712 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7713 FD->setConstexpr(false);
7714 }
John McCall13591ed2009-07-25 04:36:53 +00007715
Joey Goulyc879fe52013-11-05 12:30:39 +00007716 if (getLangOpts().OpenCL) {
7717 Diag(FD->getLocation(), diag::err_opencl_no_main)
7718 << FD->hasAttr<OpenCLKernelAttr>();
7719 FD->setInvalidDecl();
7720 return;
7721 }
7722
John McCall13591ed2009-07-25 04:36:53 +00007723 QualType T = FD->getType();
7724 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007725 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007726
John McCall75d8ba32012-02-14 19:50:52 +00007727 // All the standards say that main() should should return 'int'.
7728 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7729 // In C and C++, main magically returns 0 if you fall off the end;
7730 // set the flag which tells us that.
7731 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7732 FD->setHasImplicitReturnZero(true);
7733
7734 // In C with GNU extensions we allow main() to have non-integer return
7735 // type, but we should warn about the extension, and we disable the
7736 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007737 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007738 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7739
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007740 SourceRange ResultRange = getResultSourceRange(FD);
7741 if (ResultRange.isValid())
7742 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7743 << FixItHint::CreateReplacement(ResultRange, "int");
7744
John McCall75d8ba32012-02-14 19:50:52 +00007745 // Otherwise, this is just a flat-out error.
7746 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007747 SourceRange ResultRange = getResultSourceRange(FD);
7748 if (ResultRange.isValid())
7749 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7750 << FixItHint::CreateReplacement(ResultRange, "int");
7751 else
7752 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7753
John McCall13591ed2009-07-25 04:36:53 +00007754 FD->setInvalidDecl(true);
7755 }
7756
7757 // Treat protoless main() as nullary.
7758 if (isa<FunctionNoProtoType>(FT)) return;
7759
7760 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7761 unsigned nparams = FTP->getNumArgs();
7762 assert(FD->getNumParams() == nparams);
7763
John McCall66755862009-12-24 09:58:38 +00007764 bool HasExtraParameters = (nparams > 3);
7765
7766 // Darwin passes an undocumented fourth argument of type char**. If
7767 // other platforms start sprouting these, the logic below will start
7768 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007769 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007770 HasExtraParameters = false;
7771
7772 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007773 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7774 FD->setInvalidDecl(true);
7775 nparams = 3;
7776 }
7777
7778 // FIXME: a lot of the following diagnostics would be improved
7779 // if we had some location information about types.
7780
7781 QualType CharPP =
7782 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007783 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007784
7785 for (unsigned i = 0; i < nparams; ++i) {
7786 QualType AT = FTP->getArgType(i);
7787
7788 bool mismatch = true;
7789
7790 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7791 mismatch = false;
7792 else if (Expected[i] == CharPP) {
7793 // As an extension, the following forms are okay:
7794 // char const **
7795 // char const * const *
7796 // char * const *
7797
John McCall0953e762009-09-24 19:53:00 +00007798 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007799 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007800 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7801 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007802 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7803 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007804 qs.removeConst();
7805 mismatch = !qs.empty();
7806 }
7807 }
7808
7809 if (mismatch) {
7810 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7811 // TODO: suggest replacing given type with expected type
7812 FD->setInvalidDecl(true);
7813 }
7814 }
7815
7816 if (nparams == 1 && !FD->isInvalidDecl()) {
7817 Diag(FD->getLocation(), diag::warn_main_one_arg);
7818 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007819
7820 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007821 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7822 FD->setInvalidDecl();
7823 }
7824}
7825
7826void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7827 QualType T = FD->getType();
7828 assert(T->isFunctionType() && "function decl is not of function type");
7829 const FunctionType *FT = T->castAs<FunctionType>();
7830
7831 // Set an implicit return of 'zero' if the function can return some integral,
7832 // enumeration, pointer or nullptr type.
7833 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7834 FT->getResultType()->isAnyPointerType() ||
7835 FT->getResultType()->isNullPtrType())
7836 // DllMain is exempt because a return value of zero means it failed.
7837 if (FD->getName() != "DllMain")
7838 FD->setHasImplicitReturnZero(true);
7839
7840 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7841 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007842 FD->setInvalidDecl();
7843 }
John McCall8c4859a2009-07-24 03:03:21 +00007844}
7845
Eli Friedmanc594b322008-05-20 13:48:25 +00007846bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007847 // FIXME: Need strict checking. In C89, we need to check for
7848 // any assignment, increment, decrement, function-calls, or
7849 // commas outside of a sizeof. In C99, it's the same list,
7850 // except that the aforementioned are allowed in unevaluated
7851 // expressions. Everything else falls under the
7852 // "may accept other forms of constant expressions" exception.
7853 // (We never end up here for C++, so the constant expression
7854 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007855 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007856 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007857 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7858 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007859 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007860}
7861
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007862namespace {
7863 // Visits an initialization expression to see if OrigDecl is evaluated in
7864 // its own initialization and throws a warning if it does.
7865 class SelfReferenceChecker
7866 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7867 Sema &S;
7868 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007869 bool isRecordType;
7870 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007871 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007872
7873 public:
7874 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7875
7876 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007877 S(S), OrigDecl(OrigDecl) {
7878 isPODType = false;
7879 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007880 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007881 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7882 isPODType = VD->getType().isPODType(S.Context);
7883 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007884 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007885 }
7886 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007887
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007888 // For most expressions, the cast is directly above the DeclRefExpr.
7889 // For conditional operators, the cast can be outside the conditional
7890 // operator if both expressions are DeclRefExpr's.
7891 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007892 if (isReferenceType)
7893 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007894 E = E->IgnoreParenImpCasts();
7895 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7896 HandleDeclRefExpr(DRE);
7897 return;
7898 }
7899
7900 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7901 HandleValue(CO->getTrueExpr());
7902 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007903 return;
7904 }
7905
7906 if (isa<MemberExpr>(E)) {
7907 Expr *Base = E->IgnoreParenImpCasts();
7908 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7909 // Check for static member variables and don't warn on them.
7910 if (!isa<FieldDecl>(ME->getMemberDecl()))
7911 return;
7912 Base = ME->getBase()->IgnoreParenImpCasts();
7913 }
7914 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7915 HandleDeclRefExpr(DRE);
7916 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007917 }
7918 }
7919
Richard Trieu568f7852012-10-01 17:39:51 +00007920 // Reference types are handled here since all uses of references are
7921 // bad, not just r-value uses.
7922 void VisitDeclRefExpr(DeclRefExpr *E) {
7923 if (isReferenceType)
7924 HandleDeclRefExpr(E);
7925 }
7926
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007927 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007928 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007929 (isRecordType && E->getCastKind() == CK_NoOp))
7930 HandleValue(E->getSubExpr());
7931
7932 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007933 }
7934
Richard Trieu898267f2011-09-01 21:44:13 +00007935 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007936 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007937 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007938
Richard Trieu6b2cc422012-10-03 00:41:36 +00007939 // Warn when a non-static method call is followed by non-static member
7940 // field accesses, which is followed by a DeclRefExpr.
7941 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7942 bool Warn = (MD && !MD->isStatic());
7943 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7944 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7945 if (!isa<FieldDecl>(ME->getMemberDecl()))
7946 Warn = false;
7947 Base = ME->getBase()->IgnoreParenImpCasts();
7948 }
Richard Trieu898267f2011-09-01 21:44:13 +00007949
Richard Trieu6b2cc422012-10-03 00:41:36 +00007950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7951 if (Warn)
7952 HandleDeclRefExpr(DRE);
7953 return;
7954 }
7955
7956 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7957 // Visit that expression.
7958 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007959 }
7960
Richard Trieu8af742a2013-03-26 03:41:40 +00007961 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7962 if (E->getNumArgs() > 0)
7963 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7964 HandleDeclRefExpr(DRE);
7965
7966 Inherited::VisitCXXOperatorCallExpr(E);
7967 }
7968
Richard Trieu898267f2011-09-01 21:44:13 +00007969 void VisitUnaryOperator(UnaryOperator *E) {
7970 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007971 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7972 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7973 if (!isPODType)
7974 HandleValue(E->getSubExpr());
7975 return;
7976 }
Richard Trieu898267f2011-09-01 21:44:13 +00007977 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007978 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007979
7980 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7981
Richard Trieu898267f2011-09-01 21:44:13 +00007982 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007983 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007984 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007985 unsigned diag;
7986 if (isReferenceType) {
7987 diag = diag::warn_uninit_self_reference_in_reference_init;
7988 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7989 diag = diag::warn_static_self_reference_in_init;
7990 } else {
7991 diag = diag::warn_uninit_self_reference_in_init;
7992 }
7993
Richard Trieu898267f2011-09-01 21:44:13 +00007994 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007995 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007996 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007997 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007998 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007999 }
8000 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00008001
Richard Trieu568f7852012-10-01 17:39:51 +00008002 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8003 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8004 bool DirectInit) {
8005 // Parameters arguments are occassionially constructed with itself,
8006 // for instance, in recursive functions. Skip them.
8007 if (isa<ParmVarDecl>(OrigDecl))
8008 return;
8009
8010 E = E->IgnoreParens();
8011
8012 // Skip checking T a = a where T is not a record or reference type.
8013 // Doing so is a way to silence uninitialized warnings.
8014 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8015 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8016 if (ICE->getCastKind() == CK_LValueToRValue)
8017 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8018 if (DRE->getDecl() == OrigDecl)
8019 return;
8020
8021 SelfReferenceChecker(S, OrigDecl).Visit(E);
8022 }
Richard Trieu898267f2011-09-01 21:44:13 +00008023}
8024
Douglas Gregor09f41cf2009-01-14 15:45:31 +00008025/// AddInitializerToDecl - Adds the initializer Init to the
8026/// declaration dcl. If DirectInit is true, this is C++ direct
8027/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00008028void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8029 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008030 // If there is no declaration, there was an error parsing it. Just ignore
8031 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00008032 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008033 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008034
Douglas Gregor021c3b32009-03-11 23:00:04 +00008035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8036 // With declarators parsed the way they are, the parser cannot
8037 // distinguish between a normal initializer and a pure-specifier.
8038 // Thus this grotesque test.
8039 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008040 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008041 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8042 CheckPureMethod(Method, Init->getSourceRange());
8043 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008044 Diag(Method->getLocation(), diag::err_member_function_initialization)
8045 << Method->getDeclName() << Init->getSourceRange();
8046 Method->setInvalidDecl();
8047 }
8048 return;
8049 }
8050
Steve Naroff410e3e22007-09-12 20:13:48 +00008051 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8052 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008053 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8054 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008055 RealDecl->setInvalidDecl();
8056 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008057 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008058 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8059
Richard Smith01888722011-12-15 19:20:59 +00008060 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008061 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008062 Expr *DeduceInit = Init;
8063 // Initializer could be a C++ direct-initializer. Deduction only works if it
8064 // contains exactly one expression.
8065 if (CXXDirectInit) {
8066 if (CXXDirectInit->getNumExprs() == 0) {
8067 // It isn't possible to write this directly, but it is possible to
8068 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008069 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008070 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8071 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008072 << VDecl->getDeclName() << VDecl->getType()
8073 << VDecl->getSourceRange();
8074 RealDecl->setInvalidDecl();
8075 return;
8076 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008077 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008078 VDecl->isInitCapture()
8079 ? diag::err_init_capture_multiple_expressions
8080 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008081 << VDecl->getDeclName() << VDecl->getType()
8082 << VDecl->getSourceRange();
8083 RealDecl->setInvalidDecl();
8084 return;
8085 } else {
8086 DeduceInit = CXXDirectInit->getExpr(0);
8087 }
8088 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008089
8090 // Expressions default to 'id' when we're in a debugger.
8091 bool DefaultedToAuto = false;
8092 if (getLangOpts().DebuggerCastResultToId &&
8093 Init->getType() == Context.UnknownAnyTy) {
8094 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8095 if (Result.isInvalid()) {
8096 VDecl->setInvalidDecl();
8097 return;
8098 }
8099 Init = Result.take();
8100 DefaultedToAuto = true;
8101 }
Richard Smith9b131752013-04-30 21:23:01 +00008102
8103 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008104 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008105 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008106 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008107 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008108 RealDecl->setInvalidDecl();
8109 return;
8110 }
Richard Smith9b131752013-04-30 21:23:01 +00008111 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008112 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008113
John McCallf85e1932011-06-15 23:02:42 +00008114 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008115 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008116 VDecl->setInvalidDecl();
8117
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008118 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8119 // 'id' instead of a specific object type prevents most of our usual checks.
8120 // We only want to warn outside of template instantiations, though:
8121 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008122 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008123 DeducedType->isObjCIdType()) {
8124 SourceLocation Loc =
8125 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008126 Diag(Loc, diag::warn_auto_var_is_id)
8127 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8128 }
8129
Richard Smith34b41d92011-02-20 03:19:35 +00008130 // If this is a redeclaration, check that the type we just deduced matches
8131 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008132 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8133 // We never need to merge the type, because we cannot form an incomplete
8134 // array of auto, nor deduce such a type.
8135 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8136 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008137
8138 // Check the deduced type is valid for a variable declaration.
8139 CheckVariableDeclarationType(VDecl);
8140 if (VDecl->isInvalidDecl())
8141 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008142 }
Richard Smith01888722011-12-15 19:20:59 +00008143
8144 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8145 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8146 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8147 VDecl->setInvalidDecl();
8148 return;
8149 }
8150
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008151 if (!VDecl->getType()->isDependentType()) {
8152 // A definition must end up with a complete type, which means it must be
8153 // complete with the restriction that an array type might be completed by
8154 // the initializer; note that later code assumes this restriction.
8155 QualType BaseDeclType = VDecl->getType();
8156 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8157 BaseDeclType = Array->getElementType();
8158 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8159 diag::err_typecheck_decl_incomplete_type)) {
8160 RealDecl->setInvalidDecl();
8161 return;
8162 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008163
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008164 // The variable can not have an abstract class type.
8165 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8166 diag::err_abstract_type_in_decl,
8167 AbstractVariableType))
8168 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008169 }
8170
Sebastian Redl31310a22010-02-01 20:16:42 +00008171 const VarDecl *Def;
8172 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008173 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008174 << VDecl->getDeclName();
8175 Diag(Def->getLocation(), diag::note_previous_definition);
8176 VDecl->setInvalidDecl();
8177 return;
8178 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008179
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008180 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008181 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008182 // C++ [class.static.data]p4
8183 // If a static data member is of const integral or const
8184 // enumeration type, its declaration in the class definition can
8185 // specify a constant-initializer which shall be an integral
8186 // constant expression (5.19). In that case, the member can appear
8187 // in integral constant expressions. The member shall still be
8188 // defined in a namespace scope if it is used in the program and the
8189 // namespace scope definition shall not contain an initializer.
8190 //
8191 // We already performed a redefinition check above, but for static
8192 // data members we also need to check whether there was an in-class
8193 // declaration with an initializer.
8194 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008195 Diag(VDecl->getLocation(), diag::err_redefinition)
8196 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008197 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8198 return;
8199 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008200
Douglas Gregora31040f2010-12-16 01:31:22 +00008201 if (VDecl->hasLocalStorage())
8202 getCurFunction()->setHasBranchProtectedScope();
8203
8204 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8205 VDecl->setInvalidDecl();
8206 return;
8207 }
8208 }
John McCalle46f62c2010-08-01 01:24:59 +00008209
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008210 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8211 // a kernel function cannot be initialized."
8212 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8213 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8214 VDecl->setInvalidDecl();
8215 return;
8216 }
8217
Steve Naroffbb204692007-09-12 14:07:44 +00008218 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008219 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008220 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008221
Douglas Gregor1344e942013-03-07 22:57:58 +00008222 // Expressions default to 'id' when we're in a debugger
8223 // and we are assigning it to a variable of Objective-C pointer type.
8224 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8225 Init->getType() == Context.UnknownAnyTy) {
8226 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8227 if (Result.isInvalid()) {
8228 VDecl->setInvalidDecl();
8229 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008230 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008231 Init = Result.take();
8232 }
Richard Smith01888722011-12-15 19:20:59 +00008233
8234 // Perform the initialization.
8235 if (!VDecl->isInvalidDecl()) {
8236 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8237 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008238 = DirectInit ?
8239 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8240 Init->getLocStart(),
8241 Init->getLocEnd())
8242 : InitializationKind::CreateDirectList(
8243 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008244 : InitializationKind::CreateCopy(VDecl->getLocation(),
8245 Init->getLocStart());
8246
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008247 MultiExprArg Args = Init;
8248 if (CXXDirectInit)
8249 Args = MultiExprArg(CXXDirectInit->getExprs(),
8250 CXXDirectInit->getNumExprs());
8251
8252 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8253 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008254 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008255 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008256 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008257 }
Richard Smith01888722011-12-15 19:20:59 +00008258
8259 Init = Result.takeAs<Expr>();
8260 }
8261
Richard Trieu568f7852012-10-01 17:39:51 +00008262 // Check for self-references within variable initializers.
8263 // Variables declared within a function/method body (except for references)
8264 // are handled by a dataflow analysis.
8265 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8266 VDecl->getType()->isReferenceType()) {
8267 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8268 }
8269
Richard Smith01888722011-12-15 19:20:59 +00008270 // If the type changed, it means we had an incomplete type that was
8271 // completed by the initializer. For example:
8272 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008273 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008274 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008275 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008276
Jordan Rosee10f4d32012-09-15 02:48:31 +00008277 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008278 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8279
Jordan Rosee10f4d32012-09-15 02:48:31 +00008280 if (VDecl->hasAttr<BlocksAttr>())
8281 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008282
8283 // It is safe to assign a weak reference into a strong variable.
8284 // Although this code can still have problems:
8285 // id x = self.weakProp;
8286 // id y = self.weakProp;
8287 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8288 // paths through the function. This should be revisited if
8289 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008290 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008291 DiagnosticsEngine::Level Level =
8292 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8293 Init->getLocStart());
8294 if (Level != DiagnosticsEngine::Ignored)
8295 getCurFunction()->markSafeWeakUse(Init);
8296 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008297 }
8298
Richard Smith41956372013-01-14 22:39:08 +00008299 // The initialization is usually a full-expression.
8300 //
8301 // FIXME: If this is a braced initialization of an aggregate, it is not
8302 // an expression, and each individual field initializer is a separate
8303 // full-expression. For instance, in:
8304 //
8305 // struct Temp { ~Temp(); };
8306 // struct S { S(Temp); };
8307 // struct T { S a, b; } t = { Temp(), Temp() }
8308 //
8309 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008310 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8311 false,
8312 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008313 if (Result.isInvalid()) {
8314 VDecl->setInvalidDecl();
8315 return;
8316 }
8317 Init = Result.take();
8318
Richard Smith01888722011-12-15 19:20:59 +00008319 // Attach the initializer to the decl.
8320 VDecl->setInit(Init);
8321
8322 if (VDecl->isLocalVarDecl()) {
8323 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8324 // static storage duration shall be constant expressions or string literals.
8325 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008326 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8327 if (VDecl->getStorageClass() == SC_Static)
8328 CheckForConstantInitializer(Init, DclT);
8329 // C89 is stricter than C99 for non-static aggregate types.
8330 // C89 6.5.7p3: All the expressions [...] in an initializer list
8331 // for an object that has aggregate or union type shall be
8332 // constant expressions.
8333 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008334 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008335 !Init->isConstantInitializer(Context, false))
8336 Diag(Init->getExprLoc(),
8337 diag::ext_aggregate_init_not_constant)
8338 << Init->getSourceRange();
8339 }
Mike Stump1eb44332009-09-09 15:08:12 +00008340 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008341 VDecl->getLexicalDeclContext()->isRecord()) {
8342 // This is an in-class initialization for a static data member, e.g.,
8343 //
8344 // struct S {
8345 // static const int value = 17;
8346 // };
8347
Douglas Gregor021c3b32009-03-11 23:00:04 +00008348 // C++ [class.mem]p4:
8349 // A member-declarator can contain a constant-initializer only
8350 // if it declares a static member (9.4) of const integral or
8351 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008352 //
Richard Smith01888722011-12-15 19:20:59 +00008353 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008354 // If a non-volatile const static data member is of integral or
8355 // enumeration type, its declaration in the class definition can
8356 // specify a brace-or-equal-initializer in which every initalizer-clause
8357 // that is an assignment-expression is a constant expression. A static
8358 // data member of literal type can be declared in the class definition
8359 // with the constexpr specifier; if so, its declaration shall specify a
8360 // brace-or-equal-initializer in which every initializer-clause that is
8361 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008362
8363 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008364 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008365
Richard Smithc6d990a2011-09-29 19:11:37 +00008366 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008367 // type. We separately check that every constexpr variable is of literal
8368 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008369 } else if (VDecl->isConstexpr()) {
8370
John McCall4e635642010-09-10 23:21:22 +00008371 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008372 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008373 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8374 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008375 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008376
8377 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008378 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008379 // Check whether the expression is a constant expression.
8380 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008381 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008382 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008383 // in-class initializer cannot be volatile.
8384 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8385 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008386 ; // Nothing to check.
8387 else if (Init->isIntegerConstantExpr(Context, &Loc))
8388 ; // Ok, it's an ICE!
8389 else if (Init->isEvaluatable(Context)) {
8390 // If we can constant fold the initializer through heroics, accept it,
8391 // but report this as a use of an extension for -pedantic.
8392 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8393 << Init->getSourceRange();
8394 } else {
8395 // Otherwise, this is some crazy unknown case. Report the issue at the
8396 // location provided by the isIntegerConstantExpr failed check.
8397 Diag(Loc, diag::err_in_class_initializer_non_constant)
8398 << Init->getSourceRange();
8399 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008400 }
8401
Richard Smith01888722011-12-15 19:20:59 +00008402 // We allow foldable floating-point constants as an extension.
8403 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008404 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8405 // it anyway and provide a fixit to add the 'constexpr'.
8406 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008407 Diag(VDecl->getLocation(),
8408 diag::ext_in_class_initializer_float_type_cxx11)
8409 << DclT << Init->getSourceRange();
8410 Diag(VDecl->getLocStart(),
8411 diag::note_in_class_initializer_float_type_cxx11)
8412 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008413 } else {
8414 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8415 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008416
Richard Smithb4b1d692013-01-25 04:22:16 +00008417 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8418 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8419 << Init->getSourceRange();
8420 VDecl->setInvalidDecl();
8421 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008422 }
Richard Smith947be192011-09-29 23:18:34 +00008423
Richard Smith01888722011-12-15 19:20:59 +00008424 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008425 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008426 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008427 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008428 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8429 VDecl->setConstexpr(true);
8430
Richard Smithc6d990a2011-09-29 19:11:37 +00008431 } else {
8432 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008433 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008434 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008435 }
Steve Naroff248a7532008-04-15 22:42:06 +00008436 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008437 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008438 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008439 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008440 VDecl->isExternC())) &&
8441 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008442 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008443
Richard Smith01888722011-12-15 19:20:59 +00008444 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008445 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008446 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008447 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8448 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8449 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008450 !Init->isConstantInitializer(
8451 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008452 // GNU C++98 edits for __thread, [basic.start.init]p4:
8453 // An object of thread storage duration shall not require dynamic
8454 // initialization.
8455 // FIXME: Need strict checking here.
8456 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8457 if (getLangOpts().CPlusPlus11)
8458 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8459 }
Steve Naroffbb204692007-09-12 14:07:44 +00008460 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008461
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008462 // We will represent direct-initialization similarly to copy-initialization:
8463 // int x(1); -as-> int x = 1;
8464 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8465 //
8466 // Clients that want to distinguish between the two forms, can check for
8467 // direct initializer using VarDecl::getInitStyle().
8468 // A major benefit is that clients that don't particularly care about which
8469 // exactly form was it (like the CodeGen) can handle both cases without
8470 // special case code.
8471
8472 // C++ 8.5p11:
8473 // The form of initialization (using parentheses or '=') is generally
8474 // insignificant, but does matter when the entity being initialized has a
8475 // class type.
8476 if (CXXDirectInit) {
8477 assert(DirectInit && "Call-style initializer must be direct init.");
8478 VDecl->setInitStyle(VarDecl::CallInit);
8479 } else if (DirectInit) {
8480 // This must be list-initialization. No other way is direct-initialization.
8481 VDecl->setInitStyle(VarDecl::ListInit);
8482 }
8483
John McCall2998d6b2011-01-19 11:48:09 +00008484 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008485}
8486
John McCall7727acf2010-03-31 02:13:20 +00008487/// ActOnInitializerError - Given that there was an error parsing an
8488/// initializer for the given declaration, try to return to some form
8489/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008490void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008491 // Our main concern here is re-establishing invariants like "a
8492 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008493 if (!D || D->isInvalidDecl()) return;
8494
8495 VarDecl *VD = dyn_cast<VarDecl>(D);
8496 if (!VD) return;
8497
Richard Smith34b41d92011-02-20 03:19:35 +00008498 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008499 if (ParsingInitForAutoVars.count(D)) {
8500 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008501 return;
8502 }
8503
John McCall7727acf2010-03-31 02:13:20 +00008504 QualType Ty = VD->getType();
8505 if (Ty->isDependentType()) return;
8506
8507 // Require a complete type.
8508 if (RequireCompleteType(VD->getLocation(),
8509 Context.getBaseElementType(Ty),
8510 diag::err_typecheck_decl_incomplete_type)) {
8511 VD->setInvalidDecl();
8512 return;
8513 }
8514
8515 // Require an abstract type.
8516 if (RequireNonAbstractType(VD->getLocation(), Ty,
8517 diag::err_abstract_type_in_decl,
8518 AbstractVariableType)) {
8519 VD->setInvalidDecl();
8520 return;
8521 }
8522
8523 // Don't bother complaining about constructors or destructors,
8524 // though.
8525}
8526
John McCalld226f652010-08-21 09:40:31 +00008527void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008528 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008529 // If there is no declaration, there was an error parsing it. Just ignore it.
8530 if (RealDecl == 0)
8531 return;
8532
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008533 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8534 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008535
Richard Smithdd4b3502011-12-25 21:17:58 +00008536 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008537 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008538 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8539 << Var->getDeclName() << Type;
8540 Var->setInvalidDecl();
8541 return;
8542 }
Mike Stump1eb44332009-09-09 15:08:12 +00008543
Richard Smithdd4b3502011-12-25 21:17:58 +00008544 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008545 // the constexpr specifier; if so, its declaration shall specify
8546 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008547 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8548 // the definition of a variable [...] or the declaration of a static data
8549 // member.
8550 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8551 if (Var->isStaticDataMember())
8552 Diag(Var->getLocation(),
8553 diag::err_constexpr_static_mem_var_requires_init)
8554 << Var->getDeclName();
8555 else
8556 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008557 Var->setInvalidDecl();
8558 return;
8559 }
8560
Douglas Gregor60c93c92010-02-09 07:26:29 +00008561 switch (Var->isThisDeclarationADefinition()) {
8562 case VarDecl::Definition:
8563 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8564 break;
8565
8566 // We have an out-of-line definition of a static data member
8567 // that has an in-class initializer, so we type-check this like
8568 // a declaration.
8569 //
8570 // Fall through
8571
8572 case VarDecl::DeclarationOnly:
8573 // It's only a declaration.
8574
8575 // Block scope. C99 6.7p7: If an identifier for an object is
8576 // declared with no linkage (C99 6.2.2p6), the type for the
8577 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008578 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008579 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008580 RequireCompleteType(Var->getLocation(), Type,
8581 diag::err_typecheck_decl_incomplete_type))
8582 Var->setInvalidDecl();
8583
8584 // Make sure that the type is not abstract.
8585 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8586 RequireNonAbstractType(Var->getLocation(), Type,
8587 diag::err_abstract_type_in_decl,
8588 AbstractVariableType))
8589 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008590 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008591 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008592 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008593 Diag(Var->getLocation(), diag::note_private_extern);
8594 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008595
Douglas Gregor60c93c92010-02-09 07:26:29 +00008596 return;
8597
8598 case VarDecl::TentativeDefinition:
8599 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8600 // object that has file scope without an initializer, and without a
8601 // storage-class specifier or with the storage-class specifier "static",
8602 // constitutes a tentative definition. Note: A tentative definition with
8603 // external linkage is valid (C99 6.2.2p5).
8604 if (!Var->isInvalidDecl()) {
8605 if (const IncompleteArrayType *ArrayT
8606 = Context.getAsIncompleteArrayType(Type)) {
8607 if (RequireCompleteType(Var->getLocation(),
8608 ArrayT->getElementType(),
8609 diag::err_illegal_decl_array_incomplete_type))
8610 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008611 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008612 // C99 6.9.2p3: If the declaration of an identifier for an object is
8613 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8614 // declared type shall not be an incomplete type.
8615 // NOTE: code such as the following
8616 // static struct s;
8617 // struct s { int a; };
8618 // is accepted by gcc. Hence here we issue a warning instead of
8619 // an error and we do not invalidate the static declaration.
8620 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008621 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008622 RequireCompleteType(Var->getLocation(), Type,
8623 diag::ext_typecheck_decl_incomplete_type);
8624 }
8625 }
8626
8627 // Record the tentative definition; we're done.
8628 if (!Var->isInvalidDecl())
8629 TentativeDefinitions.push_back(Var);
8630 return;
8631 }
8632
8633 // Provide a specific diagnostic for uninitialized variable
8634 // definitions with incomplete array type.
8635 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008636 Diag(Var->getLocation(),
8637 diag::err_typecheck_incomplete_array_needs_initializer);
8638 Var->setInvalidDecl();
8639 return;
8640 }
8641
John McCallb567a8b2010-08-01 01:25:24 +00008642 // Provide a specific diagnostic for uninitialized variable
8643 // definitions with reference type.
8644 if (Type->isReferenceType()) {
8645 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8646 << Var->getDeclName()
8647 << SourceRange(Var->getLocation(), Var->getLocation());
8648 Var->setInvalidDecl();
8649 return;
8650 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008651
8652 // Do not attempt to type-check the default initializer for a
8653 // variable with dependent type.
8654 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008655 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008656
Douglas Gregor60c93c92010-02-09 07:26:29 +00008657 if (Var->isInvalidDecl())
8658 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008659
Douglas Gregor60c93c92010-02-09 07:26:29 +00008660 if (RequireCompleteType(Var->getLocation(),
8661 Context.getBaseElementType(Type),
8662 diag::err_typecheck_decl_incomplete_type)) {
8663 Var->setInvalidDecl();
8664 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008665 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008666
Douglas Gregor60c93c92010-02-09 07:26:29 +00008667 // The variable can not have an abstract class type.
8668 if (RequireNonAbstractType(Var->getLocation(), Type,
8669 diag::err_abstract_type_in_decl,
8670 AbstractVariableType)) {
8671 Var->setInvalidDecl();
8672 return;
8673 }
8674
Douglas Gregor4337dc72011-05-21 17:52:48 +00008675 // Check for jumps past the implicit initializer. C++0x
8676 // clarifies that this applies to a "variable with automatic
8677 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008678 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008679 // A program that jumps from a point where a variable with automatic
8680 // storage duration is not in scope to a point where it is in scope is
8681 // ill-formed unless the variable has scalar type, class type with a
8682 // trivial default constructor and a trivial destructor, a cv-qualified
8683 // version of one of these types, or an array of one of the preceding
8684 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008685 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008686 if (const RecordType *Record
8687 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008688 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008689 // Mark the function for further checking even if the looser rules of
8690 // C++11 do not require such checks, so that we can diagnose
8691 // incompatibilities with C++98.
8692 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008693 getCurFunction()->setHasBranchProtectedScope();
8694 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008695 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008696
8697 // C++03 [dcl.init]p9:
8698 // If no initializer is specified for an object, and the
8699 // object is of (possibly cv-qualified) non-POD class type (or
8700 // array thereof), the object shall be default-initialized; if
8701 // the object is of const-qualified type, the underlying class
8702 // type shall have a user-declared default
8703 // constructor. Otherwise, if no initializer is specified for
8704 // a non- static object, the object and its subobjects, if
8705 // any, have an indeterminate initial value); if the object
8706 // or any of its subobjects are of const-qualified type, the
8707 // program is ill-formed.
8708 // C++0x [dcl.init]p11:
8709 // If no initializer is specified for an object, the object is
8710 // default-initialized; [...].
8711 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8712 InitializationKind Kind
8713 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008714
8715 InitializationSequence InitSeq(*this, Entity, Kind, None);
8716 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008717 if (Init.isInvalid())
8718 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008719 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008720 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008721 // This is important for template substitution.
8722 Var->setInitStyle(VarDecl::CallInit);
8723 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008724
John McCall2998d6b2011-01-19 11:48:09 +00008725 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008726 }
8727}
8728
Richard Smithad762fc2011-04-14 22:09:26 +00008729void Sema::ActOnCXXForRangeDecl(Decl *D) {
8730 VarDecl *VD = dyn_cast<VarDecl>(D);
8731 if (!VD) {
8732 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8733 D->setInvalidDecl();
8734 return;
8735 }
8736
8737 VD->setCXXForRangeDecl(true);
8738
8739 // for-range-declaration cannot be given a storage class specifier.
8740 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008741 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008742 case SC_None:
8743 break;
8744 case SC_Extern:
8745 Error = 0;
8746 break;
8747 case SC_Static:
8748 Error = 1;
8749 break;
8750 case SC_PrivateExtern:
8751 Error = 2;
8752 break;
8753 case SC_Auto:
8754 Error = 3;
8755 break;
8756 case SC_Register:
8757 Error = 4;
8758 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008759 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008760 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008761 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008762 if (VD->isConstexpr())
8763 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008764 if (Error != -1) {
8765 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8766 << VD->getDeclName() << Error;
8767 D->setInvalidDecl();
8768 }
8769}
8770
John McCall2998d6b2011-01-19 11:48:09 +00008771void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8772 if (var->isInvalidDecl()) return;
8773
John McCallf85e1932011-06-15 23:02:42 +00008774 // In ARC, don't allow jumps past the implicit initialization of a
8775 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008776 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008777 var->hasLocalStorage()) {
8778 switch (var->getType().getObjCLifetime()) {
8779 case Qualifiers::OCL_None:
8780 case Qualifiers::OCL_ExplicitNone:
8781 case Qualifiers::OCL_Autoreleasing:
8782 break;
8783
8784 case Qualifiers::OCL_Weak:
8785 case Qualifiers::OCL_Strong:
8786 getCurFunction()->setHasBranchProtectedScope();
8787 break;
8788 }
8789 }
8790
Eli Friedmane4851f22012-10-23 20:19:32 +00008791 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008792 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008793 getDiagnostics().getDiagnosticLevel(
8794 diag::warn_missing_variable_declarations,
8795 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008796 // Find a previous declaration that's not a definition.
8797 VarDecl *prev = var->getPreviousDecl();
8798 while (prev && prev->isThisDeclarationADefinition())
8799 prev = prev->getPreviousDecl();
8800
8801 if (!prev)
8802 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8803 }
8804
Richard Smith6a570f62013-04-14 20:11:31 +00008805 if (var->getTLSKind() == VarDecl::TLS_Static &&
8806 var->getType().isDestructedType()) {
8807 // GNU C++98 edits for __thread, [basic.start.term]p3:
8808 // The type of an object with thread storage duration shall not
8809 // have a non-trivial destructor.
8810 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8811 if (getLangOpts().CPlusPlus11)
8812 Diag(var->getLocation(), diag::note_use_thread_local);
8813 }
8814
John McCall2998d6b2011-01-19 11:48:09 +00008815 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008816 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008817
Richard Smitha67d5032012-11-09 23:03:14 +00008818 QualType type = var->getType();
8819 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008820
8821 // __block variables might require us to capture a copy-initializer.
8822 if (var->hasAttr<BlocksAttr>()) {
8823 // It's currently invalid to ever have a __block variable with an
8824 // array type; should we diagnose that here?
8825
8826 // Regardless, we don't want to ignore array nesting when
8827 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008828 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008829 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008830 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008831 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008832 ExprResult result
8833 = PerformMoveOrCopyInitialization(
8834 InitializedEntity::InitializeBlock(poi, type, false),
8835 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008836 if (!result.isInvalid()) {
8837 result = MaybeCreateExprWithCleanups(result);
8838 Expr *init = result.takeAs<Expr>();
8839 Context.setBlockVarCopyInits(var, init);
8840 }
8841 }
8842 }
8843
Richard Smith66f85712011-11-07 22:16:17 +00008844 Expr *Init = var->getInit();
8845 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008846 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008847
Richard Smith9568f0c2012-10-29 18:26:47 +00008848 if (!var->getDeclContext()->isDependentContext() &&
8849 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008850 if (IsGlobal && !var->isConstexpr() &&
8851 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8852 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008853 != DiagnosticsEngine::Ignored) {
8854 // Warn about globals which don't have a constant initializer. Don't
8855 // warn about globals with a non-trivial destructor because we already
8856 // warned about them.
8857 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8858 if (!(RD && !RD->hasTrivialDestructor()) &&
8859 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8860 Diag(var->getLocation(), diag::warn_global_constructor)
8861 << Init->getSourceRange();
8862 }
Richard Smith099e7f62011-12-19 06:19:21 +00008863
Richard Smith099e7f62011-12-19 06:19:21 +00008864 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008865 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008866 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8867 SourceLocation DiagLoc = var->getLocation();
8868 // If the note doesn't add any useful information other than a source
8869 // location, fold it into the primary diagnostic.
8870 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8871 diag::note_invalid_subexpr_in_const_expr) {
8872 DiagLoc = Notes[0].first;
8873 Notes.clear();
8874 }
8875 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8876 << var << Init->getSourceRange();
8877 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8878 Diag(Notes[I].first, Notes[I].second);
8879 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008880 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008881 // Check whether the initializer of a const variable of integral or
8882 // enumeration type is an ICE now, since we can't tell whether it was
8883 // initialized by a constant expression if we check later.
8884 var->checkInitIsICE();
8885 }
Richard Smith66f85712011-11-07 22:16:17 +00008886 }
John McCall2998d6b2011-01-19 11:48:09 +00008887
8888 // Require the destructor.
8889 if (const RecordType *recordType = baseType->getAs<RecordType>())
8890 FinalizeVarWithDestructor(var, recordType);
8891}
8892
Richard Smith483b9f32011-02-21 20:05:19 +00008893/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8894/// any semantic actions necessary after any initializer has been attached.
8895void
8896Sema::FinalizeDeclaration(Decl *ThisDecl) {
8897 // Note that we are no longer parsing the initializer for this declaration.
8898 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008899
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008900 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008901 if (!VD)
8902 return;
8903
Rafael Espindola29535ba2013-08-16 23:18:50 +00008904 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8905 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8906 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8907 VD->dropAttr<UsedAttr>();
8908 }
8909 }
8910
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008911 if (!VD->isInvalidDecl() &&
8912 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8913 if (const VarDecl *Def = VD->getDefinition()) {
8914 if (Def->hasAttr<AliasAttr>()) {
8915 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8916 << VD->getDeclName();
8917 Diag(Def->getLocation(), diag::note_previous_definition);
8918 VD->setInvalidDecl();
8919 }
8920 }
8921 }
8922
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008923 const DeclContext *DC = VD->getDeclContext();
8924 // If there's a #pragma GCC visibility in scope, and this isn't a class
8925 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008926 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008927 AddPushedVisibilityAttribute(VD);
8928
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008929 if (VD->isFileVarDecl())
8930 MarkUnusedFileScopedDecl(VD);
8931
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008932 // Now we have parsed the initializer and can update the table of magic
8933 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008934 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8935 !VD->getType()->isIntegralOrEnumerationType())
8936 return;
8937
8938 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8939 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8940 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8941 I != E; ++I) {
8942 const Expr *MagicValueExpr = VD->getInit();
8943 if (!MagicValueExpr) {
8944 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008945 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008946 llvm::APSInt MagicValueInt;
8947 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8948 Diag(I->getRange().getBegin(),
8949 diag::err_type_tag_for_datatype_not_ice)
8950 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8951 continue;
8952 }
8953 if (MagicValueInt.getActiveBits() > 64) {
8954 Diag(I->getRange().getBegin(),
8955 diag::err_type_tag_for_datatype_too_large)
8956 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8957 continue;
8958 }
8959 uint64_t MagicValue = MagicValueInt.getZExtValue();
8960 RegisterTypeTagForDatatype(I->getArgumentKind(),
8961 MagicValue,
8962 I->getMatchingCType(),
8963 I->getLayoutCompatible(),
8964 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008965 }
Richard Smith483b9f32011-02-21 20:05:19 +00008966}
8967
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008968Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8969 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008970 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008971
8972 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008973 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008974
David Majnemeraa824612013-09-17 23:57:10 +00008975 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008976 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008977 if (Decl *D = Group[i]) {
8978 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8979 if (!FirstDeclaratorInGroup)
8980 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008981 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008982 }
Richard Smith406c38e2011-02-23 00:37:57 +00008983
Eli Friedman5e867c82013-07-10 00:30:46 +00008984 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008985 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008986 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008987 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8988 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8989 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008990 }
David Blaikie66cff722012-11-14 01:52:05 +00008991
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008992 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008993}
8994
8995/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8996/// group, performing any necessary semantic checking.
8997Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008998Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008999 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00009000 // C++0x [dcl.spec.auto]p7:
9001 // If the type deduced for the template parameter U is not the same in each
9002 // deduction, the program is ill-formed.
9003 // FIXME: When initializer-list support is added, a distinction is needed
9004 // between the deduced type U and the deduced type which 'auto' stands for.
9005 // auto a = 0, b = { 1, 2, 3 };
9006 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009007 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00009008 QualType Deduced;
9009 CanQualType DeducedCanon;
9010 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009011 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00009012 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9013 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00009014 // Don't reissue diagnostics when instantiating a template.
9015 if (AT && D->isInvalidDecl())
9016 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00009017 QualType U = AT ? AT->getDeducedType() : QualType();
9018 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009019 CanQualType UCanon = Context.getCanonicalType(U);
9020 if (Deduced.isNull()) {
9021 Deduced = U;
9022 DeducedCanon = UCanon;
9023 DeducedDecl = D;
9024 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00009025 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9026 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00009027 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00009028 << Deduced << DeducedDecl->getDeclName()
9029 << U << D->getDeclName()
9030 << DeducedDecl->getInit()->getSourceRange()
9031 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00009032 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00009033 break;
9034 }
9035 }
9036 }
9037 }
9038 }
9039
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009040 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009041
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009042 return DeclGroupPtrTy::make(
9043 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009044}
Steve Naroffe1223f72007-08-28 03:03:08 +00009045
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009046void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009047 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009048}
9049
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009050void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009051 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009052 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009053 return;
9054
9055 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9056 Group[0]->getLocation())
9057 == DiagnosticsEngine::Ignored)
9058 return;
9059
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009060 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009061 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009062 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009063 // additional declaration references:
9064 // 'typedef struct S {} S;'
9065 // 'typedef struct S *S;'
9066 // 'struct S *pS;'
9067 // FinalizeDeclaratorGroup adds these as separate declarations.
9068 Decl *MaybeTagDecl = Group[0];
9069 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009070 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009071 }
9072 }
9073
9074 // See if there are any new comments that are not attached to a decl.
9075 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9076 if (!Comments.empty() &&
9077 !Comments.back()->isAttached()) {
9078 // There is at least one comment that not attached to a decl.
9079 // Maybe it should be attached to one of these decls?
9080 //
9081 // Note that this way we pick up not only comments that precede the
9082 // declaration, but also comments that *follow* the declaration -- thanks to
9083 // the lookahead in the lexer: we've consumed the semicolon and looked
9084 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009085 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009086 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009087 }
9088}
Chris Lattner682bf922009-03-29 16:50:03 +00009089
Chris Lattner04421082008-04-08 04:40:51 +00009090/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9091/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009092Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009093 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009094
Chris Lattner04421082008-04-08 04:40:51 +00009095 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009096
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009097 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009098 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009099 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009100 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009101 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009102 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9103 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009104 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009105 Diag(DS.getStorageClassSpecLoc(),
9106 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009107 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009108 }
Eli Friedman63054b32009-04-19 20:27:55 +00009109
Richard Smithec642442013-04-12 22:46:28 +00009110 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9111 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9112 << DeclSpec::getSpecifierName(TSCS);
9113 if (DS.isConstexprSpecified())
9114 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009115 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009116
Richard Smithec642442013-04-12 22:46:28 +00009117 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009118
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009120 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009121
David Blaikie4e4d0842012-03-11 07:00:24 +00009122 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009123 // Check that there are no default arguments inside the type of this
9124 // parameter.
9125 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009126
9127 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9128 if (D.getCXXScopeSpec().isSet()) {
9129 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9130 << D.getCXXScopeSpec().getRange();
9131 D.getCXXScopeSpec().clear();
9132 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009133 }
9134
Sean Hunt7533a5b2010-11-03 01:07:06 +00009135 // Ensure we have a valid name
9136 IdentifierInfo *II = 0;
9137 if (D.hasName()) {
9138 II = D.getIdentifier();
9139 if (!II) {
9140 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9141 << GetNameForDeclarator(D).getName().getAsString();
9142 D.setInvalidType(true);
9143 }
9144 }
9145
Chris Lattnerd84aac12010-02-22 00:40:25 +00009146 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009147 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009148 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9149 ForRedeclaration);
9150 LookupName(R, S);
9151 if (R.isSingleResult()) {
9152 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009153 if (PrevDecl->isTemplateParameter()) {
9154 // Maybe we will complain about the shadowed template parameter.
9155 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9156 // Just pretend that we didn't see the previous declaration.
9157 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009158 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009159 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009160 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009161
Chris Lattnercf79b012009-01-21 02:38:50 +00009162 // Recover by removing the name
9163 II = 0;
9164 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009165 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009166 }
Chris Lattner04421082008-04-08 04:40:51 +00009167 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009168 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009169
John McCall7a9813c2010-01-22 00:28:27 +00009170 // Temporarily put parameter variables in the translation unit, not
9171 // the enclosing context. This prevents them from accidentally
9172 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009173 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009174 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009175 D.getIdentifierLoc(), II,
9176 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009177 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009178
Chris Lattnereaaebc72009-04-25 08:06:05 +00009179 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009180 New->setInvalidDecl();
9181
9182 assert(S->isFunctionPrototypeScope());
9183 assert(S->getFunctionPrototypeDepth() >= 1);
9184 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9185 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009186
Douglas Gregor44b43212008-12-11 16:49:14 +00009187 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009188 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009189 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009190 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009191
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009192 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009193
Douglas Gregore3895852011-09-12 18:37:38 +00009194 if (D.getDeclSpec().isModulePrivateSpecified())
9195 Diag(New->getLocation(), diag::err_module_private_local)
9196 << 1 << New->getDeclName()
9197 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9198 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9199
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009200 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009201 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9202 }
John McCalld226f652010-08-21 09:40:31 +00009203 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009204}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009205
John McCall82dc0092010-06-04 11:21:44 +00009206/// \brief Synthesizes a variable for a parameter arising from a
9207/// typedef.
9208ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9209 SourceLocation Loc,
9210 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009211 /* FIXME: setting StartLoc == Loc.
9212 Would it be worth to modify callers so as to provide proper source
9213 location for the unnamed parameters, embedding the parameter's type? */
9214 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009215 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009216 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009217 Param->setImplicit();
9218 return Param;
9219}
9220
John McCallfbce0e12010-08-24 09:05:15 +00009221void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9222 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009223 // Don't diagnose unused-parameter errors in template instantiations; we
9224 // will already have done so in the template itself.
9225 if (!ActiveTemplateInstantiations.empty())
9226 return;
9227
9228 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009229 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009230 !(*Param)->hasAttr<UnusedAttr>()) {
9231 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9232 << (*Param)->getDeclName();
9233 }
9234 }
9235}
9236
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009237void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9238 ParmVarDecl * const *ParamEnd,
9239 QualType ReturnTy,
9240 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009241 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009242 return;
9243
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009244 // Warn if the return value is pass-by-value and larger than the specified
9245 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009246 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009247 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009248 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009249 Diag(D->getLocation(), diag::warn_return_value_size)
9250 << D->getDeclName() << Size;
9251 }
9252
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009253 // Warn if any parameter is pass-by-value and larger than the specified
9254 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009255 for (; Param != ParamEnd; ++Param) {
9256 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009257 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009258 continue;
9259 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009260 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009261 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9262 << (*Param)->getDeclName() << Size;
9263 }
9264}
9265
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009266ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9267 SourceLocation NameLoc, IdentifierInfo *Name,
9268 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009269 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009270 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009271 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009272 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009273 T->isObjCLifetimeType()) {
9274
9275 Qualifiers::ObjCLifetime lifetime;
9276
9277 // Special cases for arrays:
9278 // - if it's const, use __unsafe_unretained
9279 // - otherwise, it's an error
9280 if (T->isArrayType()) {
9281 if (!T.isConstQualified()) {
9282 DelayedDiagnostics.add(
9283 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009284 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009285 }
9286 lifetime = Qualifiers::OCL_ExplicitNone;
9287 } else {
9288 lifetime = T->getObjCARCImplicitLifetime();
9289 }
9290 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009291 }
9292
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009293 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009294 Context.getAdjustedParameterType(T),
9295 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009296 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009297
9298 // Parameters can not be abstract class types.
9299 // For record types, this is done by the AbstractClassUsageDiagnoser once
9300 // the class has been completely parsed.
9301 if (!CurContext->isRecord() &&
9302 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9303 AbstractParamType))
9304 New->setInvalidDecl();
9305
9306 // Parameter declarators cannot be interface types. All ObjC objects are
9307 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009308 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009309 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009310 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009311 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009312 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009313 T = Context.getObjCObjectPointerType(T);
9314 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009315 }
9316
9317 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9318 // duration shall not be qualified by an address-space qualifier."
9319 // Since all parameters have automatic store duration, they can not have
9320 // an address space.
9321 if (T.getAddressSpace() != 0) {
9322 Diag(NameLoc, diag::err_arg_with_address_space);
9323 New->setInvalidDecl();
9324 }
9325
9326 return New;
9327}
9328
Douglas Gregora3a83512009-04-01 23:51:29 +00009329void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9330 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009331 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009332
Reid Spencer5f016e22007-07-11 17:01:13 +00009333 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9334 // for a K&R function.
9335 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009336 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9337 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009338 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009339 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009340 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009341 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009342 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009343 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009344 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009345 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009346
Reid Spencer5f016e22007-07-11 17:01:13 +00009347 // Implicitly declare the argument as type 'int' for lack of a better
9348 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009349 AttributeFactory attrs;
9350 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009351 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009352 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009353 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009354 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009355 // Use the identifier location for the type source range.
9356 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9357 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009358 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9359 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009360 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009361 }
9362 }
Mike Stump1eb44332009-09-09 15:08:12 +00009363 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009364}
9365
Richard Smith87162c22012-04-17 22:30:01 +00009366Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009367 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009368 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009369 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009370
Douglas Gregor45fa5602011-11-07 20:56:01 +00009371 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009372 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009373 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009374}
9375
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009376static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9377 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009378 // Don't warn about invalid declarations.
9379 if (FD->isInvalidDecl())
9380 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009381
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009382 // Or declarations that aren't global.
9383 if (!FD->isGlobal())
9384 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009385
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009386 // Don't warn about C++ member functions.
9387 if (isa<CXXMethodDecl>(FD))
9388 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009389
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009390 // Don't warn about 'main'.
9391 if (FD->isMain())
9392 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009393
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009394 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009395 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009396 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009397
9398 // Don't warn about function templates.
9399 if (FD->getDescribedFunctionTemplate())
9400 return false;
9401
9402 // Don't warn about function template specializations.
9403 if (FD->isFunctionTemplateSpecialization())
9404 return false;
9405
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009406 // Don't warn for OpenCL kernels.
9407 if (FD->hasAttr<OpenCLKernelAttr>())
9408 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009409
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009410 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009411 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9412 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009413 // Ignore any declarations that occur in function or method
9414 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009415 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009416 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009417
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009418 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009419 if (FD->getNumParams() == 0)
9420 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009421 break;
9422 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009423
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009424 return MissingPrototype;
9425}
9426
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009427void
9428Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9429 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009430 // Don't complain if we're in GNU89 mode and the previous definition
9431 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009432 const FunctionDecl *Definition = EffectiveDefinition;
9433 if (!Definition)
9434 if (!FD->isDefined(Definition))
9435 return;
9436
9437 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009438 return;
9439
9440 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9441 Definition->getStorageClass() == SC_Extern)
9442 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009443 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009444 else
9445 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9446
9447 Diag(Definition->getLocation(), diag::note_previous_definition);
9448 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009449}
Faisal Valic00e4192013-11-07 05:17:06 +00009450
9451
Faisal Valibef582b2013-10-23 16:10:50 +00009452static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9453 Sema &S) {
9454 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Valid78d6592013-11-12 01:40:44 +00009455
9456 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valibef582b2013-10-23 16:10:50 +00009457 LSI->CallOperator = CallOperator;
9458 LSI->Lambda = LambdaClass;
9459 LSI->ReturnType = CallOperator->getResultType();
9460 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9461
9462 if (LCD == LCD_None)
9463 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9464 else if (LCD == LCD_ByCopy)
9465 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9466 else if (LCD == LCD_ByRef)
9467 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9468 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9469
9470 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9471 LSI->Mutable = !CallOperator->isConst();
9472
Faisal Valic00e4192013-11-07 05:17:06 +00009473 // Add the captures to the LSI so they can be noted as already
9474 // captured within tryCaptureVar.
9475 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9476 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9477 if (C->capturesVariable()) {
9478 VarDecl *VD = C->getCapturedVar();
9479 if (VD->isInitCapture())
9480 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9481 QualType CaptureType = VD->getType();
9482 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9483 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9484 /*RefersToEnclosingLocal*/true, C->getLocation(),
9485 /*EllipsisLoc*/C->isPackExpansion()
9486 ? C->getEllipsisLoc() : SourceLocation(),
9487 CaptureType, /*Expr*/ 0);
9488
9489 } else if (C->capturesThis()) {
9490 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9491 S.getCurrentThisType(), /*Expr*/ 0);
9492 }
9493 }
Faisal Valibef582b2013-10-23 16:10:50 +00009494}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009495
John McCalld226f652010-08-21 09:40:31 +00009496Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009497 // Clear the last template instantiation error context.
9498 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9499
Douglas Gregor52591bf2009-06-24 00:54:41 +00009500 if (!D)
9501 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009502 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009503
John McCalld226f652010-08-21 09:40:31 +00009504 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009505 FD = FunTmpl->getTemplatedDecl();
9506 else
John McCalld226f652010-08-21 09:40:31 +00009507 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009508 // If we are instantiating a generic lambda call operator, push
9509 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009510 // that's already been calculated (ActOnLambdaExpr) to prime the current
9511 // LambdaScopeInfo.
9512 // When the template operator is being specialized, the LambdaScopeInfo,
9513 // has to be properly restored so that tryCaptureVariable doesn't try
9514 // and capture any new variables. In addition when calculating potential
9515 // captures during transformation of nested lambdas, it is necessary to
9516 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009517 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009518 assert(ActiveTemplateInstantiations.size() &&
9519 "There should be an active template instantiation on the stack "
9520 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009521 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009522 }
9523 else
9524 // Enter a new function scope
9525 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009526
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009527 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009528 if (!FD->isLateTemplateParsed())
9529 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009530
Douglas Gregorcda9c672009-02-16 17:45:42 +00009531 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009532 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009533 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9534 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009535 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009536 FD->setInvalidDecl();
9537 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009538 }
9539
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009540 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009541 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9542 QualType ResultType = FD->getResultType();
9543 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009544 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009545 RequireCompleteType(FD->getLocation(), ResultType,
9546 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009547 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009548
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009549 // GNU warning -Wmissing-prototypes:
9550 // Warn if a global function is defined without a previous
9551 // prototype declaration. This warning is issued even if the
9552 // definition itself provides a prototype. The aim is to detect
9553 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009554 const FunctionDecl *PossibleZeroParamPrototype = 0;
9555 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009556 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009557
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009558 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009559 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009560 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009561 if (TypeSourceInfo *TI =
9562 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9563 TypeLoc TL = TI->getTypeLoc();
9564 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9565 Diag(PossibleZeroParamPrototype->getLocation(),
9566 diag::note_declaration_not_a_prototype)
9567 << PossibleZeroParamPrototype
9568 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9569 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009570 }
9571 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009572
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009573 if (FnBodyScope)
9574 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009575
Chris Lattner04421082008-04-08 04:40:51 +00009576 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009577 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9578 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009579
9580 // Introduce our parameters into the function scope
9581 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9582 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009583 Param->setOwningFunction(FD);
9584
Chris Lattner04421082008-04-08 04:40:51 +00009585 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009586 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009587 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009588
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009589 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009590 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009591 }
Chris Lattner04421082008-04-08 04:40:51 +00009592
James Molloy16f1f712012-02-29 10:24:19 +00009593 // If we had any tags defined in the function prototype,
9594 // introduce them into the function scope.
9595 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009596 for (ArrayRef<NamedDecl *>::iterator
9597 I = FD->getDeclsInPrototypeScope().begin(),
9598 E = FD->getDeclsInPrototypeScope().end();
9599 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009600 NamedDecl *D = *I;
9601
9602 // Some of these decls (like enums) may have been pinned to the translation unit
9603 // for lack of a real context earlier. If so, remove from the translation unit
9604 // and reattach to the current context.
9605 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9606 // Is the decl actually in the context?
9607 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9608 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9609 if (*DI == D) {
9610 Context.getTranslationUnitDecl()->removeDecl(D);
9611 break;
9612 }
9613 }
9614 // Either way, reassign the lexical decl context to our FunctionDecl.
9615 D->setLexicalDeclContext(CurContext);
9616 }
9617
9618 // If the decl has a non-null name, make accessible in the current scope.
9619 if (!D->getName().empty())
9620 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9621
9622 // Similarly, dive into enums and fish their constants out, making them
9623 // accessible in this scope.
9624 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9625 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9626 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009627 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009628 }
9629 }
9630 }
9631
Richard Smith87162c22012-04-17 22:30:01 +00009632 // Ensure that the function's exception specification is instantiated.
9633 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9634 ResolveExceptionSpec(D->getLocation(), FPT);
9635
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009636 // Checking attributes of current function definition
9637 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009638 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9639 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9640 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009641 // Microsoft accepts dllimport for functions defined within class scope.
9642 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009643 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009644 Diag(FD->getLocation(),
9645 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9646 << "dllimport";
9647 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009648 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009649 }
9650
9651 // Visual C++ appears to not think this is an issue, so only issue
9652 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009653 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009654 // If a symbol previously declared dllimport is later defined, the
9655 // attribute is ignored in subsequent references, and a warning is
9656 // emitted.
9657 Diag(FD->getLocation(),
9658 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009659 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009660 }
9661 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009662 // We want to attach documentation to original Decl (which might be
9663 // a function template).
9664 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009665 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009666}
9667
Douglas Gregor5077c382010-05-15 06:01:05 +00009668/// \brief Given the set of return statements within a function body,
9669/// compute the variables that are subject to the named return value
9670/// optimization.
9671///
9672/// Each of the variables that is subject to the named return value
9673/// optimization will be marked as NRVO variables in the AST, and any
9674/// return statement that has a marked NRVO variable as its NRVO candidate can
9675/// use the named return value optimization.
9676///
9677/// This function applies a very simplistic algorithm for NRVO: if every return
9678/// statement in the function has the same NRVO candidate, that candidate is
9679/// the NRVO variable.
9680///
9681/// FIXME: Employ a smarter algorithm that accounts for multiple return
9682/// statements and the lifetimes of the NRVO candidates. We should be able to
9683/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009684void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009685 ReturnStmt **Returns = Scope->Returns.data();
9686
Douglas Gregor5077c382010-05-15 06:01:05 +00009687 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009688 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009689 if (!Returns[I]->getNRVOCandidate())
9690 return;
9691
9692 if (!NRVOCandidate)
9693 NRVOCandidate = Returns[I]->getNRVOCandidate();
9694 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9695 return;
9696 }
9697
9698 if (NRVOCandidate)
9699 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9700}
9701
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009702bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009703 if (!Consumer.shouldSkipFunctionBody(D))
9704 return false;
9705
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009706 if (isa<ObjCMethodDecl>(D))
9707 return true;
9708
9709 FunctionDecl *FD = 0;
9710 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9711 FD = FTD->getTemplatedDecl();
9712 else
9713 FD = cast<FunctionDecl>(D);
9714
9715 // We cannot skip the body of a function (or function template) which is
9716 // constexpr, since we may need to evaluate its body in order to parse the
9717 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009718 // We cannot skip the body of a function with an undeduced return type,
9719 // because any callers of that function need to know the type.
9720 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009721}
9722
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009723Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009724 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009725 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009726 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009727 MD->setHasSkippedBody();
9728 return ActOnFinishFunctionBody(Decl, 0);
9729}
9730
John McCallf312b1e2010-08-26 23:41:50 +00009731Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009732 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009733}
9734
John McCall9ae2f072010-08-23 23:25:46 +00009735Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9736 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009737 FunctionDecl *FD = 0;
9738 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9739 if (FunTmpl)
9740 FD = FunTmpl->getTemplatedDecl();
9741 else
9742 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9743
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009744 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009745 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009746
Douglas Gregord83d0402009-08-22 00:34:47 +00009747 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009748 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009749
Richard Smith25d8c852013-05-10 04:31:10 +00009750 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9751 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9752 // If the function has a deduced result type but contains no 'return'
9753 // statements, the result type as written must be exactly 'auto', and
9754 // the deduced result type is 'void'.
9755 if (!FD->getResultType()->getAs<AutoType>()) {
9756 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9757 << FD->getResultType();
9758 FD->setInvalidDecl();
9759 } else {
9760 // Substitute 'void' for the 'auto' in the type.
9761 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9762 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9763 Context.adjustDeducedFunctionResultType(
9764 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009765 }
9766 }
9767
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009768 // The only way to be included in UndefinedButUsed is if there is an
9769 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009770 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009771 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009772 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009773 UndefinedButUsed.erase(FD);
9774 else if (FD->isInlined() &&
9775 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9776 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9777 UndefinedButUsed.erase(FD);
9778 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009779
John McCall75d8ba32012-02-14 19:50:52 +00009780 // If the function implicitly returns zero (like 'main') or is naked,
9781 // don't complain about missing return statements.
9782 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009783 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009784
Francois Pichet6a247472011-05-11 02:14:46 +00009785 // MSVC permits the use of pure specifier (=0) on function definition,
9786 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009787 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009788 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9789
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009790 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009791 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009792 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9793 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009794
9795 // If this is a constructor, we need a vtable.
9796 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9797 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009798
Jordan Rose7dd900e2012-07-02 21:19:23 +00009799 // Try to apply the named return value optimization. We have to check
9800 // if we can do this here because lambdas keep return statements around
9801 // to deduce an implicit return type.
9802 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9803 !FD->isDependentContext())
9804 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009805 }
9806
Douglas Gregor76e3da52012-02-08 20:17:14 +00009807 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9808 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009809 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009810 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009811 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009812 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009813 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009814 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9815 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009816
9817 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009818 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009819 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009820 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009821 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9822 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009823 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009824 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009825 } else {
John McCalld226f652010-08-21 09:40:31 +00009826 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009827 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009828
Jordan Rose535a5d02012-10-19 16:05:26 +00009829 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009830 "This should only be set for ObjC methods, which should have been "
9831 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009832
Reid Spencer5f016e22007-07-11 17:01:13 +00009833 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009834 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009835 // C++ constructors that have function-try-blocks can't have return
9836 // statements in the handlers of that block. (C++ [except.handle]p14)
9837 // Verify this.
9838 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9839 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9840
Richard Smith37bee672011-08-12 18:44:32 +00009841 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009842 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009843 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009844 !hasAnyUnrecoverableErrorsInThisFunction() &&
9845 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009846 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009847
John McCall15442822010-08-04 01:04:25 +00009848 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9849 if (!Destructor->getParent()->isDependentType())
9850 CheckDestructor(Destructor);
9851
John McCallef027fe2010-03-16 21:39:52 +00009852 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9853 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009854 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009855
9856 // If any errors have occurred, clear out any temporaries that may have
9857 // been leftover. This ensures that these temporaries won't be picked up for
9858 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009859 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009860 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009861 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009862 }
9863 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9864 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009865 // Since the body is valid, issue any analysis-based warnings that are
9866 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009867 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009868 }
9869
Richard Smith86c3ae42012-02-13 03:54:03 +00009870 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9871 (!CheckConstexprFunctionDecl(FD) ||
9872 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009873 FD->setInvalidDecl();
9874
John McCall80ee6e82011-11-10 05:35:25 +00009875 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009876 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009877 assert(MaybeODRUseExprs.empty() &&
9878 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009879 }
9880
John McCall90f97892010-03-25 22:08:03 +00009881 if (!IsInstantiation)
9882 PopDeclContext();
9883
Eli Friedmanec9ea722012-01-05 03:35:19 +00009884 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009885 // If any errors have occurred, clear out any temporaries that may have
9886 // been leftover. This ensures that these temporaries won't be picked up for
9887 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009888 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009889 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009890 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009891
John McCalld226f652010-08-21 09:40:31 +00009892 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009893}
9894
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009895
9896/// When we finish delayed parsing of an attribute, we must attach it to the
9897/// relevant Decl.
9898void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9899 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009900 // Always attach attributes to the underlying decl.
9901 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9902 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009903 ProcessDeclAttributeList(S, D, Attrs.getList());
9904
9905 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9906 if (Method->isStatic())
9907 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009908}
9909
9910
Reid Spencer5f016e22007-07-11 17:01:13 +00009911/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9912/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009913NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009914 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009915 // Before we produce a declaration for an implicitly defined
9916 // function, see whether there was a locally-scoped declaration of
9917 // this name as a function or variable. If so, use that
9918 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009919 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9920 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9921 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9922 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009923 }
9924
Chris Lattner37d10842008-05-05 21:18:06 +00009925 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009926 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009927 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009928 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009929 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009930 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009931 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009932 diag_id = diag::warn_implicit_function_decl;
9933 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009934
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009935 // Because typo correction is expensive, only do it if the implicit
9936 // function declaration is going to be treated as an error.
9937 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9938 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009939 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009940 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009941 LookupOrdinaryName, S, 0, Validator)))
9942 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9943 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009944 }
9945
Reid Spencer5f016e22007-07-11 17:01:13 +00009946 // Set a Declarator for the implicit definition: int foo();
9947 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009948 AttributeFactory attrFactory;
9949 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009950 unsigned DiagID;
9951 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009952 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009953 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009954 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009955 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009956 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9957 /*IsAmbiguous=*/false,
9958 /*RParenLoc=*/NoLoc,
9959 /*ArgInfo=*/0,
9960 /*NumArgs=*/0,
9961 /*EllipsisLoc=*/NoLoc,
9962 /*RParenLoc=*/NoLoc,
9963 /*TypeQuals=*/0,
9964 /*RefQualifierIsLvalueRef=*/true,
9965 /*RefQualifierLoc=*/NoLoc,
9966 /*ConstQualifierLoc=*/NoLoc,
9967 /*VolatileQualifierLoc=*/NoLoc,
9968 /*MutableLoc=*/NoLoc,
9969 EST_None,
9970 /*ESpecLoc=*/NoLoc,
9971 /*Exceptions=*/0,
9972 /*ExceptionRanges=*/0,
9973 /*NumExceptions=*/0,
9974 /*NoexceptExpr=*/0,
9975 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009976 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009977 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009978 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009979
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009980 // Insert this function into translation-unit scope.
9981
9982 DeclContext *PrevDC = CurContext;
9983 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009984
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009985 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009986 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009987
9988 CurContext = PrevDC;
9989
Douglas Gregor3c385e52009-02-14 18:57:46 +00009990 AddKnownFunctionAttributes(FD);
9991
Steve Naroffe2ef8152008-04-04 14:32:09 +00009992 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009993}
9994
Douglas Gregor3c385e52009-02-14 18:57:46 +00009995/// \brief Adds any function attributes that we know a priori based on
9996/// the declaration of this function.
9997///
9998/// These attributes can apply both to implicitly-declared builtins
9999/// (like __builtin___printf_chk) or to library-declared functions
10000/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010001///
10002/// We need to check for duplicate attributes both here and where user-written
10003/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +000010004void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10005 if (FD->isInvalidDecl())
10006 return;
10007
10008 // If this is a built-in function, map its builtin attributes to
10009 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +000010010 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +000010011 // Handle printf-formatting attributes.
10012 unsigned FormatIdx;
10013 bool HasVAListArg;
10014 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010015 if (!FD->getAttr<FormatAttr>()) {
10016 const char *fmt = "printf";
10017 unsigned int NumParams = FD->getNumParams();
10018 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10019 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10020 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +000010021 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010022 &Context.Idents.get(fmt),
10023 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +000010024 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010025 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010026 }
Ted Kremenekbee05c12010-07-16 02:11:15 +000010027 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10028 HasVAListArg)) {
10029 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010030 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010031 &Context.Idents.get("scanf"),
10032 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +000010033 HasVAListArg ? 0 : FormatIdx+2));
10034 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010035
10036 // Mark const if we don't care about errno and that is the only
10037 // thing preventing the function from being const. This allows
10038 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +000010039 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010040 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010041 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010042 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010043 }
Mike Stump0feecbb2009-07-27 19:14:18 +000010044
Rafael Espindola67004152011-10-12 19:51:18 +000010045 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10046 !FD->getAttr<ReturnsTwiceAttr>())
10047 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010048 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010049 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010050 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010051 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +000010052 }
10053
10054 IdentifierInfo *Name = FD->getIdentifier();
10055 if (!Name)
10056 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010057 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010058 FD->getDeclContext()->isTranslationUnit()) ||
10059 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010060 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010061 LinkageSpecDecl::lang_c)) {
10062 // Okay: this could be a libc/libm/Objective-C function we know
10063 // about.
10064 } else
10065 return;
10066
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010067 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010068 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010069 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010070 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010071 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010072 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010073 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010074 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010075
10076 if (Name->isStr("__CFStringMakeConstantString")) {
10077 // We already have a __builtin___CFStringMakeConstantString,
10078 // but builds that use -fno-constant-cfstrings don't go through that.
10079 if (!FD->getAttr<FormatArgAttr>())
10080 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10081 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010082}
Reid Spencer5f016e22007-07-11 17:01:13 +000010083
John McCallba6a9bd2009-10-24 08:00:42 +000010084TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010085 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010086 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010087 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010088
John McCalla93c9342009-12-07 02:54:59 +000010089 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010090 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010091 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010092 }
10093
Reid Spencer5f016e22007-07-11 17:01:13 +000010094 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010095 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010096 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010097 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010098 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010099 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010100
John McCallcde5a402011-02-01 08:20:08 +000010101 // Bail out immediately if we have an invalid declaration.
10102 if (D.isInvalidType()) {
10103 NewTD->setInvalidDecl();
10104 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010105 }
Fariborz Jahanian0f3bb9e2013-11-19 00:09:48 +000010106
Douglas Gregore3895852011-09-12 18:37:38 +000010107 if (D.getDeclSpec().isModulePrivateSpecified()) {
10108 if (CurContext->isFunctionOrMethod())
10109 Diag(NewTD->getLocation(), diag::err_module_private_local)
10110 << 2 << NewTD->getDeclName()
10111 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10112 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10113 else
10114 NewTD->setModulePrivate();
10115 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010116
John McCallcde5a402011-02-01 08:20:08 +000010117 // C++ [dcl.typedef]p8:
10118 // If the typedef declaration defines an unnamed class (or
10119 // enum), the first typedef-name declared by the declaration
10120 // to be that class type (or enum type) is used to denote the
10121 // class type (or enum type) for linkage purposes only.
10122 // We need to check whether the type was declared in the declaration.
10123 switch (D.getDeclSpec().getTypeSpecType()) {
10124 case TST_enum:
10125 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010126 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010127 case TST_union:
10128 case TST_class: {
10129 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10130
10131 // Do nothing if the tag is not anonymous or already has an
10132 // associated typedef (from an earlier typedef in this decl group).
10133 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010134 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010135
10136 // A well-formed anonymous tag must always be a TUK_Definition.
10137 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10138
10139 // The type must match the tag exactly; no qualifiers allowed.
10140 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10141 break;
10142
10143 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010144 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010145 break;
10146 }
10147
10148 default:
10149 break;
10150 }
10151
Steve Naroff5912a352007-08-28 20:14:24 +000010152 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010153}
10154
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010155
Richard Smithf1c66b42012-03-14 23:13:10 +000010156/// \brief Check that this is a valid underlying type for an enum declaration.
10157bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10158 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10159 QualType T = TI->getType();
10160
Eli Friedman2fcff832012-12-18 02:37:32 +000010161 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010162 return false;
10163
Eli Friedman2fcff832012-12-18 02:37:32 +000010164 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10165 if (BT->isInteger())
10166 return false;
10167
Richard Smithf1c66b42012-03-14 23:13:10 +000010168 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10169 return true;
10170}
10171
10172/// Check whether this is a valid redeclaration of a previous enumeration.
10173/// \return true if the redeclaration was invalid.
10174bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10175 QualType EnumUnderlyingTy,
10176 const EnumDecl *Prev) {
10177 bool IsFixed = !EnumUnderlyingTy.isNull();
10178
10179 if (IsScoped != Prev->isScoped()) {
10180 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10181 << Prev->isScoped();
10182 Diag(Prev->getLocation(), diag::note_previous_use);
10183 return true;
10184 }
10185
10186 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010187 if (!EnumUnderlyingTy->isDependentType() &&
10188 !Prev->getIntegerType()->isDependentType() &&
10189 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010190 Prev->getIntegerType())) {
10191 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10192 << EnumUnderlyingTy << Prev->getIntegerType();
10193 Diag(Prev->getLocation(), diag::note_previous_use);
10194 return true;
10195 }
10196 } else if (IsFixed != Prev->isFixed()) {
10197 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10198 << Prev->isFixed();
10199 Diag(Prev->getLocation(), diag::note_previous_use);
10200 return true;
10201 }
10202
10203 return false;
10204}
10205
Joao Matos6666ed42012-08-31 18:45:21 +000010206/// \brief Get diagnostic %select index for tag kind for
10207/// redeclaration diagnostic message.
10208/// WARNING: Indexes apply to particular diagnostics only!
10209///
10210/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010211static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010212 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010213 case TTK_Struct: return 0;
10214 case TTK_Interface: return 1;
10215 case TTK_Class: return 2;
10216 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010217 }
Joao Matos6666ed42012-08-31 18:45:21 +000010218}
10219
10220/// \brief Determine if tag kind is a class-key compatible with
10221/// class for redeclaration (class, struct, or __interface).
10222///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010223/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010224static bool isClassCompatTagKind(TagTypeKind Tag)
10225{
10226 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10227}
10228
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010229/// \brief Determine whether a tag with a given kind is acceptable
10230/// as a redeclaration of the given tag declaration.
10231///
10232/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010233bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010234 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010235 SourceLocation NewTagLoc,
10236 const IdentifierInfo &Name) {
10237 // C++ [dcl.type.elab]p3:
10238 // The class-key or enum keyword present in the
10239 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010240 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010241 // refers. This rule also applies to the form of
10242 // elaborated-type-specifier that declares a class-name or
10243 // friend class since it can be construed as referring to the
10244 // definition of the class. Thus, in any
10245 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010246 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010247 // used to refer to a union (clause 9), and either the class or
10248 // struct class-key shall be used to refer to a class (clause 9)
10249 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010250 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010251 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010252 if (OldTag == NewTag)
10253 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010254
Joao Matos6666ed42012-08-31 18:45:21 +000010255 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010256 // Warn about the struct/class tag mismatch.
10257 bool isTemplate = false;
10258 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10259 isTemplate = Record->getDescribedClassTemplate();
10260
Richard Trieubbf34c02011-06-10 03:11:26 +000010261 if (!ActiveTemplateInstantiations.empty()) {
10262 // In a template instantiation, do not offer fix-its for tag mismatches
10263 // since they usually mess up the template instead of fixing the problem.
10264 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010265 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10266 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010267 return true;
10268 }
10269
10270 if (isDefinition) {
10271 // On definitions, check previous tags and issue a fix-it for each
10272 // one that doesn't match the current tag.
10273 if (Previous->getDefinition()) {
10274 // Don't suggest fix-its for redefinitions.
10275 return true;
10276 }
10277
10278 bool previousMismatch = false;
10279 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10280 E(Previous->redecls_end()); I != E; ++I) {
10281 if (I->getTagKind() != NewTag) {
10282 if (!previousMismatch) {
10283 previousMismatch = true;
10284 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010285 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10286 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010287 }
10288 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010289 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010290 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010291 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010292 }
10293 }
10294 return true;
10295 }
10296
10297 // Check for a previous definition. If current tag and definition
10298 // are same type, do nothing. If no definition, but disagree with
10299 // with previous tag type, give a warning, but no fix-it.
10300 const TagDecl *Redecl = Previous->getDefinition() ?
10301 Previous->getDefinition() : Previous;
10302 if (Redecl->getTagKind() == NewTag) {
10303 return true;
10304 }
10305
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010306 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010307 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10308 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010309 Diag(Redecl->getLocation(), diag::note_previous_use);
10310
10311 // If there is a previous defintion, suggest a fix-it.
10312 if (Previous->getDefinition()) {
10313 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010314 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010315 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010316 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010317 }
10318
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010319 return true;
10320 }
10321 return false;
10322}
10323
Steve Naroff08d92e42007-09-15 18:49:24 +000010324/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010325/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010326/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010327/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010328Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010329 SourceLocation KWLoc, CXXScopeSpec &SS,
10330 IdentifierInfo *Name, SourceLocation NameLoc,
10331 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010332 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010333 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010334 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010335 SourceLocation ScopedEnumKWLoc,
10336 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010337 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010338 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010339 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010340 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010341 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010342 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010343
Douglas Gregor402abb52009-05-28 23:31:59 +000010344 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010345 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010346 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010347
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010348 // FIXME: Check explicit specializations more carefully.
10349 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010350 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010351
10352 // We only need to do this matching if we have template parameters
10353 // or a scope specifier, which also conveniently avoids this work
10354 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010355 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010356 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010357 if (TemplateParameterList *TemplateParams =
10358 MatchTemplateParametersToScopeSpecifier(
10359 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10360 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010361 if (Kind == TTK_Enum) {
10362 Diag(KWLoc, diag::err_enum_template);
10363 return 0;
10364 }
10365
Douglas Gregord85bea22009-09-26 06:47:28 +000010366 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010367 // This is a declaration or definition of a class template (which may
10368 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010369
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010370 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010371 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010372
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010373 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010374 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010375 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010376 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010377 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010378 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010379 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010380 return Result.get();
10381 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010382 // The "template<>" header is extraneous.
10383 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010384 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010385 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010386 }
Mike Stump1eb44332009-09-09 15:08:12 +000010387 }
10388 }
10389
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010390 // Figure out the underlying type if this a enum declaration. We need to do
10391 // this early, because it's needed to detect if this is an incompatible
10392 // redeclaration.
10393 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10394
10395 if (Kind == TTK_Enum) {
10396 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10397 // No underlying type explicitly specified, or we failed to parse the
10398 // type, default to int.
10399 EnumUnderlying = Context.IntTy.getTypePtr();
10400 else if (UnderlyingType.get()) {
10401 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10402 // integral type; any cv-qualification is ignored.
10403 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010404 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010405 EnumUnderlying = TI;
10406
Richard Smithf1c66b42012-03-14 23:13:10 +000010407 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010408 // Recover by falling back to int.
10409 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010410
Richard Smithf1c66b42012-03-14 23:13:10 +000010411 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010412 UPPC_FixedUnderlyingType))
10413 EnumUnderlying = Context.IntTy.getTypePtr();
10414
David Blaikie4e4d0842012-03-11 07:00:24 +000010415 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010416 // Microsoft enums are always of int type.
10417 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010418 }
10419
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010420 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010421 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010422 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010423
Chandler Carruth7bf36002010-03-01 21:17:36 +000010424 RedeclarationKind Redecl = ForRedeclaration;
10425 if (TUK == TUK_Friend || TUK == TUK_Reference)
10426 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010427
10428 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010429 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010430 if (Name && SS.isNotEmpty()) {
10431 // We have a nested-name tag ('struct foo::bar').
10432
10433 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010434 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010435 Name = 0;
10436 goto CreateNewDecl;
10437 }
10438
John McCallc4e70192009-09-11 04:59:25 +000010439 // If this is a friend or a reference to a class in a dependent
10440 // context, don't try to make a decl for it.
10441 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10442 DC = computeDeclContext(SS, false);
10443 if (!DC) {
10444 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010445 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010446 }
John McCall77bb1aa2010-05-01 00:40:08 +000010447 } else {
10448 DC = computeDeclContext(SS, true);
10449 if (!DC) {
10450 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10451 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010452 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010453 }
John McCallc4e70192009-09-11 04:59:25 +000010454 }
10455
John McCall77bb1aa2010-05-01 00:40:08 +000010456 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010457 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010458
Douglas Gregor1931b442009-02-03 00:34:39 +000010459 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010460 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010461 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010462
John McCall68263142009-11-18 22:49:29 +000010463 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010464 return 0;
John McCall6e247262009-10-10 05:48:19 +000010465
John McCall68263142009-11-18 22:49:29 +000010466 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010467 // Name lookup did not find anything. However, if the
10468 // nested-name-specifier refers to the current instantiation,
10469 // and that current instantiation has any dependent base
10470 // classes, we might find something at instantiation time: treat
10471 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010472 // But this only makes any sense for reference-like lookups.
10473 if (Previous.wasNotFoundInCurrentInstantiation() &&
10474 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010475 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010476 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010477 }
10478
10479 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010480 Diag(NameLoc, diag::err_not_tag_in_scope)
10481 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010482 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010483 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010484 goto CreateNewDecl;
10485 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010486 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010487 // If this is a named struct, check to see if there was a previous forward
10488 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010489 // FIXME: We're looking into outer scopes here, even when we
10490 // shouldn't be. Doing so can result in ambiguities that we
10491 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010492 LookupName(Previous, S);
10493
John McCallc96cd7a2013-03-20 01:53:00 +000010494 // When declaring or defining a tag, ignore ambiguities introduced
10495 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010496 if (Previous.isAmbiguous() &&
10497 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010498 LookupResult::Filter F = Previous.makeFilter();
10499 while (F.hasNext()) {
10500 NamedDecl *ND = F.next();
10501 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10502 F.erase();
10503 }
10504 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010505 }
John McCallc96cd7a2013-03-20 01:53:00 +000010506
10507 // C++11 [namespace.memdef]p3:
10508 // If the name in a friend declaration is neither qualified nor
10509 // a template-id and the declaration is a function or an
10510 // elaborated-type-specifier, the lookup to determine whether
10511 // the entity has been previously declared shall not consider
10512 // any scopes outside the innermost enclosing namespace.
10513 //
10514 // Does it matter that this should be by scope instead of by
10515 // semantic context?
10516 if (!Previous.empty() && TUK == TUK_Friend) {
10517 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10518 LookupResult::Filter F = Previous.makeFilter();
10519 while (F.hasNext()) {
10520 NamedDecl *ND = F.next();
10521 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010522 if (DC->isFileContext() &&
10523 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010524 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010525 FriendSawTagOutsideEnclosingNamespace = true;
10526 }
John McCallc96cd7a2013-03-20 01:53:00 +000010527 }
10528 F.done();
10529 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010530
John McCall68263142009-11-18 22:49:29 +000010531 // Note: there used to be some attempt at recovery here.
10532 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010533 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010534
David Blaikie4e4d0842012-03-11 07:00:24 +000010535 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010536 // FIXME: This makes sure that we ignore the contexts associated
10537 // with C structs, unions, and enums when looking for a matching
10538 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010539 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010540 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10541 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010542 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010543 } else if (S->isFunctionPrototypeScope()) {
10544 // If this is an enum declaration in function prototype scope, set its
10545 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010546 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010547 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010548 }
10549
John McCall68263142009-11-18 22:49:29 +000010550 if (Previous.isSingleResult() &&
10551 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010552 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010553 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010554 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010555 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010556 }
10557
David Blaikie4e4d0842012-03-11 07:00:24 +000010558 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010559 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010560 // This is a declaration of or a reference to "std::bad_alloc".
10561 isStdBadAlloc = true;
10562
John McCall68263142009-11-18 22:49:29 +000010563 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010564 // std::bad_alloc has been implicitly declared (but made invisible to
10565 // name lookup). Fill in this implicit declaration as the previous
10566 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010567 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010568 }
10569 }
John McCall68263142009-11-18 22:49:29 +000010570
John McCall9c86b512010-03-25 21:28:06 +000010571 // If we didn't find a previous declaration, and this is a reference
10572 // (or friend reference), move to the correct scope. In C++, we
10573 // also need to do a redeclaration lookup there, just in case
10574 // there's a shadow friend decl.
10575 if (Name && Previous.empty() &&
10576 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10577 if (Invalid) goto CreateNewDecl;
10578 assert(SS.isEmpty());
10579
10580 if (TUK == TUK_Reference) {
10581 // C++ [basic.scope.pdecl]p5:
10582 // -- for an elaborated-type-specifier of the form
10583 //
10584 // class-key identifier
10585 //
10586 // if the elaborated-type-specifier is used in the
10587 // decl-specifier-seq or parameter-declaration-clause of a
10588 // function defined in namespace scope, the identifier is
10589 // declared as a class-name in the namespace that contains
10590 // the declaration; otherwise, except as a friend
10591 // declaration, the identifier is declared in the smallest
10592 // non-class, non-function-prototype scope that contains the
10593 // declaration.
10594 //
10595 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10596 // C structs and unions.
10597 //
10598 // It is an error in C++ to declare (rather than define) an enum
10599 // type, including via an elaborated type specifier. We'll
10600 // diagnose that later; for now, declare the enum in the same
10601 // scope as we would have picked for any other tag type.
10602 //
10603 // GNU C also supports this behavior as part of its incomplete
10604 // enum types extension, while GNU C++ does not.
10605 //
10606 // Find the context where we'll be declaring the tag.
10607 // FIXME: We would like to maintain the current DeclContext as the
10608 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010609 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010610 SearchDC = SearchDC->getParent();
10611
10612 // Find the scope where we'll be declaring the tag.
10613 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010614 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010615 S->isFunctionPrototypeScope()) ||
10616 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010617 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010618 S = S->getParent();
10619 } else {
10620 assert(TUK == TUK_Friend);
10621 // C++ [namespace.memdef]p3:
10622 // If a friend declaration in a non-local class first declares a
10623 // class or function, the friend class or function is a member of
10624 // the innermost enclosing namespace.
10625 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010626 }
10627
John McCall0d6b1642010-04-23 18:46:30 +000010628 // In C++, we need to do a redeclaration lookup to properly
10629 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010630 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010631 Previous.setRedeclarationKind(ForRedeclaration);
10632 LookupQualifiedName(Previous, SearchDC);
10633 }
10634 }
10635
John McCall68263142009-11-18 22:49:29 +000010636 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010637 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010638
10639 // It's okay to have a tag decl in the same scope as a typedef
10640 // which hides a tag decl in the same scope. Finding this
10641 // insanity with a redeclaration lookup can only actually happen
10642 // in C++.
10643 //
10644 // This is also okay for elaborated-type-specifiers, which is
10645 // technically forbidden by the current standard but which is
10646 // okay according to the likely resolution of an open issue;
10647 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010648 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010649 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010650 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10651 TagDecl *Tag = TT->getDecl();
10652 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010653 Tag->getDeclContext()->getRedeclContext()
10654 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010655 PrevDecl = Tag;
10656 Previous.clear();
10657 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010658 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010659 }
10660 }
10661 }
10662 }
10663
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010664 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010665 // If this is a use of a previous tag, or if the tag is already declared
10666 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010667 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010668 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010669 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010670 // Make sure that this wasn't declared as an enum and now used as a
10671 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010672 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10673 TUK == TUK_Definition, KWLoc,
10674 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010675 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010676 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10677 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010678 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010679 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010680 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010681 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10682 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010683 else
10684 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010685 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010686
Mike Stump1eb44332009-09-09 15:08:12 +000010687 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010688 Kind = PrevTagDecl->getTagKind();
10689 else {
10690 // Recover by making this an anonymous redefinition.
10691 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010692 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010693 Invalid = true;
10694 }
10695 }
10696
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010697 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10698 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10699
Richard Smithbdad7a22012-01-10 01:33:14 +000010700 // If this is an elaborated-type-specifier for a scoped enumeration,
10701 // the 'class' keyword is not necessary and not permitted.
10702 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10703 if (ScopedEnum)
10704 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10705 << PrevEnum->isScoped()
10706 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10707 return PrevTagDecl;
10708 }
10709
Richard Smithf1c66b42012-03-14 23:13:10 +000010710 QualType EnumUnderlyingTy;
10711 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10712 EnumUnderlyingTy = TI->getType();
10713 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10714 EnumUnderlyingTy = QualType(T, 0);
10715
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010716 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010717 // returning the previous declaration, unless this is a definition,
10718 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010719 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10720 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010721 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010722 }
10723
David Majnemer2ec2b842013-06-11 03:51:23 +000010724 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010725 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010726 // except that a nested class or member class template can be declared
10727 // and then later defined.
10728 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10729 S->isDeclScope(PrevDecl)) {
10730 Diag(NameLoc, diag::ext_member_redeclared);
10731 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10732 }
10733
Douglas Gregora3a83512009-04-01 23:51:29 +000010734 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010735 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010736
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010737 // FIXME: In the future, return a variant or some other clue
10738 // for the consumer of this Decl to know it doesn't own it.
10739 // For our current ASTs this shouldn't be a problem, but will
10740 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010741 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010742 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010743 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010744
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010745 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010746 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010747 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010748 // If we're defining a specialization and the previous definition
10749 // is from an implicit instantiation, don't emit an error
10750 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010751 bool IsExplicitSpecializationAfterInstantiation = false;
10752 if (isExplicitSpecialization) {
10753 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10754 IsExplicitSpecializationAfterInstantiation =
10755 RD->getTemplateSpecializationKind() !=
10756 TSK_ExplicitSpecialization;
10757 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10758 IsExplicitSpecializationAfterInstantiation =
10759 ED->getTemplateSpecializationKind() !=
10760 TSK_ExplicitSpecialization;
10761 }
10762
10763 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010764 // A redeclaration in function prototype scope in C isn't
10765 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010766 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010767 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10768 else
10769 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010770 Diag(Def->getLocation(), diag::note_previous_definition);
10771 // If this is a redefinition, recover by making this
10772 // struct be anonymous, which will make any later
10773 // references get the previous definition.
10774 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010775 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010776 Invalid = true;
10777 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010778 } else {
10779 // If the type is currently being defined, complain
10780 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010781 const TagType *Tag
10782 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010783 if (Tag->isBeingDefined()) {
10784 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010785 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010786 diag::note_previous_definition);
10787 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010788 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010789 Invalid = true;
10790 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010791 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010792
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010793 // Okay, this is definition of a previously declared or referenced
10794 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010795 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010796 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010797 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010798 // have a definition. Just create a new decl.
10799
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010800 } else {
10801 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010802 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010803 // new decl/type. We set PrevDecl to NULL so that the entities
10804 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010805 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010806 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010807 // If we get here, we're going to create a new Decl. If PrevDecl
10808 // is non-NULL, it's a definition of the tag declared by
10809 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010810
10811
10812 // Otherwise, PrevDecl is not a tag, but was found with tag
10813 // lookup. This is only actually possible in C++, where a few
10814 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010815 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010816 // Use a better diagnostic if an elaborated-type-specifier
10817 // found the wrong kind of type on the first
10818 // (non-redeclaration) lookup.
10819 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10820 !Previous.isForRedeclaration()) {
10821 unsigned Kind = 0;
10822 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010823 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10824 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010825 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10826 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10827 Invalid = true;
10828
10829 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010830 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10831 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010832 // do nothing
10833
10834 // Diagnose implicit declarations introduced by elaborated types.
10835 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10836 unsigned Kind = 0;
10837 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010838 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10839 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010840 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10841 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10842 Invalid = true;
10843
10844 // Otherwise it's a declaration. Call out a particularly common
10845 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010846 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10847 unsigned Kind = 0;
10848 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010849 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010850 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010851 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10852 Invalid = true;
10853
10854 // Otherwise, diagnose.
10855 } else {
10856 // The tag name clashes with something else in the target scope,
10857 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010858 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010859 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010860 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010861 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010862 }
John McCall0d6b1642010-04-23 18:46:30 +000010863
10864 // The existing declaration isn't relevant to us; we're in a
10865 // new scope, so clear out the previous declaration.
10866 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010867 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010868 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010869
Chris Lattnercc98eac2008-12-17 07:13:27 +000010870CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010871
John McCall68263142009-11-18 22:49:29 +000010872 TagDecl *PrevDecl = 0;
10873 if (Previous.isSingleResult())
10874 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10875
Reid Spencer5f016e22007-07-11 17:01:13 +000010876 // If there is an identifier, use the location of the identifier as the
10877 // location of the decl, otherwise use the location of the struct/union
10878 // keyword.
10879 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010880
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010881 // Otherwise, create a new declaration. If there is a previous
10882 // declaration of the same entity, the two will be linked via
10883 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010884 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010885
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010886 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010887 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010888 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10889 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010890 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010891 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010892 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010893 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010894 if (TUK != TUK_Definition && !Invalid) {
10895 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010896 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10897 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010898 // C++0x: 7.2p2: opaque-enum-declaration.
10899 // Conflicts are diagnosed above. Do nothing.
10900 }
10901 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010902 Diag(Loc, diag::ext_forward_ref_enum_def)
10903 << New;
10904 Diag(Def->getLocation(), diag::note_previous_definition);
10905 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010906 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010907 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010908 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010909 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010910 DiagID = diag::err_forward_ref_enum;
10911 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010912
10913 // If this is a forward-declared reference to an enumeration, make a
10914 // note of it; we won't actually be introducing the declaration into
10915 // the declaration context.
10916 if (TUK == TUK_Reference)
10917 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010918 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010919 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010920
10921 if (EnumUnderlying) {
10922 EnumDecl *ED = cast<EnumDecl>(New);
10923 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10924 ED->setIntegerTypeSourceInfo(TI);
10925 else
10926 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10927 ED->setPromotionType(ED->getIntegerType());
10928 }
10929
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010930 } else {
10931 // struct/union/class
10932
Reid Spencer5f016e22007-07-11 17:01:13 +000010933 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10934 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010935 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010936 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010937 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010938 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010939
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010940 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010941 StdBadAlloc = cast<CXXRecordDecl>(New);
10942 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010943 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010944 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010945 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010946
John McCallb6217662010-03-15 10:12:16 +000010947 // Maybe add qualifier info.
10948 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010949 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010950 // If this is either a declaration or a definition, check the
10951 // nested-name-specifier against the current context. We don't do this
10952 // for explicit specializations, because they have similar checking
10953 // (with more specific diagnostics) in the call to
10954 // CheckMemberSpecialization, below.
10955 if (!isExplicitSpecialization &&
10956 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10957 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10958 Invalid = true;
10959
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010960 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010961 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010962 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010963 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010964 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010965 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010966 }
10967 else
10968 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010969 }
10970
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010971 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10972 // Add alignment attributes if necessary; these attributes are checked when
10973 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010974 //
10975 // It is important for implementing the correct semantics that this
10976 // happen here (in act on tag decl). The #pragma pack stack is
10977 // maintained as a result of parser callbacks which can occur at
10978 // many points during the parsing of a struct declaration (because
10979 // the #pragma tokens are effectively skipped over during the
10980 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010981 if (TUK == TUK_Definition) {
10982 AddAlignmentAttributesForRecord(RD);
10983 AddMsStructLayoutForRecord(RD);
10984 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010985 }
10986
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010987 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010988 if (isExplicitSpecialization)
10989 Diag(New->getLocation(), diag::err_module_private_specialization)
10990 << 2
10991 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010992 // __module_private__ does not apply to local classes. However, we only
10993 // diagnose this as an error when the declaration specifiers are
10994 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010995 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010996 New->setModulePrivate();
10997 }
10998
Douglas Gregorf6b11852009-10-08 15:14:33 +000010999 // If this is a specialization of a member class (of a class template),
11000 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000011001 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000011002 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000011003
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011004 if (Invalid)
11005 New->setInvalidDecl();
11006
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011007 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011008 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011009
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011010 // If we're declaring or defining a tag in function prototype scope
11011 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000011012 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000011013 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11014
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011015 // Set the lexical context. If the tag has a C++ scope specifier, the
11016 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000011017 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011018
John McCall02cace72009-08-28 07:59:38 +000011019 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000011020 // In Microsoft mode, a friend declaration also acts as a forward
11021 // declaration so we always pass true to setObjectOfFriendDecl to make
11022 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000011023 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000011024 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11025 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000011026
Anders Carlsson0cf88302009-03-26 01:19:02 +000011027 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000011028 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000011029 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000011030
John McCall0f434ec2009-07-31 02:45:11 +000011031 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011032 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000011033
Reid Spencer5f016e22007-07-11 17:01:13 +000011034 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000011035 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000011036 // We might be replacing an existing declaration in the lookup tables;
11037 // if so, borrow its access specifier.
11038 if (PrevDecl)
11039 New->setAccess(PrevDecl->getAccess());
11040
Sebastian Redl7a126a42010-08-31 00:36:30 +000011041 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011042 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000011043 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000011044 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11045 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000011046 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000011047 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011048 PushOnScopeChains(New, S, !IsForwardReference);
11049 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011050 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011051
Douglas Gregor4920f1f2009-01-12 22:49:06 +000011052 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011053 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000011054 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000011055
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011056 // If this is the C FILE type, notify the AST context.
11057 if (IdentifierInfo *II = New->getIdentifier())
11058 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011059 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011060 II->isStr("FILE"))
11061 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011062
James Molloy16f1f712012-02-29 10:24:19 +000011063 // If we were in function prototype scope (and not in C++ mode), add this
11064 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011065 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011066 InFunctionDeclarator && Name)
11067 DeclsInPrototypeScope.push_back(New);
11068
Rafael Espindola98ae8342012-05-10 02:50:16 +000011069 if (PrevDecl)
11070 mergeDeclAttributes(New, PrevDecl);
11071
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011072 // If there's a #pragma GCC visibility in scope, set the visibility of this
11073 // record.
11074 AddPushedVisibilityAttribute(New);
11075
Douglas Gregor402abb52009-05-28 23:31:59 +000011076 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011077 // In C++, don't return an invalid declaration. We can't recover well from
11078 // the cases where we make the type anonymous.
11079 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011080}
11081
John McCalld226f652010-08-21 09:40:31 +000011082void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011083 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011084 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011085
Douglas Gregor72de6672009-01-08 20:45:30 +000011086 // Enter the tag context.
11087 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011088
11089 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011090
11091 // If there's a #pragma GCC visibility in scope, set the visibility of this
11092 // record.
11093 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011094}
Douglas Gregor72de6672009-01-08 20:45:30 +000011095
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011096Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011097 assert(isa<ObjCContainerDecl>(IDecl) &&
11098 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11099 DeclContext *OCD = cast<DeclContext>(IDecl);
11100 assert(getContainingDC(OCD) == CurContext &&
11101 "The next DeclContext should be lexically contained in the current one.");
11102 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011103 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011104}
11105
John McCalld226f652010-08-21 09:40:31 +000011106void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011107 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011108 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011109 SourceLocation LBraceLoc) {
11110 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011111 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011112
John McCallf9368152009-12-20 07:58:13 +000011113 FieldCollector->StartClass();
11114
11115 if (!Record->getIdentifier())
11116 return;
11117
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011118 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011119 Record->addAttr(new (Context)
11120 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11121
John McCallf9368152009-12-20 07:58:13 +000011122 // C++ [class]p2:
11123 // [...] The class-name is also inserted into the scope of the
11124 // class itself; this is known as the injected-class-name. For
11125 // purposes of access checking, the injected-class-name is treated
11126 // as if it were a public member name.
11127 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011128 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11129 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011130 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011131 /*PrevDecl=*/0,
11132 /*DelayTypeCreation=*/true);
11133 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011134 InjectedClassName->setImplicit();
11135 InjectedClassName->setAccess(AS_public);
11136 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11137 InjectedClassName->setDescribedClassTemplate(Template);
11138 PushOnScopeChains(InjectedClassName, S);
11139 assert(InjectedClassName->isInjectedClassName() &&
11140 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011141}
11142
John McCalld226f652010-08-21 09:40:31 +000011143void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011144 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011145 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011146 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011147 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011148
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011149 // Make sure we "complete" the definition even it is invalid.
11150 if (Tag->isBeingDefined()) {
11151 assert(Tag->isInvalidDecl() && "We should already have completed it");
11152 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11153 RD->completeDefinition();
11154 }
11155
Douglas Gregor72de6672009-01-08 20:45:30 +000011156 if (isa<CXXRecordDecl>(Tag))
11157 FieldCollector->FinishClass();
11158
11159 // Exit this scope of this tag's definition.
11160 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011161
11162 if (getCurLexicalContext()->isObjCContainer() &&
11163 Tag->getDeclContext()->isFileContext())
11164 Tag->setTopLevelDeclInObjCContainer();
11165
Douglas Gregor72de6672009-01-08 20:45:30 +000011166 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011167 if (!Tag->isInvalidDecl())
11168 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011169}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011170
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011171void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011172 // Exit this scope of this interface definition.
11173 PopDeclContext();
11174}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011175
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011176void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011177 assert(DC == CurContext && "Mismatch of container contexts");
11178 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011179 ActOnObjCContainerFinishDefinition();
11180}
11181
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011182void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11183 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011184 OriginalLexicalContext = 0;
11185}
11186
John McCalld226f652010-08-21 09:40:31 +000011187void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011188 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011189 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011190 Tag->setInvalidDecl();
11191
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011192 // Make sure we "complete" the definition even it is invalid.
11193 if (Tag->isBeingDefined()) {
11194 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11195 RD->completeDefinition();
11196 }
11197
John McCalla8cab012010-03-17 19:25:57 +000011198 // We're undoing ActOnTagStartDefinition here, not
11199 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11200 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011201
11202 PopDeclContext();
11203}
11204
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011205// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011206ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11207 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011208 QualType FieldTy, bool IsMsStruct,
11209 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011210 // Default to true; that shouldn't confuse checks for emptiness
11211 if (ZeroWidth)
11212 *ZeroWidth = true;
11213
Chris Lattner24793662009-03-05 22:45:59 +000011214 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011215 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011216 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011217 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011218 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011219 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011220 if (FieldName)
11221 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11222 << FieldName << FieldTy << BitWidth->getSourceRange();
11223 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11224 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011225 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11226 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011227 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011228
11229 // If the bit-width is type- or value-dependent, don't try to check
11230 // it now.
11231 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011232 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011233
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011234 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011235 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11236 if (ICE.isInvalid())
11237 return ICE;
11238 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011239
Eli Friedman1d954f62009-08-15 21:55:26 +000011240 if (Value != 0 && ZeroWidth)
11241 *ZeroWidth = false;
11242
Chris Lattnercd087072008-12-12 04:56:04 +000011243 // Zero-width bitfield is ok for anonymous field.
11244 if (Value == 0 && FieldName)
11245 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011246
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011247 if (Value.isSigned() && Value.isNegative()) {
11248 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011249 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011250 << FieldName << Value.toString(10);
11251 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11252 << Value.toString(10);
11253 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011254
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011255 if (!FieldTy->isDependentType()) {
11256 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011257 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011258 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011259 if (FieldName)
11260 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11261 << FieldName << (unsigned)Value.getZExtValue()
11262 << (unsigned)TypeSize;
11263
11264 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11265 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11266 }
11267
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011268 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011269 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11270 << FieldName << (unsigned)Value.getZExtValue()
11271 << (unsigned)TypeSize;
11272 else
11273 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11274 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011275 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011276 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011277
Richard Smith282e7e62012-02-04 09:53:13 +000011278 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011279}
11280
Richard Smith7a614d82011-06-11 17:19:42 +000011281/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011282/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011283Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011284 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011285 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011286 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011287 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011288 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011289}
11290
11291/// HandleField - Analyze a field of a C struct or a C++ data member.
11292///
11293FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11294 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011295 Declarator &D, Expr *BitWidth,
11296 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011297 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011298 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011299 SourceLocation Loc = DeclStart;
11300 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011301
John McCallbf1a0282010-06-04 23:28:52 +000011302 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11303 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011304 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011305 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011306
Douglas Gregore1862692010-12-15 23:18:36 +000011307 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11308 UPPC_DataMemberType)) {
11309 D.setInvalidType();
11310 T = Context.IntTy;
11311 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11312 }
11313 }
11314
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011315 // TR 18037 does not allow fields to be declared with address spaces.
11316 if (T.getQualifiers().hasAddressSpace()) {
11317 Diag(Loc, diag::err_field_with_address_space);
11318 D.setInvalidType();
11319 }
11320
Guy Benyeie6b9d802013-01-20 12:31:11 +000011321 // OpenCL 1.2 spec, s6.9 r:
11322 // The event type cannot be used to declare a structure or union field.
11323 if (LangOpts.OpenCL && T->isEventT()) {
11324 Diag(Loc, diag::err_event_t_struct_field);
11325 D.setInvalidType();
11326 }
11327
Richard Smithc7f81162013-03-18 22:52:47 +000011328 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011329
Richard Smithec642442013-04-12 22:46:28 +000011330 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11331 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11332 diag::err_invalid_thread)
11333 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011334
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011335 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011336 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011337 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11338 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011339 switch (Previous.getResultKind()) {
11340 case LookupResult::Found:
11341 case LookupResult::FoundUnresolvedValue:
11342 PrevDecl = Previous.getAsSingle<NamedDecl>();
11343 break;
11344
11345 case LookupResult::FoundOverloaded:
11346 PrevDecl = Previous.getRepresentativeDecl();
11347 break;
11348
11349 case LookupResult::NotFound:
11350 case LookupResult::NotFoundInCurrentInstantiation:
11351 case LookupResult::Ambiguous:
11352 break;
11353 }
11354 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011355
11356 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11357 // Maybe we will complain about the shadowed template parameter.
11358 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11359 // Just pretend that we didn't see the previous declaration.
11360 PrevDecl = 0;
11361 }
11362
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011363 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11364 PrevDecl = 0;
11365
Steve Naroffea218b82009-07-14 14:58:18 +000011366 bool Mutable
11367 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011368 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011369 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011370 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011371 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011372
11373 if (NewFD->isInvalidDecl())
11374 Record->setInvalidDecl();
11375
Douglas Gregor591dc842011-09-12 16:11:24 +000011376 if (D.getDeclSpec().isModulePrivateSpecified())
11377 NewFD->setModulePrivate();
11378
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011379 if (NewFD->isInvalidDecl() && PrevDecl) {
11380 // Don't introduce NewFD into scope; there's already something
11381 // with the same name in the same scope.
11382 } else if (II) {
11383 PushOnScopeChains(NewFD, S);
11384 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011385 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011386
11387 return NewFD;
11388}
11389
11390/// \brief Build a new FieldDecl and check its well-formedness.
11391///
11392/// This routine builds a new FieldDecl given the fields name, type,
11393/// record, etc. \p PrevDecl should refer to any previous declaration
11394/// with the same name and in the same scope as the field to be
11395/// created.
11396///
11397/// \returns a new FieldDecl.
11398///
Mike Stump1eb44332009-09-09 15:08:12 +000011399/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011400FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011401 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011402 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011403 bool Mutable, Expr *BitWidth,
11404 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011405 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011406 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011407 Declarator *D) {
11408 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011409 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011410 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011411
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011412 // If we receive a broken type, recover by assuming 'int' and
11413 // marking this declaration as invalid.
11414 if (T.isNull()) {
11415 InvalidDecl = true;
11416 T = Context.IntTy;
11417 }
11418
Eli Friedman721e77d2009-12-07 00:22:08 +000011419 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011420 if (!EltTy->isDependentType()) {
11421 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11422 // Fields of incomplete type force their record to be invalid.
11423 Record->setInvalidDecl();
11424 InvalidDecl = true;
11425 } else {
11426 NamedDecl *Def;
11427 EltTy->isIncompleteType(&Def);
11428 if (Def && Def->isInvalidDecl()) {
11429 Record->setInvalidDecl();
11430 InvalidDecl = true;
11431 }
11432 }
John McCall2d7d2d92010-08-16 23:42:35 +000011433 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011434
Joey Gouly617bb312013-01-17 17:35:00 +000011435 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11436 if (BitWidth && getLangOpts().OpenCL) {
11437 Diag(Loc, diag::err_opencl_bitfields);
11438 InvalidDecl = true;
11439 }
11440
Reid Spencer5f016e22007-07-11 17:01:13 +000011441 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11442 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011443 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011444 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011445 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011446
11447 TypeSourceInfo *FixedTInfo =
11448 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11449 SizeIsNegative,
11450 Oversized);
11451 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011452 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011453 TInfo = FixedTInfo;
11454 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011455 } else {
11456 if (SizeIsNegative)
11457 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011458 else if (Oversized.getBoolValue())
11459 Diag(Loc, diag::err_array_too_large)
11460 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011461 else
11462 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011463 InvalidDecl = true;
11464 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011465 }
Mike Stump1eb44332009-09-09 15:08:12 +000011466
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011467 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011468 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11469 diag::err_abstract_type_in_decl,
11470 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011471 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011472
Eli Friedman1d954f62009-08-15 21:55:26 +000011473 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011474 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011475 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011476 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11477 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011478 if (!BitWidth) {
11479 InvalidDecl = true;
11480 BitWidth = 0;
11481 ZeroWidth = false;
11482 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011483 }
Mike Stump1eb44332009-09-09 15:08:12 +000011484
John McCall4bde1e12010-06-04 08:34:12 +000011485 // Check that 'mutable' is consistent with the type of the declaration.
11486 if (!InvalidDecl && Mutable) {
11487 unsigned DiagID = 0;
11488 if (T->isReferenceType())
11489 DiagID = diag::err_mutable_reference;
11490 else if (T.isConstQualified())
11491 DiagID = diag::err_mutable_const;
11492
11493 if (DiagID) {
11494 SourceLocation ErrLoc = Loc;
11495 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11496 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11497 Diag(ErrLoc, DiagID);
11498 Mutable = false;
11499 InvalidDecl = true;
11500 }
11501 }
11502
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011503 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011504 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011505 if (InvalidDecl)
11506 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011507
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011508 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11509 Diag(Loc, diag::err_duplicate_member) << II;
11510 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11511 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011512 }
11513
David Blaikie4e4d0842012-03-11 07:00:24 +000011514 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011515 if (Record->isUnion()) {
11516 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11517 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11518 if (RDecl->getDefinition()) {
11519 // C++ [class.union]p1: An object of a class with a non-trivial
11520 // constructor, a non-trivial copy constructor, a non-trivial
11521 // destructor, or a non-trivial copy assignment operator
11522 // cannot be a member of a union, nor can an array of such
11523 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011524 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011525 NewFD->setInvalidDecl();
11526 }
11527 }
11528
11529 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011530 // the program is ill-formed, except when compiling with MSVC extensions
11531 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011532 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011533 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11534 diag::ext_union_member_of_reference_type :
11535 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011536 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011537 if (!getLangOpts().MicrosoftExt)
11538 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011539 }
11540 }
11541 }
11542
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011543 // FIXME: We need to pass in the attributes given an AST
11544 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011545 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011546 // FIXME: The current scope is almost... but not entirely... correct here.
11547 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011548
Richard Smithbe507b62013-02-01 08:12:08 +000011549 if (NewFD->hasAttrs())
11550 CheckAlignasUnderalignment(NewFD);
11551 }
11552
John McCallf85e1932011-06-15 23:02:42 +000011553 // In auto-retain/release, infer strong retension for fields of
11554 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011555 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011556 NewFD->setInvalidDecl();
11557
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011558 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011559 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011560
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011561 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011562 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011563}
11564
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011565bool Sema::CheckNontrivialField(FieldDecl *FD) {
11566 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011567 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011568
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011569 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11570 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011571
11572 QualType EltTy = Context.getBaseElementType(FD->getType());
11573 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011574 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011575 if (RDecl->getDefinition()) {
11576 // We check for copy constructors before constructors
11577 // because otherwise we'll never get complaints about
11578 // copy constructors.
11579
11580 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011581 // We're required to check for any non-trivial constructors. Since the
11582 // implicit default constructor is suppressed if there are any
11583 // user-declared constructors, we just need to check that there is a
11584 // trivial default constructor and a trivial copy constructor. (We don't
11585 // worry about move constructors here, since this is a C++98 check.)
11586 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011587 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011588 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011589 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011590 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011591 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011592 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011593 member = CXXDestructor;
11594
11595 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011596 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011597 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011598 // Objective-C++ ARC: it is an error to have a non-trivial field of
11599 // a union. However, system headers in Objective-C programs
11600 // occasionally have Objective-C lifetime objects within unions,
11601 // and rather than cause the program to fail, we make those
11602 // members unavailable.
11603 SourceLocation Loc = FD->getLocation();
11604 if (getSourceManager().isInSystemHeader(Loc)) {
11605 if (!FD->hasAttr<UnavailableAttr>())
11606 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011607 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011608 return false;
11609 }
11610 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011611
Richard Smith80ad52f2013-01-02 11:42:31 +000011612 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011613 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11614 diag::err_illegal_union_or_anon_struct_member)
11615 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011616 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011617 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011618 }
11619 }
11620 }
Richard Smithac713512012-12-08 02:53:02 +000011621
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011622 return false;
11623}
11624
Mike Stump1eb44332009-09-09 15:08:12 +000011625/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011626/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011627static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011628TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011629 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011630 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011631 case tok::objc_private: return ObjCIvarDecl::Private;
11632 case tok::objc_public: return ObjCIvarDecl::Public;
11633 case tok::objc_protected: return ObjCIvarDecl::Protected;
11634 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011635 }
11636}
11637
Mike Stump1eb44332009-09-09 15:08:12 +000011638/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011639/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011640Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011641 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011642 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011643 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011644
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011645 IdentifierInfo *II = D.getIdentifier();
11646 Expr *BitWidth = (Expr*)BitfieldWidth;
11647 SourceLocation Loc = DeclStart;
11648 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011649
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011650 // FIXME: Unnamed fields can be handled in various different ways, for
11651 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011652
John McCallbf1a0282010-06-04 23:28:52 +000011653 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11654 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011655
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011656 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011657 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011658 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011659 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011660 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011661 } else {
11662 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011663
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011664 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011665
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011666 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011667 if (T->isReferenceType()) {
11668 Diag(Loc, diag::err_ivar_reference_type);
11669 D.setInvalidType();
11670 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011671 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11672 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011673 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011674 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011675 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011676 }
Mike Stump1eb44332009-09-09 15:08:12 +000011677
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011678 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011679 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011680 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11681 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011682 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011683 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011684 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11685 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011686 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011687 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011688 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011689 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011690 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011691 EnclosingContext = IMPDecl->getClassInterface();
11692 assert(EnclosingContext && "Implementation has no class interface!");
11693 }
11694 else
11695 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011696 } else {
11697 if (ObjCCategoryDecl *CDecl =
11698 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011699 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011700 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011701 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011702 }
11703 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011704 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011705 }
Mike Stump1eb44332009-09-09 15:08:12 +000011706
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011707 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011708 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11709 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011710 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011711
Douglas Gregor72de6672009-01-08 20:45:30 +000011712 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011713 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011714 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011715 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011716 && !isa<TagDecl>(PrevDecl)) {
11717 Diag(Loc, diag::err_duplicate_member) << II;
11718 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11719 NewID->setInvalidDecl();
11720 }
11721 }
11722
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011723 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011724 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011725
Chris Lattnereaaebc72009-04-25 08:06:05 +000011726 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011727 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011728
John McCallf85e1932011-06-15 23:02:42 +000011729 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011730 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011731 NewID->setInvalidDecl();
11732
Douglas Gregor591dc842011-09-12 16:11:24 +000011733 if (D.getDeclSpec().isModulePrivateSpecified())
11734 NewID->setModulePrivate();
11735
Douglas Gregor72de6672009-01-08 20:45:30 +000011736 if (II) {
11737 // FIXME: When interfaces are DeclContexts, we'll need to add
11738 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011739 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011740 IdResolver.AddDecl(NewID);
11741 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011742
John McCall260611a2012-06-20 06:18:46 +000011743 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011744 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011745 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011746
John McCalld226f652010-08-21 09:40:31 +000011747 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011748}
11749
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011750/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011751/// class and class extensions. For every class \@interface and class
11752/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011753/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011754void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011755 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011756 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011757 return;
11758
11759 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11760 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11761
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011762 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011763 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011764 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011765 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011766 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011767 if (!CD->IsClassExtension())
11768 return;
11769 }
11770 // No need to add this to end of @implementation.
11771 else
11772 return;
11773 }
11774 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011775 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11776 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011777
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011778 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011779 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011780 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011781 Context.getTrivialTypeSourceInfo(Context.CharTy,
11782 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011783 ObjCIvarDecl::Private, BW,
11784 true);
11785 AllIvarDecls.push_back(Ivar);
11786}
11787
Robert Wilhelm834c0582013-08-09 18:02:13 +000011788void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11789 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11790 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011791 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011792
Eric Christopher6dba4a12012-07-19 22:22:51 +000011793 // If this is an Objective-C @implementation or category and we have
11794 // new fields here we should reset the layout of the interface since
11795 // it will now change.
11796 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11797 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11798 switch (DC->getKind()) {
11799 default: break;
11800 case Decl::ObjCCategory:
11801 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11802 break;
11803 case Decl::ObjCImplementation:
11804 Context.
11805 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11806 break;
11807 }
11808 }
11809
Eli Friedman11e70d72012-02-07 05:00:47 +000011810 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11811
11812 // Start counting up the number of named members; make sure to include
11813 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011814 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011815 if (Record) {
11816 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11817 e = Record->decls_end(); i != e; i++) {
11818 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11819 if (IFD->getDeclName())
11820 ++NumNamedMembers;
11821 }
11822 }
11823
11824 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011825 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011826
John McCallf85e1932011-06-15 23:02:42 +000011827 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011828 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011829 i != end; ++i) {
11830 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011831
Reid Spencer5f016e22007-07-11 17:01:13 +000011832 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011833 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011834
Douglas Gregor72de6672009-01-08 20:45:30 +000011835 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011836 // Remember all fields written by the user.
11837 RecFields.push_back(FD);
11838 }
Mike Stump1eb44332009-09-09 15:08:12 +000011839
Chris Lattner24793662009-03-05 22:45:59 +000011840 // If the field is already invalid for some reason, don't emit more
11841 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011842 if (FD->isInvalidDecl()) {
11843 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011844 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011845 }
Mike Stump1eb44332009-09-09 15:08:12 +000011846
Douglas Gregore7450f52009-03-24 19:52:54 +000011847 // C99 6.7.2.1p2:
11848 // A structure or union shall not contain a member with
11849 // incomplete or function type (hence, a structure shall not
11850 // contain an instance of itself, but may contain a pointer to
11851 // an instance of itself), except that the last member of a
11852 // structure with more than one named member may have incomplete
11853 // array type; such a structure (and any union containing,
11854 // possibly recursively, a member that is such a structure)
11855 // shall not be a member of a structure or an element of an
11856 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011857 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011858 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011859 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011860 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011861 FD->setInvalidDecl();
11862 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011863 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011864 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011865 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011866 ((getLangOpts().MicrosoftExt ||
11867 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011868 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011869 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011870 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011871 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011872 // as the sole element of a struct/class.
David Majnemer633c0c22013-11-02 10:38:05 +000011873 unsigned DiagID = 0;
11874 if (Record->isUnion())
11875 DiagID = getLangOpts().MicrosoftExt
11876 ? diag::ext_flexible_array_union_ms
11877 : getLangOpts().CPlusPlus
11878 ? diag::ext_flexible_array_union_gnu
11879 : diag::err_flexible_array_union;
11880 else if (Fields.size() == 1)
11881 DiagID = getLangOpts().MicrosoftExt
11882 ? diag::ext_flexible_array_empty_aggregate_ms
11883 : getLangOpts().CPlusPlus
11884 ? diag::ext_flexible_array_empty_aggregate_gnu
11885 : NumNamedMembers < 1
11886 ? diag::err_flexible_array_empty_aggregate
11887 : 0;
11888
11889 if (DiagID)
11890 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11891 << Record->getTagKind();
David Majnemer3a665572013-11-02 11:19:13 +000011892 // While the layout of types that contain virtual bases is not specified
11893 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11894 // virtual bases after the derived members. This would make a flexible
11895 // array member declared at the end of an object not adjacent to the end
11896 // of the type.
11897 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11898 if (RD->getNumVBases() != 0)
11899 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11900 << FD->getDeclName() << Record->getTagKind();
David Majnemer633c0c22013-11-02 10:38:05 +000011901 if (!getLangOpts().C99)
11902 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11903 << FD->getDeclName() << Record->getTagKind();
11904
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011905 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011906 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011907 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011908 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011909 FD->setInvalidDecl();
11910 EnclosingDecl->setInvalidDecl();
11911 continue;
11912 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011913 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011914 if (Record)
11915 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011916 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011917 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011918 diag::err_field_incomplete)) {
11919 // Incomplete type
11920 FD->setInvalidDecl();
11921 EnclosingDecl->setInvalidDecl();
11922 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011923 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011924 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11925 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011926 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011927 Record->setHasFlexibleArrayMember(true);
11928 } else {
11929 // If this is a struct/class and this is not the last element, reject
11930 // it. Note that GCC supports variable sized arrays in the middle of
11931 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011932 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011933 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011934 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011935 else {
11936 // We support flexible arrays at the end of structs in
11937 // other structs as an extension.
11938 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11939 << FD->getDeclName();
11940 if (Record)
11941 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011942 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011943 }
11944 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011945 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11946 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11947 diag::err_abstract_type_in_decl,
11948 AbstractIvarType)) {
11949 // Ivars can not have abstract class types
11950 FD->setInvalidDecl();
11951 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011952 if (Record && FDTTy->getDecl()->hasObjectMember())
11953 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011954 if (Record && FDTTy->getDecl()->hasVolatileMember())
11955 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011956 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011957 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011958 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11959 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11960 QualType T = Context.getObjCObjectPointerType(FD->getType());
11961 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011962 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11963 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11964 // It's an error in ARC if a field has lifetime.
11965 // We don't want to report this in a system header, though,
11966 // so we just make the field unavailable.
11967 // FIXME: that's really not sufficient; we need to make the type
11968 // itself invalid to, say, initialize or copy.
11969 QualType T = FD->getType();
11970 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11971 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11972 SourceLocation loc = FD->getLocation();
11973 if (getSourceManager().isInSystemHeader(loc)) {
11974 if (!FD->hasAttr<UnavailableAttr>()) {
11975 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11976 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011977 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011978 } else {
11979 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011980 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011981 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011982 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011983 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011984 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011985 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011986 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011987 if (FD->getType()->isObjCObjectPointerType() ||
11988 FD->getType().isObjCGCStrong())
11989 Record->setHasObjectMember(true);
11990 else if (Context.getAsArrayType(FD->getType())) {
11991 QualType BaseType = Context.getBaseElementType(FD->getType());
11992 if (BaseType->isRecordType() &&
11993 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011994 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011995 else if (BaseType->isObjCObjectPointerType() ||
11996 BaseType.isObjCGCStrong())
11997 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011998 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011999 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000012000 if (Record && FD->getType().isVolatileQualified())
12001 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000012002 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000012003 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000012004 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000012005 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000012006
Reid Spencer5f016e22007-07-11 17:01:13 +000012007 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000012008 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012009 bool Completed = false;
12010 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12011 if (!CXXRecord->isInvalidDecl()) {
12012 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000012013 for (CXXRecordDecl::conversion_iterator
12014 I = CXXRecord->conversion_begin(),
12015 E = CXXRecord->conversion_end(); I != E; ++I)
12016 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012017
12018 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000012019 if (CXXRecord->hasUserDeclaredDestructor()) {
12020 // Adjust user-defined destructor exception spec.
12021 if (getLangOpts().CPlusPlus11)
12022 AdjustDestructorExceptionSpec(CXXRecord,
12023 CXXRecord->getDestructor());
12024
12025 // The Microsoft ABI requires that we perform the destructor body
12026 // checks (i.e. operator delete() lookup) at every declaration, as
12027 // any translation unit may need to emit a deleting destructor.
12028 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12029 CheckDestructor(CXXRecord->getDestructor());
12030 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000012031
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012032 // Add any implicitly-declared members to this class.
12033 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12034
12035 // If we have virtual base classes, we may end up finding multiple
12036 // final overriders for a given virtual function. Check for this
12037 // problem now.
12038 if (CXXRecord->getNumVBases()) {
12039 CXXFinalOverriderMap FinalOverriders;
12040 CXXRecord->getFinalOverriders(FinalOverriders);
12041
12042 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12043 MEnd = FinalOverriders.end();
12044 M != MEnd; ++M) {
12045 for (OverridingMethods::iterator SO = M->second.begin(),
12046 SOEnd = M->second.end();
12047 SO != SOEnd; ++SO) {
12048 assert(SO->second.size() > 0 &&
12049 "Virtual function without overridding functions?");
12050 if (SO->second.size() == 1)
12051 continue;
12052
12053 // C++ [class.virtual]p2:
12054 // In a derived class, if a virtual member function of a base
12055 // class subobject has more than one final overrider the
12056 // program is ill-formed.
12057 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000012058 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012059 Diag(M->first->getLocation(),
12060 diag::note_overridden_virtual_function);
12061 for (OverridingMethods::overriding_iterator
12062 OM = SO->second.begin(),
12063 OMEnd = SO->second.end();
12064 OM != OMEnd; ++OM)
12065 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012066 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012067
12068 Record->setInvalidDecl();
12069 }
12070 }
12071 CXXRecord->completeDefinition(&FinalOverriders);
12072 Completed = true;
12073 }
12074 }
12075 }
12076 }
12077
12078 if (!Completed)
12079 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012080
Richard Smithbe507b62013-02-01 08:12:08 +000012081 if (Record->hasAttrs())
12082 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012083
Serge Pavlov142ab062013-11-14 02:13:03 +000012084 // Check if the structure/union declaration is a type that can have zero
12085 // size in C. For C this is a language extension, for C++ it may cause
12086 // compatibility problems.
12087 bool CheckForZeroSize;
Serge Pavlov122e6012013-06-08 13:29:58 +000012088 if (!getLangOpts().CPlusPlus) {
Serge Pavlov142ab062013-11-14 02:13:03 +000012089 CheckForZeroSize = true;
12090 } else {
12091 // For C++ filter out types that cannot be referenced in C code.
12092 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12093 CheckForZeroSize =
12094 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12095 !CXXRecord->isDependentType() &&
12096 CXXRecord->isCLike();
12097 }
12098 if (CheckForZeroSize) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012099 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012100 bool IsEmpty = true;
12101 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012102 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012103 E = Record->field_end();
12104 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12105 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012106 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012107 if (I->getBitWidthValue(Context) > 0)
12108 ZeroSize = false;
12109 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012110 ++NonBitFields;
12111 QualType FieldType = I->getType();
12112 if (FieldType->isIncompleteType() ||
12113 !Context.getTypeSizeInChars(FieldType).isZero())
12114 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012115 }
12116 }
12117
Serge Pavlov142ab062013-11-14 02:13:03 +000012118 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12119 // allowed in C++, but warn if its declaration is inside
12120 // extern "C" block.
12121 if (ZeroSize) {
12122 Diag(RecLoc, getLangOpts().CPlusPlus ?
12123 diag::warn_zero_size_struct_union_in_extern_c :
12124 diag::warn_zero_size_struct_union_compat)
12125 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12126 }
Serge Pavlov122e6012013-06-08 13:29:58 +000012127
Serge Pavlov142ab062013-11-14 02:13:03 +000012128 // Structs without named members are extension in C (C99 6.7.2.1p7),
12129 // but are accepted by GCC.
12130 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12131 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12132 diag::ext_no_named_members_in_struct_union)
12133 << Record->isUnion();
Serge Pavlov122e6012013-06-08 13:29:58 +000012134 }
12135 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012136 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012137 ObjCIvarDecl **ClsFields =
12138 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012139 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012140 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012141 // Add ivar's to class's DeclContext.
12142 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12143 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012144 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012145 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012146 // Must enforce the rule that ivars in the base classes may not be
12147 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012148 if (ID->getSuperClass())
12149 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012150 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012151 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012152 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012153 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12154 // Ivar declared in @implementation never belongs to the implementation.
12155 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012156 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012157 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012158 IMPDecl->setIvarLBraceLoc(LBrac);
12159 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012160 } else if (ObjCCategoryDecl *CDecl =
12161 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012162 // case of ivars in class extension; all other cases have been
12163 // reported as errors elsewhere.
12164 // FIXME. Class extension does not have a LocEnd field.
12165 // CDecl->setLocEnd(RBrac);
12166 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012167 // Diagnose redeclaration of private ivars.
12168 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012169 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012170 if (IDecl) {
12171 if (const ObjCIvarDecl *ClsIvar =
12172 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12173 Diag(ClsFields[i]->getLocation(),
12174 diag::err_duplicate_ivar_declaration);
12175 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12176 continue;
12177 }
Douglas Gregord3297242013-01-16 23:00:23 +000012178 for (ObjCInterfaceDecl::known_extensions_iterator
12179 Ext = IDecl->known_extensions_begin(),
12180 ExtEnd = IDecl->known_extensions_end();
12181 Ext != ExtEnd; ++Ext) {
12182 if (const ObjCIvarDecl *ClsExtIvar
12183 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012184 Diag(ClsFields[i]->getLocation(),
12185 diag::err_duplicate_ivar_declaration);
12186 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12187 continue;
12188 }
12189 }
12190 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012191 ClsFields[i]->setLexicalDeclContext(CDecl);
12192 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012193 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012194 CDecl->setIvarLBraceLoc(LBrac);
12195 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012196 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012197 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012198
12199 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012200 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012201}
12202
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012203/// \brief Determine whether the given integral value is representable within
12204/// the given type T.
12205static bool isRepresentableIntegerValue(ASTContext &Context,
12206 llvm::APSInt &Value,
12207 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012208 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012209 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012210
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012211 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012212 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012213 --BitWidth;
12214 return Value.getActiveBits() <= BitWidth;
12215 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012216 return Value.getMinSignedBits() <= BitWidth;
12217}
12218
12219// \brief Given an integral type, return the next larger integral type
12220// (or a NULL type of no such type exists).
12221static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12222 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12223 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012224 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012225 const unsigned NumTypes = 4;
12226 QualType SignedIntegralTypes[NumTypes] = {
12227 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12228 };
12229 QualType UnsignedIntegralTypes[NumTypes] = {
12230 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12231 Context.UnsignedLongLongTy
12232 };
12233
12234 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012235 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12236 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012237 for (unsigned I = 0; I != NumTypes; ++I)
12238 if (Context.getTypeSize(Types[I]) > BitWidth)
12239 return Types[I];
12240
12241 return QualType();
12242}
12243
Douglas Gregor879fd492009-03-17 19:05:46 +000012244EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12245 EnumConstantDecl *LastEnumConst,
12246 SourceLocation IdLoc,
12247 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012248 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012249 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012250 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012251 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012252
12253 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12254 Val = 0;
12255
Eli Friedman19efa3e2011-12-06 00:10:34 +000012256 if (Val)
12257 Val = DefaultLvalueConversion(Val).take();
12258
Douglas Gregor4912c342009-11-06 00:03:12 +000012259 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012260 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012261 EltTy = Context.DependentTy;
12262 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012263 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012264 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012265 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012266 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12267 // constant-expression in the enumerator-definition shall be a converted
12268 // constant expression of the underlying type.
12269 EltTy = Enum->getIntegerType();
12270 ExprResult Converted =
12271 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12272 CCEK_Enumerator);
12273 if (Converted.isInvalid())
12274 Val = 0;
12275 else
12276 Val = Converted.take();
12277 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012278 !(Val = VerifyIntegerConstantExpression(Val,
12279 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012280 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012281 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012282 if (Enum->isFixed()) {
12283 EltTy = Enum->getIntegerType();
12284
Richard Smith8ef7b202012-01-18 23:55:52 +000012285 // In Obj-C and Microsoft mode, require the enumeration value to be
12286 // representable in the underlying type of the enumeration. In C++11,
12287 // we perform a non-narrowing conversion as part of converted constant
12288 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012289 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012290 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012291 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012292 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012293 } else
12294 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012295 } else
John Wiegley429bb272011-04-08 18:41:53 +000012296 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012297 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012298 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012299 // If the underlying type is not fixed, the type of each enumerator
12300 // is the type of its initializing value:
12301 // - If an initializer is specified for an enumerator, the
12302 // initializing value has the same type as the expression.
12303 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012304 } else {
12305 // C99 6.7.2.2p2:
12306 // The expression that defines the value of an enumeration constant
12307 // shall be an integer constant expression that has a value
12308 // representable as an int.
12309
12310 // Complain if the value is not representable in an int.
12311 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12312 Diag(IdLoc, diag::ext_enum_value_not_int)
12313 << EnumVal.toString(10) << Val->getSourceRange()
12314 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12315 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12316 // Force the type of the expression to 'int'.
12317 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12318 }
12319 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012320 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012321 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012322 }
12323 }
Mike Stump1eb44332009-09-09 15:08:12 +000012324
Douglas Gregor879fd492009-03-17 19:05:46 +000012325 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012326 if (Enum->isDependentType())
12327 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012328 else if (!LastEnumConst) {
12329 // C++0x [dcl.enum]p5:
12330 // If the underlying type is not fixed, the type of each enumerator
12331 // is the type of its initializing value:
12332 // - If no initializer is specified for the first enumerator, the
12333 // initializing value has an unspecified integral type.
12334 //
12335 // GCC uses 'int' for its unspecified integral type, as does
12336 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012337 if (Enum->isFixed()) {
12338 EltTy = Enum->getIntegerType();
12339 }
12340 else {
12341 EltTy = Context.IntTy;
12342 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012343 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012344 // Assign the last value + 1.
12345 EnumVal = LastEnumConst->getInitVal();
12346 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012347 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012348
12349 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012350 if (EnumVal < LastEnumConst->getInitVal()) {
12351 // C++0x [dcl.enum]p5:
12352 // If the underlying type is not fixed, the type of each enumerator
12353 // is the type of its initializing value:
12354 //
12355 // - Otherwise the type of the initializing value is the same as
12356 // the type of the initializing value of the preceding enumerator
12357 // unless the incremented value is not representable in that type,
12358 // in which case the type is an unspecified integral type
12359 // sufficient to contain the incremented value. If no such type
12360 // exists, the program is ill-formed.
12361 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012362 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012363 // There is no integral type larger enough to represent this
12364 // value. Complain, then allow the value to wrap around.
12365 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012366 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012367 ++EnumVal;
12368 if (Enum->isFixed())
12369 // When the underlying type is fixed, this is ill-formed.
12370 Diag(IdLoc, diag::err_enumerator_wrapped)
12371 << EnumVal.toString(10)
12372 << EltTy;
12373 else
12374 Diag(IdLoc, diag::warn_enumerator_too_large)
12375 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012376 } else {
12377 EltTy = T;
12378 }
12379
12380 // Retrieve the last enumerator's value, extent that type to the
12381 // type that is supposed to be large enough to represent the incremented
12382 // value, then increment.
12383 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012384 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012385 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012386 ++EnumVal;
12387
12388 // If we're not in C++, diagnose the overflow of enumerator values,
12389 // which in C99 means that the enumerator value is not representable in
12390 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12391 // permits enumerator values that are representable in some larger
12392 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012393 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012394 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012395 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012396 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12397 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12398 Diag(IdLoc, diag::ext_enum_value_not_int)
12399 << EnumVal.toString(10) << 1;
12400 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012401 }
12402 }
Mike Stump1eb44332009-09-09 15:08:12 +000012403
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012404 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012405 // Make the enumerator value match the signedness and size of the
12406 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012407 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012408 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012409 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012410
Douglas Gregor879fd492009-03-17 19:05:46 +000012411 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012412 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012413}
12414
12415
John McCall5b629aa2010-10-22 23:36:17 +000012416Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12417 SourceLocation IdLoc, IdentifierInfo *Id,
12418 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012419 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012420 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012421 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012422 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012423
Chris Lattner31e05722007-08-26 06:24:45 +000012424 // The scope passed in may not be a decl scope. Zip up the scope tree until
12425 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012426 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012427
Reid Spencer5f016e22007-07-11 17:01:13 +000012428 // Verify that there isn't already something declared with this name in this
12429 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012430 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012431 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012432 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012433 // Maybe we will complain about the shadowed template parameter.
12434 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12435 // Just pretend that we didn't see the previous declaration.
12436 PrevDecl = 0;
12437 }
12438
12439 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012440 // When in C++, we may get a TagDecl with the same name; in this case the
12441 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012442 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012443 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012444 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012445 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012446 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012447 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012448 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012449 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012450 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012451 }
12452 }
12453
Aaron Ballmanf8167872012-07-19 03:12:23 +000012454 // C++ [class.mem]p15:
12455 // If T is the name of a class, then each of the following shall have a name
12456 // different from T:
12457 // - every enumerator of every member of class T that is an unscoped
12458 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012459 if (CXXRecordDecl *Record
12460 = dyn_cast<CXXRecordDecl>(
12461 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012462 if (!TheEnumDecl->isScoped() &&
12463 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012464 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12465
John McCall5b629aa2010-10-22 23:36:17 +000012466 EnumConstantDecl *New =
12467 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012468
John McCall92f88312010-01-23 00:46:32 +000012469 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012470 // Process attributes.
12471 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12472
12473 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012474 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012475 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012476 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012477
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012478 ActOnDocumentableDecl(New);
12479
John McCalld226f652010-08-21 09:40:31 +000012480 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012481}
12482
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012483// Returns true when the enum initial expression does not trigger the
12484// duplicate enum warning. A few common cases are exempted as follows:
12485// Element2 = Element1
12486// Element2 = Element1 + 1
12487// Element2 = Element1 - 1
12488// Where Element2 and Element1 are from the same enum.
12489static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12490 Expr *InitExpr = ECD->getInitExpr();
12491 if (!InitExpr)
12492 return true;
12493 InitExpr = InitExpr->IgnoreImpCasts();
12494
12495 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12496 if (!BO->isAdditiveOp())
12497 return true;
12498 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12499 if (!IL)
12500 return true;
12501 if (IL->getValue() != 1)
12502 return true;
12503
12504 InitExpr = BO->getLHS();
12505 }
12506
12507 // This checks if the elements are from the same enum.
12508 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12509 if (!DRE)
12510 return true;
12511
12512 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12513 if (!EnumConstant)
12514 return true;
12515
12516 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12517 Enum)
12518 return true;
12519
12520 return false;
12521}
12522
12523struct DupKey {
12524 int64_t val;
12525 bool isTombstoneOrEmptyKey;
12526 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12527 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12528};
12529
12530static DupKey GetDupKey(const llvm::APSInt& Val) {
12531 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12532 false);
12533}
12534
12535struct DenseMapInfoDupKey {
12536 static DupKey getEmptyKey() { return DupKey(0, true); }
12537 static DupKey getTombstoneKey() { return DupKey(1, true); }
12538 static unsigned getHashValue(const DupKey Key) {
12539 return (unsigned)(Key.val * 37);
12540 }
12541 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12542 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12543 LHS.val == RHS.val;
12544 }
12545};
12546
12547// Emits a warning when an element is implicitly set a value that
12548// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012549static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12550 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012551 QualType EnumType) {
12552 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12553 Enum->getLocation()) ==
12554 DiagnosticsEngine::Ignored)
12555 return;
12556 // Avoid anonymous enums
12557 if (!Enum->getIdentifier())
12558 return;
12559
12560 // Only check for small enums.
12561 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12562 return;
12563
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012564 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12565 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012566
12567 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12568 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12569 ValueToVectorMap;
12570
12571 DuplicatesVector DupVector;
12572 ValueToVectorMap EnumMap;
12573
12574 // Populate the EnumMap with all values represented by enum constants without
12575 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012576 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012577 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012578
12579 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12580 // this constant. Skip this enum since it may be ill-formed.
12581 if (!ECD) {
12582 return;
12583 }
12584
12585 if (ECD->getInitExpr())
12586 continue;
12587
12588 DupKey Key = GetDupKey(ECD->getInitVal());
12589 DeclOrVector &Entry = EnumMap[Key];
12590
12591 // First time encountering this value.
12592 if (Entry.isNull())
12593 Entry = ECD;
12594 }
12595
12596 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012597 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012598 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12599 if (!ValidDuplicateEnum(ECD, Enum))
12600 continue;
12601
12602 DupKey Key = GetDupKey(ECD->getInitVal());
12603
12604 DeclOrVector& Entry = EnumMap[Key];
12605 if (Entry.isNull())
12606 continue;
12607
12608 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12609 // Ensure constants are different.
12610 if (D == ECD)
12611 continue;
12612
12613 // Create new vector and push values onto it.
12614 ECDVector *Vec = new ECDVector();
12615 Vec->push_back(D);
12616 Vec->push_back(ECD);
12617
12618 // Update entry to point to the duplicates vector.
12619 Entry = Vec;
12620
12621 // Store the vector somewhere we can consult later for quick emission of
12622 // diagnostics.
12623 DupVector.push_back(Vec);
12624 continue;
12625 }
12626
12627 ECDVector *Vec = Entry.get<ECDVector*>();
12628 // Make sure constants are not added more than once.
12629 if (*Vec->begin() == ECD)
12630 continue;
12631
12632 Vec->push_back(ECD);
12633 }
12634
12635 // Emit diagnostics.
12636 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12637 DupVectorEnd = DupVector.end();
12638 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12639 ECDVector *Vec = *DupVectorIter;
12640 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12641
12642 // Emit warning for one enum constant.
12643 ECDVector::iterator I = Vec->begin();
12644 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12645 << (*I)->getName() << (*I)->getInitVal().toString(10)
12646 << (*I)->getSourceRange();
12647 ++I;
12648
12649 // Emit one note for each of the remaining enum constants with
12650 // the same value.
12651 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12652 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12653 << (*I)->getName() << (*I)->getInitVal().toString(10)
12654 << (*I)->getSourceRange();
12655 delete Vec;
12656 }
12657}
12658
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012659void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012660 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012661 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012662 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012663 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012664 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012665
12666 if (Attr)
12667 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012668
Eli Friedmaned0716b2009-12-11 01:34:50 +000012669 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012670 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012671 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012672 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012673 if (!ECD) continue;
12674
12675 ECD->setType(EnumType);
12676 }
12677
John McCall1b5a6182010-05-06 08:49:23 +000012678 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012679 return;
12680 }
12681
Chris Lattnere37f0be2007-08-28 05:10:31 +000012682 // TODO: If the result value doesn't fit in an int, it must be a long or long
12683 // long value. ISO C does not support this, but GCC does as an extension,
12684 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012685 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12686 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12687 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012688
Chris Lattnerac609682007-08-28 06:15:15 +000012689 // Verify that all the values are okay, compute the size of the values, and
12690 // reverse the list.
12691 unsigned NumNegativeBits = 0;
12692 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012693
Chris Lattnerac609682007-08-28 06:15:15 +000012694 // Keep track of whether all elements have type int.
12695 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012696
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012697 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012698 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012699 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012700 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012701
Chris Lattner211a30e2007-08-28 05:27:00 +000012702 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012703
Chris Lattnerac609682007-08-28 06:15:15 +000012704 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012705 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012706 NumPositiveBits = std::max(NumPositiveBits,
12707 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012708 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012709 NumNegativeBits = std::max(NumNegativeBits,
12710 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012711
Chris Lattnerac609682007-08-28 06:15:15 +000012712 // Keep track of whether every enum element has type int (very commmon).
12713 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012714 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012715 }
Mike Stump1eb44332009-09-09 15:08:12 +000012716
Chris Lattnerac609682007-08-28 06:15:15 +000012717 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012718 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012719 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012720
John McCall842aef82009-12-09 09:09:27 +000012721 // C++0x N3000 [conv.prom]p3:
12722 // An rvalue of an unscoped enumeration type whose underlying
12723 // type is not fixed can be converted to an rvalue of the first
12724 // of the following types that can represent all the values of
12725 // the enumeration: int, unsigned int, long int, unsigned long
12726 // int, long long int, or unsigned long long int.
12727 // C99 6.4.4.3p2:
12728 // An identifier declared as an enumeration constant has type int.
12729 // The C99 rule is modified by a gcc extension
12730 QualType BestPromotionType;
12731
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012732 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012733 // -fshort-enums is the equivalent to specifying the packed attribute on all
12734 // enum definitions.
12735 if (LangOpts.ShortEnums)
12736 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012737
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012738 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012739 BestType = Enum->getIntegerType();
12740 if (BestType->isPromotableIntegerType())
12741 BestPromotionType = Context.getPromotedIntegerType(BestType);
12742 else
12743 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012744 // We don't need to set BestWidth, because BestType is going to be the type
12745 // of the enumerators, but we do anyway because otherwise some compilers
12746 // warn that it might be used uninitialized.
12747 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012748 }
12749 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012750 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012751 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012752 // If it's packed, check also if it fits a char or a short.
12753 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012754 BestType = Context.SignedCharTy;
12755 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012756 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012757 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012758 BestType = Context.ShortTy;
12759 BestWidth = ShortWidth;
12760 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012761 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012762 BestWidth = IntWidth;
12763 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012764 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012765
John McCall842aef82009-12-09 09:09:27 +000012766 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012767 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012768 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012769 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012770
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012771 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012772 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12773 BestType = Context.LongLongTy;
12774 }
12775 }
John McCall842aef82009-12-09 09:09:27 +000012776 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012777 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012778 // If there is no negative value, figure out the smallest type that fits
12779 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012780 // If it's packed, check also if it fits a char or a short.
12781 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012782 BestType = Context.UnsignedCharTy;
12783 BestPromotionType = Context.IntTy;
12784 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012785 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012786 BestType = Context.UnsignedShortTy;
12787 BestPromotionType = Context.IntTy;
12788 BestWidth = ShortWidth;
12789 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012790 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012791 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012792 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012793 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012794 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012795 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012796 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012797 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012798 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012799 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012800 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012801 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012802 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012803 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012804 "How could an initializer get larger than ULL?");
12805 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012806 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012807 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012808 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012809 }
12810 }
Mike Stump1eb44332009-09-09 15:08:12 +000012811
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012812 // Loop over all of the enumerator constants, changing their types to match
12813 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012814 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012815 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012816 if (!ECD) continue; // Already issued a diagnostic.
12817
12818 // Standard C says the enumerators have int type, but we allow, as an
12819 // extension, the enumerators to be larger than int size. If each
12820 // enumerator value fits in an int, type it as an int, otherwise type it the
12821 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12822 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012823
12824 // Determine whether the value fits into an int.
12825 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012826
12827 // If it fits into an integer type, force it. Otherwise force it to match
12828 // the enum decl type.
12829 QualType NewTy;
12830 unsigned NewWidth;
12831 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012832 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012833 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012834 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012835 NewTy = Context.IntTy;
12836 NewWidth = IntWidth;
12837 NewSign = true;
12838 } else if (ECD->getType() == BestType) {
12839 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012840 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012841 // C++ [dcl.enum]p4: Following the closing brace of an
12842 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012843 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012844 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012845 continue;
12846 } else {
12847 NewTy = BestType;
12848 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012849 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012850 }
12851
12852 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012853 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012854 InitVal.setIsSigned(NewSign);
12855 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012856
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012857 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012858 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012859 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012860 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012861 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012862 ECD->getInitExpr(),
12863 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012864 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012865 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012866 // C++ [dcl.enum]p4: Following the closing brace of an
12867 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012868 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012869 ECD->setType(EnumType);
12870 else
12871 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012872 }
Mike Stump1eb44332009-09-09 15:08:12 +000012873
John McCall1b5a6182010-05-06 08:49:23 +000012874 Enum->completeDefinition(BestType, BestPromotionType,
12875 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012876
12877 // If we're declaring a function, ensure this decl isn't forgotten about -
12878 // it needs to go into the function scope.
12879 if (InFunctionDeclarator)
12880 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012881
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012882 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012883
12884 // Now that the enum type is defined, ensure it's not been underaligned.
12885 if (Enum->hasAttrs())
12886 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012887}
12888
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012889Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12890 SourceLocation StartLoc,
12891 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012892 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012893
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012894 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012895 AsmString, StartLoc,
12896 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012897 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012898 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012899}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012900
Douglas Gregor5948ae12012-01-03 18:04:46 +000012901DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12902 SourceLocation ImportLoc,
12903 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012904 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012905 Module::AllVisible,
12906 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012907 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012908 return true;
12909
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012910 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012911 Module *ModCheck = Mod;
12912 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12913 // If we've run out of module parents, just drop the remaining identifiers.
12914 // We need the length to be consistent.
12915 if (!ModCheck)
12916 break;
12917 ModCheck = ModCheck->Parent;
12918
12919 IdentifierLocs.push_back(Path[I].second);
12920 }
12921
12922 ImportDecl *Import = ImportDecl::Create(Context,
12923 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012924 AtLoc.isValid()? AtLoc : ImportLoc,
12925 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012926 Context.getTranslationUnitDecl()->addDecl(Import);
12927 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012928}
12929
Richard Smith26297f52013-11-15 04:24:58 +000012930void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12931 // FIXME: Should we synthesize an ImportDecl here?
12932 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12933 /*Complain=*/true);
12934}
12935
Douglas Gregorca2ab452013-01-12 01:29:50 +000012936void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12937 // Create the implicit import declaration.
12938 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12939 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12940 Loc, Mod, Loc);
12941 TU->addDecl(ImportD);
12942 Consumer.HandleImplicitImportDecl(ImportD);
12943
12944 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012945 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12946 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012947}
12948
David Chisnall5f3c1632012-02-18 16:12:34 +000012949void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12950 IdentifierInfo* AliasName,
12951 SourceLocation PragmaLoc,
12952 SourceLocation NameLoc,
12953 SourceLocation AliasNameLoc) {
12954 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12955 LookupOrdinaryName);
12956 AsmLabelAttr *Attr =
12957 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012958
12959 if (PrevDecl)
12960 PrevDecl->addAttr(Attr);
12961 else
12962 (void)ExtnameUndeclaredIdentifiers.insert(
12963 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12964}
12965
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012966void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12967 SourceLocation PragmaLoc,
12968 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012969 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012970
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012971 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012972 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012973 } else {
12974 (void)WeakUndeclaredIdentifiers.insert(
12975 std::pair<IdentifierInfo*,WeakInfo>
12976 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012977 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012978}
12979
12980void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12981 IdentifierInfo* AliasName,
12982 SourceLocation PragmaLoc,
12983 SourceLocation NameLoc,
12984 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012985 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12986 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012987 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012988
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012989 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012990 if (!PrevDecl->hasAttr<AliasAttr>())
12991 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012992 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012993 } else {
12994 (void)WeakUndeclaredIdentifiers.insert(
12995 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012996 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012997}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012998
12999Decl *Sema::getObjCDeclContext() const {
13000 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13001}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000013002
13003AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000013004 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000013005 return D->getAvailability();
13006}