blob: 10137a1095eaf58a8952fd1057eb04d1207950dc [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000015#include "TypeLocBuilder.h"
Chris Lattner622c1932008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000017#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000021#include "clang/AST/CommentDiagnostic.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000026#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000027#include "clang/AST/StmtCXX.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-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 Valia17d19f2013-11-07 05:17:06 +000043#include "clang/Sema/Template.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000044#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000045#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000046#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000047#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000048#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000049using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000050using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000051
Richard Smithcd1c0552011-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 McCall48871652010-08-21 09:40:31 +000058 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000059}
60
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000061namespace {
62
63class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64 public:
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrainb1378402012-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 Uhrain9cb8e9f2012-06-22 23:37:05 +000077 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000078 }
79
80 private:
81 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000082 bool WantClassName;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000083};
84
85}
86
Kaelyn Uhrain237c7d32012-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 Majnemera5e92552013-09-22 01:24:26 +0000113 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-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 Gregorec6e1892009-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 Gregor9817f4a2009-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 Gribenko5267fdf2013-05-03 13:12:11 +0000132ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000133 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000134 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000135 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000136 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000137 bool WantNontrivialTypeSourceInfo,
138 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000139 // Determine where we will perform name lookup.
140 DeclContext *LookupCtx = 0;
141 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000142 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000143 if (ObjectType->isRecordType())
144 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000145 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-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 Smith23d55872012-04-02 01:30:27 +0000159 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000161
John McCallc392f372010-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 Gregor844cb502011-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 McCallba7bf592010-08-24 05:47:05 +0000168 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000170 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000171
172 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000173 }
174
John McCallba7bf592010-08-24 05:47:05 +0000175 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000176 }
177
John McCall0b66eb32010-05-01 00:40:08 +0000178 if (!LookupCtx->isDependentContext() &&
179 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000181 }
Eli Friedman9025ec22009-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 Gregora25d65d2009-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 Gregorc9f9b862009-05-11 19:58:34 +0000194
Douglas Gregora25d65d2009-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 Lattnera3778332009-02-16 22:07:16 +0000209 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000210 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000211 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000212 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000213 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000214 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000216 Kind, S, SS, Validator);
Kaelyn Uhrain85308c62011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000232 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-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 Bagnara4244b432012-01-27 08:46:19 +0000237 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000238 WantNontrivialTypeSourceInfo);
239 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000240 diagnoseTypo(Correction,
241 PDiag(diag::err_unknown_type_or_class_name_suggest)
242 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-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 Lattnera3778332009-02-16 22:07:16 +0000251 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000252 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000253 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000254 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000255
Chris Lattnere40853a2009-10-25 22:09:09 +0000256 case LookupResult::Ambiguous:
John McCall6538c932009-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 McCall27b18f82009-11-17 02:14:36 +0000262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
263 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000264 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000265 }
John McCall6538c932009-10-10 05:48:19 +0000266
Douglas Gregorfe3d7d02009-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 Stump11289f42009-09-09 15:08:12 +0000271 if (!IIDecl ||
272 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000273 IIDecl->getLocation().getRawEncoding())
274 IIDecl = *Res;
Douglas Gregorfe3d7d02009-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 McCall27b18f82009-11-17 02:14:36 +0000285 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000286 return ParsedType();
Douglas Gregorfe3d7d02009-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 Gregorfe3d7d02009-04-01 21:51:26 +0000293 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000294
Chris Lattnera3778332009-02-16 22:07:16 +0000295 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000296 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000297 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000298 }
299
Chris Lattner17e15f12009-10-25 17:16:46 +0000300 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000301
Chris Lattner17e15f12009-10-25 17:16:46 +0000302 QualType T;
303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000304 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000305
Chris Lattner17e15f12009-10-25 17:16:46 +0000306 if (T.isNull())
307 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-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 Gregor844cb502011-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 Bagnara9033e2b2012-02-06 19:09:27 +0000320 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-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 Lattner17e15f12009-10-25 17:16:46 +0000327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000328 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000329 if (!HasTrailingDot)
330 T = Context.getObjCInterfaceType(IDecl);
331 }
332
333 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000334 // If it's not plausibly a type, suppress diagnostics.
335 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000336 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000337 }
John McCallba7bf592010-08-24 05:47:05 +0000338 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000339}
340
Chris Lattnerffaa0e62009-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 Matosdc86f942012-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 Lattnerffaa0e62009-04-12 21:49:30 +0000346DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
347 // Do a tag name lookup in this scope.
John McCall27b18f82009-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 McCall67c00872009-12-02 08:25:40 +0000352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000353 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000354 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000355 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-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 Lattnerffaa0e62009-04-12 21:49:30 +0000359 }
360 }
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000362 return DeclSpec::TST_unspecified;
363}
364
Francois Pichet48c946e2011-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 Pichet9a57fb52011-10-11 01:50:09 +0000379bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000380 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000381 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-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 Pichet9a57fb52011-10-11 01:50:09 +0000388 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000389 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000391}
392
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000393bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000394 SourceLocation IILoc,
395 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000396 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000397 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000398 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000399 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000400
Douglas Gregor2d435302009-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 Uhrainb1378402012-01-18 21:41:41 +0000403 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000405 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000406 Validator)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000407 if (Corrected.isKeyword()) {
408 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
410 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000411 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000412 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000413 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000414 diagnoseTypo(Corrected,
415 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000417 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-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 Uhrainb1378402012-01-18 21:41:41 +0000424 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000425 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000426
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000427 CXXScopeSpec tmpSS;
428 if (Corrected.getCorrectionSpecifier())
429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
430 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
433 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000434 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000435 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000436 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000437 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000438 }
439
David Blaikiebbafb8a2012-03-11 07:00:24 +0000440 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-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 Uhrainb5b17fe2012-06-15 23:45:58 +0000443 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000444 CXXScopeSpec EmptySS;
445 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000446 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000448 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000449 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000450 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-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 Gregor15e56022009-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 Gregor2d435302009-12-30 17:04:44 +0000463 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000464 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000465 else if (DeclContext *DC = computeDeclContext(*SS, false))
466 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000467 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000468 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000469 unsigned DiagID = diag::err_typename_missing;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000471 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000472
473 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000474 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000475 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000477 SuggestedType = ActOnTypenameType(S, SourceLocation(),
478 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-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 Lattnerffaa0e62009-04-12 21:49:30 +0000486
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-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 Uhrain71792052012-05-02 00:11:40 +0000504static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505 Scope *S, CXXScopeSpec &SS,
506 IdentifierInfo *&Name,
507 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-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 Uhrain71792052012-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 Matosdc86f942012-08-31 18:45:21 +0000529 case TTK_Interface:
530 TagName = "__interface";
531 FixItTagName = "__interface ";
532 break;
533
Kaelyn Uhrain71792052012-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 Smithaa31b4b2012-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 Uhrain71792052012-05-02 00:11:40 +0000552 return true;
553 }
554
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000555 return false;
556}
557
Richard Smith4f605af2012-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 Gregor0e7dde52011-04-24 05:37:28 +0000573Sema::NameClassification Sema::ClassifyName(Scope *S,
574 CXXScopeSpec &SS,
575 IdentifierInfo *&Name,
576 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000577 const Token &NextToken,
578 bool IsAddressOfOperand,
579 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-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 Gregorb90f5182011-04-25 15:05:41 +0000598 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000599 return E;
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-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 Uhrain71792052012-05-02 00:11:40 +0000638 if (!getLangOpts().CPlusPlus && !SecondTry &&
639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640 break;
Douglas Gregor0e7dde52011-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 Smith4f605af2012-08-18 00:55:03 +0000645 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000646 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000648 Result.getLookupKind(), S,
Richard Smith4f605af2012-08-18 00:55:03 +0000649 &SS, *CCC)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000652
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000654 NamedDecl *UnderlyingFirstDecl
655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000658 UnqualifiedDiag = diag::err_no_template_suggest;
659 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 } else if (UnderlyingFirstDecl &&
661 (isa<TypeDecl>(UnderlyingFirstDecl) ||
662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000664 UnqualifiedDiag = diag::err_unknown_typename_suggest;
665 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000667
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000668 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000670 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000671 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000673 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675 << Name << computeDeclContext(SS, false)
676 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000677 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000678
679 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000680 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000681
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000682 // Typo correction corrected to a keyword.
683 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000684 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000685
Douglas Gregorc2fa1692011-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 Smithf9b15102013-08-17 00:46:16 +0000690 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000691 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-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 Kramer62b95d82012-08-23 21:35:17 +0000700 return E;
Douglas Gregor0e7dde52011-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 Bagnara7945c982012-01-27 09:46:47 +0000711 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-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 Smith4f605af2012-08-18 00:55:03 +0000726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727 NameInfo, IsAddressOfOperand,
728 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000729 }
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000738 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-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 Gregor8b02cd02011-04-27 04:48:22 +0000772 if (!Result.empty()) {
773 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000774 bool IsVarTemplate;
Douglas Gregor8b02cd02011-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 Voufo39a1e502013-08-06 01:03:05 +0000784 IsVarTemplate = isa<VarTemplateDecl>(TD);
785
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000786 if (SS.isSet() && !SS.isInvalid())
787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000788 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000789 TD);
790 else
791 Template = TemplateName(TD);
792 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000793
Douglas Gregor8b02cd02011-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 Voufo39a1e502013-08-06 01:03:05 +0000802
803 return IsVarTemplate ? NameClassification::VarTemplate(Template)
804 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000805 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000806 }
Richard Smith4f605af2012-08-18 00:55:03 +0000807
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810 DiagnoseUseOfDecl(Type, NameLoc);
811 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000812 if (SS.isNotEmpty())
813 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000814 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000815 }
Richard Smith4f605af2012-08-18 00:55:03 +0000816
Douglas Gregor0e7dde52011-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 Uhrain71792052012-05-02 00:11:40 +0000838
Richard Smith4f605af2012-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 Uhrain71792052012-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 Kyrtzidisc64c0292013-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 Uhrain71792052012-05-02 00:11:40 +0000856 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000857
Richard Smith4f605af2012-08-18 00:55:03 +0000858 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000860
Douglas Gregor0e7dde52011-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 McCall5ed6e8f2009-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 Kyrtzidis16ac9be2008-11-08 17:17:31 +0000868DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000869
John McCall5ed6e8f2009-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.
Faisal Valibb9071e2013-12-04 22:43:08 +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 McCall5ed6e8f2009-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 Kyrtzidis0d09c492008-11-19 18:01:13 +0000893 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-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 Kyrtzidis0d09c492008-11-19 18:01:13 +0000901 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000902}
903
Douglas Gregor91f84212008-12-11 16:49:14 +0000904void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000905 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000906 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000907 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000908 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000909}
910
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000911void Sema::PopDeclContext() {
912 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000913
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000914 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000915 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000916}
917
Argyrios Kyrtzidis9941a4d2009-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 McCall6df5fef2009-12-19 10:49:29 +0000920///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000921void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-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 Kyrtzidis7bcce492009-06-17 23:15:40 +0000946 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000947 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000948}
949
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000950void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000951 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952
John McCall6df5fef2009-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 Kremenekc37877d2013-10-08 17:08:03 +0000957 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000958
959 // We don't need to do anything with the scope, which is going to
960 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000961}
962
Caitlin Sadowski990d5712011-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 Hutchins6f860042012-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 Sadowski990d5712011-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 Hutchins6f860042012-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 Gregor4e5cbdc2009-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 McCall1f82f242009-11-18 22:49:29 +00001010static bool AllowOverloadingOfFunction(LookupResult &Previous,
1011 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001012 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001013 return true;
1014
John McCall1f82f242009-11-18 22:49:29 +00001015 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001016 return true;
1017
John McCall1f82f242009-11-18 22:49:29 +00001018 return (Previous.getResultKind() == LookupResult::Found
1019 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020}
1021
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001022/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001023void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-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 Kremenekc37877d2013-10-08 17:08:03 +00001027 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001028 S = S->getParent();
1029
Douglas Gregor8b9ccca2008-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 McCall759e32b2009-08-31 22:39:49 +00001033 if (AddToContext)
1034 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001035
Richard Smith541b38b2013-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 Gregorf7b98952011-10-09 22:57:49 +00001039 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001040 D->getLexicalDeclContext()->getRedeclContext()) &&
1041 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-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 Gregor5ad7c542009-09-28 18:41:37 +00001047 return;
1048
John McCall9f3059a2009-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 McCall48871652010-08-21 09:40:31 +00001053 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1054 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001055 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001056
John McCall9f3059a2009-10-09 21:13:30 +00001057 // Should only need to replace one decl.
1058 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001059 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001060 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061
John McCall48871652010-08-21 09:40:31 +00001062 S->AddDecl(D);
Douglas Gregor88764cf2011-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 Gregord7d7e0d2011-03-24 14:35:16 +00001069 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001070 if (IDC == CurContext) {
1071 if (!S->isDeclScope(*I))
1072 continue;
1073 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001074 break;
1075 }
1076
Douglas Gregor46c04e72011-03-16 16:39:03 +00001077 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001078 } else {
1079 IdResolver.AddDecl(D);
1080 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001081}
1082
Douglas Gregor935bc7a22011-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 Smith1c34fb72013-08-13 18:18:50 +00001088bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001089 bool AllowInlineNamespace) {
1090 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001091}
1092
John McCallcc14d1f2010-08-24 08:50:51 +00001093Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1094 DeclContext *TargetDC = DC->getPrimaryContext();
1095 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001096 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001097 if (ScopeDC->getPrimaryContext() == TargetDC)
1098 return S;
1099 } while ((S = S->getParent()));
1100
1101 return 0;
1102}
1103
John McCall1f82f242009-11-18 22:49:29 +00001104static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1105 DeclContext*,
1106 ASTContext&);
1107
1108/// Filters out lookup results that don't fall within the given scope
1109/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001110void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001111 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001112 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001113 LookupResult::Filter F = R.makeFilter();
1114 while (F.hasNext()) {
1115 NamedDecl *D = F.next();
1116
Richard Smith72bcaec2013-12-05 04:30:04 +00001117 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001118 continue;
1119
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001121 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001122
John McCall1f82f242009-11-18 22:49:29 +00001123 F.erase();
1124 }
1125
1126 F.done();
1127}
1128
1129static bool isUsingDecl(NamedDecl *D) {
1130 return isa<UsingShadowDecl>(D) ||
1131 isa<UnresolvedUsingTypenameDecl>(D) ||
1132 isa<UnresolvedUsingValueDecl>(D);
1133}
1134
1135/// Removes using shadow declarations from the lookup results.
1136static void RemoveUsingDecls(LookupResult &R) {
1137 LookupResult::Filter F = R.makeFilter();
1138 while (F.hasNext())
1139 if (isUsingDecl(F.next()))
1140 F.erase();
1141
1142 F.done();
1143}
1144
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001145/// \brief Check for this common pattern:
1146/// @code
1147/// class S {
1148/// S(const S&); // DO NOT IMPLEMENT
1149/// void operator=(const S&); // DO NOT IMPLEMENT
1150/// };
1151/// @endcode
1152static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1153 // FIXME: Should check for private access too but access is set after we get
1154 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001155 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001156 return false;
1157
1158 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1159 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001160 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1161 return Method->isCopyAssignmentOperator();
1162 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001163}
1164
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001165// We need this to handle
1166//
1167// typedef struct {
1168// void *foo() { return 0; }
1169// } A;
1170//
1171// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1172// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001173// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001174// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001175// Callers should verify at the end of the TU if it D has external linkage or
1176// not.
1177bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1178 const DeclContext *DC = D->getDeclContext();
1179 while (!DC->isTranslationUnit()) {
1180 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1181 if (!RD->hasNameForLinkage())
1182 return true;
1183 }
1184 DC = DC->getParent();
1185 }
1186
Rafael Espindola3ae00052013-05-13 00:12:11 +00001187 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001188}
1189
Eli Friedman5ef21752013-09-10 03:05:56 +00001190// FIXME: This needs to be refactored; some other isInMainFile users want
1191// these semantics.
1192static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1193 if (S.TUKind != TU_Complete)
1194 return false;
1195 return S.SourceMgr.isInMainFile(Loc);
1196}
1197
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001198bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1199 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001200
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001201 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1202 return false;
1203
1204 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001205 if (D->getDeclContext()->isDependentContext() ||
1206 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001207 return false;
1208
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001209 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001210 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1211 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001212
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001213 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1214 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1215 return false;
1216 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001217 // 'static inline' functions are defined in headers; don't warn.
1218 if (FD->isInlineSpecified() &&
1219 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001220 return false;
1221 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001222
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001223 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001224 Context.DeclMustBeEmitted(FD))
1225 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001226 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001227 // Constants and utility variables are defined in headers with internal
1228 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1229 // like "inline".)
1230 if (!isMainFileLoc(*this, VD->getLocation()))
1231 return false;
1232
Eli Friedman5ef21752013-09-10 03:05:56 +00001233 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001234 return false;
1235
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001236 if (VD->isStaticDataMember() &&
1237 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1238 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001239 } else {
1240 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001241 }
1242
John McCalld37d35b2010-10-27 01:41:35 +00001243 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001244 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001245}
1246
1247void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001248 if (!D)
1249 return;
1250
1251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001252 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254 return; // First should already be in the vector.
1255 }
1256
1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001258 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001259 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1260 return; // First should already be in the vector.
1261 }
1262
David Blaikie3d8edc22012-05-26 05:35:39 +00001263 if (ShouldWarnIfUnusedFileScopedDecl(D))
1264 UnusedFileScopedDecls.push_back(D);
1265}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001266
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001267static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001268 if (D->isInvalidDecl())
1269 return false;
1270
Eli Friedmanc09e0552012-01-13 23:41:25 +00001271 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001272 return false;
John McCall67da35c2010-02-04 22:26:26 +00001273
Chris Lattnercab02a62011-02-17 20:34:02 +00001274 if (isa<LabelDecl>(D))
1275 return true;
1276
John McCall67da35c2010-02-04 22:26:26 +00001277 // White-list anything that isn't a local variable.
1278 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1279 !D->getDeclContext()->isFunctionOrMethod())
1280 return false;
1281
1282 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001283 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001284
1285 // White-list anything with an __attribute__((unused)) type.
1286 QualType Ty = VD->getType();
1287
1288 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001289 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001290 if (TT->getDecl()->hasAttr<UnusedAttr>())
1291 return false;
1292 }
1293
Douglas Gregor14f232e2010-05-08 23:05:03 +00001294 // If we failed to complete the type for some reason, or if the type is
1295 // dependent, don't diagnose the variable.
1296 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001297 return false;
1298
John McCallcef15822010-03-31 02:47:45 +00001299 if (const TagType *TT = Ty->getAs<TagType>()) {
1300 const TagDecl *Tag = TT->getDecl();
1301 if (Tag->hasAttr<UnusedAttr>())
1302 return false;
1303
1304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001305 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001306 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001307
1308 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001309 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1310 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001311 const CXXConstructExpr *Construct =
1312 dyn_cast<CXXConstructExpr>(Init);
1313 if (Construct && !Construct->isElidable()) {
1314 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001315 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001316 return false;
1317 }
1318 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001319 }
1320 }
John McCallcef15822010-03-31 02:47:45 +00001321
1322 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001323 }
1324
John McCall67da35c2010-02-04 22:26:26 +00001325 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001326}
1327
Anna Zaks964f4c62011-07-28 20:52:06 +00001328static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1329 FixItHint &Hint) {
1330 if (isa<LabelDecl>(D)) {
1331 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001332 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001333 if (AfterColon.isInvalid())
1334 return;
1335 Hint = FixItHint::CreateRemoval(CharSourceRange::
1336 getCharRange(D->getLocStart(), AfterColon));
1337 }
1338 return;
1339}
1340
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001341/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1342/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001343void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001344 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001345 if (!ShouldDiagnoseUnusedDecl(D))
1346 return;
1347
Anna Zaks964f4c62011-07-28 20:52:06 +00001348 GenerateFixForUnusedDecl(D, Context, Hint);
1349
Chris Lattnercab02a62011-02-17 20:34:02 +00001350 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001351 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001352 DiagID = diag::warn_unused_exception_param;
1353 else if (isa<LabelDecl>(D))
1354 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001355 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001356 DiagID = diag::warn_unused_variable;
1357
Anna Zaks964f4c62011-07-28 20:52:06 +00001358 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001359}
1360
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001361static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1362 // Verify that we have no forward references left. If so, there was a goto
1363 // or address of a label taken, but no definition of it. Label fwd
1364 // definitions are indicated with a null substmt.
1365 if (L->getStmt() == 0)
1366 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1367}
1368
Steve Naroffc62adb62007-10-09 22:01:59 +00001369void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001370 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001371 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001372 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001373
Chris Lattner302b4be2006-11-19 02:31:38 +00001374 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1375 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001376 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001377 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001378
Douglas Gregor91f84212008-12-11 16:49:14 +00001379 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1380 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001381
Douglas Gregor91f84212008-12-11 16:49:14 +00001382 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001383
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001384 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001385 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001386 DiagnoseUnusedDecl(D);
1387
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001388 // If this was a forward reference to a label, verify it was defined.
1389 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1390 CheckPoppedLabel(LD, *this);
1391
Douglas Gregor91f84212008-12-11 16:49:14 +00001392 // Remove this name from our lexical scope.
1393 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001394 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00001395 DiagnoseUnusedBackingIvarInAccessor(S);
Chris Lattner302b4be2006-11-19 02:31:38 +00001396}
1397
James Molloy6f8780b2012-02-29 10:24:19 +00001398void Sema::ActOnStartFunctionDeclarator() {
1399 ++InFunctionDeclarator;
1400}
1401
1402void Sema::ActOnEndFunctionDeclarator() {
1403 assert(InFunctionDeclarator);
1404 --InFunctionDeclarator;
1405}
1406
Douglas Gregor1c283312010-08-11 12:19:30 +00001407/// \brief Look for an Objective-C class in the translation unit.
1408///
1409/// \param Id The name of the Objective-C class we're looking for. If
1410/// typo-correction fixes this name, the Id will be updated
1411/// to the fixed name.
1412///
1413/// \param IdLoc The location of the name in the translation unit.
1414///
James Dennett41725122012-06-22 10:16:05 +00001415/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001416/// if there is no class with the given name.
1417///
1418/// \returns The declaration of the named Objective-C class, or NULL if the
1419/// class could not be found.
1420ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1421 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001422 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001423 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1424 // creation from this context.
1425 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1426
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001427 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001428 // Perform typo correction at the given location, but only if we
1429 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001430 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1431 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1432 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001433 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001434 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001435 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001436 Id = IDecl->getIdentifier();
1437 }
1438 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001439 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1440 // This routine must always return a class definition, if any.
1441 if (Def && Def->getDefinition())
1442 Def = Def->getDefinition();
1443 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001444}
1445
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001446/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1447/// from S, where a non-field would be declared. This routine copes
1448/// with the difference between C and C++ scoping rules in structs and
1449/// unions. For example, the following code is well-formed in C but
1450/// ill-formed in C++:
1451/// @code
1452/// struct S6 {
1453/// enum { BAR } e;
1454/// };
Mike Stump11289f42009-09-09 15:08:12 +00001455///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001456/// void test_S6() {
1457/// struct S6 a;
1458/// a.e = BAR;
1459/// }
1460/// @endcode
1461/// For the declaration of BAR, this routine will return a different
1462/// scope. The scope S will be the scope of the unnamed enumeration
1463/// within S6. In C++, this routine will return the scope associated
1464/// with S6, because the enumeration's scope is a transparent
1465/// context but structures can contain non-field names. In C, this
1466/// routine will return the translation unit scope, since the
1467/// enumeration's scope is a transparent context and structures cannot
1468/// contain non-field names.
1469Scope *Sema::getNonFieldDeclScope(Scope *S) {
1470 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001471 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001472 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001473 S = S->getParent();
1474 return S;
1475}
1476
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001477/// \brief Looks up the declaration of "struct objc_super" and
1478/// saves it for later use in building builtin declaration of
1479/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1480/// pre-existing declaration exists no action takes place.
1481static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1482 IdentifierInfo *II) {
1483 if (!II->isStr("objc_msgSendSuper"))
1484 return;
1485 ASTContext &Context = ThisSema.Context;
1486
1487 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1488 SourceLocation(), Sema::LookupTagName);
1489 ThisSema.LookupName(Result, S);
1490 if (Result.getResultKind() == LookupResult::Found)
1491 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1492 Context.setObjCSuperType(Context.getTagDeclType(TD));
1493}
1494
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001495/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1496/// file scope. lazily create a decl for it. ForRedeclaration is true
1497/// if we're creating this built-in in anticipation of redeclaring the
1498/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001499NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001500 Scope *S, bool ForRedeclaration,
1501 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001502 LookupPredefedObjCSuperType(*this, S, II);
1503
Chris Lattner9561a0b2007-01-28 08:20:04 +00001504 Builtin::ID BID = (Builtin::ID)bid;
1505
Chris Lattnerecd79c62009-06-14 00:45:47 +00001506 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001507 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001508 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001509 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001510 // Okay
1511 break;
1512
Mike Stump93246cc2009-07-28 23:57:15 +00001513 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001514 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001515 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001516 << Context.BuiltinInfo.GetName(BID);
1517 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001518
Mike Stump93246cc2009-07-28 23:57:15 +00001519 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001520 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001521 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001522 << Context.BuiltinInfo.GetName(BID);
1523 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001524
1525 case ASTContext::GE_Missing_ucontext:
1526 if (ForRedeclaration)
1527 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1528 << Context.BuiltinInfo.GetName(BID);
1529 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001530 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001531
1532 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1533 Diag(Loc, diag::ext_implicit_lib_function_decl)
1534 << Context.BuiltinInfo.GetName(BID)
1535 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001536 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001537 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001538 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001539 Diag(Loc, diag::note_please_include_header)
1540 << Context.BuiltinInfo.getHeaderName(BID)
1541 << Context.BuiltinInfo.GetName(BID);
1542 }
1543
Warren Hunt445d83e2013-11-01 23:46:51 +00001544 DeclContext *Parent = Context.getTranslationUnitDecl();
1545 if (getLangOpts().CPlusPlus) {
1546 LinkageSpecDecl *CLinkageDecl =
1547 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1548 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001549 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001550 Parent->addDecl(CLinkageDecl);
1551 Parent = CLinkageDecl;
1552 }
1553
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001554 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001555 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001556 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001557 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001558 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001559 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001560 New->setImplicit();
1561
Chris Lattner4dd27102008-05-05 22:18:14 +00001562 // Create Decl objects for each parameter, adding them to the
1563 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001564 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001565 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001566 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1567 ParmVarDecl *parm =
1568 ParmVarDecl::Create(Context, New, SourceLocation(),
1569 SourceLocation(), 0,
1570 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001571 SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001572 parm->setScopeInfo(0, i);
1573 Params.push_back(parm);
1574 }
David Blaikie9c70e042011-09-21 18:16:56 +00001575 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
1578 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001579 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001581 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001582 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1583 // relate Scopes to DeclContexts, and probably eliminate CurContext
1584 // entirely, but we're not there yet.
1585 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001586 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001587 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001588 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001589 return New;
1590}
1591
Douglas Gregor3552dab2013-01-09 00:47:56 +00001592/// \brief Filter out any previous declarations that the given declaration
1593/// should not consider because they are not permitted to conflict, e.g.,
1594/// because they come from hidden sub-modules and do not refer to the same
1595/// entity.
1596static void filterNonConflictingPreviousDecls(ASTContext &context,
1597 NamedDecl *decl,
1598 LookupResult &previous){
1599 // This is only interesting when modules are enabled.
1600 if (!context.getLangOpts().Modules)
1601 return;
1602
1603 // Empty sets are uninteresting.
1604 if (previous.empty())
1605 return;
1606
Douglas Gregor3552dab2013-01-09 00:47:56 +00001607 LookupResult::Filter filter = previous.makeFilter();
1608 while (filter.hasNext()) {
1609 NamedDecl *old = filter.next();
1610
1611 // Non-hidden declarations are never ignored.
1612 if (!old->isHidden())
1613 continue;
1614
Rafael Espindola3ae00052013-05-13 00:12:11 +00001615 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001616 filter.erase();
1617 }
1618
1619 filter.done();
1620}
1621
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001622bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1623 QualType OldType;
1624 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1625 OldType = OldTypedef->getUnderlyingType();
1626 else
1627 OldType = Context.getTypeDeclType(Old);
1628 QualType NewType = New->getUnderlyingType();
1629
Douglas Gregoraab36982012-01-11 22:33:48 +00001630 if (NewType->isVariablyModifiedType()) {
1631 // Must not redefine a typedef with a variably-modified type.
1632 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1633 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1634 << Kind << NewType;
1635 if (Old->getLocation().isValid())
1636 Diag(Old->getLocation(), diag::note_previous_definition);
1637 New->setInvalidDecl();
1638 return true;
1639 }
1640
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001641 if (OldType != NewType &&
1642 !OldType->isDependentType() &&
1643 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001644 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001645 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1646 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1647 << Kind << NewType << OldType;
1648 if (Old->getLocation().isValid())
1649 Diag(Old->getLocation(), diag::note_previous_definition);
1650 New->setInvalidDecl();
1651 return true;
1652 }
1653 return false;
1654}
1655
Richard Smithdda56e42011-04-15 14:24:37 +00001656/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001657/// same name and scope as a previous declaration 'Old'. Figure out
1658/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001659/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001660///
Richard Smithdda56e42011-04-15 14:24:37 +00001661void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001662 // If the new decl is known invalid already, don't bother doing any
1663 // merging checks.
1664 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001665
Steve Naroff44cfcb62008-09-09 14:32:20 +00001666 // Allow multiple definitions for ObjC built-in typedefs.
1667 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001668 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001669 const IdentifierInfo *TypeID = New->getIdentifier();
1670 switch (TypeID->getLength()) {
1671 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001672 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001673 {
1674 if (!TypeID->isStr("id"))
1675 break;
1676 QualType T = New->getUnderlyingType();
1677 if (!T->isPointerType())
1678 break;
1679 if (!T->isVoidPointerType()) {
1680 QualType PT = T->getAs<PointerType>()->getPointeeType();
1681 if (!PT->isStructureType())
1682 break;
1683 }
1684 Context.setObjCIdRedefinitionType(T);
1685 // Install the built-in type for 'id', ignoring the current definition.
1686 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1687 return;
1688 }
Chris Lattner66e32812008-11-20 05:41:43 +00001689 case 5:
1690 if (!TypeID->isStr("Class"))
1691 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001692 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001693 // Install the built-in type for 'Class', ignoring the current definition.
1694 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001695 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001696 case 3:
1697 if (!TypeID->isStr("SEL"))
1698 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001699 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001700 // Install the built-in type for 'SEL', ignoring the current definition.
1701 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001702 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001703 }
1704 // Fall through - the typedef name was not a builtin type.
1705 }
John McCall1f82f242009-11-18 22:49:29 +00001706
Douglas Gregorfb034662009-01-28 17:15:10 +00001707 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001708 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1709 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001710 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001711 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001712
1713 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001714 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001715 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001716
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001717 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001718 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001719
John McCall1f82f242009-11-18 22:49:29 +00001720 // If the old declaration is invalid, just give up here.
1721 if (Old->isInvalidDecl())
1722 return New->setInvalidDecl();
1723
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001724 // If the typedef types are not identical, reject them in all languages and
1725 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001726 if (isIncompatibleTypedef(Old, New))
1727 return;
Mike Stump11289f42009-09-09 15:08:12 +00001728
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001729 // The types match. Link up the redeclaration chain and merge attributes if
1730 // the old declaration was a typedef.
1731 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001732 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001733 mergeDeclAttributes(New, Old);
1734 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001735
David Blaikiebbafb8a2012-03-11 07:00:24 +00001736 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001737 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001738
David Blaikiebbafb8a2012-03-11 07:00:24 +00001739 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001740 // C++ [dcl.typedef]p2:
1741 // In a given non-class scope, a typedef specifier can be used to
1742 // redefine the name of any type declared in that scope to refer
1743 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001744 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001745 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001746
1747 // C++0x [dcl.typedef]p4:
1748 // In a given class scope, a typedef specifier can be used to redefine
1749 // any class-name declared in that scope that is not also a typedef-name
1750 // to refer to the type to which it already refers.
1751 //
1752 // This wording came in via DR424, which was a correction to the
1753 // wording in DR56, which accidentally banned code like:
1754 //
1755 // struct S {
1756 // typedef struct A { } A;
1757 // };
1758 //
1759 // in the C++03 standard. We implement the C++0x semantics, which
1760 // allow the above but disallow
1761 //
1762 // struct S {
1763 // typedef int I;
1764 // typedef int I;
1765 // };
1766 //
1767 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001768 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001769 return;
1770
Chris Lattner2581fc32009-04-17 22:04:20 +00001771 Diag(New->getLocation(), diag::err_redefinition)
1772 << New->getDeclName();
1773 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001774 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001775 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001776
Douglas Gregor7363fb02012-01-11 04:25:01 +00001777 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001778 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001779 return;
1780
Chris Lattner2581fc32009-04-17 22:04:20 +00001781 // If we have a redefinition of a typedef in C, emit a warning. This warning
1782 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001783 // -Wtypedef-redefinition. If either the original or the redefinition is
1784 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001785 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001786 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1787 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001788 return;
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattner2581fc32009-04-17 22:04:20 +00001790 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1791 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001792 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001793 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001794}
1795
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001796/// DeclhasAttr - returns true if decl Declaration already has the target
1797/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001798static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001799DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001800 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1801 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1802 // responsible for making sure they are consistent.
1803 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1804 if (AA)
1805 return false;
1806
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001807 // The following thread safety attributes can also be duplicated.
1808 switch (A->getKind()) {
1809 case attr::ExclusiveLocksRequired:
1810 case attr::SharedLocksRequired:
1811 case attr::LocksExcluded:
1812 case attr::ExclusiveLockFunction:
1813 case attr::SharedLockFunction:
1814 case attr::UnlockFunction:
1815 case attr::ExclusiveTrylockFunction:
1816 case attr::SharedTrylockFunction:
1817 case attr::GuardedBy:
1818 case attr::PtGuardedBy:
1819 case attr::AcquiredBefore:
1820 case attr::AcquiredAfter:
1821 return false;
DeLesley Hutchins6c6e8592012-10-12 21:49:04 +00001822 default:
1823 ;
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001824 }
1825
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001826 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001827 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001828 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1829 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001830 if (Ann) {
1831 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1832 return true;
1833 continue;
1834 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001835 // FIXME: Don't hardcode this check
1836 if (OA && isa<OwnershipAttr>(*i))
1837 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001838 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001839 }
Chris Lattner84966392008-03-03 03:28:21 +00001840
1841 return false;
1842}
1843
Richard Smithbc8caaf2013-02-22 04:55:39 +00001844static bool isAttributeTargetADefinition(Decl *D) {
1845 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1846 return VD->isThisDeclarationADefinition();
1847 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1848 return TD->isCompleteDefinition() || TD->isBeingDefined();
1849 return true;
1850}
1851
1852/// Merge alignment attributes from \p Old to \p New, taking into account the
1853/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1854///
1855/// \return \c true if any attributes were added to \p New.
1856static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1857 // Look for alignas attributes on Old, and pick out whichever attribute
1858 // specifies the strictest alignment requirement.
1859 AlignedAttr *OldAlignasAttr = 0;
1860 AlignedAttr *OldStrictestAlignAttr = 0;
1861 unsigned OldAlign = 0;
1862 for (specific_attr_iterator<AlignedAttr>
1863 I = Old->specific_attr_begin<AlignedAttr>(),
1864 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1865 // FIXME: We have no way of representing inherited dependent alignments
1866 // in a case like:
1867 // template<int A, int B> struct alignas(A) X;
1868 // template<int A, int B> struct alignas(B) X {};
1869 // For now, we just ignore any alignas attributes which are not on the
1870 // definition in such a case.
1871 if (I->isAlignmentDependent())
1872 return false;
1873
1874 if (I->isAlignas())
1875 OldAlignasAttr = *I;
1876
1877 unsigned Align = I->getAlignment(S.Context);
1878 if (Align > OldAlign) {
1879 OldAlign = Align;
1880 OldStrictestAlignAttr = *I;
1881 }
1882 }
1883
1884 // Look for alignas attributes on New.
1885 AlignedAttr *NewAlignasAttr = 0;
1886 unsigned NewAlign = 0;
1887 for (specific_attr_iterator<AlignedAttr>
1888 I = New->specific_attr_begin<AlignedAttr>(),
1889 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1890 if (I->isAlignmentDependent())
1891 return false;
1892
1893 if (I->isAlignas())
1894 NewAlignasAttr = *I;
1895
1896 unsigned Align = I->getAlignment(S.Context);
1897 if (Align > NewAlign)
1898 NewAlign = Align;
1899 }
1900
1901 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1902 // Both declarations have 'alignas' attributes. We require them to match.
1903 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1904 // fall short. (If two declarations both have alignas, they must both match
1905 // every definition, and so must match each other if there is a definition.)
1906
1907 // If either declaration only contains 'alignas(0)' specifiers, then it
1908 // specifies the natural alignment for the type.
1909 if (OldAlign == 0 || NewAlign == 0) {
1910 QualType Ty;
1911 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1912 Ty = VD->getType();
1913 else
1914 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1915
1916 if (OldAlign == 0)
1917 OldAlign = S.Context.getTypeAlign(Ty);
1918 if (NewAlign == 0)
1919 NewAlign = S.Context.getTypeAlign(Ty);
1920 }
1921
1922 if (OldAlign != NewAlign) {
1923 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1924 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1925 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1926 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1927 }
1928 }
1929
1930 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1931 // C++11 [dcl.align]p6:
1932 // if any declaration of an entity has an alignment-specifier,
1933 // every defining declaration of that entity shall specify an
1934 // equivalent alignment.
1935 // C11 6.7.5/7:
1936 // If the definition of an object does not have an alignment
1937 // specifier, any other declaration of that object shall also
1938 // have no alignment specifier.
1939 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1940 << OldAlignasAttr->isC11();
1941 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1942 << OldAlignasAttr->isC11();
1943 }
1944
1945 bool AnyAdded = false;
1946
1947 // Ensure we have an attribute representing the strictest alignment.
1948 if (OldAlign > NewAlign) {
1949 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1950 Clone->setInherited(true);
1951 New->addAttr(Clone);
1952 AnyAdded = true;
1953 }
1954
1955 // Ensure we have an alignas attribute if the old declaration had one.
1956 if (OldAlignasAttr && !NewAlignasAttr &&
1957 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1958 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1959 Clone->setInherited(true);
1960 New->addAttr(Clone);
1961 AnyAdded = true;
1962 }
1963
1964 return AnyAdded;
1965}
1966
1967static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1968 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001969 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001970 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001971 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001972 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1973 AA->getIntroduced(), AA->getDeprecated(),
1974 AA->getObsoleted(), AA->getUnavailable(),
1975 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001976 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001977 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1978 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1979 AttrSpellingListIndex);
1980 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1981 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1982 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001983 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001984 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1985 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001986 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001987 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1988 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001989 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001990 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1991 FA->getFormatIdx(), FA->getFirstArg(),
1992 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001993 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001994 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1995 AttrSpellingListIndex);
1996 else if (isa<AlignedAttr>(Attr))
1997 // AlignedAttrs are handled separately, because we need to handle all
1998 // such attributes on a declaration at the same time.
1999 NewAttr = 0;
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002000 else if (!DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002001 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00002002
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002003 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002004 NewAttr->setInherited(true);
2005 D->addAttr(NewAttr);
2006 return true;
2007 }
2008
2009 return false;
2010}
2011
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002012static const Decl *getDefinition(const Decl *D) {
2013 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00002014 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002015 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2016 const VarDecl *Def = VD->getDefinition();
2017 if (Def)
2018 return Def;
2019 return VD->getActingDefinition();
2020 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00002022 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002023 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00002024 return Def;
2025 }
2026 return NULL;
2027}
2028
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002029static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2030 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2031 I != E; ++I) {
2032 Attr *Attribute = *I;
2033 if (Attribute->getKind() == Kind)
2034 return true;
2035 }
2036 return false;
2037}
2038
2039/// checkNewAttributesAfterDef - If we already have a definition, check that
2040/// there are no new attributes in this declaration.
2041static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2042 if (!New->hasAttrs())
2043 return;
2044
2045 const Decl *Def = getDefinition(Old);
2046 if (!Def || Def == New)
2047 return;
2048
2049 AttrVec &NewAttributes = New->getAttrs();
2050 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2051 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002052
2053 if (isa<AliasAttr>(NewAttribute)) {
2054 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2055 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2056 else {
2057 VarDecl *VD = cast<VarDecl>(New);
2058 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2059 VarDecl::TentativeDefinition
2060 ? diag::err_alias_after_tentative
2061 : diag::err_redefinition;
2062 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2063 S.Diag(Def->getLocation(), diag::note_previous_definition);
2064 VD->setInvalidDecl();
2065 }
2066 ++I;
2067 continue;
2068 }
2069
2070 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2071 // Tentative definitions are only interesting for the alias check above.
2072 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2073 ++I;
2074 continue;
2075 }
2076 }
2077
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002078 if (hasAttribute(Def, NewAttribute->getKind())) {
2079 ++I;
2080 continue; // regular attr merging will take care of validating this.
2081 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002082
Richard Smithdebc59d2013-01-30 05:45:05 +00002083 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002084 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002085 ++I;
2086 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002087 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2088 if (AA->isAlignas()) {
2089 // C++11 [dcl.align]p6:
2090 // if any declaration of an entity has an alignment-specifier,
2091 // every defining declaration of that entity shall specify an
2092 // equivalent alignment.
2093 // C11 6.7.5/7:
2094 // If the definition of an object does not have an alignment
2095 // specifier, any other declaration of that object shall also
2096 // have no alignment specifier.
2097 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2098 << AA->isC11();
2099 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2100 << AA->isC11();
2101 NewAttributes.erase(NewAttributes.begin() + I);
2102 --E;
2103 continue;
2104 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002105 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002106
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002107 S.Diag(NewAttribute->getLocation(),
2108 diag::warn_attribute_precede_definition);
2109 S.Diag(Def->getLocation(), diag::note_previous_definition);
2110 NewAttributes.erase(NewAttributes.begin() + I);
2111 --E;
2112 }
2113}
2114
John McCallf79e87d2011-03-02 04:00:57 +00002115/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002116void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002117 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002118 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2119 UsedAttr *NewAttr = OldAttr->clone(Context);
2120 NewAttr->setInherited(true);
2121 New->addAttr(NewAttr);
2122 }
2123
Richard Smithe233fbf2013-01-28 22:42:45 +00002124 if (!Old->hasAttrs() && !New->hasAttrs())
2125 return;
2126
Rafael Espindola36191042012-05-18 01:47:00 +00002127 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002128 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002129
Douglas Gregor32c17572012-01-01 20:30:41 +00002130 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002131 return;
John McCallf79e87d2011-03-02 04:00:57 +00002132
Douglas Gregor32c17572012-01-01 20:30:41 +00002133 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002134
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002135 // Ensure that any moving of objects within the allocated map is done before
2136 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002137 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002138
Peter Collingbourneab8bc062011-01-21 02:08:36 +00002139 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00002140 i = Old->specific_attr_begin<InheritableAttr>(),
2141 e = Old->specific_attr_end<InheritableAttr>();
2142 i != e; ++i) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002143 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002144 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002145 if (isa<DeprecatedAttr>(*i) ||
2146 isa<UnavailableAttr>(*i) ||
2147 isa<AvailabilityAttr>(*i)) {
2148 switch (AMK) {
2149 case AMK_None:
2150 continue;
John McCalld2930c22011-07-22 02:45:48 +00002151
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002152 case AMK_Redeclaration:
2153 break;
2154
2155 case AMK_Override:
2156 Override = true;
2157 break;
2158 }
2159 }
2160
Rafael Espindolab0938852013-10-25 01:28:12 +00002161 // Already handled.
2162 if (isa<UsedAttr>(*i))
2163 continue;
2164
Richard Smithbc8caaf2013-02-22 04:55:39 +00002165 if (mergeDeclAttribute(*this, New, *i, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002166 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002167 }
John McCallf79e87d2011-03-02 04:00:57 +00002168
Richard Smithbc8caaf2013-02-22 04:55:39 +00002169 if (mergeAlignedAttrs(*this, New, Old))
2170 foundAny = true;
2171
Douglas Gregor32c17572012-01-01 20:30:41 +00002172 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002173}
2174
2175/// mergeParamDeclAttributes - Copy attributes from the old parameter
2176/// to the new one.
2177static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2178 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002179 Sema &S) {
2180 // C++11 [dcl.attr.depend]p2:
2181 // The first declaration of a function shall specify the
2182 // carries_dependency attribute for its declarator-id if any declaration
2183 // of the function specifies the carries_dependency attribute.
2184 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2185 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2186 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2187 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2188 // Find the first declaration of the parameter.
2189 // FIXME: Should we build redeclaration chains for function parameters?
2190 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002191 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002192 const ParmVarDecl *FirstVD =
2193 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2194 S.Diag(FirstVD->getLocation(),
2195 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2196 }
2197
John McCallf79e87d2011-03-02 04:00:57 +00002198 if (!oldDecl->hasAttrs())
2199 return;
2200
2201 bool foundAny = newDecl->hasAttrs();
2202
2203 // Ensure that any moving of objects within the allocated map is
2204 // done before we process them.
2205 if (!foundAny) newDecl->setAttrs(AttrVec());
2206
2207 for (specific_attr_iterator<InheritableParamAttr>
2208 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2209 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2210 if (!DeclHasAttr(newDecl, *i)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002211 InheritableAttr *newAttr =
2212 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002213 newAttr->setInherited(true);
2214 newDecl->addAttr(newAttr);
2215 foundAny = true;
2216 }
2217 }
2218
2219 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002220}
2221
Dan Gohman28ade552010-07-26 21:25:24 +00002222namespace {
2223
Douglas Gregora74a2972009-03-06 22:43:54 +00002224/// Used in MergeFunctionDecl to keep track of function parameters in
2225/// C.
2226struct GNUCompatibleParamWarning {
2227 ParmVarDecl *OldParm;
2228 ParmVarDecl *NewParm;
2229 QualType PromotedType;
2230};
2231
Dan Gohman28ade552010-07-26 21:25:24 +00002232}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002233
2234/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002235Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002236 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002237 if (Ctor->isDefaultConstructor())
2238 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002239
2240 if (Ctor->isCopyConstructor())
2241 return Sema::CXXCopyConstructor;
2242
2243 if (Ctor->isMoveConstructor())
2244 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002245 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002246 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002247 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002248 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002249 } else if (MD->isMoveAssignmentOperator()) {
2250 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002251 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002252
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002253 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002254}
2255
Sebastian Redl243d9052010-06-09 21:17:41 +00002256/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002257/// only extern inline functions can be redefined, and even then only in
2258/// GNU89 mode.
2259static bool canRedefineFunction(const FunctionDecl *FD,
2260 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002261 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2262 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002263 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002264 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002265}
2266
Reid Kleckner78af0702013-08-27 23:08:25 +00002267const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2268 const AttributedType *AT = T->getAs<AttributedType>();
2269 while (AT && !AT->isCallingConv())
2270 AT = AT->getModifiedType()->getAs<AttributedType>();
2271 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002272}
2273
Benjamin Kramer3e350262013-02-15 12:30:38 +00002274template <typename T>
2275static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002276 const DeclContext *DC = Old->getDeclContext();
2277 if (DC->isRecord())
2278 return false;
2279
2280 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002281 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002282 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002283 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002284 return true;
2285 return false;
2286}
2287
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002288/// MergeFunctionDecl - We just parsed a function 'New' from
2289/// declarator D which has the same name and scope as a previous
2290/// declaration 'Old'. Figure out how to resolve this situation,
2291/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292///
2293/// In C++, New and Old must be declarations that are not
2294/// overloaded. Use IsOverload to determine whether New and Old are
2295/// overloaded, and to select the Old declaration that New should be
2296/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002297///
2298/// Returns true if there was an error, false otherwise.
Richard Smith1c34fb72013-08-13 18:18:50 +00002299bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2300 bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002301 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002302 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002303 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002304 = dyn_cast<FunctionTemplateDecl>(OldD))
2305 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002306 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002307 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00002308 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002309 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002310 if (New->getFriendObjectKind()) {
2311 Diag(New->getLocation(), diag::err_using_decl_friend);
2312 Diag(Shadow->getTargetDecl()->getLocation(),
2313 diag::note_using_decl_target);
2314 Diag(Shadow->getUsingDecl()->getLocation(),
2315 diag::note_using_decl) << 0;
2316 return true;
2317 }
2318
John McCalle29c5cd2009-12-10 19:51:03 +00002319 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2320 Diag(Shadow->getTargetDecl()->getLocation(),
2321 diag::note_using_decl_target);
2322 Diag(Shadow->getUsingDecl()->getLocation(),
2323 diag::note_using_decl) << 0;
2324 return true;
2325 }
2326
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002327 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002328 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002329 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002330 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00002331 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002332
David Majnemerea5092a2013-07-07 23:49:50 +00002333 // If the old declaration is invalid, just give up here.
2334 if (Old->isInvalidDecl())
2335 return true;
2336
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002337 // Determine whether the previous declaration was a definition,
2338 // implicit declaration, or a declaration.
2339 diag::kind PrevDiag;
2340 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002341 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002342 else if (Old->isImplicit())
2343 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002344 else
Chris Lattner0369c572008-11-23 23:12:31 +00002345 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002346
Charles Davisfea48452010-02-18 02:00:42 +00002347 // Don't complain about this if we're in GNU89 mode and the old function
2348 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002349 // Don't complain about specializations. They are not supposed to have
2350 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002351 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002352 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002353 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002354 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002355 !canRedefineFunction(Old, getLangOpts())) {
2356 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002357 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2358 Diag(Old->getLocation(), PrevDiag);
2359 } else {
2360 Diag(New->getLocation(), diag::err_static_non_static) << New;
2361 Diag(Old->getLocation(), PrevDiag);
2362 return true;
2363 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002364 }
2365
Reid Kleckner78af0702013-08-27 23:08:25 +00002366
2367 // If a function is first declared with a calling convention, but is later
2368 // declared or defined without one, all following decls assume the calling
2369 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002370 //
John McCalla5f46fb2012-08-25 02:00:03 +00002371 // It's OK if a function is first declared without a calling convention,
2372 // but is later declared or defined with the default calling convention.
2373 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002374 // To test if either decl has an explicit calling convention, we look for
2375 // AttributedType sugar nodes on the type as written. If they are missing or
2376 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002377 //
2378 // Note also that we DO NOT return at this point, because we still have
2379 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002380 QualType OldQType = Context.getCanonicalType(Old->getType());
2381 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002382 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002383 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002384 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2385 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2386 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002387
Reid Kleckner78af0702013-08-27 23:08:25 +00002388 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002389 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002390 const FunctionType *FT =
2391 First->getType().getCanonicalType()->castAs<FunctionType>();
2392 FunctionType::ExtInfo FI = FT->getExtInfo();
2393 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2394 if (!NewCCExplicit) {
2395 // Inherit the CC from the previous declaration if it was specified
2396 // there but not here.
2397 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2398 RequiresAdjustment = true;
2399 } else {
2400 // Calling conventions aren't compatible, so complain.
2401 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2402 Diag(New->getLocation(), diag::err_cconv_change)
2403 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2404 << !FirstCCExplicit
2405 << (!FirstCCExplicit ? "" :
2406 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002407
Reid Kleckner78af0702013-08-27 23:08:25 +00002408 // Put the note on the first decl, since it is the one that matters.
2409 Diag(First->getLocation(), diag::note_previous_declaration);
2410 return true;
2411 }
John McCallcddbad02010-02-04 05:44:44 +00002412 }
2413
John McCallab26cfa2010-02-05 21:31:56 +00002414 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002415 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2416 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2417 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002418 }
2419
Douglas Gregor77e274f2010-06-18 21:30:25 +00002420 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002421 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2422 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2423 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002424 Diag(New->getLocation(), diag::err_regparm_mismatch)
2425 << NewType->getRegParmType()
2426 << OldType->getRegParmType();
2427 Diag(Old->getLocation(), diag::note_previous_declaration);
2428 return true;
2429 }
John McCall4f5019e2010-12-19 02:44:49 +00002430
2431 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2432 RequiresAdjustment = true;
2433 }
2434
Douglas Gregorf1404d72011-10-14 15:55:40 +00002435 // Merge ns_returns_retained attribute.
2436 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2437 if (NewTypeInfo.getProducesResult()) {
2438 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2439 Diag(Old->getLocation(), diag::note_previous_declaration);
2440 return true;
2441 }
2442
2443 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2444 RequiresAdjustment = true;
2445 }
2446
John McCall4f5019e2010-12-19 02:44:49 +00002447 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002448 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2449 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2450 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002451 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002452 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002453 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002454
2455 // If this redeclaration makes the function inline, we may need to add it to
2456 // UndefinedButUsed.
2457 if (!Old->isInlined() && New->isInlined() &&
2458 !New->hasAttr<GNUInlineAttr>() &&
2459 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2460 Old->isUsed(false) &&
2461 !Old->isDefined() && !New->isThisDeclarationADefinition())
2462 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2463 SourceLocation()));
2464
2465 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2466 // about it.
2467 if (New->hasAttr<GNUInlineAttr>() &&
2468 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2469 UndefinedButUsed.erase(Old->getCanonicalDecl());
2470 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002471
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002473 // (C++98 13.1p2):
2474 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002475 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002476 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002477
2478 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002479 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002480 // Redeclarations or specializations of a function or function template
2481 // with a declared return type that uses a placeholder type shall also
2482 // use that placeholder, not a deduced type.
2483 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2484 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2485 : OldType)->getResultType();
2486 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2487 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2488 : NewType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002489 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002490 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2491 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2492 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002493 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2494 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002495 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2496 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002497 if (New->isCXXClassMember() && New->isOutOfLine())
2498 Diag(New->getLocation(),
2499 diag::err_member_def_does_not_match_ret_type) << New;
2500 else
2501 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002502 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2503 return true;
2504 }
2505 else
2506 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002507 }
2508
Richard Smith2a7d4812013-05-04 07:00:32 +00002509 QualType OldReturnType = OldType->getResultType();
2510 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2511 if (OldReturnType != NewReturnType) {
2512 // If this function has a deduced return type and has already been
2513 // defined, copy the deduced value from the old declaration.
2514 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2515 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002516 New->setType(
2517 SubstAutoType(New->getType(),
2518 OldAT->isDependentType() ? Context.DependentTy
2519 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002520 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002521 SubstAutoType(NewQType,
2522 OldAT->isDependentType() ? Context.DependentTy
2523 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002524 }
2525 }
2526
2527 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2528 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002529 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002530 // Preserve triviality.
2531 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002532
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002533 // MSVC allows explicit template specialization at class scope:
2534 // 2 CXMethodDecls referring to the same function will be injected.
2535 // We don't want a redeclartion error.
2536 bool IsClassScopeExplicitSpecialization =
2537 OldMethod->isFunctionTemplateSpecialization() &&
2538 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002539 bool isFriend = NewMethod->getFriendObjectKind();
2540
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002541 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2542 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002543 // -- Member function declarations with the same name and the
2544 // same parameter types cannot be overloaded if any of them
2545 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002546 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002547 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2548 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2549 return true;
2550 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002551
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002552 // C++ [class.mem]p1:
2553 // [...] A member shall not be declared twice in the
2554 // member-specification, except that a nested class or member
2555 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002556 if (ActiveTemplateInstantiations.empty()) {
2557 unsigned NewDiag;
2558 if (isa<CXXConstructorDecl>(OldMethod))
2559 NewDiag = diag::err_constructor_redeclared;
2560 else if (isa<CXXDestructorDecl>(NewMethod))
2561 NewDiag = diag::err_destructor_redeclared;
2562 else if (isa<CXXConversionDecl>(NewMethod))
2563 NewDiag = diag::err_conv_function_redeclared;
2564 else
2565 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002566
Richard Smith57e7ff92012-07-13 04:12:04 +00002567 Diag(New->getLocation(), NewDiag);
2568 } else {
2569 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2570 << New << New->getType();
2571 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002572 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002573
2574 // Complain if this is an explicit declaration of a special
2575 // member that was initially declared implicitly.
2576 //
2577 // As an exception, it's okay to befriend such methods in order
2578 // to permit the implicit constructor/destructor/operator calls.
2579 } else if (OldMethod->isImplicit()) {
2580 if (isFriend) {
2581 NewMethod->setImplicit();
2582 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002583 Diag(NewMethod->getLocation(),
2584 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002585 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002586 return true;
2587 }
Richard Smith337a5a12012-06-08 01:30:54 +00002588 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002589 Diag(NewMethod->getLocation(),
2590 diag::err_definition_of_explicitly_defaulted_member)
2591 << getSpecialMember(OldMethod);
2592 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002593 }
2594 }
2595
Richard Smith10876ef2013-01-17 01:30:42 +00002596 // C++11 [dcl.attr.noreturn]p1:
2597 // The first declaration of a function shall specify the noreturn
2598 // attribute if any declaration of that function specifies the noreturn
2599 // attribute.
2600 if (New->hasAttr<CXX11NoReturnAttr>() &&
2601 !Old->hasAttr<CXX11NoReturnAttr>()) {
2602 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2603 diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002604 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002605 diag::note_noreturn_missing_first_decl);
2606 }
2607
Richard Smithe233fbf2013-01-28 22:42:45 +00002608 // C++11 [dcl.attr.depend]p2:
2609 // The first declaration of a function shall specify the
2610 // carries_dependency attribute for its declarator-id if any declaration
2611 // of the function specifies the carries_dependency attribute.
2612 if (New->hasAttr<CarriesDependencyAttr>() &&
2613 !Old->hasAttr<CarriesDependencyAttr>()) {
2614 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2615 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002616 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002617 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2618 }
2619
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002620 // (C++98 8.3.5p3):
2621 // All declarations for a function shall agree exactly in both the
2622 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002623 // We also want to respect all the extended bits except noreturn.
2624
2625 // noreturn should now match unless the old type info didn't have it.
2626 QualType OldQTypeForComparison = OldQType;
2627 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2628 assert(OldQType == QualType(OldType, 0));
2629 const FunctionType *OldTypeForComparison
2630 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2631 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2632 assert(OldQTypeForComparison.isCanonical());
2633 }
2634
Rafael Espindolaf4187652013-02-14 01:18:37 +00002635 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002636 // As a special case, retain the language linkage from previous
2637 // declarations of a friend function as an extension.
2638 //
2639 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2640 // and is useful because there's otherwise no way to specify language
2641 // linkage within class scope.
2642 //
2643 // Check cautiously as the friend object kind isn't yet complete.
2644 if (New->getFriendObjectKind() != Decl::FOK_None) {
2645 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2646 Diag(Old->getLocation(), PrevDiag);
2647 } else {
2648 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2649 Diag(Old->getLocation(), PrevDiag);
2650 return true;
2651 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002652 }
2653
John McCall4f5019e2010-12-19 02:44:49 +00002654 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002655 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002656
Richard Smith541b38b2013-09-20 01:15:31 +00002657 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2658 New->isLocalExternDecl()) {
2659 // It's OK if we couldn't merge types for a local function declaraton
2660 // if either the old or new type is dependent. We'll merge the types
2661 // when we instantiate the function.
2662 return false;
2663 }
2664
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002665 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002666 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002667
2668 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002669 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002670 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002671 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002672 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2673 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002674 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002675 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002676 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002677 // The old declaration provided a function prototype, but the
2678 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002679 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002680 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002681 OldProto->arg_type_end());
2682 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002683 ParamTypes,
John McCalldb40c7f2010-12-14 08:05:40 +00002684 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002685 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002686 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002687
2688 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002689 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002690 for (FunctionProtoType::arg_type_iterator
2691 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002692 ParamEnd = OldProto->arg_type_end();
2693 ParamType != ParamEnd; ++ParamType) {
2694 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002695 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002696 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002697 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002698 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002699 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002700 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002701 Param->setImplicit();
2702 Params.push_back(Param);
2703 }
2704
David Blaikie9c70e042011-09-21 18:16:56 +00002705 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002706 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002707
Richard Smith1c34fb72013-08-13 18:18:50 +00002708 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002709 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002710
Douglas Gregora74a2972009-03-06 22:43:54 +00002711 // GNU C permits a K&R definition to follow a prototype declaration
2712 // if the declared types of the parameters in the K&R definition
2713 // match the types in the prototype declaration, even when the
2714 // promoted types of the parameters from the K&R definition differ
2715 // from the types in the prototype. GCC then keeps the types from
2716 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002717 //
2718 // If a variadic prototype is followed by a non-variadic K&R definition,
2719 // the K&R definition becomes variadic. This is sort of an edge case, but
2720 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2721 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002722 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002723 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002724 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002725 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002726 SmallVector<QualType, 16> ArgTypes;
2727 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002728 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002729 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002730 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002731 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002732
Douglas Gregora74a2972009-03-06 22:43:54 +00002733 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002734 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2735 NewProto->getResultType());
2736 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002737 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002738 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002739 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2740 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002741 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002742 NewProto->getArgType(Idx))) {
2743 ArgTypes.push_back(NewParm->getType());
2744 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002745 NewParm->getType(),
2746 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002747 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002748 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2749 Warnings.push_back(Warn);
2750 ArgTypes.push_back(NewParm->getType());
2751 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002752 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002753 }
2754
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002755 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002756 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2757 Diag(Warnings[Warn].NewParm->getLocation(),
2758 diag::ext_param_promoted_not_compatible_with_prototype)
2759 << Warnings[Warn].PromotedType
2760 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002761 if (Warnings[Warn].OldParm->getLocation().isValid())
2762 Diag(Warnings[Warn].OldParm->getLocation(),
2763 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002764 }
2765
Richard Smith1c34fb72013-08-13 18:18:50 +00002766 if (MergeTypeWithOld)
2767 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2768 OldProto->getExtProtoInfo()));
2769 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002770 }
2771
2772 // Fall through to diagnose conflicting types.
2773 }
2774
John McCallad327cd2013-04-14 08:50:55 +00002775 // A function that has already been declared has been redeclared or
2776 // defined with a different type; show an appropriate diagnostic.
2777
2778 // If the previous declaration was an implicitly-generated builtin
2779 // declaration, then at the very least we should use a specialized note.
2780 unsigned BuiltinID;
2781 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2782 // If it's actually a library-defined builtin function like 'malloc'
2783 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002784 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002785 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2786 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2787 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002788
2789 // If this is a global redeclaration, just forget hereafter
2790 // about the "builtin-ness" of the function.
2791 //
2792 // Doing this for local extern declarations is problematic. If
2793 // the builtin declaration remains visible, a second invalid
2794 // local declaration will produce a hard error; if it doesn't
2795 // remain visible, a single bogus local redeclaration (which is
2796 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002797 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002798 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2799
Douglas Gregor893c2c92009-03-23 17:47:24 +00002800 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002801 }
Steve Naroff17832a42008-01-16 15:01:34 +00002802
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002803 PrevDiag = diag::note_previous_builtin_declaration;
2804 }
2805
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002806 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002807 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002808 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002809}
2810
Douglas Gregore62c0a42009-02-24 01:23:02 +00002811/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002812/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002813///
2814/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002815/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002816/// the new declaration, once we know that New is in fact a
2817/// redeclaration of Old.
2818///
2819/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002820bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002821 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002822 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002823 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002824
Douglas Gregore62c0a42009-02-24 01:23:02 +00002825 // Merge "pure" flag.
2826 if (Old->isPure())
2827 New->setPure();
2828
Rafael Espindolabefe1302012-11-25 14:07:59 +00002829 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002830 if (Old->getMostRecentDecl()->isUsed(false))
2831 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002832
John McCallf79e87d2011-03-02 04:00:57 +00002833 // Merge attributes from the parameters. These can mismatch with K&R
2834 // declarations.
2835 if (New->getNumParams() == Old->getNumParams())
2836 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2837 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002838 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002839
David Blaikiebbafb8a2012-03-11 07:00:24 +00002840 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002841 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002842
Rafael Espindola8778c282012-11-29 16:09:03 +00002843 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002844 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2845 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002846 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002847 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002848 New->setType(Merged);
2849
Douglas Gregore62c0a42009-02-24 01:23:02 +00002850 return false;
2851}
2852
John McCall31168b02011-06-15 23:02:42 +00002853
John McCallf79e87d2011-03-02 04:00:57 +00002854void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002855 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002856
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002857 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002858 AvailabilityMergeKind MergeKind =
2859 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2860 : AMK_Override;
2861 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002862
2863 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002864 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2865 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002866 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002867 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002868 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002869 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002870
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002871 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002872}
2873
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002874/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2875/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002876/// emitting diagnostics as appropriate.
2877///
2878/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002879/// to here in AddInitializerToDecl. We can't check them before the initializer
2880/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002881void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2882 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002883 if (New->isInvalidDecl() || Old->isInvalidDecl())
2884 return;
2885
2886 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002887 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002888 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002889 // We don't know what the new type is until the initializer is attached.
2890 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002891 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2892 // These could still be something that needs exception specs checked.
2893 return MergeVarDeclExceptionSpecs(New, Old);
2894 }
Richard Smith30482bc2011-02-20 03:19:35 +00002895 // C++ [basic.link]p10:
2896 // [...] the types specified by all declarations referring to a given
2897 // object or function shall be identical, except that declarations for an
2898 // array object can specify array types that differ by the presence or
2899 // absence of a major array bound (8.3.4).
2900 else if (Old->getType()->isIncompleteArrayType() &&
2901 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002902 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2903 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2904 if (Context.hasSameType(OldArray->getElementType(),
2905 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002906 MergedT = New->getType();
2907 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002908 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002909 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2910 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2911 if (Context.hasSameType(OldArray->getElementType(),
2912 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002913 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002914 } else if (New->getType()->isObjCObjectPointerType() &&
2915 Old->getType()->isObjCObjectPointerType()) {
2916 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2917 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002918 }
2919 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002920 // C 6.2.7p2:
2921 // All declarations that refer to the same object or function shall have
2922 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002923 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2924 }
2925 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002926 // It's OK if we couldn't merge types if either type is dependent, for a
2927 // block-scope variable. In other cases (static data members of class
2928 // templates, variable templates, ...), we require the types to be
2929 // equivalent.
2930 // FIXME: The C++ standard doesn't say anything about this.
2931 if ((New->getType()->isDependentType() ||
2932 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2933 // If the old type was dependent, we can't merge with it, so the new type
2934 // becomes dependent for now. We'll reproduce the original type when we
2935 // instantiate the TypeSourceInfo for the variable.
2936 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2937 New->setType(Context.DependentTy);
2938 return;
2939 }
2940
2941 // FIXME: Even if this merging succeeds, some other non-visible declaration
2942 // of this variable might have an incompatible type. For instance:
2943 //
2944 // extern int arr[];
2945 // void f() { extern int arr[2]; }
2946 // void g() { extern int arr[3]; }
2947 //
2948 // Neither C nor C++ requires a diagnostic for this, but we should still try
2949 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002950 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002951 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002952 Diag(Old->getLocation(), diag::note_previous_definition);
2953 return New->setInvalidDecl();
2954 }
John McCallb65e8fe2013-04-01 18:34:28 +00002955
2956 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002957 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002958 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002959 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002960}
2961
Richard Smith3c785782013-09-03 21:00:58 +00002962static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2963 LookupResult &Previous) {
2964 // C11 6.2.7p4:
2965 // For an identifier with internal or external linkage declared
2966 // in a scope in which a prior declaration of that identifier is
2967 // visible, if the prior declaration specifies internal or
2968 // external linkage, the type of the identifier at the later
2969 // declaration becomes the composite type.
2970 //
2971 // If the variable isn't visible, we do not merge with its type.
2972 if (Previous.isShadowed())
2973 return false;
2974
2975 if (S.getLangOpts().CPlusPlus) {
2976 // C++11 [dcl.array]p3:
2977 // If there is a preceding declaration of the entity in the same
2978 // scope in which the bound was specified, an omitted array bound
2979 // is taken to be the same as in that earlier declaration.
2980 return NewVD->isPreviousDeclInSameBlockScope() ||
2981 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2982 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2983 } else {
2984 // If the old declaration was function-local, don't merge with its
2985 // type unless we're in the same function.
2986 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2987 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2988 }
2989}
2990
Chris Lattner01564d92007-01-27 19:27:06 +00002991/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2992/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2993/// situation, merging decls or emitting diagnostics as appropriate.
2994///
Mike Stump11289f42009-09-09 15:08:12 +00002995/// Tentative definition rules (C99 6.9.2p2) are checked by
2996/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002997/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002998///
Richard Smith3c785782013-09-03 21:00:58 +00002999void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00003000 // If the new decl is already invalid, don't do any other checking.
3001 if (New->isInvalidDecl())
3002 return;
Mike Stump11289f42009-09-09 15:08:12 +00003003
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003004 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00003005 VarDecl *Old = 0;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003006 if (Previous.isSingleResult() &&
3007 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003008 if (New->getDescribedVarTemplate())
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003009 Old = Old->getDescribedVarTemplate() ? Old : 0;
3010 else
3011 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3012 }
3013 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003014 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003015 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003016 Diag(Previous.getRepresentativeDecl()->getLocation(),
3017 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003018 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003019 }
Chris Lattner84966392008-03-03 03:28:21 +00003020
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003021 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3022 return;
3023
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003024 // C++ [class.mem]p1:
3025 // A member shall not be declared twice in the member-specification [...]
3026 //
3027 // Here, we need only consider static data members.
3028 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3029 Diag(New->getLocation(), diag::err_duplicate_member)
3030 << New->getIdentifier();
3031 Diag(Old->getLocation(), diag::note_previous_declaration);
3032 New->setInvalidDecl();
3033 }
3034
Douglas Gregor32c17572012-01-01 20:30:41 +00003035 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003036 // Warn if an already-declared variable is made a weak_import in a subsequent
3037 // declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003038 if (New->getAttr<WeakImportAttr>() &&
3039 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003040 !Old->getAttr<WeakImportAttr>()) {
3041 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3042 Diag(Old->getLocation(), diag::note_previous_definition);
3043 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003044 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003045 }
Chris Lattner84966392008-03-03 03:28:21 +00003046
Richard Smith30482bc2011-02-20 03:19:35 +00003047 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003048 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3049
Richard Smith30482bc2011-02-20 03:19:35 +00003050 if (New->isInvalidDecl())
3051 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003052
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003053 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003054 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003055 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003056 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003057 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003058 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003059 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003060 }
Mike Stump11289f42009-09-09 15:08:12 +00003061 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003062 // For an identifier declared with the storage-class specifier
3063 // extern in a scope in which a prior declaration of that
3064 // identifier is visible,23) if the prior declaration specifies
3065 // internal or external linkage, the linkage of the identifier at
3066 // the later declaration is the same as the linkage specified at
3067 // the prior declaration. If no prior declaration is visible, or
3068 // if the prior declaration specifies no linkage, then the
3069 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003070 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003071 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003072 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003073 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003074 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003075 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003076 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003077 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003078 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003079
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003080 // Check if extern is followed by non-extern and vice-versa.
3081 if (New->hasExternalStorage() &&
3082 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3083 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3084 Diag(Old->getLocation(), diag::note_previous_definition);
3085 return New->setInvalidDecl();
3086 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003087 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3088 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003089 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3090 Diag(Old->getLocation(), diag::note_previous_definition);
3091 return New->setInvalidDecl();
3092 }
3093
Steve Naroffa5629372008-09-17 14:05:40 +00003094 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003095
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003096 // FIXME: The test for external storage here seems wrong? We still
3097 // need to check for mismatches.
3098 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003099 // Don't complain about out-of-line definitions of static members.
3100 !(Old->getLexicalDeclContext()->isRecord() &&
3101 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003102 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003103 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003104 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003105 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003106
Richard Smithfd3834f2013-04-13 02:43:54 +00003107 if (New->getTLSKind() != Old->getTLSKind()) {
3108 if (!Old->getTLSKind()) {
3109 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3110 Diag(Old->getLocation(), diag::note_previous_declaration);
3111 } else if (!New->getTLSKind()) {
3112 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3113 Diag(Old->getLocation(), diag::note_previous_declaration);
3114 } else {
3115 // Do not allow redeclaration to change the variable between requiring
3116 // static and dynamic initialization.
3117 // FIXME: GCC allows this, but uses the TLS keyword on the first
3118 // declaration to determine the kind. Do we need to be compatible here?
3119 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3120 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3121 Diag(Old->getLocation(), diag::note_previous_declaration);
3122 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003123 }
3124
Sebastian Redlf1842912010-02-02 18:35:11 +00003125 // C++ doesn't have tentative definitions, so go right ahead and check here.
3126 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003127 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003128 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003129 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003130 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003131 Diag(Def->getLocation(), diag::note_previous_definition);
3132 New->setInvalidDecl();
3133 return;
3134 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003135
Rafael Espindolaf4187652013-02-14 01:18:37 +00003136 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003137 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3138 Diag(Old->getLocation(), diag::note_previous_definition);
3139 New->setInvalidDecl();
3140 return;
3141 }
3142
Rafael Espindolabefe1302012-11-25 14:07:59 +00003143 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003144 if (Old->getMostRecentDecl()->isUsed(false))
3145 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003146
Douglas Gregor0760fa12009-03-10 23:43:53 +00003147 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003148 New->setPreviousDecl(Old);
John McCall401982f2010-01-20 21:53:11 +00003149
3150 // Inherit access appropriately.
3151 New->setAccess(Old->getAccess());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003152
3153 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3154 if (New->isStaticDataMember() && New->isOutOfLine())
3155 VTD->setAccess(New->getAccess());
3156 }
Chris Lattner01564d92007-01-27 19:27:06 +00003157}
3158
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003159/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3160/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003161Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003162 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003163 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003164}
3165
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003166static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003167 if (!S.Context.getLangOpts().CPlusPlus)
3168 return;
3169
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003170 if (isa<CXXRecordDecl>(Tag->getParent())) {
3171 // If this tag is the direct child of a class, number it if
3172 // it is anonymous.
3173 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3174 return;
3175 MangleNumberingContext &MCtx =
3176 S.Context.getManglingNumberContext(Tag->getParent());
3177 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3178 return;
3179 }
3180
3181 // If this tag isn't a direct child of a class, number it if it is local.
3182 Decl *ManglingContextDecl;
3183 if (MangleNumberingContext *MCtx =
3184 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3185 ManglingContextDecl)) {
3186 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3187 }
3188}
3189
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003190/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003191/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003192/// parameters to cope with template friend declarations.
3193Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3194 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003195 MultiTemplateParamsArg TemplateParams,
3196 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003197 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003198 TagDecl *Tag = 0;
3199 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3200 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003201 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003202 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003203 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003204 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003205
3206 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003207 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003208
John McCall07e91c02009-08-06 02:15:43 +00003209 // Note that the above type specs guarantee that the
3210 // type rep is a Decl, whereas in many of the others
3211 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003212 if (isa<TagDecl>(TagD))
3213 Tag = cast<TagDecl>(TagD);
3214 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3215 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003216 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003217
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003218 if (Tag) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003219 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003220 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003221 if (Tag->isInvalidDecl())
3222 return Tag;
3223 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003224
Nuno Lopese9823fa2009-12-17 11:35:26 +00003225 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3226 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3227 // or incomplete types shall not be restrict-qualified."
3228 if (TypeQuals & DeclSpec::TQ_restrict)
3229 Diag(DS.getRestrictSpecLoc(),
3230 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3231 << DS.getSourceRange();
3232 }
3233
Richard Smitha77a0a62011-08-15 21:04:07 +00003234 if (DS.isConstexprSpecified()) {
3235 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3236 // and definitions of functions and variables.
3237 if (Tag)
3238 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3239 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3240 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003241 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3242 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003243 else
3244 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3245 // Don't emit warnings after this error.
3246 return TagD;
3247 }
3248
Richard Smithb1402ae2013-03-18 22:52:47 +00003249 DiagnoseFunctionSpecifiers(DS);
3250
Douglas Gregor3dad8422009-09-26 06:47:28 +00003251 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003252 // If we're dealing with a decl but not a TagDecl, assume that
3253 // whatever routines created it handled the friendship aspect.
3254 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003255 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003256 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003257 }
John McCallaa017372011-03-22 23:00:04 +00003258
Richard Smithb1402ae2013-03-18 22:52:47 +00003259 CXXScopeSpec &SS = DS.getTypeSpecScope();
3260 bool IsExplicitSpecialization =
3261 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3262 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3263 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3264 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3265 // nested-name-specifier unless it is an explicit instantiation
3266 // or an explicit specialization.
3267 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3268 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3269 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3270 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3271 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3272 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3273 << SS.getRange();
3274 return 0;
3275 }
3276
3277 // Track whether this decl-specifier declares anything.
3278 bool DeclaresAnything = true;
3279
3280 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003281 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003282 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003283 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003284 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003285 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00003286 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003287
Richard Smithb1402ae2013-03-18 22:52:47 +00003288 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003289 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003290 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003291
Richard Smithb1402ae2013-03-18 22:52:47 +00003292 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003293 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003294 CurContext->isRecord() &&
3295 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3296 // Handle 2 kinds of anonymous struct:
3297 // struct STRUCT;
3298 // and
3299 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3300 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003301 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003302 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3303 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003304 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003305 << DS.getSourceRange();
3306 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3307 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003308 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003309
3310 // Skip all the checks below if we have a type error.
3311 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3312 (TagD && TagD->isInvalidDecl()))
3313 return TagD;
3314
3315 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003316 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3317 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3318 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003319 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3320 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003321
John McCallaa017372011-03-22 23:00:04 +00003322 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003323 // Customize diagnostic for a typedef missing a name.
3324 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003325 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003326 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003327 else
3328 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003329 }
Mike Stump11289f42009-09-09 15:08:12 +00003330
Richard Smithb1402ae2013-03-18 22:52:47 +00003331 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003332 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3333 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3334 << Tag->getTagKind()
3335 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3336
Richard Smithb1402ae2013-03-18 22:52:47 +00003337 ActOnDocumentableDecl(TagD);
3338
3339 // C 6.7/2:
3340 // A declaration [...] shall declare at least a declarator [...], a tag,
3341 // or the members of an enumeration.
3342 // C++ [dcl.dcl]p3:
3343 // [If there are no declarators], and except for the declaration of an
3344 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3345 // names into the program, or shall redeclare a name introduced by a
3346 // previous declaration.
3347 if (!DeclaresAnything) {
3348 // In C, we allow this as a (popular) extension / bug. Don't bother
3349 // producing further diagnostics for redundant qualifiers after this.
3350 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3351 return TagD;
3352 }
3353
3354 // C++ [dcl.stc]p1:
3355 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3356 // init-declarator-list of the declaration shall not be empty.
3357 // C++ [dcl.fct.spec]p1:
3358 // If a cv-qualifier appears in a decl-specifier-seq, the
3359 // init-declarator-list of the declaration shall not be empty.
3360 //
3361 // Spurious qualifiers here appear to be valid in C.
3362 unsigned DiagID = diag::warn_standalone_specifier;
3363 if (getLangOpts().CPlusPlus)
3364 DiagID = diag::ext_standalone_specifier;
3365
3366 // Note that a linkage-specification sets a storage class, but
3367 // 'extern "C" struct foo;' is actually valid and not theoretically
3368 // useless.
3369 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3370 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3371 Diag(DS.getStorageClassSpecLoc(), DiagID)
3372 << DeclSpec::getSpecifierName(SCS);
3373
Richard Smithb4a9e862013-04-12 22:46:28 +00003374 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3375 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3376 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003377 if (DS.getTypeQualifiers()) {
3378 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3379 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3380 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3381 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3382 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003383 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3384 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003385 }
3386
Eli Friedmane3217952011-12-17 00:36:09 +00003387 // Warn about ignored type attributes, for example:
3388 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003389 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003390 if (!DS.getAttributes().empty()) {
3391 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3392 if (TypeSpecType == DeclSpec::TST_class ||
3393 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003394 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003395 TypeSpecType == DeclSpec::TST_union ||
3396 TypeSpecType == DeclSpec::TST_enum) {
3397 AttributeList* attrs = DS.getAttributes().getList();
3398 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003399 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003400 << attrs->getName()
3401 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3402 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003403 TypeSpecType == DeclSpec::TST_union ? 2 :
3404 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003405 attrs = attrs->getNext();
3406 }
3407 }
3408 }
John McCallaa017372011-03-22 23:00:04 +00003409
John McCall48871652010-08-21 09:40:31 +00003410 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003411}
3412
John McCallea305ed2009-12-18 10:40:03 +00003413/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003414/// check if there's an existing declaration that can't be overloaded.
3415///
3416/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003417static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3418 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003419 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003420 DeclarationName Name,
3421 SourceLocation NameLoc,
3422 unsigned diagnostic) {
3423 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3424 Sema::ForRedeclaration);
3425 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003426
John McCallea305ed2009-12-18 10:40:03 +00003427 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003428 return false;
3429
3430 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003431 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003432 assert(PrevDecl && "Expected a non-null Decl");
3433
3434 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3435 return false;
John McCall1f82f242009-11-18 22:49:29 +00003436
John McCallea305ed2009-12-18 10:40:03 +00003437 SemaRef.Diag(NameLoc, diagnostic) << Name;
3438 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003439
3440 return true;
3441}
3442
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003443/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3444/// anonymous struct or union AnonRecord into the owning context Owner
3445/// and scope S. This routine will be invoked just after we realize
3446/// that an unnamed union or struct is actually an anonymous union or
3447/// struct, e.g.,
3448///
3449/// @code
3450/// union {
3451/// int i;
3452/// float f;
3453/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3454/// // f into the surrounding scope.x
3455/// @endcode
3456///
3457/// This routine is recursive, injecting the names of nested anonymous
3458/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003459static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003460 DeclContext *Owner,
3461 RecordDecl *AnonRecord,
3462 AccessSpecifier AS,
3463 SmallVectorImpl<NamedDecl *> &Chaining,
3464 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003465 unsigned diagKind
3466 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3467 : diag::err_anonymous_struct_member_redecl;
3468
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003469 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003470
3471 // Look every FieldDecl and IndirectFieldDecl with a name.
3472 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3473 DEnd = AnonRecord->decls_end();
3474 D != DEnd; ++D) {
3475 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3476 cast<NamedDecl>(*D)->getDeclName()) {
3477 ValueDecl *VD = cast<ValueDecl>(*D);
3478 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3479 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003480 // C++ [class.union]p2:
3481 // The names of the members of an anonymous union shall be
3482 // distinct from the names of any other entity in the
3483 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003484 Invalid = true;
3485 } else {
3486 // C++ [class.union]p2:
3487 // For the purpose of name lookup, after the anonymous union
3488 // definition, the members of the anonymous union are
3489 // considered to have been defined in the scope in which the
3490 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003491 unsigned OldChainingSize = Chaining.size();
3492 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3493 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3494 PE = IF->chain_end(); PI != PE; ++PI)
3495 Chaining.push_back(*PI);
3496 else
3497 Chaining.push_back(VD);
3498
Francois Pichet783dd6e2010-11-21 06:08:52 +00003499 assert(Chaining.size() >= 2);
3500 NamedDecl **NamedChain =
3501 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3502 for (unsigned i = 0; i < Chaining.size(); i++)
3503 NamedChain[i] = Chaining[i];
3504
3505 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003506 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3507 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003508 NamedChain, Chaining.size());
3509
3510 IndirectField->setAccess(AS);
3511 IndirectField->setImplicit();
3512 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003513
3514 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003515 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003516
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003517 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003518 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003519 }
3520 }
3521
3522 return Invalid;
3523}
3524
Douglas Gregorc4df4072010-04-19 22:54:31 +00003525/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3526/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003527/// illegal input values are mapped to SC_None.
3528static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003529StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3530 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3531 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3532 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003533 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003534 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003535 case DeclSpec::SCS_extern:
3536 if (DS.isExternInLinkageSpec())
3537 return SC_None;
3538 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003539 case DeclSpec::SCS_static: return SC_Static;
3540 case DeclSpec::SCS_auto: return SC_Auto;
3541 case DeclSpec::SCS_register: return SC_Register;
3542 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003543 // Illegal SCSs map to None: error reporting is up to the caller.
3544 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003545 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003546 }
3547 llvm_unreachable("unknown storage class specifier");
3548}
3549
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003550/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003551/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003552/// (C++ [class.union]) and a C11 feature; anonymous structures
3553/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003554Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3555 AccessSpecifier AS,
3556 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003557 DeclContext *Owner = Record->getDeclContext();
3558
3559 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003560 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003561 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003562 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003563 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003564 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003565 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003566
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003567 // C and C++ require different kinds of checks for anonymous
3568 // structs/unions.
3569 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003570 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003571 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003572 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003573 if (Record->isUnion()) {
3574 // C++ [class.union]p6:
3575 // Anonymous unions declared in a named namespace or in the
3576 // global namespace shall be declared static.
3577 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3578 (isa<TranslationUnitDecl>(Owner) ||
3579 (isa<NamespaceDecl>(Owner) &&
3580 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003581 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3582 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003583
3584 // Recover by adding 'static'.
3585 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3586 PrevSpec, DiagID);
3587 }
3588 // C++ [class.union]p6:
3589 // A storage class is not allowed in a declaration of an
3590 // anonymous union in a class scope.
3591 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3592 isa<RecordDecl>(Owner)) {
3593 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003594 diag::err_anonymous_union_with_storage_spec)
3595 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003596
3597 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003598 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3599 SourceLocation(),
David Blaikie0a8e8992011-10-19 22:43:29 +00003600 PrevSpec, DiagID);
3601 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003602 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003603
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003604 // Ignore const/volatile/restrict qualifiers.
3605 if (DS.getTypeQualifiers()) {
3606 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3607 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003608 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003609 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3610 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003611 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003612 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003613 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003614 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3615 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003616 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003617 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003618 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003619 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003620 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3621 Diag(DS.getAtomicSpecLoc(),
3622 diag::ext_anonymous_struct_union_qualified)
3623 << Record->isUnion() << "_Atomic"
3624 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003625
3626 DS.ClearTypeQualifiers();
3627 }
3628
Mike Stump11289f42009-09-09 15:08:12 +00003629 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003630 // The member-specification of an anonymous union shall only
3631 // define non-static data members. [Note: nested types and
3632 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003633 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3634 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003635 Mem != MemEnd; ++Mem) {
3636 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3637 // C++ [class.union]p3:
3638 // An anonymous union shall not have private or protected
3639 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003640 assert(FD->getAccess() != AS_none);
3641 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003642 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3643 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3644 Invalid = true;
3645 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003646
Alexis Hunt97ab5542011-05-16 22:41:40 +00003647 // C++ [class.union]p1
3648 // An object of a class with a non-trivial constructor, a non-trivial
3649 // copy constructor, a non-trivial destructor, or a non-trivial copy
3650 // assignment operator cannot be a member of a union, nor can an
3651 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003652 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003653 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003654 } else if ((*Mem)->isImplicit()) {
3655 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003656 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3657 // This is a type that showed up in an
3658 // elaborated-type-specifier inside the anonymous struct or
3659 // union, but which actually declares a type outside of the
3660 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003661 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3662 if (!MemRecord->isAnonymousStructOrUnion() &&
3663 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003664 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003665 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003666 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3667 << (int)Record->isUnion();
3668 else {
3669 // This is a nested type declaration.
3670 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3671 << (int)Record->isUnion();
3672 Invalid = true;
3673 }
Richard Smith254d2662013-01-28 00:54:05 +00003674 } else {
3675 // This is an anonymous type definition within another anonymous type.
3676 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3677 // not part of standard C++.
3678 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003679 diag::ext_anonymous_record_with_anonymous_type)
3680 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003681 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003682 } else if (isa<AccessSpecDecl>(*Mem)) {
3683 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003684 } else {
3685 // We have something that isn't a non-static data
3686 // member. Complain about it.
3687 unsigned DK = diag::err_anonymous_record_bad_member;
3688 if (isa<TypeDecl>(*Mem))
3689 DK = diag::err_anonymous_record_with_type;
3690 else if (isa<FunctionDecl>(*Mem))
3691 DK = diag::err_anonymous_record_with_function;
3692 else if (isa<VarDecl>(*Mem))
3693 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003694
3695 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003696 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003697 DK == diag::err_anonymous_record_with_type)
3698 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003699 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003700 else {
3701 Diag((*Mem)->getLocation(), DK)
3702 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003703 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003704 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003705 }
3706 }
Mike Stump11289f42009-09-09 15:08:12 +00003707 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003708
3709 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003710 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003711 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003712 Invalid = true;
3713 }
3714
John McCallfa2d6922009-10-22 23:31:08 +00003715 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003716 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003717 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003718 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003719
Mike Stump11289f42009-09-09 15:08:12 +00003720 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003721 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003722 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003723 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003724 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003725 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003726 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003727 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003728 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003729 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003730 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003731 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003732 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003733 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003734 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003735 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003736 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003737 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003738 // mutable can only appear on non-static class members, so it's always
3739 // an error here
3740 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3741 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003742 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003743 }
3744
Abramo Bagnaradff19302011-03-08 08:55:46 +00003745 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003746 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003747 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003748 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003749 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003750
3751 // Default-initialize the implicit variable. This initialization will be
3752 // trivial in almost all cases, except if a union member has an in-class
3753 // initializer:
3754 // union { int n = 0; };
3755 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003756 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003757 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003758
3759 // Add the anonymous struct/union object to the current
3760 // context. We'll be referencing this object when we refer to one of
3761 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003762 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00003763
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003764 // Inject the members of the anonymous struct/union into the owning
3765 // context and into the identifier resolver chain for name lookup
3766 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003767 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003768 Chain.push_back(Anon);
3769
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003770 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3771 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003772 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003773
3774 // Mark this as an anonymous struct/union type. Note that we do not
3775 // do this until after we have already checked and injected the
3776 // members of this anonymous struct/union type, because otherwise
3777 // the members could be injected twice: once by DeclContext when it
3778 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00003779 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003780 Record->setAnonymousStructOrUnion(true);
3781
3782 if (Invalid)
3783 Anon->setInvalidDecl();
3784
John McCall48871652010-08-21 09:40:31 +00003785 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003786}
3787
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003788/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3789/// Microsoft C anonymous structure.
3790/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3791/// Example:
3792///
3793/// struct A { int a; };
3794/// struct B { struct A; int b; };
3795///
3796/// void foo() {
3797/// B var;
3798/// var.a = 3;
3799/// }
3800///
3801Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3802 RecordDecl *Record) {
3803
3804 // If there is no Record, get the record via the typedef.
3805 if (!Record)
3806 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3807
3808 // Mock up a declarator.
3809 Declarator Dc(DS, Declarator::TypeNameContext);
3810 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3811 assert(TInfo && "couldn't build declarator info for anonymous struct");
3812
3813 // Create a declaration for this anonymous struct.
3814 NamedDecl* Anon = FieldDecl::Create(Context,
3815 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003816 DS.getLocStart(),
3817 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003818 /*IdentifierInfo=*/0,
3819 Context.getTypeDeclType(Record),
3820 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003821 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003822 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003823 Anon->setImplicit();
3824
3825 // Add the anonymous struct object to the current context.
3826 CurContext->addDecl(Anon);
3827
3828 // Inject the members of the anonymous struct into the current
3829 // context and into the identifier resolver chain for name lookup
3830 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003831 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003832 Chain.push_back(Anon);
3833
Nico Weberf8bb3de2012-02-01 00:41:00 +00003834 RecordDecl *RecordDef = Record->getDefinition();
3835 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3836 RecordDef, AS_none,
3837 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003838 Anon->setInvalidDecl();
3839
3840 return Anon;
3841}
Steve Naroff2fea1392007-09-02 02:04:30 +00003842
Douglas Gregor92751d42008-11-17 22:58:34 +00003843/// GetNameForDeclarator - Determine the full declaration name for the
3844/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003845DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003846 return GetNameFromUnqualifiedId(D.getName());
3847}
3848
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003849/// \brief Retrieves the declaration name from a parsed unqualified-id.
3850DeclarationNameInfo
3851Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3852 DeclarationNameInfo NameInfo;
3853 NameInfo.setLoc(Name.StartLocation);
3854
Douglas Gregor7861a802009-11-03 01:35:08 +00003855 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003856
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003857 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003858 case UnqualifiedId::IK_Identifier:
3859 NameInfo.setName(Name.Identifier);
3860 NameInfo.setLoc(Name.StartLocation);
3861 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003862
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003863 case UnqualifiedId::IK_OperatorFunctionId:
3864 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3865 Name.OperatorFunctionId.Operator));
3866 NameInfo.setLoc(Name.StartLocation);
3867 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3868 = Name.OperatorFunctionId.SymbolLocations[0];
3869 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3870 = Name.EndLocation.getRawEncoding();
3871 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003872
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003873 case UnqualifiedId::IK_LiteralOperatorId:
3874 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3875 Name.Identifier));
3876 NameInfo.setLoc(Name.StartLocation);
3877 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3878 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003879
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003880 case UnqualifiedId::IK_ConversionFunctionId: {
3881 TypeSourceInfo *TInfo;
3882 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3883 if (Ty.isNull())
3884 return DeclarationNameInfo();
3885 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3886 Context.getCanonicalType(Ty)));
3887 NameInfo.setLoc(Name.StartLocation);
3888 NameInfo.setNamedTypeInfo(TInfo);
3889 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003890 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003891
3892 case UnqualifiedId::IK_ConstructorName: {
3893 TypeSourceInfo *TInfo;
3894 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3895 if (Ty.isNull())
3896 return DeclarationNameInfo();
3897 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3898 Context.getCanonicalType(Ty)));
3899 NameInfo.setLoc(Name.StartLocation);
3900 NameInfo.setNamedTypeInfo(TInfo);
3901 return NameInfo;
3902 }
3903
3904 case UnqualifiedId::IK_ConstructorTemplateId: {
3905 // In well-formed code, we can only have a constructor
3906 // template-id that refers to the current context, so go there
3907 // to find the actual type being constructed.
3908 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3909 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3910 return DeclarationNameInfo();
3911
3912 // Determine the type of the class being constructed.
3913 QualType CurClassType = Context.getTypeDeclType(CurClass);
3914
3915 // FIXME: Check two things: that the template-id names the same type as
3916 // CurClassType, and that the template-id does not occur when the name
3917 // was qualified.
3918
3919 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3920 Context.getCanonicalType(CurClassType)));
3921 NameInfo.setLoc(Name.StartLocation);
3922 // FIXME: should we retrieve TypeSourceInfo?
3923 NameInfo.setNamedTypeInfo(0);
3924 return NameInfo;
3925 }
3926
3927 case UnqualifiedId::IK_DestructorName: {
3928 TypeSourceInfo *TInfo;
3929 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3930 if (Ty.isNull())
3931 return DeclarationNameInfo();
3932 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3933 Context.getCanonicalType(Ty)));
3934 NameInfo.setLoc(Name.StartLocation);
3935 NameInfo.setNamedTypeInfo(TInfo);
3936 return NameInfo;
3937 }
3938
3939 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003940 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003941 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3942 return Context.getNameForTemplate(TName, TNameLoc);
3943 }
3944
3945 } // switch (Name.getKind())
3946
David Blaikie83d382b2011-09-23 05:06:16 +00003947 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003948}
3949
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003950static QualType getCoreType(QualType Ty) {
3951 do {
3952 if (Ty->isPointerType() || Ty->isReferenceType())
3953 Ty = Ty->getPointeeType();
3954 else if (Ty->isArrayType())
3955 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3956 else
3957 return Ty.withoutLocalFastQualifiers();
3958 } while (true);
3959}
3960
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003961/// hasSimilarParameters - Determine whether the C++ functions Declaration
3962/// and Definition have "nearly" matching parameters. This heuristic is
3963/// used to improve diagnostics in the case where an out-of-line function
3964/// definition doesn't match any declaration within the class or namespace.
3965/// Also sets Params to the list of indices to the parameters that differ
3966/// between the declaration and the definition. If hasSimilarParameters
3967/// returns true and Params is empty, then all of the parameters match.
3968static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003969 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003970 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003971 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003972 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003973 if (Declaration->param_size() != Definition->param_size())
3974 return false;
3975 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3976 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3977 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3978
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003979 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003980 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003981 continue;
3982
3983 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3984 QualType DefParamBaseTy = getCoreType(DefParamTy);
3985 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3986 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3987
3988 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3989 (DeclTyName && DeclTyName == DefTyName))
3990 Params.push_back(Idx);
3991 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00003992 return false;
3993 }
3994
3995 return true;
3996}
3997
John McCall99b2fe52010-04-29 23:50:39 +00003998/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3999/// declarator needs to be rebuilt in the current instantiation.
4000/// Any bits of declarator which appear before the name are valid for
4001/// consideration here. That's specifically the type in the decl spec
4002/// and the base type in any member-pointer chunks.
4003static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4004 DeclarationName Name) {
4005 // The types we specifically need to rebuild are:
4006 // - typenames, typeofs, and decltypes
4007 // - types which will become injected class names
4008 // Of course, we also need to rebuild any type referencing such a
4009 // type. It's safest to just say "dependent", but we call out a
4010 // few cases here.
4011
4012 DeclSpec &DS = D.getMutableDeclSpec();
4013 switch (DS.getTypeSpecType()) {
4014 case DeclSpec::TST_typename:
4015 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004016 case DeclSpec::TST_underlyingType:
4017 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004018 // Grab the type from the parser.
4019 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004020 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004021 if (T.isNull() || !T->isDependentType()) break;
4022
4023 // Make sure there's a type source info. This isn't really much
4024 // of a waste; most dependent types should have type source info
4025 // attached already.
4026 if (!TSI)
4027 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4028
4029 // Rebuild the type in the current instantiation.
4030 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4031 if (!TSI) return true;
4032
4033 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004034 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4035 DS.UpdateTypeRep(LocType);
4036 break;
4037 }
4038
Richard Smith1620ebd2012-10-01 20:35:07 +00004039 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004040 case DeclSpec::TST_typeofExpr: {
4041 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004042 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004043 if (Result.isInvalid()) return true;
4044 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004045 break;
4046 }
4047
4048 default:
4049 // Nothing to do for these decl specs.
4050 break;
4051 }
4052
4053 // It doesn't matter what order we do this in.
4054 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4055 DeclaratorChunk &Chunk = D.getTypeObject(I);
4056
4057 // The only type information in the declarator which can come
4058 // before the declaration name is the base type of a member
4059 // pointer.
4060 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4061 continue;
4062
4063 // Rebuild the scope specifier in-place.
4064 CXXScopeSpec &SS = Chunk.Mem.Scope();
4065 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4066 return true;
4067 }
4068
4069 return false;
4070}
4071
Anders Carlsson1052fd72011-07-04 16:28:17 +00004072Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004073 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004074 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004075
4076 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004077 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004078 Dcl->setTopLevelDeclInObjCContainer();
4079
4080 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004081}
4082
Richard Smithdda56e42011-04-15 14:24:37 +00004083/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4084/// If T is the name of a class, then each of the following shall have a
4085/// name different from T:
4086/// - every static data member of class T;
4087/// - every member function of class T
4088/// - every member of class T that is itself a type;
4089/// \returns true if the declaration name violates these rules.
4090bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4091 DeclarationNameInfo NameInfo) {
4092 DeclarationName Name = NameInfo.getName();
4093
4094 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4095 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4096 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4097 return true;
4098 }
4099
4100 return false;
4101}
Douglas Gregor31feb332012-03-17 23:06:31 +00004102
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004103/// \brief Diagnose a declaration whose declarator-id has the given
4104/// nested-name-specifier.
4105///
4106/// \param SS The nested-name-specifier of the declarator-id.
4107///
4108/// \param DC The declaration context to which the nested-name-specifier
4109/// resolves.
4110///
4111/// \param Name The name of the entity being declared.
4112///
4113/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004114///
4115/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004116bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004117 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004118 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004119 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004120 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004121 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004122
4123 // If the user provided a superfluous scope specifier that refers back to the
4124 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004125 //
4126 // class X {
4127 // void X::f();
4128 // };
Richard Smitha2302242013-12-05 07:51:02 +00004129 //
4130 // Note, it was once ill-formed to give redundant qualification in all
4131 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004132 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004133 if (Cur->isRecord()) {
4134 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4135 : diag::err_member_extra_qualification)
4136 << Name << FixItHint::CreateRemoval(SS.getRange());
4137 SS.clear();
4138 } else {
4139 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4140 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004141 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004142 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004143
4144 // Check whether the qualifying scope encloses the scope of the original
4145 // declaration.
4146 if (!Cur->Encloses(DC)) {
4147 if (Cur->isRecord())
4148 Diag(Loc, diag::err_member_qualification)
4149 << Name << SS.getRange();
4150 else if (isa<TranslationUnitDecl>(DC))
4151 Diag(Loc, diag::err_invalid_declarator_global_scope)
4152 << Name << SS.getRange();
4153 else if (isa<FunctionDecl>(Cur))
4154 Diag(Loc, diag::err_invalid_declarator_in_function)
4155 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004156 else if (isa<BlockDecl>(Cur))
4157 Diag(Loc, diag::err_invalid_declarator_in_block)
4158 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004159 else
4160 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004161 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004162
Douglas Gregor31feb332012-03-17 23:06:31 +00004163 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004164 }
4165
4166 if (Cur->isRecord()) {
4167 // Cannot qualify members within a class.
4168 Diag(Loc, diag::err_member_qualification)
4169 << Name << SS.getRange();
4170 SS.clear();
4171
4172 // C++ constructors and destructors with incorrect scopes can break
4173 // our AST invariants by having the wrong underlying types. If
4174 // that's the case, then drop this declaration entirely.
4175 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4176 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4177 !Context.hasSameType(Name.getCXXNameType(),
4178 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4179 return true;
4180
4181 return false;
4182 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004183
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004184 // C++11 [dcl.meaning]p1:
4185 // [...] "The nested-name-specifier of the qualified declarator-id shall
4186 // not begin with a decltype-specifer"
4187 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4188 while (SpecLoc.getPrefix())
4189 SpecLoc = SpecLoc.getPrefix();
4190 if (dyn_cast_or_null<DecltypeType>(
4191 SpecLoc.getNestedNameSpecifier()->getAsType()))
4192 Diag(Loc, diag::err_decltype_in_declarator)
4193 << SpecLoc.getTypeLoc().getSourceRange();
4194
Douglas Gregor31feb332012-03-17 23:06:31 +00004195 return false;
4196}
4197
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004198NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4199 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004200 // TODO: consider using NameInfo for diagnostic.
4201 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4202 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004203
Chris Lattner02c04392007-07-25 00:24:17 +00004204 // All of these full declarators require an identifier. If it doesn't have
4205 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004206 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004207 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004208 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004209 diag::err_declarator_need_ident)
4210 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004211 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004212 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4213 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004215 // The scope passed in may not be a decl scope. Zip up the scope tree until
4216 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004217 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004218 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004219 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004220
John McCall99b2fe52010-04-29 23:50:39 +00004221 DeclContext *DC = CurContext;
4222 if (D.getCXXScopeSpec().isInvalid())
4223 D.setInvalidType();
4224 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004225 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4226 UPPC_DeclarationQualifier))
4227 return 0;
4228
John McCall99b2fe52010-04-29 23:50:39 +00004229 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4230 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004231 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004232 // If we could not compute the declaration context, it's because the
4233 // declaration context is dependent but does not refer to a class,
4234 // class template, or class template partial specialization. Complain
4235 // and return early, to avoid the coming semantic disaster.
4236 Diag(D.getIdentifierLoc(),
4237 diag::err_template_qualified_declarator_no_match)
4238 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4239 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004240 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004241 }
John McCall99b2fe52010-04-29 23:50:39 +00004242 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004243
John McCall99b2fe52010-04-29 23:50:39 +00004244 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004245 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004246 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004247
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004248 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4249 Diag(D.getIdentifierLoc(),
4250 diag::err_member_def_undefined_record)
4251 << Name << DC << D.getCXXScopeSpec().getRange();
4252 D.setInvalidType();
4253 } else if (!D.getDeclSpec().isFriendSpecified()) {
4254 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4255 Name, D.getIdentifierLoc())) {
4256 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004257 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004258
4259 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004260 }
John McCall99b2fe52010-04-29 23:50:39 +00004261 }
4262
4263 // Check whether we need to rebuild the type of the given
4264 // declaration in the current instantiation.
4265 if (EnteringContext && IsDependentContext &&
4266 TemplateParamLists.size() != 0) {
4267 ContextRAII SavedContext(*this, DC);
4268 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4269 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004270 }
4271 }
Richard Smithdda56e42011-04-15 14:24:37 +00004272
4273 if (DiagnoseClassNameShadow(DC, NameInfo))
4274 // If this is a typedef, we'll end up spewing multiple diagnostics.
4275 // Just return early; it's safer.
4276 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4277 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004278
John McCall8cb7bdf2010-06-04 23:28:52 +00004279 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4280 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004281
Douglas Gregor506bd562010-12-13 22:49:22 +00004282 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4283 UPPC_DeclarationType))
4284 D.setInvalidType();
4285
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004286 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004287 ForRedeclaration);
4288
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004289 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004290 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004291 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004292 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004293
4294 // If the declaration we're planning to build will be a function
4295 // or object with linkage, then look for another declaration with
4296 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004297 //
4298 // If the declaration we're planning to build will be declared with
4299 // external linkage in the translation unit, create any builtin with
4300 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004301 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4302 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004303 else if (CurContext->isFunctionOrMethod() &&
4304 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4305 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004306 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004307 CreateBuiltins =
4308 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4309 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4310 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4311 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004312
4313 if (IsLinkageLookup)
4314 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004315
Richard Smith1c34fb72013-08-13 18:18:50 +00004316 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004317 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004318 LookupQualifiedName(Previous, DC);
4319
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004320 // C++ [dcl.meaning]p1:
4321 // When the declarator-id is qualified, the declaration shall refer to a
4322 // previously declared member of the class or namespace to which the
4323 // qualifier refers (or, in the case of a namespace, of an element of the
4324 // inline namespace set of that namespace (7.3.1)) or to a specialization
4325 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004326 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004327 // Note that we already checked the context above, and that we do not have
4328 // enough information to make sure that Previous contains the declaration
4329 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004330 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004331 // class X {
4332 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004333 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004334 // };
4335 //
Douglas Gregorad590502008-12-15 23:53:10 +00004336 // void X::f(int) { } // ill-formed
4337 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004338 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004339 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004340 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004341
4342 // C++ [dcl.meaning]p1:
4343 // [...] the member shall not merely have been introduced by a
4344 // using-declaration in the scope of the class or namespace nominated by
4345 // the nested-name-specifier of the declarator-id.
4346 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004347 }
4348
John McCall1f82f242009-11-18 22:49:29 +00004349 if (Previous.isSingleResult() &&
4350 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004351 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004352 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004353 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4354 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004355
Douglas Gregor5101c242008-12-05 18:15:24 +00004356 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004357 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004358 }
4359
Douglas Gregor83a586e2008-04-13 21:07:44 +00004360 // In C++, the previous declaration we find might be a tag type
4361 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004362 // tag type. Note that this does does not apply if we're declaring a
4363 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004364 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00004365 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004366 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004367
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004368 // Check that there are no default arguments other than in the parameters
4369 // of a function declaration (C++ only).
4370 if (getLangOpts().CPlusPlus)
4371 CheckExtraCXXDefaultArguments(D);
4372
Nico Webercb4c7f42012-12-23 00:40:46 +00004373 NamedDecl *New;
4374
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004375 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004376 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004377 if (TemplateParamLists.size()) {
4378 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004379 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004380 }
Mike Stump11289f42009-09-09 15:08:12 +00004381
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004382 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004383 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004384 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004385 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004386 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004387 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004388 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4389 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004390 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004391
4392 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004393 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004394
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004395 // If this has an identifier and is not an invalid redeclaration or
4396 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004397 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004398 !(D.isRedeclaration() && New->isInvalidDecl())) {
4399 // Only make a locally-scoped extern declaration visible if it is the first
4400 // declaration of this entity. Qualified lookup for such an entity should
4401 // only find this declaration if there is no visible declaration of it.
4402 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4403 PushOnScopeChains(New, S, AddToContext);
4404 if (!AddToContext)
4405 CurContext->addHiddenDecl(New);
4406 }
Mike Stump11289f42009-09-09 15:08:12 +00004407
John McCall48871652010-08-21 09:40:31 +00004408 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004409}
4410
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004411/// Helper method to turn variable array types into constant array
4412/// types in certain situations which would otherwise be errors (for
4413/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004414static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4415 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004416 bool &SizeIsNegative,
4417 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004418 // This method tries to turn a variable array into a constant
4419 // array even when the size isn't an ICE. This is necessary
4420 // for compatibility with code that depends on gcc's buggy
4421 // constant expression folding, like struct {char x[(int)(char*)2];}
4422 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004423 Oversized = 0;
4424
4425 if (T->isDependentType())
4426 return QualType();
4427
John McCall8ccfcb52009-09-24 19:53:00 +00004428 QualifierCollector Qs;
4429 const Type *Ty = Qs.strip(T);
4430
4431 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004432 QualType Pointee = PTy->getPointeeType();
4433 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004434 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4435 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004436 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004437 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004438 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004439 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004440 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4441 QualType Inner = PTy->getInnerType();
4442 QualType FixedType =
4443 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4444 Oversized);
4445 if (FixedType.isNull()) return FixedType;
4446 FixedType = Context.getParenType(FixedType);
4447 return Qs.apply(Context, FixedType);
4448 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004449
4450 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004451 if (!VLATy)
4452 return QualType();
4453 // FIXME: We should probably handle this case
4454 if (VLATy->getElementType()->isVariablyModifiedType())
4455 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004456
Richard Smith42d3af92011-12-07 00:43:50 +00004457 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004458 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004459 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004460 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004461
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004462 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004463 if (Res.isSigned() && Res.isNegative()) {
4464 SizeIsNegative = true;
4465 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004466 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004467
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004468 // Check whether the array is too large to be addressed.
4469 unsigned ActiveSizeBits
4470 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4471 Res);
4472 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4473 Oversized = Res;
4474 return QualType();
4475 }
4476
4477 return Context.getConstantArrayType(VLATy->getElementType(),
4478 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004479}
4480
Abramo Bagnara341ab732012-11-08 14:44:42 +00004481static void
4482FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004483 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4484 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4485 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4486 DstPTL.getPointeeLoc());
4487 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004488 return;
4489 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004490 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4491 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4493 DstPTL.getInnerLoc());
4494 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4495 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004496 return;
4497 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004498 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4499 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4500 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4501 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004502 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004503 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4504 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4505 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004506}
4507
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004508/// Helper method to turn variable array types into constant array
4509/// types in certain situations which would otherwise be errors (for
4510/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004511static TypeSourceInfo*
4512TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4513 ASTContext &Context,
4514 bool &SizeIsNegative,
4515 llvm::APSInt &Oversized) {
4516 QualType FixedTy
4517 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4518 SizeIsNegative, Oversized);
4519 if (FixedTy.isNull())
4520 return 0;
4521 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4522 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4523 FixedTInfo->getTypeLoc());
4524 return FixedTInfo;
4525}
4526
Richard Smith78165b52013-01-10 23:43:47 +00004527/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004528/// that it can be found later for redeclarations. We include any extern "C"
4529/// declaration that is not visible in the translation unit here, not just
4530/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004531void
Richard Smith39b79682013-06-18 20:15:12 +00004532Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004533 if (!getLangOpts().CPlusPlus &&
4534 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4535 // Don't need to track declarations in the TU in C.
4536 return;
4537
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004538 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004539 // FIXME: There can be multiple such declarations if they are functions marked
4540 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004541 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004542}
4543
Richard Smith39b79682013-06-18 20:15:12 +00004544NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004545 if (ExternalSource) {
4546 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004547 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004548 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004549 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004550 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4551 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004552 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4553 if (Pos == LocallyScopedExternCDecls.end())
4554 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004555 }
4556 }
Richard Smith39b79682013-06-18 20:15:12 +00004557
4558 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004559 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004560}
4561
Eli Friedman574c7452009-04-07 19:37:57 +00004562/// \brief Diagnose function specifiers on a declaration of an identifier that
4563/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004564void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004565 // FIXME: We should probably indicate the identifier in question to avoid
4566 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004567 if (DS.isInlineSpecified())
4568 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004569 diag::err_inline_non_function);
4570
Richard Smithb1402ae2013-03-18 22:52:47 +00004571 if (DS.isVirtualSpecified())
4572 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004573 diag::err_virtual_non_function);
4574
Richard Smithb1402ae2013-03-18 22:52:47 +00004575 if (DS.isExplicitSpecified())
4576 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004577 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004578
Richard Smithb1402ae2013-03-18 22:52:47 +00004579 if (DS.isNoreturnSpecified())
4580 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004581 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004582}
4583
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004584NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004585Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004586 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004587 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4588 if (D.getCXXScopeSpec().isSet()) {
4589 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4590 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004591 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004592 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004593 DC = CurContext;
4594 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004595 }
4596
Richard Smithb1402ae2013-03-18 22:52:47 +00004597 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004598
Richard Smitha77a0a62011-08-15 21:04:07 +00004599 if (D.getDeclSpec().isConstexprSpecified())
4600 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4601 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004602
Douglas Gregord8f446f2010-07-13 06:37:01 +00004603 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4604 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4605 << D.getName().getSourceRange();
4606 return 0;
4607 }
4608
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004609 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004610 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004611
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004612 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004613 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004614
Richard Smith3f1b5d02011-05-05 21:57:07 +00004615 CheckTypedefForVariablyModifiedType(S, NewTD);
4616
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004617 bool Redeclaration = D.isRedeclaration();
4618 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4619 D.setRedeclaration(Redeclaration);
4620 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004621}
4622
Richard Smith3f1b5d02011-05-05 21:57:07 +00004623void
4624Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004625 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4626 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004627 // Note that variably modified types must be fixed before merging the decl so
4628 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004629 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4630 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004631 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004632 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004633
Chris Lattner9fecd742009-04-19 05:21:20 +00004634 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004635 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004636 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004637 TypeSourceInfo *FixedTInfo =
4638 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4639 SizeIsNegative,
4640 Oversized);
4641 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004642 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004643 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004644 } else {
4645 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004646 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004647 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004648 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004649 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004650 Diag(NewTD->getLocation(), diag::err_array_too_large)
4651 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004652 else
Richard Smithdda56e42011-04-15 14:24:37 +00004653 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004654 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004655 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004656 }
4657 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004658}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004659
Richard Smith3f1b5d02011-05-05 21:57:07 +00004660
4661/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4662/// declares a typedef-name, either using the 'typedef' type specifier or via
4663/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4664NamedDecl*
4665Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4666 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004667 // Merge the decl with the existing one if appropriate. If the decl is
4668 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004669 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4670 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004671 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004672 if (!Previous.empty()) {
4673 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004674 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004675 }
4676
Douglas Gregor27821ce2009-07-07 16:35:42 +00004677 // If this is the C FILE type, notify the AST context.
4678 if (IdentifierInfo *II = NewTD->getIdentifier())
4679 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004680 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004681 if (II->isStr("FILE"))
4682 Context.setFILEDecl(NewTD);
4683 else if (II->isStr("jmp_buf"))
4684 Context.setjmp_bufDecl(NewTD);
4685 else if (II->isStr("sigjmp_buf"))
4686 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004687 else if (II->isStr("ucontext_t"))
4688 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004689 }
4690
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004691 return NewTD;
4692}
4693
Douglas Gregor5d68a202009-02-24 19:23:27 +00004694/// \brief Determines whether the given declaration is an out-of-scope
4695/// previous declaration.
4696///
4697/// This routine should be invoked when name lookup has found a
4698/// previous declaration (PrevDecl) that is not in the scope where a
4699/// new declaration by the same name is being introduced. If the new
4700/// declaration occurs in a local scope, previous declarations with
4701/// linkage may still be considered previous declarations (C99
4702/// 6.2.2p4-5, C++ [basic.link]p6).
4703///
4704/// \param PrevDecl the previous declaration found by name
4705/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004706///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004707/// \param DC the context in which the new declaration is being
4708/// declared.
4709///
4710/// \returns true if PrevDecl is an out-of-scope previous declaration
4711/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004712static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004713isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4714 ASTContext &Context) {
4715 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004716 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004717
Douglas Gregoreddf4332009-02-24 20:03:32 +00004718 if (!PrevDecl->hasLinkage())
4719 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004720
David Blaikiebbafb8a2012-03-11 07:00:24 +00004721 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004722 // C++ [basic.link]p6:
4723 // If there is a visible declaration of an entity with linkage
4724 // having the same name and type, ignoring entities declared
4725 // outside the innermost enclosing namespace scope, the block
4726 // scope declaration declares that same entity and receives the
4727 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004728 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004729 if (!OuterContext->isFunctionOrMethod())
4730 // This rule only applies to block-scope declarations.
4731 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004732
4733 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4734 if (PrevOuterContext->isRecord())
4735 // We found a member function: ignore it.
4736 return false;
4737
4738 // Find the innermost enclosing namespace for the new and
4739 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004740 OuterContext = OuterContext->getEnclosingNamespaceContext();
4741 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004742
Douglas Gregorfcee9462010-08-27 22:55:10 +00004743 // The previous declaration is in a different namespace, so it
4744 // isn't the same function.
4745 if (!OuterContext->Equals(PrevOuterContext))
4746 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004747 }
4748
Douglas Gregor5d68a202009-02-24 19:23:27 +00004749 return true;
4750}
4751
John McCall3e11ebe2010-03-15 10:12:16 +00004752static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4753 CXXScopeSpec &SS = D.getCXXScopeSpec();
4754 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004755 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004756}
4757
John McCall31168b02011-06-15 23:02:42 +00004758bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4759 QualType type = decl->getType();
4760 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4761 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4762 // Various kinds of declaration aren't allowed to be __autoreleasing.
4763 unsigned kind = -1U;
4764 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4765 if (var->hasAttr<BlocksAttr>())
4766 kind = 0; // __block
4767 else if (!var->hasLocalStorage())
4768 kind = 1; // global
4769 } else if (isa<ObjCIvarDecl>(decl)) {
4770 kind = 3; // ivar
4771 } else if (isa<FieldDecl>(decl)) {
4772 kind = 2; // field
4773 }
4774
4775 if (kind != -1U) {
4776 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4777 << kind;
4778 }
4779 } else if (lifetime == Qualifiers::OCL_None) {
4780 // Try to infer lifetime.
4781 if (!type->isObjCLifetimeType())
4782 return false;
4783
4784 lifetime = type->getObjCARCImplicitLifetime();
4785 type = Context.getLifetimeQualifiedType(type, lifetime);
4786 decl->setType(type);
4787 }
4788
4789 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4790 // Thread-local variables cannot have lifetime.
4791 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004792 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004793 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004794 << var->getType();
4795 return true;
4796 }
4797 }
4798
4799 return false;
4800}
4801
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004802static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4803 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004804 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004805 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004806 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4807 ND.dropAttr<WeakAttr>();
4808 }
4809 }
4810 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004811 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004812 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4813 ND.dropAttr<WeakRefAttr>();
4814 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004815 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004816
4817 // 'selectany' only applies to externally visible varable declarations.
4818 // It does not apply to functions.
4819 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4820 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4821 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4822 ND.dropAttr<SelectAnyAttr>();
4823 }
4824 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004825}
4826
John McCallc87d9722013-04-02 02:48:58 +00004827/// Given that we are within the definition of the given function,
4828/// will that definition behave like C99's 'inline', where the
4829/// definition is discarded except for optimization purposes?
4830static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4831 // Try to avoid calling GetGVALinkageForFunction.
4832
4833 // All cases of this require the 'inline' keyword.
4834 if (!FD->isInlined()) return false;
4835
4836 // This is only possible in C++ with the gnu_inline attribute.
4837 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4838 return false;
4839
4840 // Okay, go ahead and call the relatively-more-expensive function.
4841
4842#ifndef NDEBUG
4843 // AST quite reasonably asserts that it's working on a function
4844 // definition. We don't really have a way to tell it that we're
4845 // currently defining the function, so just lie to it in +Asserts
4846 // builds. This is an awful hack.
4847 FD->setLazyBody(1);
4848#endif
4849
4850 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4851
4852#ifndef NDEBUG
4853 FD->setLazyBody(0);
4854#endif
4855
4856 return isC99Inline;
4857}
4858
Richard Smithac974a32013-06-30 09:48:50 +00004859/// Determine whether a variable is extern "C" prior to attaching
4860/// an initializer. We can't just call isExternC() here, because that
4861/// will also compute and cache whether the declaration is externally
4862/// visible, which might change when we attach the initializer.
4863///
4864/// This can only be used if the declaration is known to not be a
4865/// redeclaration of an internal linkage declaration.
4866///
4867/// For instance:
4868///
4869/// auto x = []{};
4870///
4871/// Attaching the initializer here makes this declaration not externally
4872/// visible, because its type has internal linkage.
4873///
4874/// FIXME: This is a hack.
4875template<typename T>
4876static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4877 if (S.getLangOpts().CPlusPlus) {
4878 // In C++, the overloadable attribute negates the effects of extern "C".
4879 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4880 return false;
4881 }
4882 return D->isExternC();
4883}
4884
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004885static bool shouldConsiderLinkage(const VarDecl *VD) {
4886 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4887 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004888 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004889 if (DC->isFileContext())
4890 return true;
4891 if (DC->isRecord())
4892 return false;
4893 llvm_unreachable("Unexpected context");
4894}
4895
4896static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4897 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4898 if (DC->isFileContext() || DC->isFunctionOrMethod())
4899 return true;
4900 if (DC->isRecord())
4901 return false;
4902 llvm_unreachable("Unexpected context");
4903}
4904
Richard Smith541b38b2013-09-20 01:15:31 +00004905/// Adjust the \c DeclContext for a function or variable that might be a
4906/// function-local external declaration.
4907bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4908 if (!DC->isFunctionOrMethod())
4909 return false;
4910
4911 // If this is a local extern function or variable declared within a function
4912 // template, don't add it into the enclosing namespace scope until it is
4913 // instantiated; it might have a dependent type right now.
4914 if (DC->isDependentContext())
4915 return true;
4916
4917 // C++11 [basic.link]p7:
4918 // When a block scope declaration of an entity with linkage is not found to
4919 // refer to some other declaration, then that entity is a member of the
4920 // innermost enclosing namespace.
4921 //
4922 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4923 // semantically-enclosing namespace, not a lexically-enclosing one.
4924 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4925 DC = DC->getParent();
4926 return true;
4927}
4928
Larisse Voufo39a1e502013-08-06 01:03:05 +00004929NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004930Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004931 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004932 MultiTemplateParamsArg TemplateParamLists,
4933 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004934 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004935 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004936
Douglas Gregorc4df4072010-04-19 22:54:31 +00004937 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004938 VarDecl::StorageClass SC =
4939 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004940
Richard Smith541b38b2013-09-20 01:15:31 +00004941 DeclContext *OriginalDC = DC;
4942 bool IsLocalExternDecl = SC == SC_Extern &&
4943 adjustContextForLocalExternDecl(DC);
4944
Richard Smith5990db62013-04-15 08:33:22 +00004945 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004946 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4947 // half array type (unless the cl_khr_fp16 extension is enabled).
4948 if (Context.getBaseElementType(R)->isHalfType()) {
4949 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4950 D.setInvalidType();
4951 }
4952 }
4953
Douglas Gregorc4df4072010-04-19 22:54:31 +00004954 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004955 // mutable can only appear on non-static class members, so it's always
4956 // an error here
4957 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004958 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004959 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004960 }
John McCallc87d9722013-04-02 02:48:58 +00004961
Richard Smithf2c9afc2013-06-17 01:34:01 +00004962 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4963 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4964 D.getDeclSpec().getStorageClassSpecLoc())) {
4965 // In C++11, the 'register' storage class specifier is deprecated.
4966 // Suppress the warning in system macros, it's used in macros in some
4967 // popular C system headers, such as in glibc's htonl() macro.
4968 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4969 diag::warn_deprecated_register)
4970 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4971 }
4972
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004973 IdentifierInfo *II = Name.getAsIdentifierInfo();
4974 if (!II) {
4975 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00004976 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004977 return 0;
4978 }
4979
Richard Smithb1402ae2013-03-18 22:52:47 +00004980 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00004981
Douglas Gregor212cab32009-03-11 20:22:50 +00004982 if (!DC->isRecord() && S->getFnParent() == 0) {
4983 // C99 6.9p2: The storage-class specifiers auto and register shall not
4984 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00004985 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004986 // If this is a register variable with an asm label specified, then this
4987 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00004988 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004989 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4990 else
4991 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004992 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004993 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004994 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00004995
David Blaikiebbafb8a2012-03-11 07:00:24 +00004996 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004997 // Set up the special work-group-local storage class for variables in the
4998 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00004999 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005000 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005001 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005002
Guy Benyei61054192013-02-07 10:55:47 +00005003 // OpenCL v1.2 s6.9.b p4:
5004 // The sampler type cannot be used with the __local and __global address
5005 // space qualifiers.
5006 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5007 R.getAddressSpace() == LangAS::opencl_global)) {
5008 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5009 }
5010
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005011 // OpenCL 1.2 spec, p6.9 r:
5012 // The event type cannot be used to declare a program scope variable.
5013 // The event type cannot be used with the __local, __constant and __global
5014 // address space qualifiers.
5015 if (R->isEventT()) {
5016 if (S->getParent() == 0) {
5017 Diag(D.getLocStart(), diag::err_event_t_global_var);
5018 D.setInvalidType();
5019 }
5020
5021 if (R.getAddressSpace()) {
5022 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5023 D.setInvalidType();
5024 }
5025 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005026 }
5027
Larisse Voufo39a1e502013-08-06 01:03:05 +00005028 bool IsExplicitSpecialization = false;
5029 bool IsVariableTemplateSpecialization = false;
5030 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005031 bool IsVariableTemplate = false;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005032 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005033 VarDecl *NewVD = 0;
5034 VarTemplateDecl *NewTemplate = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005035 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005036 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005037 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005038 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005039
5040 if (D.isInvalidType())
5041 NewVD->setInvalidDecl();
5042 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005043 bool Invalid = false;
5044
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005045 if (DC->isRecord() && !CurContext->isRecord()) {
5046 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005047 switch (SC) {
5048 case SC_None:
5049 break;
5050 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005051 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5052 diag::err_static_out_of_line)
5053 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005054 break;
5055 case SC_Auto:
5056 case SC_Register:
5057 case SC_Extern:
5058 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5059 // to names of variables declared in a block or to function parameters.
5060 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5061 // of class members
5062
5063 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5064 diag::err_storage_class_for_static_member)
5065 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5066 break;
5067 case SC_PrivateExtern:
5068 llvm_unreachable("C storage class in c++!");
5069 case SC_OpenCLWorkGroupLocal:
5070 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005071 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005072 }
5073
Richard Smith42973752012-02-16 20:41:22 +00005074 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005075 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5076 if (RD->isLocalClass())
5077 Diag(D.getIdentifierLoc(),
5078 diag::err_static_data_member_not_allowed_in_local_class)
5079 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005080
Richard Smith42973752012-02-16 20:41:22 +00005081 // C++98 [class.union]p1: If a union contains a static data member,
5082 // the program is ill-formed. C++11 drops this restriction.
5083 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005084 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005085 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005086 ? diag::warn_cxx98_compat_static_data_member_in_union
5087 : diag::ext_static_data_member_in_union) << Name;
5088 // We conservatively disallow static data members in anonymous structs.
5089 else if (!RD->getDeclName())
5090 Diag(D.getIdentifierLoc(),
5091 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005092 << Name << RD->isUnion();
5093 }
5094 }
5095
Larisse Voufo39a1e502013-08-06 01:03:05 +00005096 NamedDecl *PrevDecl = 0;
5097 if (Previous.begin() != Previous.end())
5098 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5099 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5100
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005101 // Match up the template parameter lists with the scope specifier, then
5102 // determine whether we have a template or a template specialization.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005103 TemplateParameterList *TemplateParams =
5104 MatchTemplateParametersToScopeSpecifier(
5105 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5106 D.getCXXScopeSpec(), TemplateParamLists,
5107 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005108 if (TemplateParams) {
5109 if (!TemplateParams->size() &&
5110 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005111 // There is an extraneous 'template<>' for this variable. Complain
5112 // about it, but allow the declaration of the variable.
5113 Diag(TemplateParams->getTemplateLoc(),
5114 diag::err_template_variable_noparams)
5115 << II
5116 << SourceRange(TemplateParams->getTemplateLoc(),
5117 TemplateParams->getRAngleLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005118 } else {
5119 // Only C++1y supports variable templates (N3651).
5120 Diag(D.getIdentifierLoc(),
5121 getLangOpts().CPlusPlus1y
5122 ? diag::warn_cxx11_compat_variable_template
5123 : diag::ext_variable_template);
5124
5125 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5126 // This is an explicit specialization or a partial specialization.
5127 // Check that we can declare a specialization here
5128
5129 IsVariableTemplateSpecialization = true;
5130 IsPartialSpecialization = TemplateParams->size() > 0;
5131
5132 } else { // if (TemplateParams->size() > 0)
Larisse Voufo21de36b2013-08-06 03:43:07 +00005133 // This is a template declaration.
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005134 IsVariableTemplate = true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005135
5136 // Check that we can declare a template here.
5137 if (CheckTemplateDeclScope(S, TemplateParams))
5138 return 0;
5139
5140 // If there is a previous declaration with the same name, check
5141 // whether this is a valid redeclaration.
5142 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5143 PrevDecl = PrevVarTemplate = 0;
5144
5145 if (PrevVarTemplate) {
5146 // Ensure that the template parameter lists are compatible.
5147 if (!TemplateParameterListsAreEqual(
5148 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5149 /*Complain=*/true, TPL_TemplateMatch))
5150 return 0;
5151 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5152 // Maybe we will complain about the shadowed template parameter.
5153 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5154
5155 // Just pretend that we didn't see the previous declaration.
5156 PrevDecl = 0;
5157 } else if (PrevDecl) {
5158 // C++ [temp]p5:
5159 // ... a template name declared in namespace scope or in class
5160 // scope shall be unique in that scope.
5161 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5162 << Name;
5163 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5164 return 0;
5165 }
5166
5167 // Check the template parameter list of this declaration, possibly
5168 // merging in the template parameter list from the previous variable
5169 // template declaration.
5170 if (CheckTemplateParameterList(
5171 TemplateParams,
5172 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5173 : 0,
5174 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5175 DC->isDependentContext())
5176 ? TPC_ClassTemplateMember
5177 : TPC_VarTemplate))
5178 Invalid = true;
5179
5180 if (D.getCXXScopeSpec().isSet()) {
5181 // If the name of the template was qualified, we must be defining
5182 // the template out-of-line.
5183 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5184 !PrevVarTemplate) {
Richard Smith114394f2013-08-09 04:35:01 +00005185 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5186 << Name << DC << /*IsDefinition*/true
5187 << D.getCXXScopeSpec().getRange();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005188 Invalid = true;
5189 }
5190 }
5191 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005192 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005193 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5194 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5195
5196 // We have encountered something that the user meant to be a
5197 // specialization (because it has explicitly-specified template
5198 // arguments) but that was not introduced with a "template<>" (or had
5199 // too few of them).
5200 // FIXME: Differentiate between attempts for explicit instantiations
5201 // (starting with "template") and the rest.
5202 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5203 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5204 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5205 "template<> ");
5206 IsVariableTemplateSpecialization = true;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005207 }
Mike Stump11289f42009-09-09 15:08:12 +00005208
Larisse Voufo39a1e502013-08-06 01:03:05 +00005209 if (IsVariableTemplateSpecialization) {
5210 if (!PrevVarTemplate) {
5211 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5212 << IsPartialSpecialization;
5213 return 0;
5214 }
5215
5216 SourceLocation TemplateKWLoc =
5217 TemplateParamLists.size() > 0
5218 ? TemplateParamLists[0]->getTemplateLoc()
5219 : SourceLocation();
5220 DeclResult Res = ActOnVarTemplateSpecialization(
5221 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5222 IsPartialSpecialization);
5223 if (Res.isInvalid())
5224 return 0;
5225 NewVD = cast<VarDecl>(Res.get());
5226 AddToScope = false;
5227 } else
5228 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5229 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005230
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005231 // If this is supposed to be a variable template, create it as such.
5232 if (IsVariableTemplate) {
5233 NewTemplate =
5234 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5235 TemplateParams, NewVD, PrevVarTemplate);
5236 NewVD->setDescribedVarTemplate(NewTemplate);
5237 }
5238
Richard Smithb2bc2e62011-02-21 20:05:19 +00005239 // If this decl has an auto type in need of deduction, make a note of the
5240 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005241 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005242 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005243
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005244 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005245 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005246 if (NewTemplate)
5247 NewTemplate->setInvalidDecl();
5248 }
Mike Stump11289f42009-09-09 15:08:12 +00005249
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005250 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005251
Larisse Voufo39a1e502013-08-06 01:03:05 +00005252 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5253 if (TemplateParams && TemplateParamLists.size() > 1 &&
5254 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5255 NewVD->setTemplateParameterListsInfo(
5256 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5257 } else if (IsVariableTemplateSpecialization ||
5258 (!TemplateParams && TemplateParamLists.size() > 0 &&
5259 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005260 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00005261 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005262 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005263 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005264
Richard Smith6331c402012-02-13 22:16:19 +00005265 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005266 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005267 }
5268
Douglas Gregor41866812011-09-12 18:37:38 +00005269 // Set the lexical context. If the declarator has a C++ scope specifier, the
5270 // lexical context will be different from the semantic context.
5271 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005272 if (NewTemplate)
5273 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005274
Richard Smith541b38b2013-09-20 01:15:31 +00005275 if (IsLocalExternDecl)
5276 NewVD->setLocalExternDecl();
5277
Richard Smithb4a9e862013-04-12 22:46:28 +00005278 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005279 if (NewVD->hasLocalStorage()) {
5280 // C++11 [dcl.stc]p4:
5281 // When thread_local is applied to a variable of block scope the
5282 // storage-class-specifier static is implied if it does not appear
5283 // explicitly.
5284 // Core issue: 'static' is not implied if the variable is declared
5285 // 'extern'.
5286 if (SCSpec == DeclSpec::SCS_unspecified &&
5287 TSCS == DeclSpec::TSCS_thread_local &&
5288 DC->isFunctionOrMethod())
5289 NewVD->setTSCSpec(TSCS);
5290 else
5291 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5292 diag::err_thread_non_global)
5293 << DeclSpec::getSpecifierName(TSCS);
5294 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005295 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5296 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005297 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005298 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005299 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005300
John McCallc87d9722013-04-02 02:48:58 +00005301 // C99 6.7.4p3
5302 // An inline definition of a function with external linkage shall
5303 // not contain a definition of a modifiable object with static or
5304 // thread storage duration...
5305 // We only apply this when the function is required to be defined
5306 // elsewhere, i.e. when the function is not 'extern inline'. Note
5307 // that a local variable with thread storage duration still has to
5308 // be marked 'static'. Also note that it's possible to get these
5309 // semantics in C++ using __attribute__((gnu_inline)).
5310 if (SC == SC_Static && S->getFnParent() != 0 &&
5311 !NewVD->getType().isConstQualified()) {
5312 FunctionDecl *CurFD = getCurFunctionDecl();
5313 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5314 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5315 diag::warn_static_local_in_extern_inline);
5316 MaybeSuggestAddingStaticToDecl(CurFD);
5317 }
5318 }
5319
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005320 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005321 if (IsVariableTemplateSpecialization)
5322 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5323 << (IsPartialSpecialization ? 1 : 0)
5324 << FixItHint::CreateRemoval(
5325 D.getDeclSpec().getModulePrivateSpecLoc());
5326 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005327 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5328 << 2
5329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005330 else if (NewVD->hasLocalStorage())
5331 Diag(NewVD->getLocation(), diag::err_module_private_local)
5332 << 0 << NewVD->getDeclName()
5333 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5334 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005335 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005336 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005337 if (NewTemplate)
5338 NewTemplate->setModulePrivate();
5339 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005340 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005341
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005342 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005343 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005344
Richard Smith848e1f12013-02-01 08:12:08 +00005345 if (NewVD->hasAttrs())
5346 CheckAlignasUnderalignment(NewVD);
5347
Peter Collingbournec6b08572012-08-28 20:37:50 +00005348 if (getLangOpts().CUDA) {
5349 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5350 // storage [duration]."
5351 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005352 (NewVD->hasAttr<CUDASharedAttr>() ||
5353 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005354 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005355 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005356 }
5357
John McCall31168b02011-06-15 23:02:42 +00005358 // In auto-retain/release, infer strong retension for variables of
5359 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005360 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005361 NewVD->setInvalidDecl();
5362
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005363 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005364 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005365 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005366 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005367 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005368 if (S->getFnParent() != 0) {
5369 switch (SC) {
5370 case SC_None:
5371 case SC_Auto:
5372 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5373 break;
5374 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005375 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005376 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5377 break;
5378 case SC_Static:
5379 case SC_Extern:
5380 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005381 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005382 break;
5383 }
5384 }
5385
5386 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00005387 Context, Label));
David Chisnall0867d9c2012-02-18 16:12:34 +00005388 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5389 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5390 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5391 if (I != ExtnameUndeclaredIdentifiers.end()) {
5392 NewVD->addAttr(I->second);
5393 ExtnameUndeclaredIdentifiers.erase(I);
5394 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005395 }
5396
John McCalla2a3f7d2010-03-16 21:48:18 +00005397 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005398 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005399 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005400
John McCall1f82f242009-11-18 22:49:29 +00005401 // Don't consider existing declarations that are in a different
5402 // scope and are out-of-semantic-context declarations (if the new
5403 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005404 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5405 D.getCXXScopeSpec().isNotEmpty() ||
5406 IsExplicitSpecialization ||
5407 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005408
Richard Smith1c34fb72013-08-13 18:18:50 +00005409 // Check whether the previous declaration is in the same block scope. This
5410 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5411 if (getLangOpts().CPlusPlus &&
5412 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5413 NewVD->setPreviousDeclInSameBlockScope(
5414 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005415 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005416
David Blaikiebbafb8a2012-03-11 07:00:24 +00005417 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005418 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5419 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005420 // Merge the decl with the existing one if appropriate.
5421 if (!Previous.empty()) {
5422 if (Previous.isSingleResult() &&
5423 isa<FieldDecl>(Previous.getFoundDecl()) &&
5424 D.getCXXScopeSpec().isSet()) {
5425 // The user tried to define a non-static data member
5426 // out-of-line (C++ [dcl.meaning]p1).
5427 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5428 << D.getCXXScopeSpec().getRange();
5429 Previous.clear();
5430 NewVD->setInvalidDecl();
5431 }
5432 } else if (D.getCXXScopeSpec().isSet()) {
5433 // No previous declaration in the qualifying scope.
5434 Diag(D.getIdentifierLoc(), diag::err_no_member)
5435 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005436 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005437 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005438 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005439
Larisse Voufo39a1e502013-08-06 01:03:05 +00005440 if (!IsVariableTemplateSpecialization) {
5441 if (PrevVarTemplate) {
5442 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5443 LookupOrdinaryName, ForRedeclaration);
5444 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005445 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005446 } else
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005447 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005448 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005449
5450 // This is an explicit specialization of a static data member. Check it.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005451 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005452 CheckMemberSpecialization(NewVD, Previous))
5453 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005454 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005455
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005456 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005457 checkAttributesAfterMerging(*this, *NewVD);
5458
Richard Smithac974a32013-06-30 09:48:50 +00005459 // If this is the first declaration of an extern C variable, update
5460 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005461 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005462 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005463 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005464
Reid Klecknerd8110b62013-09-10 20:14:30 +00005465 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005466 Decl *ManglingContextDecl;
5467 if (MangleNumberingContext *MCtx =
5468 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5469 ManglingContextDecl)) {
5470 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5471 }
5472 }
5473
Larisse Voufo39a1e502013-08-06 01:03:05 +00005474 // If we are providing an explicit specialization of a static variable
5475 // template, make a note of that.
5476 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo4cda4612013-08-22 00:28:27 +00005477 PrevVarTemplate->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005478
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005479 if (NewTemplate) {
5480 ActOnDocumentableDecl(NewTemplate);
5481 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005482 }
5483
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005484 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005485}
5486
John McCalldf8b37c2010-03-22 09:20:08 +00005487/// \brief Diagnose variable or built-in function shadowing. Implements
5488/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005489///
John McCalldf8b37c2010-03-22 09:20:08 +00005490/// This method is called whenever a VarDecl is added to a "useful"
5491/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005492///
John McCall2d8c7602010-03-20 04:12:52 +00005493/// \param S the scope in which the shadowing name is being declared
5494/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005495///
John McCalldf8b37c2010-03-22 09:20:08 +00005496void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005497 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005498 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005499 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005500 return;
5501
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005502 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005503 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005504 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005505
5506 DeclContext *NewDC = D->getDeclContext();
5507
John McCall2d8c7602010-03-20 04:12:52 +00005508 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005509 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005510 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005511
John McCalla2a3f7d2010-03-16 21:48:18 +00005512 NamedDecl* ShadowedDecl = R.getFoundDecl();
5513 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5514 return;
5515
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005516 // Fields are not shadowed by variables in C++ static methods.
5517 if (isa<FieldDecl>(ShadowedDecl))
5518 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5519 if (MD->isStatic())
5520 return;
5521
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005522 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5523 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005524 // For shadowing external vars, make sure that we point to the global
5525 // declaration, not a locally scoped extern declaration.
5526 for (VarDecl::redecl_iterator
5527 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5528 I != E; ++I)
5529 if (I->isFileVarDecl()) {
5530 ShadowedDecl = *I;
5531 break;
5532 }
5533 }
5534
5535 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5536
John McCall2d8c7602010-03-20 04:12:52 +00005537 // Only warn about certain kinds of shadowing for class members.
5538 if (NewDC && NewDC->isRecord()) {
5539 // In particular, don't warn about shadowing non-class members.
5540 if (!OldDC->isRecord())
5541 return;
5542
5543 // TODO: should we warn about static data members shadowing
5544 // static data members from base classes?
5545
5546 // TODO: don't diagnose for inaccessible shadowed members.
5547 // This is hard to do perfectly because we might friend the
5548 // shadowing context, but that's just a false negative.
5549 }
5550
5551 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005552 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005553 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005554 if (isa<FieldDecl>(ShadowedDecl))
5555 Kind = 3; // field
5556 else
5557 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005558 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005559 Kind = 1; // global
5560 else
5561 Kind = 0; // local
5562
John McCall2d8c7602010-03-20 04:12:52 +00005563 DeclarationName Name = R.getLookupName();
5564
John McCalla2a3f7d2010-03-16 21:48:18 +00005565 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00005566 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005567 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5568}
5569
John McCalldf8b37c2010-03-22 09:20:08 +00005570/// \brief Check -Wshadow without the advantage of a previous lookup.
5571void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005572 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005573 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005574 return;
5575
John McCalldf8b37c2010-03-22 09:20:08 +00005576 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5577 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5578 LookupName(R, S);
5579 CheckShadow(S, D, R);
5580}
5581
Richard Smithac974a32013-06-30 09:48:50 +00005582/// Check for conflict between this global or extern "C" declaration and
5583/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005584template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005585static bool checkGlobalOrExternCConflict(
5586 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5587 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5588 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005589
Richard Smithac974a32013-06-30 09:48:50 +00005590 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5591 // The common case: this global doesn't conflict with any extern "C"
5592 // declaration.
5593 return false;
5594 }
5595
5596 if (Prev) {
5597 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5598 // Both the old and new declarations have C language linkage. This is a
5599 // redeclaration.
5600 Previous.clear();
5601 Previous.addDecl(Prev);
5602 return true;
5603 }
5604
5605 // This is a global, non-extern "C" declaration, and there is a previous
5606 // non-global extern "C" declaration. Diagnose if this is a variable
5607 // declaration.
5608 if (!isa<VarDecl>(ND))
5609 return false;
5610 } else {
5611 // The declaration is extern "C". Check for any declaration in the
5612 // translation unit which might conflict.
5613 if (IsGlobal) {
5614 // We have already performed the lookup into the translation unit.
5615 IsGlobal = false;
5616 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5617 I != E; ++I) {
5618 if (isa<VarDecl>(*I)) {
5619 Prev = *I;
5620 break;
5621 }
5622 }
5623 } else {
5624 DeclContext::lookup_result R =
5625 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5626 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5627 I != E; ++I) {
5628 if (isa<VarDecl>(*I)) {
5629 Prev = *I;
5630 break;
5631 }
5632 // FIXME: If we have any other entity with this name in global scope,
5633 // the declaration is ill-formed, but that is a defect: it breaks the
5634 // 'stat' hack, for instance. Only variables can have mangled name
5635 // clashes with extern "C" declarations, so only they deserve a
5636 // diagnostic.
5637 }
5638 }
5639
5640 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005641 return false;
5642 }
5643
Richard Smithac974a32013-06-30 09:48:50 +00005644 // Use the first declaration's location to ensure we point at something which
5645 // is lexically inside an extern "C" linkage-spec.
5646 assert(Prev && "should have found a previous declaration to diagnose");
5647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005648 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005649 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005650 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005651
5652 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5653 << IsGlobal << ND;
5654 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5655 << IsGlobal;
5656 return false;
5657}
5658
5659/// Apply special rules for handling extern "C" declarations. Returns \c true
5660/// if we have found that this is a redeclaration of some prior entity.
5661///
5662/// Per C++ [dcl.link]p6:
5663/// Two declarations [for a function or variable] with C language linkage
5664/// with the same name that appear in different scopes refer to the same
5665/// [entity]. An entity with C language linkage shall not be declared with
5666/// the same name as an entity in global scope.
5667template<typename T>
5668static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5669 LookupResult &Previous) {
5670 if (!S.getLangOpts().CPlusPlus) {
5671 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005672 // variable declared in function scope. We don't need this in C++, because
5673 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005674 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5675 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5676 Previous.clear();
5677 Previous.addDecl(Prev);
5678 return true;
5679 }
5680 }
5681 return false;
5682 }
5683
5684 // A declaration in the translation unit can conflict with an extern "C"
5685 // declaration.
5686 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5687 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5688
5689 // An extern "C" declaration can conflict with a declaration in the
5690 // translation unit or can be a redeclaration of an extern "C" declaration
5691 // in another scope.
5692 if (isIncompleteDeclExternC(S,ND))
5693 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5694
5695 // Neither global nor extern "C": nothing to do.
5696 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005697}
5698
Richard Smith27d807c2013-04-30 13:56:41 +00005699void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005700 // If the decl is already known invalid, don't check it.
5701 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005702 return;
Mike Stump11289f42009-09-09 15:08:12 +00005703
Abramo Bagnara341ab732012-11-08 14:44:42 +00005704 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5705 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005706
Richard Smith27d807c2013-04-30 13:56:41 +00005707 // Defer checking an 'auto' type until its initializer is attached.
5708 if (T->isUndeducedType())
5709 return;
5710
John McCall8b07ec22010-05-15 11:32:37 +00005711 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005712 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5713 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005714 T = Context.getObjCObjectPointerType(T);
5715 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005716 }
Mike Stump11289f42009-09-09 15:08:12 +00005717
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005718 // Emit an error if an address space was applied to decl with local storage.
5719 // This includes arrays of objects with address space qualifiers, but not
5720 // automatic variables that point to other address spaces.
5721 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005722 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005723 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005724 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005725 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005726 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005727
Tanya Lattner713eef42013-04-05 20:14:50 +00005728 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5729 // __constant address space.
5730 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5731 && T.getAddressSpace() != LangAS::opencl_constant
5732 && !T->isSamplerT()){
5733 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5734 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005735 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005736 }
5737
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005738 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5739 // scope.
5740 if ((getLangOpts().OpenCLVersion >= 120)
5741 && NewVD->isStaticLocal()) {
5742 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5743 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005744 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005745 }
5746
Mike Stumpca5ae662009-04-14 00:57:29 +00005747 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005748 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005749 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005750 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005751 else {
5752 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005753 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005754 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005755 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005756
Chris Lattner9fecd742009-04-19 05:21:20 +00005757 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005758 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005759 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005760 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005761
Chris Lattner9fecd742009-04-19 05:21:20 +00005762 if ((isVM && NewVD->hasLinkage()) ||
5763 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005764 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005765 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005766 TypeSourceInfo *FixedTInfo =
5767 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5768 SizeIsNegative, Oversized);
5769 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005770 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005771 // FIXME: This won't give the correct result for
5772 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005773 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005774
Anders Carlsson6c885802009-02-28 21:56:50 +00005775 if (NewVD->isFileVarDecl())
5776 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005777 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005778 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005779 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005780 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005781 else
5782 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005783 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005784 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005785 return;
Mike Stump11289f42009-09-09 15:08:12 +00005786 }
5787
Abramo Bagnara341ab732012-11-08 14:44:42 +00005788 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005789 if (NewVD->isFileVarDecl())
5790 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5791 else
5792 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005793 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005794 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005795 }
Mike Stump11289f42009-09-09 15:08:12 +00005796
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005797 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005798 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005799 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005800 }
5801
David Majnemer0ffa3312013-05-29 00:56:45 +00005802 if (T->isVoidType()) {
5803 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5804 // of objects and functions.
5805 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5806 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5807 << T;
5808 NewVD->setInvalidDecl();
5809 return;
5810 }
Richard Smith27d807c2013-04-30 13:56:41 +00005811 }
5812
5813 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5814 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5815 NewVD->setInvalidDecl();
5816 return;
5817 }
5818
5819 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5820 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5821 NewVD->setInvalidDecl();
5822 return;
5823 }
5824
5825 if (NewVD->isConstexpr() && !T->isDependentType() &&
5826 RequireLiteralType(NewVD->getLocation(), T,
5827 diag::err_constexpr_var_non_literal)) {
5828 // Can't perform this check until the type is deduced.
5829 NewVD->setInvalidDecl();
5830 return;
5831 }
5832}
5833
5834/// \brief Perform semantic checking on a newly-created variable
5835/// declaration.
5836///
5837/// This routine performs all of the type-checking required for a
5838/// variable declaration once it has been built. It is used both to
5839/// check variables after they have been parsed and their declarators
5840/// have been translated into a declaration, and to check variables
5841/// that have been instantiated from a template.
5842///
5843/// Sets NewVD->isInvalidDecl() if an error was encountered.
5844///
5845/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005846bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005847 CheckVariableDeclarationType(NewVD);
5848
5849 // If the decl is already known invalid, don't check it.
5850 if (NewVD->isInvalidDecl())
5851 return false;
5852
John McCallb65e8fe2013-04-01 18:34:28 +00005853 // If we did not find anything by this name, look for a non-visible
5854 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005855 if (Previous.empty() &&
5856 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005857 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005858
Douglas Gregor3552dab2013-01-09 00:47:56 +00005859 // Filter out any non-conflicting previous declarations.
5860 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5861
John McCall1f82f242009-11-18 22:49:29 +00005862 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005863 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005864 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005865 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005866 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005867}
5868
Douglas Gregor36d1b142009-10-06 17:59:45 +00005869/// \brief Data used with FindOverriddenMethod
5870struct FindOverriddenMethodData {
5871 Sema *S;
5872 CXXMethodDecl *Method;
5873};
5874
5875/// \brief Member lookup function that determines whether a given C++
5876/// method overrides a method in a base class, to be used with
5877/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005878static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005879 CXXBasePath &Path,
5880 void *UserData) {
5881 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005882
Douglas Gregor36d1b142009-10-06 17:59:45 +00005883 FindOverriddenMethodData *Data
5884 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005885
5886 DeclarationName Name = Data->Method->getDeclName();
5887
5888 // FIXME: Do we care about other names here too?
5889 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005890 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005891 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5892 CanQualType CT = Data->S->Context.getCanonicalType(T);
5893
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005894 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005895 }
5896
5897 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005898 !Path.Decls.empty();
5899 Path.Decls = Path.Decls.slice(1)) {
5900 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005901 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5902 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005903 return true;
5904 }
5905 }
5906
5907 return false;
5908}
5909
David Blaikie7e414262012-10-17 00:47:58 +00005910namespace {
5911 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5912}
5913/// \brief Report an error regarding overriding, along with any relevant
5914/// overriden methods.
5915///
5916/// \param DiagID the primary error to report.
5917/// \param MD the overriding method.
5918/// \param OEK which overrides to include as notes.
5919static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5920 OverrideErrorKind OEK = OEK_All) {
5921 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5922 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5923 E = MD->end_overridden_methods();
5924 I != E; ++I) {
5925 // This check (& the OEK parameter) could be replaced by a predicate, but
5926 // without lambdas that would be overkill. This is still nicer than writing
5927 // out the diag loop 3 times.
5928 if ((OEK == OEK_All) ||
5929 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5930 (OEK == OEK_Deleted && (*I)->isDeleted()))
5931 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5932 }
5933}
5934
Sebastian Redld5b24532009-11-18 21:51:29 +00005935/// AddOverriddenMethods - See if a method overrides any in the base classes,
5936/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005937bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005938 // Look for virtual methods in base classes that this method might override.
5939 CXXBasePaths Paths;
5940 FindOverriddenMethodData Data;
5941 Data.Method = MD;
5942 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005943 bool hasDeletedOverridenMethods = false;
5944 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005945 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005946 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5947 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5948 E = Paths.found_decls_end(); I != E; ++I) {
5949 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005950 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005951 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005952 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005953 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005954 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005955 hasDeletedOverridenMethods |= OldMD->isDeleted();
5956 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005957 AddedAny = true;
5958 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005959 }
5960 }
5961 }
David Blaikie7e414262012-10-17 00:47:58 +00005962
5963 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5964 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5965 }
5966 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5967 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5968 }
5969
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005970 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005971}
5972
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005973namespace {
5974 // Struct for holding all of the extra arguments needed by
5975 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5976 struct ActOnFDArgs {
5977 Scope *S;
5978 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005979 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005980 bool AddToScope;
5981 };
5982}
5983
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005984namespace {
5985
5986// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005987// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005988class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5989 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005990 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5991 CXXRecordDecl *Parent)
5992 : Context(Context), OriginalFD(TypoFD),
5993 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005994
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005995 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005996 if (candidate.getEditDistance() == 0)
5997 return false;
5998
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005999 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006000 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6001 CDeclEnd = candidate.end();
6002 CDecl != CDeclEnd; ++CDecl) {
6003 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6004
6005 if (FD && !FD->hasBody() &&
6006 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6008 CXXRecordDecl *Parent = MD->getParent();
6009 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6010 return true;
6011 } else if (!ExpectedParent) {
6012 return true;
6013 }
6014 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006015 }
6016
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006017 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006018 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006019
6020 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006021 ASTContext &Context;
6022 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006023 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006024};
6025
6026}
6027
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006028/// \brief Generate diagnostics for an invalid function redeclaration.
6029///
6030/// This routine handles generating the diagnostic messages for an invalid
6031/// function redeclaration, including finding possible similar declarations
6032/// or performing typo correction if there are no previous declarations with
6033/// the same name.
6034///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006035/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006036/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006037static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006038 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006039 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006040 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006041 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006042 SmallVector<unsigned, 1> MismatchedParams;
6043 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006044 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006045 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006046 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6047 : diag::err_member_decl_does_not_match;
6048 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6049 IsLocalFriend ? Sema::LookupLocalFriendName
6050 : Sema::LookupOrdinaryName,
6051 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006052
6053 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006054 if (IsLocalFriend)
6055 SemaRef.LookupName(Prev, S);
6056 else
6057 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006058 assert(!Prev.isAmbiguous() &&
6059 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006060 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006061 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6062 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006063 if (!Prev.empty()) {
6064 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6065 Func != FuncEnd; ++Func) {
6066 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006067 if (FD &&
6068 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006069 // Add 1 to the index so that 0 can mean the mismatch didn't
6070 // involve a parameter
6071 unsigned ParamNum =
6072 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6073 NearMatches.push_back(std::make_pair(FD, ParamNum));
6074 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006075 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006076 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006077 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006078 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6079 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6080 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006081 // Set up everything for the call to ActOnFunctionDeclarator
6082 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6083 ExtraArgs.D.getIdentifierLoc());
6084 Previous.clear();
6085 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006086 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6087 CDeclEnd = Correction.end();
6088 CDecl != CDeclEnd; ++CDecl) {
6089 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006090 if (FD && !FD->hasBody() &&
6091 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006092 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006093 }
6094 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006095 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006096
6097 NamedDecl *Result;
6098 // Retry building the function declaration with the new previous
6099 // declarations, and with errors suppressed.
6100 {
6101 // Trap errors.
6102 Sema::SFINAETrap Trap(SemaRef);
6103
6104 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6105 // pieces need to verify the typo-corrected C++ declaration and hopefully
6106 // eliminate the need for the parameter pack ExtraArgs.
6107 Result = SemaRef.ActOnFunctionDeclarator(
6108 ExtraArgs.S, ExtraArgs.D,
6109 Correction.getCorrectionDecl()->getDeclContext(),
6110 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6111 ExtraArgs.AddToScope);
6112
6113 if (Trap.hasErrorOccurred())
6114 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006115 }
Richard Smithf9b15102013-08-17 00:46:16 +00006116
6117 if (Result) {
6118 // Determine which correction we picked.
6119 Decl *Canonical = Result->getCanonicalDecl();
6120 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6121 I != E; ++I)
6122 if ((*I)->getCanonicalDecl() == Canonical)
6123 Correction.setCorrectionDecl(*I);
6124
6125 SemaRef.diagnoseTypo(
6126 Correction,
6127 SemaRef.PDiag(IsLocalFriend
6128 ? diag::err_no_matching_local_friend_suggest
6129 : diag::err_member_decl_does_not_match_suggest)
6130 << Name << NewDC << IsDefinition);
6131 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006132 }
Richard Smithf9b15102013-08-17 00:46:16 +00006133
6134 // Pretend the typo correction never occurred
6135 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6136 ExtraArgs.D.getIdentifierLoc());
6137 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6138 Previous.clear();
6139 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006140 }
6141
Richard Smithf9b15102013-08-17 00:46:16 +00006142 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6143 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006144
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006145 bool NewFDisConst = false;
6146 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006147 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006148
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006149 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006150 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6151 NearMatch != NearMatchEnd; ++NearMatch) {
6152 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006153 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6154 bool FDisConst = MD && MD->isConst();
6155 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006156
Richard Smith541b38b2013-09-20 01:15:31 +00006157 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006158 if (unsigned Idx = NearMatch->second) {
6159 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006160 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6161 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006162 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6163 : diag::note_local_decl_close_param_match)
6164 << Idx << FDParam->getType()
6165 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006166 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006167 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006168 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006169 } else
Richard Smith114394f2013-08-09 04:35:01 +00006170 SemaRef.Diag(FD->getLocation(),
6171 IsMember ? diag::note_member_def_close_match
6172 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006173 }
Richard Smithf9b15102013-08-17 00:46:16 +00006174 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006175}
6176
David Blaikie30d15442011-10-19 22:56:21 +00006177static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6178 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006179 switch (D.getDeclSpec().getStorageClassSpec()) {
6180 default: llvm_unreachable("Unknown storage class!");
6181 case DeclSpec::SCS_auto:
6182 case DeclSpec::SCS_register:
6183 case DeclSpec::SCS_mutable:
6184 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6185 diag::err_typecheck_sclass_func);
6186 D.setInvalidType();
6187 break;
6188 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006189 case DeclSpec::SCS_extern:
6190 if (D.getDeclSpec().isExternInLinkageSpec())
6191 return SC_None;
6192 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006193 case DeclSpec::SCS_static: {
6194 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6195 // C99 6.7.1p5:
6196 // The declaration of an identifier for a function that has
6197 // block scope shall have no explicit storage-class specifier
6198 // other than extern
6199 // See also (C++ [dcl.stc]p4).
6200 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6201 diag::err_static_block_func);
6202 break;
6203 } else
6204 return SC_Static;
6205 }
6206 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6207 }
6208
6209 // No explicit storage class has already been returned
6210 return SC_None;
6211}
6212
6213static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6214 DeclContext *DC, QualType &R,
6215 TypeSourceInfo *TInfo,
6216 FunctionDecl::StorageClass SC,
6217 bool &IsVirtualOkay) {
6218 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6219 DeclarationName Name = NameInfo.getName();
6220
6221 FunctionDecl *NewFD = 0;
6222 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006223
David Blaikiebbafb8a2012-03-11 07:00:24 +00006224 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006225 // Determine whether the function was written with a
6226 // prototype. This true when:
6227 // - there is a prototype in the declarator, or
6228 // - the type R of the function is some kind of typedef or other reference
6229 // to a type name (which eventually refers to a function type).
6230 bool HasPrototype =
6231 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6232 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6233
David Blaikie30d15442011-10-19 22:56:21 +00006234 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006235 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006236 TInfo, SC, isInline,
6237 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006238 if (D.isInvalidType())
6239 NewFD->setInvalidDecl();
6240
6241 // Set the lexical context.
6242 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6243
6244 return NewFD;
6245 }
6246
6247 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6248 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6249
6250 // Check that the return type is not an abstract class type.
6251 // For record types, this is done by the AbstractClassUsageDiagnoser once
6252 // the class has been completely parsed.
6253 if (!DC->isRecord() &&
6254 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6255 R->getAs<FunctionType>()->getResultType(),
6256 diag::err_abstract_type_in_decl,
6257 SemaRef.AbstractReturnType))
6258 D.setInvalidType();
6259
6260 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6261 // This is a C++ constructor declaration.
6262 assert(DC->isRecord() &&
6263 "Constructors can only be declared in a member context");
6264
6265 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6266 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006267 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006268 R, TInfo, isExplicit, isInline,
6269 /*isImplicitlyDeclared=*/false,
6270 isConstexpr);
6271
6272 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6273 // This is a C++ destructor declaration.
6274 if (DC->isRecord()) {
6275 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6276 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6277 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6278 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006279 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006280 NameInfo, R, TInfo, isInline,
6281 /*isImplicitlyDeclared=*/false);
6282
6283 // If the class is complete, then we now create the implicit exception
6284 // specification. If the class is incomplete or dependent, we can't do
6285 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006286 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006287 Record->getDefinition() && !Record->isBeingDefined() &&
6288 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6289 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6290 }
6291
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006292 // The Microsoft ABI requires that we perform the destructor body
6293 // checks (i.e. operator delete() lookup) at every declaration, as
6294 // any translation unit may need to emit a deleting destructor.
6295 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6296 !Record->isDependentType() && Record->getDefinition() &&
6297 !Record->isBeingDefined()) {
6298 SemaRef.CheckDestructor(NewDD);
6299 }
6300
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006301 IsVirtualOkay = true;
6302 return NewDD;
6303
6304 } else {
6305 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6306 D.setInvalidType();
6307
6308 // Create a FunctionDecl to satisfy the function definition parsing
6309 // code path.
6310 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006311 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006312 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006313 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006314 /*hasPrototype=*/true, isConstexpr);
6315 }
6316
6317 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6318 if (!DC->isRecord()) {
6319 SemaRef.Diag(D.getIdentifierLoc(),
6320 diag::err_conv_function_not_member);
6321 return 0;
6322 }
6323
6324 SemaRef.CheckConversionDeclarator(D, R, SC);
6325 IsVirtualOkay = true;
6326 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006327 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006328 R, TInfo, isInline, isExplicit,
6329 isConstexpr, SourceLocation());
6330
6331 } else if (DC->isRecord()) {
6332 // If the name of the function is the same as the name of the record,
6333 // then this must be an invalid constructor that has a return type.
6334 // (The parser checks for a return type and makes the declarator a
6335 // constructor if it has no return type).
6336 if (Name.getAsIdentifierInfo() &&
6337 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6338 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6339 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6340 << SourceRange(D.getIdentifierLoc());
6341 return 0;
6342 }
6343
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006344 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006345 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6346 cast<CXXRecordDecl>(DC),
6347 D.getLocStart(), NameInfo, R,
6348 TInfo, SC, isInline,
6349 isConstexpr, SourceLocation());
6350 IsVirtualOkay = !Ret->isStatic();
6351 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006352 } else {
6353 // Determine whether the function was written with a
6354 // prototype. This true when:
6355 // - we're in C++ (where every function has a prototype),
6356 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006357 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006358 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006359 true/*HasPrototype*/, isConstexpr);
6360 }
6361}
6362
Eli Friedman8f5e9832012-09-20 01:40:23 +00006363void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6364 // In C++, the empty parameter-type-list must be spelled "void"; a
6365 // typedef of void is not permitted.
6366 if (getLangOpts().CPlusPlus &&
6367 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6368 bool IsTypeAlias = false;
6369 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6370 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6371 else if (const TemplateSpecializationType *TST =
6372 Param->getType()->getAs<TemplateSpecializationType>())
6373 IsTypeAlias = TST->isTypeAlias();
6374 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6375 << IsTypeAlias;
6376 }
6377}
6378
Matt Arsenaultefb38192013-07-23 01:23:36 +00006379enum OpenCLParamType {
6380 ValidKernelParam,
6381 PtrPtrKernelParam,
6382 PtrKernelParam,
6383 InvalidKernelParam,
6384 RecordKernelParam
6385};
6386
6387static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6388 if (PT->isPointerType()) {
6389 QualType PointeeType = PT->getPointeeType();
6390 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6391 }
6392
6393 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6394 // be used as builtin types.
6395
6396 if (PT->isImageType())
6397 return PtrKernelParam;
6398
6399 if (PT->isBooleanType())
6400 return InvalidKernelParam;
6401
6402 if (PT->isEventT())
6403 return InvalidKernelParam;
6404
6405 if (PT->isHalfType())
6406 return InvalidKernelParam;
6407
6408 if (PT->isRecordType())
6409 return RecordKernelParam;
6410
6411 return ValidKernelParam;
6412}
6413
6414static void checkIsValidOpenCLKernelParameter(
6415 Sema &S,
6416 Declarator &D,
6417 ParmVarDecl *Param,
6418 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6419 QualType PT = Param->getType();
6420
6421 // Cache the valid types we encounter to avoid rechecking structs that are
6422 // used again
6423 if (ValidTypes.count(PT.getTypePtr()))
6424 return;
6425
6426 switch (getOpenCLKernelParameterType(PT)) {
6427 case PtrPtrKernelParam:
6428 // OpenCL v1.2 s6.9.a:
6429 // A kernel function argument cannot be declared as a
6430 // pointer to a pointer type.
6431 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6432 D.setInvalidType();
6433 return;
6434
6435 // OpenCL v1.2 s6.9.k:
6436 // Arguments to kernel functions in a program cannot be declared with the
6437 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6438 // uintptr_t or a struct and/or union that contain fields declared to be
6439 // one of these built-in scalar types.
6440
6441 case InvalidKernelParam:
6442 // OpenCL v1.2 s6.8 n:
6443 // A kernel function argument cannot be declared
6444 // of event_t type.
6445 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6446 D.setInvalidType();
6447 return;
6448
6449 case PtrKernelParam:
6450 case ValidKernelParam:
6451 ValidTypes.insert(PT.getTypePtr());
6452 return;
6453
6454 case RecordKernelParam:
6455 break;
6456 }
6457
6458 // Track nested structs we will inspect
6459 SmallVector<const Decl *, 4> VisitStack;
6460
6461 // Track where we are in the nested structs. Items will migrate from
6462 // VisitStack to HistoryStack as we do the DFS for bad field.
6463 SmallVector<const FieldDecl *, 4> HistoryStack;
6464 HistoryStack.push_back((const FieldDecl *) 0);
6465
6466 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6467 VisitStack.push_back(PD);
6468
6469 assert(VisitStack.back() && "First decl null?");
6470
6471 do {
6472 const Decl *Next = VisitStack.pop_back_val();
6473 if (!Next) {
6474 assert(!HistoryStack.empty());
6475 // Found a marker, we have gone up a level
6476 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6477 ValidTypes.insert(Hist->getType().getTypePtr());
6478
6479 continue;
6480 }
6481
6482 // Adds everything except the original parameter declaration (which is not a
6483 // field itself) to the history stack.
6484 const RecordDecl *RD;
6485 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6486 HistoryStack.push_back(Field);
6487 RD = Field->getType()->castAs<RecordType>()->getDecl();
6488 } else {
6489 RD = cast<RecordDecl>(Next);
6490 }
6491
6492 // Add a null marker so we know when we've gone back up a level
6493 VisitStack.push_back((const Decl *) 0);
6494
6495 for (RecordDecl::field_iterator I = RD->field_begin(),
6496 E = RD->field_end(); I != E; ++I) {
6497 const FieldDecl *FD = *I;
6498 QualType QT = FD->getType();
6499
6500 if (ValidTypes.count(QT.getTypePtr()))
6501 continue;
6502
6503 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6504 if (ParamType == ValidKernelParam)
6505 continue;
6506
6507 if (ParamType == RecordKernelParam) {
6508 VisitStack.push_back(FD);
6509 continue;
6510 }
6511
6512 // OpenCL v1.2 s6.9.p:
6513 // Arguments to kernel functions that are declared to be a struct or union
6514 // do not allow OpenCL objects to be passed as elements of the struct or
6515 // union.
6516 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6517 S.Diag(Param->getLocation(),
6518 diag::err_record_with_pointers_kernel_param)
6519 << PT->isUnionType()
6520 << PT;
6521 } else {
6522 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6523 }
6524
6525 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6526 << PD->getDeclName();
6527
6528 // We have an error, now let's go back up through history and show where
6529 // the offending field came from
6530 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6531 E = HistoryStack.end(); I != E; ++I) {
6532 const FieldDecl *OuterField = *I;
6533 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6534 << OuterField->getType();
6535 }
6536
6537 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6538 << QT->isPointerType()
6539 << QT;
6540 D.setInvalidType();
6541 return;
6542 }
6543 } while (!VisitStack.empty());
6544}
6545
Mike Stump11289f42009-09-09 15:08:12 +00006546NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006547Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006548 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006549 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006550 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006551 QualType R = TInfo->getType();
6552
Zhongxing Xubece5d62009-01-16 01:13:29 +00006553 assert(R.getTypePtr()->isFunctionType());
6554
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006555 // TODO: consider using NameInfo for diagnostic.
6556 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6557 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006558 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006559
Richard Smithb4a9e862013-04-12 22:46:28 +00006560 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6561 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6562 diag::err_invalid_thread)
6563 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006564
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006565 if (D.isFirstDeclarationOfMember())
6566 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006567
Douglas Gregor513e63c2010-12-10 19:28:19 +00006568 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006569 FunctionTemplateDecl *FunctionTemplate = 0;
6570 bool isExplicitSpecialization = false;
6571 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006572
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006573 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006574 bool HasExplicitTemplateArgs = false;
6575 TemplateArgumentListInfo TemplateArgs;
6576
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006577 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006578
Richard Smith541b38b2013-09-20 01:15:31 +00006579 DeclContext *OriginalDC = DC;
6580 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6581
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006582 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6583 isVirtualOkay);
6584 if (!NewFD) return 0;
6585
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006586 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6587 NewFD->setTopLevelDeclInObjCContainer();
6588
Richard Smith541b38b2013-09-20 01:15:31 +00006589 // Set the lexical context. If this is a function-scope declaration, or has a
6590 // C++ scope specifier, or is the object of a friend declaration, the lexical
6591 // context will be different from the semantic context.
6592 NewFD->setLexicalDeclContext(CurContext);
6593
6594 if (IsLocalExternDecl)
6595 NewFD->setLocalExternDecl();
6596
David Blaikiebbafb8a2012-03-11 07:00:24 +00006597 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006598 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006599 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6600 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006601 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006602 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006603 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006604 // C++ [class.friend]p5
6605 // A function can be defined in a friend declaration of a
6606 // class . . . . Such a function is implicitly inline.
6607 NewFD->setImplicitlyInline();
6608 }
6609
John McCalldb632ac2012-09-25 07:32:39 +00006610 // If this is a method defined in an __interface, and is not a constructor
6611 // or an overloaded operator, then set the pure flag (isVirtual will already
6612 // return true).
6613 if (const CXXRecordDecl *Parent =
6614 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6615 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006616 NewFD->setPure(true);
6617 }
6618
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006619 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006620 isExplicitSpecialization = false;
6621 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006622 if (D.isInvalidType())
6623 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006624
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006625 // Match up the template parameter lists with the scope specifier, then
6626 // determine whether we have a template or a template specialization.
6627 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006628 if (TemplateParameterList *TemplateParams =
6629 MatchTemplateParametersToScopeSpecifier(
6630 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6631 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6632 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006633 if (TemplateParams->size() > 0) {
6634 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006635
Abramo Bagnara60804e12011-03-18 15:16:37 +00006636 // Check that we can declare a template here.
6637 if (CheckTemplateDeclScope(S, TemplateParams))
6638 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006639
Abramo Bagnara60804e12011-03-18 15:16:37 +00006640 // A destructor cannot be a template.
6641 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6642 Diag(NewFD->getLocation(), diag::err_destructor_template);
6643 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006644 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006645
6646 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006647 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006648 // now that we know what the current instantiation is.
6649 if (DC->isDependentContext()) {
6650 ContextRAII SavedContext(*this, DC);
6651 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6652 Invalid = true;
6653 }
6654
John McCall1f0479e2010-03-24 08:27:58 +00006655
Abramo Bagnara60804e12011-03-18 15:16:37 +00006656 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6657 NewFD->getLocation(),
6658 Name, TemplateParams,
6659 NewFD);
6660 FunctionTemplate->setLexicalDeclContext(CurContext);
6661 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6662
6663 // For source fidelity, store the other template param lists.
6664 if (TemplateParamLists.size() > 1) {
6665 NewFD->setTemplateParameterListsInfo(Context,
6666 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006667 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006668 }
6669 } else {
6670 // This is a function template specialization.
6671 isFunctionTemplateSpecialization = true;
6672 // For source fidelity, store all the template param lists.
6673 NewFD->setTemplateParameterListsInfo(Context,
6674 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006675 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006676
6677 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6678 if (isFriend) {
6679 // We want to remove the "template<>", found here.
6680 SourceRange RemoveRange = TemplateParams->getSourceRange();
6681
6682 // If we remove the template<> and the name is not a
6683 // template-id, we're actually silently creating a problem:
6684 // the friend declaration will refer to an untemplated decl,
6685 // and clearly the user wants a template specialization. So
6686 // we need to insert '<>' after the name.
6687 SourceLocation InsertLoc;
6688 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6689 InsertLoc = D.getName().getSourceRange().getEnd();
6690 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6691 }
6692
6693 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6694 << Name << RemoveRange
6695 << FixItHint::CreateRemoval(RemoveRange)
6696 << FixItHint::CreateInsertion(InsertLoc, "<>");
6697 }
6698 }
6699 }
6700 else {
6701 // All template param lists were matched against the scope specifier:
6702 // this is NOT (an explicit specialization of) a template.
6703 if (TemplateParamLists.size() > 0)
6704 // For source fidelity, store all the template param lists.
6705 NewFD->setTemplateParameterListsInfo(Context,
6706 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006707 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006708 }
6709
6710 if (Invalid) {
6711 NewFD->setInvalidDecl();
6712 if (FunctionTemplate)
6713 FunctionTemplate->setInvalidDecl();
6714 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006715
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006716 // C++ [dcl.fct.spec]p5:
6717 // The virtual specifier shall only be used in declarations of
6718 // nonstatic class member functions that appear within a
6719 // member-specification of a class declaration; see 10.3.
6720 //
6721 if (isVirtual && !NewFD->isInvalidDecl()) {
6722 if (!isVirtualOkay) {
6723 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6724 diag::err_virtual_non_function);
6725 } else if (!CurContext->isRecord()) {
6726 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006727 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6728 diag::err_virtual_out_of_class)
6729 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6730 } else if (NewFD->getDescribedFunctionTemplate()) {
6731 // C++ [temp.mem]p3:
6732 // A member function template shall not be virtual.
6733 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6734 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006735 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6736 } else {
6737 // Okay: Add virtual to the method.
6738 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006739 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006740
6741 if (getLangOpts().CPlusPlus1y &&
6742 NewFD->getResultType()->isUndeducedType())
6743 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006744 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006745
Richard Smithc1564702013-11-15 02:58:23 +00006746 if (getLangOpts().CPlusPlus1y &&
6747 (NewFD->isDependentContext() ||
6748 (isFriend && CurContext->isDependentContext())) &&
Richard Smithc58f38f2013-08-14 20:16:31 +00006749 NewFD->getResultType()->isUndeducedType()) {
6750 // If the function template is referenced directly (for instance, as a
6751 // member of the current instantiation), pretend it has a dependent type.
6752 // This is not really justified by the standard, but is the only sane
6753 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006754 // FIXME: For a friend function, we have not marked the function as being
6755 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006756 const FunctionProtoType *FPT =
6757 NewFD->getType()->castAs<FunctionProtoType>();
6758 QualType Result = SubstAutoType(FPT->getResultType(),
6759 Context.DependentTy);
6760 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6761 FPT->getExtProtoInfo()));
6762 }
6763
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006764 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006765 // The inline specifier shall not appear on a block scope function
6766 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006767 if (isInline && !NewFD->isInvalidDecl()) {
6768 if (CurContext->isFunctionOrMethod()) {
6769 // 'inline' is not allowed on block scope function declaration.
6770 Diag(D.getDeclSpec().getInlineSpecLoc(),
6771 diag::err_inline_declaration_block_scope) << Name
6772 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6773 }
6774 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006775
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006776 // C++ [dcl.fct.spec]p6:
6777 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006778 // constructor or conversion function within its class definition;
6779 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006780 if (isExplicit && !NewFD->isInvalidDecl()) {
6781 if (!CurContext->isRecord()) {
6782 // 'explicit' was specified outside of the class.
6783 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6784 diag::err_explicit_out_of_class)
6785 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6786 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6787 !isa<CXXConversionDecl>(NewFD)) {
6788 // 'explicit' was specified on a function that wasn't a constructor
6789 // or conversion function.
6790 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6791 diag::err_explicit_non_ctor_or_conv_function)
6792 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6793 }
6794 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006795
Richard Smitha77a0a62011-08-15 21:04:07 +00006796 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006797 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006798 // are implicitly inline.
6799 NewFD->setImplicitlyInline();
6800
Richard Smith574f4f62013-01-14 05:37:29 +00006801 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006802 // be either constructors or to return a literal type. Therefore,
6803 // destructors cannot be declared constexpr.
6804 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006805 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006806 }
6807
Douglas Gregor26701a42011-09-09 02:06:17 +00006808 // If __module_private__ was specified, mark the function accordingly.
6809 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006810 if (isFunctionTemplateSpecialization) {
6811 SourceLocation ModulePrivateLoc
6812 = D.getDeclSpec().getModulePrivateSpecLoc();
6813 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6814 << 0
6815 << FixItHint::CreateRemoval(ModulePrivateLoc);
6816 } else {
6817 NewFD->setModulePrivate();
6818 if (FunctionTemplate)
6819 FunctionTemplate->setModulePrivate();
6820 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006821 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006822
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006823 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006824 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006825 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006826 FunctionTemplate->setAccess(AS_public);
6827 }
Richard Smith64017682013-07-17 23:53:16 +00006828 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006829 NewFD->setAccess(AS_public);
6830 }
6831
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006832 // If a function is defined as defaulted or deleted, mark it as such now.
6833 switch (D.getFunctionDefinitionKind()) {
6834 case FDK_Declaration:
6835 case FDK_Definition:
6836 break;
6837
6838 case FDK_Defaulted:
6839 NewFD->setDefaulted();
6840 break;
6841
6842 case FDK_Deleted:
6843 NewFD->setDeletedAsWritten();
6844 break;
6845 }
6846
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006847 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6848 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006849 // C++ [class.mfct]p2:
6850 // A member function may be defined (8.4) in its class definition, in
6851 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006852 NewFD->setImplicitlyInline();
6853 }
6854
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006855 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6856 !CurContext->isRecord()) {
6857 // C++ [class.static]p1:
6858 // A data or function member of a class may be declared static
6859 // in a class definition, in which case it is a static member of
6860 // the class.
6861
6862 // Complain about the 'static' specifier if it's on an out-of-line
6863 // member function definition.
6864 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6865 diag::err_static_out_of_line)
6866 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6867 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006868
6869 // C++11 [except.spec]p15:
6870 // A deallocation function with no exception-specification is treated
6871 // as if it were specified with noexcept(true).
6872 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6873 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6874 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006875 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006876 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6877 EPI.ExceptionSpecType = EST_BasicNoexcept;
6878 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00006879 FPT->getArgTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006880 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006881 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006882
6883 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006884 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006885 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006886 isExplicitSpecialization ||
6887 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006888
Zhongxing Xubece5d62009-01-16 01:13:29 +00006889 // Handle GNU asm-label extension (encoded as an attribute).
6890 if (Expr *E = (Expr*) D.getAsmLabel()) {
6891 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006892 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006893 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6894 SE->getString()));
David Chisnall0867d9c2012-02-18 16:12:34 +00006895 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6896 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6897 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6898 if (I != ExtnameUndeclaredIdentifiers.end()) {
6899 NewFD->addAttr(I->second);
6900 ExtnameUndeclaredIdentifiers.erase(I);
6901 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006902 }
6903
Chris Lattner9af40c12009-04-25 06:12:16 +00006904 // Copy the parameter declarations from the declarator D to the function
6905 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006906 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006907 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006908 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006909
Zhongxing Xubece5d62009-01-16 01:13:29 +00006910 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6911 // function that takes no arguments, not a function that takes a
6912 // single void argument.
6913 // We let through "const void" here because Sema::GetTypeForDeclarator
6914 // already checks for that case.
6915 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6916 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006917 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006918 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00006919 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00006920 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006921 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00006922 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006923 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6924 Param->setDeclContext(NewFD);
6925 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006926
6927 if (Param->isInvalidDecl())
6928 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006929 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006930 }
Mike Stump11289f42009-09-09 15:08:12 +00006931
John McCall9dd450b2009-09-21 23:43:11 +00006932 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006933 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006934 // following example, we'll need to synthesize (unnamed)
6935 // parameters for use in the declaration.
6936 //
6937 // @code
6938 // typedef void fn(int);
6939 // fn f;
6940 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006941
Chris Lattner47c0d002009-04-25 06:03:53 +00006942 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00006943 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6944 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006945 ParmVarDecl *Param =
6946 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006947 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006948 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006949 }
Chris Lattner49303b22009-04-25 18:38:18 +00006950 } else {
6951 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6952 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006953 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006954
Chris Lattner9af40c12009-04-25 06:12:16 +00006955 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006956 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006957
James Molloy6f8780b2012-02-29 10:24:19 +00006958 // Find all anonymous symbols defined during the declaration of this function
6959 // and add to NewFD. This lets us track decls such 'enum Y' in:
6960 //
6961 // void f(enum Y {AA} x) {}
6962 //
6963 // which would otherwise incorrectly end up in the translation unit scope.
6964 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6965 DeclsInPrototypeScope.clear();
6966
Richard Smithdebc59d2013-01-30 05:45:05 +00006967 if (D.getDeclSpec().isNoreturnSpecified())
6968 NewFD->addAttr(
6969 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6970 Context));
6971
Richard Smith84208dc2012-03-13 05:56:40 +00006972 // Functions returning a variably modified type violate C99 6.7.5.2p2
6973 // because all functions have linkage.
6974 if (!NewFD->isInvalidDecl() &&
6975 NewFD->getResultType()->isVariablyModifiedType()) {
6976 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6977 NewFD->setInvalidDecl();
6978 }
6979
Rafael Espindolac67f2232012-05-10 02:50:16 +00006980 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00006981 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00006982
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006983 QualType RetType = NewFD->getResultType();
6984 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6985 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6986 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6987 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006988 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramer9940a5d2013-10-16 16:21:04 +00006989 // Attach the attribute to the new decl. Don't apply the attribute if it
6990 // returns an instance of the class (e.g. assignment operators).
6991 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006992 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6993 Context));
6994 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006995 }
6996
David Blaikiebbafb8a2012-03-11 07:00:24 +00006997 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006998 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00006999 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007000 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7001 CheckMain(NewFD, D.getDeclSpec());
7002
David Majnemerc729b0b2013-09-16 22:44:20 +00007003 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7004 CheckMSVCRTEntryPoint(NewFD);
7005
David Majnemer027f9c42013-07-06 02:13:46 +00007006 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007007 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7008 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007009 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007010 // Make graceful recovery from an invalid redeclaration.
7011 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007012 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007013 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7014 "previous declaration set still overloaded");
7015 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007016 // C++11 [replacement.functions]p3:
7017 // The program's definitions shall not be specified as inline.
7018 //
7019 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7020 //
7021 // Suppress the diagnostic if the function is __attribute__((used)), since
7022 // that forces an external definition to be emitted.
7023 if (D.getDeclSpec().isInlineSpecified() &&
7024 NewFD->isReplaceableGlobalAllocationFunction() &&
7025 !NewFD->hasAttr<UsedAttr>())
7026 Diag(D.getDeclSpec().getInlineSpecLoc(),
7027 diag::ext_operator_new_delete_declared_inline)
7028 << NewFD->getDeclName();
7029
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007030 // If the declarator is a template-id, translate the parser's template
7031 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007032 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7033 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7034 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7035 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007036 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007037 TemplateId->NumArgs);
7038 translateTemplateArguments(TemplateArgsPtr,
7039 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007040
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007041 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007042
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007043 if (NewFD->isInvalidDecl()) {
7044 HasExplicitTemplateArgs = false;
7045 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007046 // Function template with explicit template arguments.
7047 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7048 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7049
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007050 HasExplicitTemplateArgs = false;
7051 } else if (!isFunctionTemplateSpecialization &&
7052 !D.getDeclSpec().isFriendSpecified()) {
7053 // We have encountered something that the user meant to be a
7054 // specialization (because it has explicitly-specified template
7055 // arguments) but that was not introduced with a "template<>" (or had
7056 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007057 // FIXME: Differentiate between attempts for explicit instantiations
7058 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007059 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7060 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7061 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007062 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007063 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007064 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007065 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007066 // "friend void foo<>(int);" is an implicit specialization decl.
7067 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007068 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007069 } else if (isFriend && isFunctionTemplateSpecialization) {
7070 // This combination is only possible in a recovery case; the user
7071 // wrote something like:
7072 // template <> friend void foo(int);
7073 // which we're recovering from as if the user had written:
7074 // friend void foo<>(int);
7075 // Go ahead and fake up a template id.
7076 HasExplicitTemplateArgs = true;
7077 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7078 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007079 }
John McCallf7cfb222010-10-13 05:45:15 +00007080
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007081 // If it's a friend (and only if it's a friend), it's possible
7082 // that either the specialized function type or the specialized
7083 // template is dependent, and therefore matching will fail. In
7084 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007085 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007086 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007087 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7088 TemplateSpecializationType::anyDependentTemplateArguments(
7089 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7090 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007091 assert(HasExplicitTemplateArgs &&
7092 "friend function specialization without template args");
7093 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7094 Previous))
7095 NewFD->setInvalidDecl();
7096 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007097 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007098 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007099 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007100 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007101 diag::ext_function_specialization_in_class :
7102 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007103 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007104 } else if (CheckFunctionTemplateSpecialization(NewFD,
7105 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7106 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007107 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007108
7109 // C++ [dcl.stc]p1:
7110 // A storage-class-specifier shall not be specified in an explicit
7111 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007112 FunctionTemplateSpecializationInfo *Info =
7113 NewFD->getTemplateSpecializationInfo();
7114 if (Info && SC != SC_None) {
7115 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007116 Diag(NewFD->getLocation(),
7117 diag::err_explicit_specialization_inconsistent_storage_class)
7118 << SC
7119 << FixItHint::CreateRemoval(
7120 D.getDeclSpec().getStorageClassSpecLoc());
7121
7122 else
7123 Diag(NewFD->getLocation(),
7124 diag::ext_explicit_specialization_storage_class)
7125 << FixItHint::CreateRemoval(
7126 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007127 }
7128
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007129 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7130 if (CheckMemberSpecialization(NewFD, Previous))
7131 NewFD->setInvalidDecl();
7132 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007133
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007134 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007135 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007136 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7137 CheckMain(NewFD, D.getDeclSpec());
7138
David Majnemerc729b0b2013-09-16 22:44:20 +00007139 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7140 CheckMSVCRTEntryPoint(NewFD);
7141
David Blaikied937bf12011-09-08 06:33:04 +00007142 if (NewFD->isInvalidDecl()) {
7143 // If this is a class member, mark the class invalid immediately.
7144 // This avoids some consistency errors later.
7145 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7146 methodDecl->getParent()->setInvalidDecl();
David Majnemer027f9c42013-07-06 02:13:46 +00007147 } else
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007148 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7149 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007150 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007151
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007152 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007153 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7154 "previous declaration set still overloaded");
7155
7156 NamedDecl *PrincipalDecl = (FunctionTemplate
7157 ? cast<NamedDecl>(FunctionTemplate)
7158 : NewFD);
7159
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007160 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007161 AccessSpecifier Access = AS_public;
7162 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007163 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007164
7165 NewFD->setAccess(Access);
7166 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007167 }
7168
7169 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7170 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7171 PrincipalDecl->setNonMemberOperator();
7172
7173 // If we have a function template, check the template parameter
7174 // list. This will check and merge default template arguments.
7175 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007176 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007177 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007178 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007179 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007180 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007181 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007182 ? TPC_FriendFunctionTemplateDefinition
7183 : TPC_FriendFunctionTemplate)
7184 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007185 DC && DC->isRecord() &&
7186 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007187 ? TPC_ClassTemplateMember
7188 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007189 }
7190
7191 if (NewFD->isInvalidDecl()) {
7192 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007193 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007194 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007195 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007196 // Fake up an access specifier if it's supposed to be a class member.
7197 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7198 NewFD->setAccess(AS_public);
7199
7200 // Qualified decls generally require a previous declaration.
7201 if (D.getCXXScopeSpec().isSet()) {
7202 // ...with the major exception of templated-scope or
7203 // dependent-scope friend declarations.
7204
7205 // TODO: we currently also suppress this check in dependent
7206 // contexts because (1) the parameter depth will be off when
7207 // matching friend templates and (2) we might actually be
7208 // selecting a friend based on a dependent factor. But there
7209 // are situations where these conditions don't apply and we
7210 // can actually do this check immediately.
7211 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007212 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007213 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7214 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007215 // ignore these
7216 } else {
7217 // The user tried to provide an out-of-line definition for a
7218 // function that is a member of a class or namespace, but there
7219 // was no such member function declared (C++ [class.mfct]p2,
7220 // C++ [namespace.memdef]p2). For example:
7221 //
7222 // class X {
7223 // void f() const;
7224 // };
7225 //
7226 // void X::f() { } // ill-formed
7227 //
7228 // Complain about this problem, and attempt to suggest close
7229 // matches (e.g., those that differ only in cv-qualifiers and
7230 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007231
Richard Smith114394f2013-08-09 04:35:01 +00007232 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7233 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007234 AddToScope = ExtraArgs.AddToScope;
7235 return Result;
7236 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007237 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007238
7239 // Unqualified local friend declarations are required to resolve
7240 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007241 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007242 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7243 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007244 AddToScope = ExtraArgs.AddToScope;
7245 return Result;
7246 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007247 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007248
Richard Smitha2302242013-12-05 07:51:02 +00007249 } else if (!D.isFunctionDefinition() &&
7250 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007251 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007252 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007253 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007254 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007255 // Note that this is not the case for explicit specializations of
7256 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007257 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7258 // extension for compatibility with old SWIG code which likes to
7259 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007260 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7261 << D.getCXXScopeSpec().getRange();
7262 }
7263 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007264
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007265 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007266 checkAttributesAfterMerging(*this, *NewFD);
7267
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007268 AddKnownFunctionAttributes(NewFD);
7269
Douglas Gregor72609052010-08-06 13:50:58 +00007270 if (NewFD->hasAttr<OverloadableAttr>() &&
7271 !NewFD->getType()->getAs<FunctionProtoType>()) {
7272 Diag(NewFD->getLocation(),
7273 diag::err_attribute_overloadable_no_prototype)
7274 << NewFD;
7275
7276 // Turn this into a variadic function with no parameters.
7277 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007278 FunctionProtoType::ExtProtoInfo EPI(
7279 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007280 EPI.Variadic = true;
7281 EPI.ExtInfo = FT->getExtInfo();
7282
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007283 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007284 NewFD->setType(R);
7285 }
7286
Eli Friedman570024a2010-08-05 06:57:20 +00007287 // If there's a #pragma GCC visibility in scope, and this isn't a class
7288 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007289 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007290 AddPushedVisibilityAttribute(NewFD);
7291
John McCall32f5fe12011-09-30 05:12:12 +00007292 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7293 // marking the function.
7294 AddCFAuditedAttribute(NewFD);
7295
Richard Smithac974a32013-06-30 09:48:50 +00007296 // If this is the first declaration of an extern C variable, update
7297 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007298 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007299 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007300 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007301
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007302 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007303 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007304
David Blaikiebbafb8a2012-03-11 07:00:24 +00007305 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007306 if (FunctionTemplate) {
7307 if (NewFD->isInvalidDecl())
7308 FunctionTemplate->setInvalidDecl();
7309 return FunctionTemplate;
7310 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007311 }
Mike Stump11289f42009-09-09 15:08:12 +00007312
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007313 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007314 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7315 if ((getLangOpts().OpenCLVersion >= 120)
7316 && (SC == SC_Static)) {
7317 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7318 D.setInvalidType();
7319 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007320
7321 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7322 if (!NewFD->getResultType()->isVoidType()) {
7323 Diag(D.getIdentifierLoc(),
7324 diag::err_expected_kernel_void_return_type);
7325 D.setInvalidType();
7326 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007327
7328 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007329 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7330 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly39989da2013-01-29 10:54:06 +00007331 ParmVarDecl *Param = *PI;
Matt Arsenaultefb38192013-07-23 01:23:36 +00007332 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007333 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007334 }
7335
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007336 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007337
David Blaikiebbafb8a2012-03-11 07:00:24 +00007338 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007339 if (IdentifierInfo *II = NewFD->getIdentifier())
7340 if (!NewFD->isInvalidDecl() &&
7341 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7342 if (II->isStr("cudaConfigureCall")) {
7343 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7344 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7345
7346 Context.setcudaConfigureCallDecl(NewFD);
7347 }
7348 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007349
7350 // Here we have an function template explicit specialization at class scope.
7351 // The actually specialization will be postponed to template instatiation
7352 // time via the ClassScopeFunctionSpecializationDecl node.
7353 if (isDependentClassScopeExplicitSpecialization) {
7354 ClassScopeFunctionSpecializationDecl *NewSpec =
7355 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007356 Context, CurContext, SourceLocation(),
7357 cast<CXXMethodDecl>(NewFD),
7358 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007359 CurContext->addDecl(NewSpec);
7360 AddToScope = false;
7361 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007362
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007363 return NewFD;
7364}
7365
7366/// \brief Perform semantic checking of a new function declaration.
7367///
7368/// Performs semantic analysis of the new function declaration
7369/// NewFD. This routine performs all semantic checking that does not
7370/// require the actual declarator involved in the declaration, and is
7371/// used both for the declaration of functions as they are parsed
7372/// (called via ActOnDeclarator) and for the declaration of functions
7373/// that have been instantiated via C++ template instantiation (called
7374/// via InstantiateDecl).
7375///
James Dennettffad8b72012-06-22 08:10:18 +00007376/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007377/// an explicit specialization of the previous declaration.
7378///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007379/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007380///
James Dennettffad8b72012-06-22 08:10:18 +00007381/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007382bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007383 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007384 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00007385 assert(!NewFD->getResultType()->isVariablyModifiedType()
7386 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007387
Richard Smith1c34fb72013-08-13 18:18:50 +00007388 // Determine whether the type of this function should be merged with
7389 // a previous visible declaration. This never happens for functions in C++,
7390 // and always happens in C if the previous declaration was visible.
7391 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7392 !Previous.isShadowed();
7393
Douglas Gregor3552dab2013-01-09 00:47:56 +00007394 // Filter out any non-conflicting previous declarations.
7395 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7396
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007397 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007398 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007399
Douglas Gregore62c0a42009-02-24 01:23:02 +00007400 // Merge or overload the declaration with an existing declaration of
7401 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007402 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007403 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007404 // a declaration that requires merging. If it's an overload,
7405 // there's no more work to do here; we'll just add the new
7406 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007407 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007408 NamedDecl *Candidate = Previous.getFoundDecl();
7409 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7410 Redeclaration = true;
7411 OldDecl = Candidate;
7412 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007413 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007414 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7415 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007416 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007417 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007418 break;
7419
7420 case Ovl_NonFunction:
7421 Redeclaration = true;
7422 break;
7423
7424 case Ovl_Overload:
7425 Redeclaration = false;
7426 break;
John McCall1f82f242009-11-18 22:49:29 +00007427 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007428
David Blaikiebbafb8a2012-03-11 07:00:24 +00007429 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007430 // If a function name is overloadable in C, then every function
7431 // with that name must be marked "overloadable".
7432 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7433 << Redeclaration << NewFD;
7434 NamedDecl *OverloadedDecl = 0;
7435 if (Redeclaration)
7436 OverloadedDecl = OldDecl;
7437 else if (!Previous.empty())
7438 OverloadedDecl = Previous.getRepresentativeDecl();
7439 if (OverloadedDecl)
7440 Diag(OverloadedDecl->getLocation(),
7441 diag::note_attribute_overloadable_prev_overload);
7442 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7443 Context));
7444 }
John McCall1f82f242009-11-18 22:49:29 +00007445 }
Richard Smith574f4f62013-01-14 05:37:29 +00007446 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007447
Richard Smithac974a32013-06-30 09:48:50 +00007448 // Check for a previous extern "C" declaration with this name.
7449 if (!Redeclaration &&
7450 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7451 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7452 if (!Previous.empty()) {
7453 // This is an extern "C" declaration with the same name as a previous
7454 // declaration, and thus redeclares that entity...
7455 Redeclaration = true;
7456 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007457 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007458
7459 // ... except in the presence of __attribute__((overloadable)).
7460 if (OldDecl->hasAttr<OverloadableAttr>()) {
7461 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7462 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7463 << Redeclaration << NewFD;
7464 Diag(Previous.getFoundDecl()->getLocation(),
7465 diag::note_attribute_overloadable_prev_overload);
7466 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7467 Context));
7468 }
7469 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7470 Redeclaration = false;
7471 OldDecl = 0;
7472 }
7473 }
7474 }
7475 }
7476
Richard Smith574f4f62013-01-14 05:37:29 +00007477 // C++11 [dcl.constexpr]p8:
7478 // A constexpr specifier for a non-static member function that is not
7479 // a constructor declares that member function to be const.
7480 //
7481 // This needs to be delayed until we know whether this is an out-of-line
7482 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007483 //
7484 // This rule is not present in C++1y, so we produce a backwards
7485 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007486 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007487 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7488 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007489 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7490 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7491 if (FunctionTemplateDecl *OldTD =
7492 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7493 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7494 if (!OldMD || !OldMD->isStatic()) {
7495 const FunctionProtoType *FPT =
7496 MD->getType()->castAs<FunctionProtoType>();
7497 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7498 EPI.TypeQuals |= Qualifiers::Const;
7499 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00007500 FPT->getArgTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007501
7502 // Warn that we did this, if we're not performing template instantiation.
7503 // In that case, we'll have warned already when the template was defined.
7504 if (ActiveTemplateInstantiations.empty()) {
7505 SourceLocation AddConstLoc;
7506 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7507 .IgnoreParens().getAs<FunctionTypeLoc>())
7508 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7509
7510 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7511 << FixItHint::CreateInsertion(AddConstLoc, " const");
7512 }
Richard Smith574f4f62013-01-14 05:37:29 +00007513 }
7514 }
7515
7516 if (Redeclaration) {
7517 // NewFD and OldDecl represent declarations that need to be
7518 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007519 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007520 NewFD->setInvalidDecl();
7521 return Redeclaration;
7522 }
7523
7524 Previous.clear();
7525 Previous.addDecl(OldDecl);
7526
7527 if (FunctionTemplateDecl *OldTemplateDecl
7528 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7529 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7530 FunctionTemplateDecl *NewTemplateDecl
7531 = NewFD->getDescribedFunctionTemplate();
7532 assert(NewTemplateDecl && "Template/non-template mismatch");
7533 if (CXXMethodDecl *Method
7534 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7535 Method->setAccess(OldTemplateDecl->getAccess());
7536 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007537 }
Richard Smith574f4f62013-01-14 05:37:29 +00007538
7539 // If this is an explicit specialization of a member that is a function
7540 // template, mark it as a member specialization.
7541 if (IsExplicitSpecialization &&
7542 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7543 NewTemplateDecl->setMemberSpecialization();
7544 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007545 }
Richard Smith574f4f62013-01-14 05:37:29 +00007546
7547 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007548 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007549 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007550
7551 if (isa<CXXMethodDecl>(NewFD)) {
7552 // A valid redeclaration of a C++ method must be out-of-line,
7553 // but (unfortunately) it's not necessarily a definition
7554 // because of templates, which means that the previous
7555 // declaration is not necessarily from the class definition.
7556
7557 // For just setting the access, that doesn't matter.
7558 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7559 NewFD->setAccess(oldMethod->getAccess());
7560
7561 // Update the key-function state if necessary for this ABI.
7562 if (NewFD->isInlined() &&
7563 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7564 // setNonKeyFunction needs to work with the original
7565 // declaration from the class definition, and isVirtual() is
7566 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007567 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007568 if (oldMethod->isVirtual()) {
7569 Context.setNonKeyFunction(oldMethod);
7570 }
7571 }
7572 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007573 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007574 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007575
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007576 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007577 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007578 // C++-specific checks.
7579 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7580 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007581 } else if (CXXDestructorDecl *Destructor =
7582 dyn_cast<CXXDestructorDecl>(NewFD)) {
7583 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007584 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007585
Douglas Gregor7454c562010-07-02 20:37:36 +00007586 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007587 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007588 if (!ClassType->isDependentType()) {
7589 DeclarationName Name
7590 = Context.DeclarationNames.getCXXDestructorName(
7591 Context.getCanonicalType(ClassType));
7592 if (NewFD->getDeclName() != Name) {
7593 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007594 NewFD->setInvalidDecl();
7595 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007596 }
7597 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007598 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007599 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007600 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007601 }
7602
7603 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7605 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007606 !Method->getDescribedFunctionTemplate() &&
7607 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007608 if (AddOverriddenMethods(Method->getParent(), Method)) {
7609 // If the function was marked as "static", we have a problem.
7610 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007611 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007612 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007613 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007614 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007615
7616 if (Method->isStatic())
7617 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007618 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007619
7620 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7621 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007622 CheckOverloadedOperatorDeclaration(NewFD)) {
7623 NewFD->setInvalidDecl();
7624 return Redeclaration;
7625 }
Alexis Huntc88db062010-01-13 09:01:02 +00007626
7627 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7628 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007629 CheckLiteralOperatorDeclaration(NewFD)) {
7630 NewFD->setInvalidDecl();
7631 return Redeclaration;
7632 }
Alexis Huntc88db062010-01-13 09:01:02 +00007633
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007634 // In C++, check default arguments now that we have merged decls. Unless
7635 // the lexical context is the class, because in this case this is done
7636 // during delayed parsing anyway.
7637 if (!CurContext->isRecord())
7638 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007639
Douglas Gregor9246b682010-12-21 19:47:46 +00007640 // If this function declares a builtin function, check the type of this
7641 // declaration against the expected type for the builtin.
7642 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7643 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007644 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007645 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7646 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7647 // The type of this function differs from the type of the builtin,
7648 // so forget about the builtin entirely.
7649 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7650 }
7651 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007652
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007653 // If this function is declared as being extern "C", then check to see if
7654 // the function returns a UDT (class, struct, or union type) that is not C
7655 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007656 // But, issue any diagnostic on the first declaration only.
7657 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007658 QualType R = NewFD->getResultType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007659 if (R->isIncompleteType() && !R->isVoidType())
7660 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7661 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007662 else if (!R.isPODType(Context) && !R->isVoidType() &&
7663 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007664 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007665 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007666 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007667 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007668}
7669
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007670static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7671 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7672 if (!TSI)
7673 return SourceRange();
7674
7675 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007676 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007677 if (!FunctionTL)
7678 return SourceRange();
7679
David Blaikie6adc78e2013-02-18 22:06:02 +00007680 TypeLoc ResultTL = FunctionTL.getResultLoc();
7681 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007682 return ResultTL.getSourceRange();
7683
7684 return SourceRange();
7685}
7686
David Blaikied937bf12011-09-08 06:33:04 +00007687void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00007688 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7689 // static or constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007690 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7691 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007692 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007693 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007694 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007695 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007696 ? diag::err_static_main : diag::warn_static_main)
7697 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7698 if (FD->isInlineSpecified())
7699 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7700 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007701 if (DS.isNoreturnSpecified()) {
7702 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7703 SourceRange NoreturnRange(NoreturnLoc,
7704 PP.getLocForEndOfToken(NoreturnLoc));
7705 Diag(NoreturnLoc, diag::ext_noreturn_main);
7706 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7707 << FixItHint::CreateRemoval(NoreturnRange);
7708 }
Richard Smith3f333f22012-02-04 06:10:17 +00007709 if (FD->isConstexpr()) {
7710 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7711 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7712 FD->setConstexpr(false);
7713 }
John McCall02dee0a2009-07-25 04:36:53 +00007714
Joey Goulya7310a82013-11-05 12:30:39 +00007715 if (getLangOpts().OpenCL) {
7716 Diag(FD->getLocation(), diag::err_opencl_no_main)
7717 << FD->hasAttr<OpenCLKernelAttr>();
7718 FD->setInvalidDecl();
7719 return;
7720 }
7721
John McCall02dee0a2009-07-25 04:36:53 +00007722 QualType T = FD->getType();
7723 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007724 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007725
John McCall5ed3caf2012-02-14 19:50:52 +00007726 // All the standards say that main() should should return 'int'.
7727 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7728 // In C and C++, main magically returns 0 if you fall off the end;
7729 // set the flag which tells us that.
7730 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7731 FD->setHasImplicitReturnZero(true);
7732
7733 // In C with GNU extensions we allow main() to have non-integer return
7734 // type, but we should warn about the extension, and we disable the
7735 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007736 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007737 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7738
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007739 SourceRange ResultRange = getResultSourceRange(FD);
7740 if (ResultRange.isValid())
7741 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7742 << FixItHint::CreateReplacement(ResultRange, "int");
7743
John McCall5ed3caf2012-02-14 19:50:52 +00007744 // Otherwise, this is just a flat-out error.
7745 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007746 SourceRange ResultRange = getResultSourceRange(FD);
7747 if (ResultRange.isValid())
7748 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7749 << FixItHint::CreateReplacement(ResultRange, "int");
7750 else
7751 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7752
John McCall02dee0a2009-07-25 04:36:53 +00007753 FD->setInvalidDecl(true);
7754 }
7755
7756 // Treat protoless main() as nullary.
7757 if (isa<FunctionNoProtoType>(FT)) return;
7758
7759 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7760 unsigned nparams = FTP->getNumArgs();
7761 assert(FD->getNumParams() == nparams);
7762
John McCall0e21fcc2009-12-24 09:58:38 +00007763 bool HasExtraParameters = (nparams > 3);
7764
7765 // Darwin passes an undocumented fourth argument of type char**. If
7766 // other platforms start sprouting these, the logic below will start
7767 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007768 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007769 HasExtraParameters = false;
7770
7771 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007772 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7773 FD->setInvalidDecl(true);
7774 nparams = 3;
7775 }
7776
7777 // FIXME: a lot of the following diagnostics would be improved
7778 // if we had some location information about types.
7779
7780 QualType CharPP =
7781 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007782 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007783
7784 for (unsigned i = 0; i < nparams; ++i) {
7785 QualType AT = FTP->getArgType(i);
7786
7787 bool mismatch = true;
7788
7789 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7790 mismatch = false;
7791 else if (Expected[i] == CharPP) {
7792 // As an extension, the following forms are okay:
7793 // char const **
7794 // char const * const *
7795 // char * const *
7796
John McCall8ccfcb52009-09-24 19:53:00 +00007797 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007798 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007799 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7800 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007801 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7802 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007803 qs.removeConst();
7804 mismatch = !qs.empty();
7805 }
7806 }
7807
7808 if (mismatch) {
7809 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7810 // TODO: suggest replacing given type with expected type
7811 FD->setInvalidDecl(true);
7812 }
7813 }
7814
7815 if (nparams == 1 && !FD->isInvalidDecl()) {
7816 Diag(FD->getLocation(), diag::warn_main_one_arg);
7817 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007818
7819 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemerc729b0b2013-09-16 22:44:20 +00007820 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7821 FD->setInvalidDecl();
7822 }
7823}
7824
7825void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7826 QualType T = FD->getType();
7827 assert(T->isFunctionType() && "function decl is not of function type");
7828 const FunctionType *FT = T->castAs<FunctionType>();
7829
7830 // Set an implicit return of 'zero' if the function can return some integral,
7831 // enumeration, pointer or nullptr type.
7832 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7833 FT->getResultType()->isAnyPointerType() ||
7834 FT->getResultType()->isNullPtrType())
7835 // DllMain is exempt because a return value of zero means it failed.
7836 if (FD->getName() != "DllMain")
7837 FD->setHasImplicitReturnZero(true);
7838
7839 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7840 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregorbff62032010-10-21 16:57:46 +00007841 FD->setInvalidDecl();
7842 }
John McCalld9baf6a2009-07-24 03:03:21 +00007843}
7844
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007845bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007846 // FIXME: Need strict checking. In C89, we need to check for
7847 // any assignment, increment, decrement, function-calls, or
7848 // commas outside of a sizeof. In C99, it's the same list,
7849 // except that the aforementioned are allowed in unevaluated
7850 // expressions. Everything else falls under the
7851 // "may accept other forms of constant expressions" exception.
7852 // (We never end up here for C++, so the constant expression
7853 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007854 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007855 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007856 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7857 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007858 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007859}
7860
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007861namespace {
7862 // Visits an initialization expression to see if OrigDecl is evaluated in
7863 // its own initialization and throws a warning if it does.
7864 class SelfReferenceChecker
7865 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7866 Sema &S;
7867 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007868 bool isRecordType;
7869 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007870 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007871
7872 public:
7873 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7874
7875 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007876 S(S), OrigDecl(OrigDecl) {
7877 isPODType = false;
7878 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007879 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007880 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7881 isPODType = VD->getType().isPODType(S.Context);
7882 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007883 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007884 }
7885 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007886
Richard Trieu64c51ab2012-05-09 00:21:34 +00007887 // For most expressions, the cast is directly above the DeclRefExpr.
7888 // For conditional operators, the cast can be outside the conditional
7889 // operator if both expressions are DeclRefExpr's.
7890 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007891 if (isReferenceType)
7892 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007893 E = E->IgnoreParenImpCasts();
7894 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7895 HandleDeclRefExpr(DRE);
7896 return;
7897 }
7898
7899 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7900 HandleValue(CO->getTrueExpr());
7901 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007902 return;
7903 }
7904
7905 if (isa<MemberExpr>(E)) {
7906 Expr *Base = E->IgnoreParenImpCasts();
7907 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7908 // Check for static member variables and don't warn on them.
7909 if (!isa<FieldDecl>(ME->getMemberDecl()))
7910 return;
7911 Base = ME->getBase()->IgnoreParenImpCasts();
7912 }
7913 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7914 HandleDeclRefExpr(DRE);
7915 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007916 }
7917 }
7918
Richard Trieu32673472012-10-01 17:39:51 +00007919 // Reference types are handled here since all uses of references are
7920 // bad, not just r-value uses.
7921 void VisitDeclRefExpr(DeclRefExpr *E) {
7922 if (isReferenceType)
7923 HandleDeclRefExpr(E);
7924 }
7925
Richard Trieu64c51ab2012-05-09 00:21:34 +00007926 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007927 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007928 (isRecordType && E->getCastKind() == CK_NoOp))
7929 HandleValue(E->getSubExpr());
7930
7931 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007932 }
7933
Richard Trieua04ad1a2011-09-01 21:44:13 +00007934 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007935 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007936 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007937
Richard Trieu742c6ed2012-10-03 00:41:36 +00007938 // Warn when a non-static method call is followed by non-static member
7939 // field accesses, which is followed by a DeclRefExpr.
7940 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7941 bool Warn = (MD && !MD->isStatic());
7942 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7943 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7944 if (!isa<FieldDecl>(ME->getMemberDecl()))
7945 Warn = false;
7946 Base = ME->getBase()->IgnoreParenImpCasts();
7947 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007948
Richard Trieu742c6ed2012-10-03 00:41:36 +00007949 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7950 if (Warn)
7951 HandleDeclRefExpr(DRE);
7952 return;
7953 }
7954
7955 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7956 // Visit that expression.
7957 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007958 }
7959
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007960 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7961 if (E->getNumArgs() > 0)
7962 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7963 HandleDeclRefExpr(DRE);
7964
7965 Inherited::VisitCXXOperatorCallExpr(E);
7966 }
7967
Richard Trieua04ad1a2011-09-01 21:44:13 +00007968 void VisitUnaryOperator(UnaryOperator *E) {
7969 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007970 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7971 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7972 if (!isPODType)
7973 HandleValue(E->getSubExpr());
7974 return;
7975 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007976 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007977 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007978
7979 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7980
Richard Trieua04ad1a2011-09-01 21:44:13 +00007981 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007982 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007983 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007984 unsigned diag;
7985 if (isReferenceType) {
7986 diag = diag::warn_uninit_self_reference_in_reference_init;
7987 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7988 diag = diag::warn_static_self_reference_in_init;
7989 } else {
7990 diag = diag::warn_uninit_self_reference_in_init;
7991 }
7992
Richard Trieua04ad1a2011-09-01 21:44:13 +00007993 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007994 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007995 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007996 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007997 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007998 }
7999 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008000
Richard Trieu32673472012-10-01 17:39:51 +00008001 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8002 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8003 bool DirectInit) {
8004 // Parameters arguments are occassionially constructed with itself,
8005 // for instance, in recursive functions. Skip them.
8006 if (isa<ParmVarDecl>(OrigDecl))
8007 return;
8008
8009 E = E->IgnoreParens();
8010
8011 // Skip checking T a = a where T is not a record or reference type.
8012 // Doing so is a way to silence uninitialized warnings.
8013 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8014 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8015 if (ICE->getCastKind() == CK_LValueToRValue)
8016 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8017 if (DRE->getDecl() == OrigDecl)
8018 return;
8019
8020 SelfReferenceChecker(S, OrigDecl).Visit(E);
8021 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008022}
8023
Douglas Gregor5fb53972009-01-14 15:45:31 +00008024/// AddInitializerToDecl - Adds the initializer Init to the
8025/// declaration dcl. If DirectInit is true, this is C++ direct
8026/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008027void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8028 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008029 // If there is no declaration, there was an error parsing it. Just ignore
8030 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008031 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008032 return;
Mike Stump11289f42009-09-09 15:08:12 +00008033
Douglas Gregor0c880302009-03-11 23:00:04 +00008034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8035 // With declarators parsed the way they are, the parser cannot
8036 // distinguish between a normal initializer and a pure-specifier.
8037 // Thus this grotesque test.
8038 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008039 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008040 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8041 CheckPureMethod(Method, Init->getSourceRange());
8042 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008043 Diag(Method->getLocation(), diag::err_member_function_initialization)
8044 << Method->getDeclName() << Init->getSourceRange();
8045 Method->setInvalidDecl();
8046 }
8047 return;
8048 }
8049
Steve Naroff437b4d82007-09-12 20:13:48 +00008050 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8051 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008052 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8053 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008054 RealDecl->setInvalidDecl();
8055 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008056 }
Sebastian Redla9351792012-02-11 23:51:47 +00008057 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8058
Richard Smith0cc85782011-12-15 19:20:59 +00008059 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008060 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008061 Expr *DeduceInit = Init;
8062 // Initializer could be a C++ direct-initializer. Deduction only works if it
8063 // contains exactly one expression.
8064 if (CXXDirectInit) {
8065 if (CXXDirectInit->getNumExprs() == 0) {
8066 // It isn't possible to write this directly, but it is possible to
8067 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008068 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008069 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8070 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008071 << VDecl->getDeclName() << VDecl->getType()
8072 << VDecl->getSourceRange();
8073 RealDecl->setInvalidDecl();
8074 return;
8075 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008076 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008077 VDecl->isInitCapture()
8078 ? diag::err_init_capture_multiple_expressions
8079 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008080 << VDecl->getDeclName() << VDecl->getType()
8081 << VDecl->getSourceRange();
8082 RealDecl->setInvalidDecl();
8083 return;
8084 } else {
8085 DeduceInit = CXXDirectInit->getExpr(0);
8086 }
8087 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008088
8089 // Expressions default to 'id' when we're in a debugger.
8090 bool DefaultedToAuto = false;
8091 if (getLangOpts().DebuggerCastResultToId &&
8092 Init->getType() == Context.UnknownAnyTy) {
8093 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8094 if (Result.isInvalid()) {
8095 VDecl->setInvalidDecl();
8096 return;
8097 }
8098 Init = Result.take();
8099 DefaultedToAuto = true;
8100 }
Richard Smith061f1e22013-04-30 21:23:01 +00008101
8102 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008103 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008104 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008105 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008106 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008107 RealDecl->setInvalidDecl();
8108 return;
8109 }
Richard Smith061f1e22013-04-30 21:23:01 +00008110 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008111 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008112
John McCall31168b02011-06-15 23:02:42 +00008113 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008114 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008115 VDecl->setInvalidDecl();
8116
Jordan Rosed8d56692012-06-08 22:46:07 +00008117 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8118 // 'id' instead of a specific object type prevents most of our usual checks.
8119 // We only want to warn outside of template instantiations, though:
8120 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008121 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008122 DeducedType->isObjCIdType()) {
8123 SourceLocation Loc =
8124 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008125 Diag(Loc, diag::warn_auto_var_is_id)
8126 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8127 }
8128
Richard Smith30482bc2011-02-20 03:19:35 +00008129 // If this is a redeclaration, check that the type we just deduced matches
8130 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008131 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8132 // We never need to merge the type, because we cannot form an incomplete
8133 // array of auto, nor deduce such a type.
8134 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8135 }
Richard Smith27d807c2013-04-30 13:56:41 +00008136
8137 // Check the deduced type is valid for a variable declaration.
8138 CheckVariableDeclarationType(VDecl);
8139 if (VDecl->isInvalidDecl())
8140 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008141 }
Richard Smith0cc85782011-12-15 19:20:59 +00008142
8143 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8144 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8145 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8146 VDecl->setInvalidDecl();
8147 return;
8148 }
8149
Sebastian Redla9351792012-02-11 23:51:47 +00008150 if (!VDecl->getType()->isDependentType()) {
8151 // A definition must end up with a complete type, which means it must be
8152 // complete with the restriction that an array type might be completed by
8153 // the initializer; note that later code assumes this restriction.
8154 QualType BaseDeclType = VDecl->getType();
8155 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8156 BaseDeclType = Array->getElementType();
8157 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8158 diag::err_typecheck_decl_incomplete_type)) {
8159 RealDecl->setInvalidDecl();
8160 return;
8161 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008162
Sebastian Redla9351792012-02-11 23:51:47 +00008163 // The variable can not have an abstract class type.
8164 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8165 diag::err_abstract_type_in_decl,
8166 AbstractVariableType))
8167 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008168 }
8169
Sebastian Redl5ca79842010-02-01 20:16:42 +00008170 const VarDecl *Def;
8171 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008172 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008173 << VDecl->getDeclName();
8174 Diag(Def->getLocation(), diag::note_previous_definition);
8175 VDecl->setInvalidDecl();
8176 return;
8177 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008178
Douglas Gregorf0f83692010-08-24 05:27:49 +00008179 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008180 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008181 // C++ [class.static.data]p4
8182 // If a static data member is of const integral or const
8183 // enumeration type, its declaration in the class definition can
8184 // specify a constant-initializer which shall be an integral
8185 // constant expression (5.19). In that case, the member can appear
8186 // in integral constant expressions. The member shall still be
8187 // defined in a namespace scope if it is used in the program and the
8188 // namespace scope definition shall not contain an initializer.
8189 //
8190 // We already performed a redefinition check above, but for static
8191 // data members we also need to check whether there was an in-class
8192 // declaration with an initializer.
8193 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008194 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8195 << VDecl->getDeclName();
8196 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008197 return;
8198 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008199
Douglas Gregor71f39c92010-12-16 01:31:22 +00008200 if (VDecl->hasLocalStorage())
8201 getCurFunction()->setHasBranchProtectedScope();
8202
8203 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8204 VDecl->setInvalidDecl();
8205 return;
8206 }
8207 }
John McCalld4e1b762010-08-01 01:24:59 +00008208
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008209 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8210 // a kernel function cannot be initialized."
8211 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8212 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8213 VDecl->setInvalidDecl();
8214 return;
8215 }
8216
Steve Naroff61091402007-09-12 14:07:44 +00008217 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008218 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008219 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008220
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008221 // Expressions default to 'id' when we're in a debugger
8222 // and we are assigning it to a variable of Objective-C pointer type.
8223 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8224 Init->getType() == Context.UnknownAnyTy) {
8225 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8226 if (Result.isInvalid()) {
8227 VDecl->setInvalidDecl();
8228 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008229 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008230 Init = Result.take();
8231 }
Richard Smith0cc85782011-12-15 19:20:59 +00008232
8233 // Perform the initialization.
8234 if (!VDecl->isInvalidDecl()) {
8235 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8236 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008237 = DirectInit ?
8238 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8239 Init->getLocStart(),
8240 Init->getLocEnd())
8241 : InitializationKind::CreateDirectList(
8242 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008243 : InitializationKind::CreateCopy(VDecl->getLocation(),
8244 Init->getLocStart());
8245
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008246 MultiExprArg Args = Init;
8247 if (CXXDirectInit)
8248 Args = MultiExprArg(CXXDirectInit->getExprs(),
8249 CXXDirectInit->getNumExprs());
8250
8251 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8252 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008253 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008254 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008255 return;
Steve Naroff61091402007-09-12 14:07:44 +00008256 }
Richard Smith0cc85782011-12-15 19:20:59 +00008257
8258 Init = Result.takeAs<Expr>();
8259 }
8260
Richard Trieu32673472012-10-01 17:39:51 +00008261 // Check for self-references within variable initializers.
8262 // Variables declared within a function/method body (except for references)
8263 // are handled by a dataflow analysis.
8264 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8265 VDecl->getType()->isReferenceType()) {
8266 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8267 }
8268
Richard Smith0cc85782011-12-15 19:20:59 +00008269 // If the type changed, it means we had an incomplete type that was
8270 // completed by the initializer. For example:
8271 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008272 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008273 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008274 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008275
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008276 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008277 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8278
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008279 if (VDecl->hasAttr<BlocksAttr>())
8280 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008281
8282 // It is safe to assign a weak reference into a strong variable.
8283 // Although this code can still have problems:
8284 // id x = self.weakProp;
8285 // id y = self.weakProp;
8286 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8287 // paths through the function. This should be revisited if
8288 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008289 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008290 DiagnosticsEngine::Level Level =
8291 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8292 Init->getLocStart());
8293 if (Level != DiagnosticsEngine::Ignored)
8294 getCurFunction()->markSafeWeakUse(Init);
8295 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008296 }
8297
Richard Smith945f8d32013-01-14 22:39:08 +00008298 // The initialization is usually a full-expression.
8299 //
8300 // FIXME: If this is a braced initialization of an aggregate, it is not
8301 // an expression, and each individual field initializer is a separate
8302 // full-expression. For instance, in:
8303 //
8304 // struct Temp { ~Temp(); };
8305 // struct S { S(Temp); };
8306 // struct T { S a, b; } t = { Temp(), Temp() }
8307 //
8308 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008309 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8310 false,
8311 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008312 if (Result.isInvalid()) {
8313 VDecl->setInvalidDecl();
8314 return;
8315 }
8316 Init = Result.take();
8317
Richard Smith0cc85782011-12-15 19:20:59 +00008318 // Attach the initializer to the decl.
8319 VDecl->setInit(Init);
8320
8321 if (VDecl->isLocalVarDecl()) {
8322 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8323 // static storage duration shall be constant expressions or string literals.
8324 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008325 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8326 if (VDecl->getStorageClass() == SC_Static)
8327 CheckForConstantInitializer(Init, DclT);
8328 // C89 is stricter than C99 for non-static aggregate types.
8329 // C89 6.5.7p3: All the expressions [...] in an initializer list
8330 // for an object that has aggregate or union type shall be
8331 // constant expressions.
8332 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008333 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008334 !Init->isConstantInitializer(Context, false))
8335 Diag(Init->getExprLoc(),
8336 diag::ext_aggregate_init_not_constant)
8337 << Init->getSourceRange();
8338 }
Mike Stump11289f42009-09-09 15:08:12 +00008339 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008340 VDecl->getLexicalDeclContext()->isRecord()) {
8341 // This is an in-class initialization for a static data member, e.g.,
8342 //
8343 // struct S {
8344 // static const int value = 17;
8345 // };
8346
Douglas Gregor0c880302009-03-11 23:00:04 +00008347 // C++ [class.mem]p4:
8348 // A member-declarator can contain a constant-initializer only
8349 // if it declares a static member (9.4) of const integral or
8350 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008351 //
Richard Smith0cc85782011-12-15 19:20:59 +00008352 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008353 // If a non-volatile const static data member is of integral or
8354 // enumeration type, its declaration in the class definition can
8355 // specify a brace-or-equal-initializer in which every initalizer-clause
8356 // that is an assignment-expression is a constant expression. A static
8357 // data member of literal type can be declared in the class definition
8358 // with the constexpr specifier; if so, its declaration shall specify a
8359 // brace-or-equal-initializer in which every initializer-clause that is
8360 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008361
8362 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008363 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008364
Richard Smith2316cd82011-09-29 19:11:37 +00008365 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008366 // type. We separately check that every constexpr variable is of literal
8367 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008368 } else if (VDecl->isConstexpr()) {
8369
John McCalldb768922010-09-10 23:21:22 +00008370 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008371 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008372 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8373 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008374 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008375
8376 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008377 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008378 // Check whether the expression is a constant expression.
8379 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008380 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008381 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008382 // in-class initializer cannot be volatile.
8383 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8384 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008385 ; // Nothing to check.
8386 else if (Init->isIntegerConstantExpr(Context, &Loc))
8387 ; // Ok, it's an ICE!
8388 else if (Init->isEvaluatable(Context)) {
8389 // If we can constant fold the initializer through heroics, accept it,
8390 // but report this as a use of an extension for -pedantic.
8391 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8392 << Init->getSourceRange();
8393 } else {
8394 // Otherwise, this is some crazy unknown case. Report the issue at the
8395 // location provided by the isIntegerConstantExpr failed check.
8396 Diag(Loc, diag::err_in_class_initializer_non_constant)
8397 << Init->getSourceRange();
8398 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008399 }
8400
Richard Smith0cc85782011-12-15 19:20:59 +00008401 // We allow foldable floating-point constants as an extension.
8402 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008403 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8404 // it anyway and provide a fixit to add the 'constexpr'.
8405 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008406 Diag(VDecl->getLocation(),
8407 diag::ext_in_class_initializer_float_type_cxx11)
8408 << DclT << Init->getSourceRange();
8409 Diag(VDecl->getLocStart(),
8410 diag::note_in_class_initializer_float_type_cxx11)
8411 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008412 } else {
8413 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8414 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008415
Richard Smithcf656382013-01-25 04:22:16 +00008416 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8417 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8418 << Init->getSourceRange();
8419 VDecl->setInvalidDecl();
8420 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008421 }
Richard Smith256336d2011-09-29 23:18:34 +00008422
Richard Smith0cc85782011-12-15 19:20:59 +00008423 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008424 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008425 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008426 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008427 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8428 VDecl->setConstexpr(true);
8429
Richard Smith2316cd82011-09-29 19:11:37 +00008430 } else {
8431 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008432 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008433 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008434 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008435 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008436 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008437 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008438 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008439 VDecl->isExternC())) &&
8440 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008441 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008442
Richard Smith0cc85782011-12-15 19:20:59 +00008443 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008444 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008445 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008446 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8447 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8448 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008449 !Init->isConstantInitializer(
8450 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008451 // GNU C++98 edits for __thread, [basic.start.init]p4:
8452 // An object of thread storage duration shall not require dynamic
8453 // initialization.
8454 // FIXME: Need strict checking here.
8455 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8456 if (getLangOpts().CPlusPlus11)
8457 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8458 }
Steve Naroff61091402007-09-12 14:07:44 +00008459 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008460
Sebastian Redla9351792012-02-11 23:51:47 +00008461 // We will represent direct-initialization similarly to copy-initialization:
8462 // int x(1); -as-> int x = 1;
8463 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8464 //
8465 // Clients that want to distinguish between the two forms, can check for
8466 // direct initializer using VarDecl::getInitStyle().
8467 // A major benefit is that clients that don't particularly care about which
8468 // exactly form was it (like the CodeGen) can handle both cases without
8469 // special case code.
8470
8471 // C++ 8.5p11:
8472 // The form of initialization (using parentheses or '=') is generally
8473 // insignificant, but does matter when the entity being initialized has a
8474 // class type.
8475 if (CXXDirectInit) {
8476 assert(DirectInit && "Call-style initializer must be direct init.");
8477 VDecl->setInitStyle(VarDecl::CallInit);
8478 } else if (DirectInit) {
8479 // This must be list-initialization. No other way is direct-initialization.
8480 VDecl->setInitStyle(VarDecl::ListInit);
8481 }
8482
John McCall8b7fd8f12011-01-19 11:48:09 +00008483 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008484}
8485
John McCalleae5acb2010-03-31 02:13:20 +00008486/// ActOnInitializerError - Given that there was an error parsing an
8487/// initializer for the given declaration, try to return to some form
8488/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008489void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008490 // Our main concern here is re-establishing invariants like "a
8491 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008492 if (!D || D->isInvalidDecl()) return;
8493
8494 VarDecl *VD = dyn_cast<VarDecl>(D);
8495 if (!VD) return;
8496
Richard Smith30482bc2011-02-20 03:19:35 +00008497 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008498 if (ParsingInitForAutoVars.count(D)) {
8499 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008500 return;
8501 }
8502
John McCalleae5acb2010-03-31 02:13:20 +00008503 QualType Ty = VD->getType();
8504 if (Ty->isDependentType()) return;
8505
8506 // Require a complete type.
8507 if (RequireCompleteType(VD->getLocation(),
8508 Context.getBaseElementType(Ty),
8509 diag::err_typecheck_decl_incomplete_type)) {
8510 VD->setInvalidDecl();
8511 return;
8512 }
8513
8514 // Require an abstract type.
8515 if (RequireNonAbstractType(VD->getLocation(), Ty,
8516 diag::err_abstract_type_in_decl,
8517 AbstractVariableType)) {
8518 VD->setInvalidDecl();
8519 return;
8520 }
8521
8522 // Don't bother complaining about constructors or destructors,
8523 // though.
8524}
8525
John McCall48871652010-08-21 09:40:31 +00008526void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008527 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008528 // If there is no declaration, there was an error parsing it. Just ignore it.
8529 if (RealDecl == 0)
8530 return;
8531
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008532 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8533 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008534
Richard Smithf0215fe2011-12-25 21:17:58 +00008535 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008536 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008537 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8538 << Var->getDeclName() << Type;
8539 Var->setInvalidDecl();
8540 return;
8541 }
Mike Stump11289f42009-09-09 15:08:12 +00008542
Richard Smithf0215fe2011-12-25 21:17:58 +00008543 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008544 // the constexpr specifier; if so, its declaration shall specify
8545 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008546 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8547 // the definition of a variable [...] or the declaration of a static data
8548 // member.
8549 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8550 if (Var->isStaticDataMember())
8551 Diag(Var->getLocation(),
8552 diag::err_constexpr_static_mem_var_requires_init)
8553 << Var->getDeclName();
8554 else
8555 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008556 Var->setInvalidDecl();
8557 return;
8558 }
8559
Douglas Gregore6565622010-02-09 07:26:29 +00008560 switch (Var->isThisDeclarationADefinition()) {
8561 case VarDecl::Definition:
8562 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8563 break;
8564
8565 // We have an out-of-line definition of a static data member
8566 // that has an in-class initializer, so we type-check this like
8567 // a declaration.
8568 //
8569 // Fall through
8570
8571 case VarDecl::DeclarationOnly:
8572 // It's only a declaration.
8573
8574 // Block scope. C99 6.7p7: If an identifier for an object is
8575 // declared with no linkage (C99 6.2.2p6), the type for the
8576 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008577 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008578 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008579 RequireCompleteType(Var->getLocation(), Type,
8580 diag::err_typecheck_decl_incomplete_type))
8581 Var->setInvalidDecl();
8582
8583 // Make sure that the type is not abstract.
8584 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8585 RequireNonAbstractType(Var->getLocation(), Type,
8586 diag::err_abstract_type_in_decl,
8587 AbstractVariableType))
8588 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008589 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008590 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008591 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008592 Diag(Var->getLocation(), diag::note_private_extern);
8593 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008594
Douglas Gregore6565622010-02-09 07:26:29 +00008595 return;
8596
8597 case VarDecl::TentativeDefinition:
8598 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8599 // object that has file scope without an initializer, and without a
8600 // storage-class specifier or with the storage-class specifier "static",
8601 // constitutes a tentative definition. Note: A tentative definition with
8602 // external linkage is valid (C99 6.2.2p5).
8603 if (!Var->isInvalidDecl()) {
8604 if (const IncompleteArrayType *ArrayT
8605 = Context.getAsIncompleteArrayType(Type)) {
8606 if (RequireCompleteType(Var->getLocation(),
8607 ArrayT->getElementType(),
8608 diag::err_illegal_decl_array_incomplete_type))
8609 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008610 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008611 // C99 6.9.2p3: If the declaration of an identifier for an object is
8612 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8613 // declared type shall not be an incomplete type.
8614 // NOTE: code such as the following
8615 // static struct s;
8616 // struct s { int a; };
8617 // is accepted by gcc. Hence here we issue a warning instead of
8618 // an error and we do not invalidate the static declaration.
8619 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008620 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008621 RequireCompleteType(Var->getLocation(), Type,
8622 diag::ext_typecheck_decl_incomplete_type);
8623 }
8624 }
8625
8626 // Record the tentative definition; we're done.
8627 if (!Var->isInvalidDecl())
8628 TentativeDefinitions.push_back(Var);
8629 return;
8630 }
8631
8632 // Provide a specific diagnostic for uninitialized variable
8633 // definitions with incomplete array type.
8634 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008635 Diag(Var->getLocation(),
8636 diag::err_typecheck_incomplete_array_needs_initializer);
8637 Var->setInvalidDecl();
8638 return;
8639 }
8640
John McCalla755f0f2010-08-01 01:25:24 +00008641 // Provide a specific diagnostic for uninitialized variable
8642 // definitions with reference type.
8643 if (Type->isReferenceType()) {
8644 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8645 << Var->getDeclName()
8646 << SourceRange(Var->getLocation(), Var->getLocation());
8647 Var->setInvalidDecl();
8648 return;
8649 }
Douglas Gregore6565622010-02-09 07:26:29 +00008650
8651 // Do not attempt to type-check the default initializer for a
8652 // variable with dependent type.
8653 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008654 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008655
Douglas Gregore6565622010-02-09 07:26:29 +00008656 if (Var->isInvalidDecl())
8657 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008658
Douglas Gregore6565622010-02-09 07:26:29 +00008659 if (RequireCompleteType(Var->getLocation(),
8660 Context.getBaseElementType(Type),
8661 diag::err_typecheck_decl_incomplete_type)) {
8662 Var->setInvalidDecl();
8663 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008664 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008665
Douglas Gregore6565622010-02-09 07:26:29 +00008666 // The variable can not have an abstract class type.
8667 if (RequireNonAbstractType(Var->getLocation(), Type,
8668 diag::err_abstract_type_in_decl,
8669 AbstractVariableType)) {
8670 Var->setInvalidDecl();
8671 return;
8672 }
8673
Douglas Gregor9574af62011-05-21 17:52:48 +00008674 // Check for jumps past the implicit initializer. C++0x
8675 // clarifies that this applies to a "variable with automatic
8676 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008677 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008678 // A program that jumps from a point where a variable with automatic
8679 // storage duration is not in scope to a point where it is in scope is
8680 // ill-formed unless the variable has scalar type, class type with a
8681 // trivial default constructor and a trivial destructor, a cv-qualified
8682 // version of one of these types, or an array of one of the preceding
8683 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008684 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008685 if (const RecordType *Record
8686 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008687 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008688 // Mark the function for further checking even if the looser rules of
8689 // C++11 do not require such checks, so that we can diagnose
8690 // incompatibilities with C++98.
8691 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008692 getCurFunction()->setHasBranchProtectedScope();
8693 }
Douglas Gregore6565622010-02-09 07:26:29 +00008694 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008695
8696 // C++03 [dcl.init]p9:
8697 // If no initializer is specified for an object, and the
8698 // object is of (possibly cv-qualified) non-POD class type (or
8699 // array thereof), the object shall be default-initialized; if
8700 // the object is of const-qualified type, the underlying class
8701 // type shall have a user-declared default
8702 // constructor. Otherwise, if no initializer is specified for
8703 // a non- static object, the object and its subobjects, if
8704 // any, have an indeterminate initial value); if the object
8705 // or any of its subobjects are of const-qualified type, the
8706 // program is ill-formed.
8707 // C++0x [dcl.init]p11:
8708 // If no initializer is specified for an object, the object is
8709 // default-initialized; [...].
8710 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8711 InitializationKind Kind
8712 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008713
8714 InitializationSequence InitSeq(*this, Entity, Kind, None);
8715 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008716 if (Init.isInvalid())
8717 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008718 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008719 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008720 // This is important for template substitution.
8721 Var->setInitStyle(VarDecl::CallInit);
8722 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008723
John McCall8b7fd8f12011-01-19 11:48:09 +00008724 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008725 }
8726}
8727
Richard Smith02e85f32011-04-14 22:09:26 +00008728void Sema::ActOnCXXForRangeDecl(Decl *D) {
8729 VarDecl *VD = dyn_cast<VarDecl>(D);
8730 if (!VD) {
8731 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8732 D->setInvalidDecl();
8733 return;
8734 }
8735
8736 VD->setCXXForRangeDecl(true);
8737
8738 // for-range-declaration cannot be given a storage class specifier.
8739 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008740 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008741 case SC_None:
8742 break;
8743 case SC_Extern:
8744 Error = 0;
8745 break;
8746 case SC_Static:
8747 Error = 1;
8748 break;
8749 case SC_PrivateExtern:
8750 Error = 2;
8751 break;
8752 case SC_Auto:
8753 Error = 3;
8754 break;
8755 case SC_Register:
8756 Error = 4;
8757 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008758 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008759 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008760 }
Richard Smith2316cd82011-09-29 19:11:37 +00008761 if (VD->isConstexpr())
8762 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008763 if (Error != -1) {
8764 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8765 << VD->getDeclName() << Error;
8766 D->setInvalidDecl();
8767 }
8768}
8769
John McCall8b7fd8f12011-01-19 11:48:09 +00008770void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8771 if (var->isInvalidDecl()) return;
8772
John McCall31168b02011-06-15 23:02:42 +00008773 // In ARC, don't allow jumps past the implicit initialization of a
8774 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008775 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008776 var->hasLocalStorage()) {
8777 switch (var->getType().getObjCLifetime()) {
8778 case Qualifiers::OCL_None:
8779 case Qualifiers::OCL_ExplicitNone:
8780 case Qualifiers::OCL_Autoreleasing:
8781 break;
8782
8783 case Qualifiers::OCL_Weak:
8784 case Qualifiers::OCL_Strong:
8785 getCurFunction()->setHasBranchProtectedScope();
8786 break;
8787 }
8788 }
8789
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008790 if (var->isThisDeclarationADefinition() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008791 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008792 getDiagnostics().getDiagnosticLevel(
8793 diag::warn_missing_variable_declarations,
8794 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008795 // Find a previous declaration that's not a definition.
8796 VarDecl *prev = var->getPreviousDecl();
8797 while (prev && prev->isThisDeclarationADefinition())
8798 prev = prev->getPreviousDecl();
8799
8800 if (!prev)
8801 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8802 }
8803
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008804 if (var->getTLSKind() == VarDecl::TLS_Static &&
8805 var->getType().isDestructedType()) {
8806 // GNU C++98 edits for __thread, [basic.start.term]p3:
8807 // The type of an object with thread storage duration shall not
8808 // have a non-trivial destructor.
8809 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8810 if (getLangOpts().CPlusPlus11)
8811 Diag(var->getLocation(), diag::note_use_thread_local);
8812 }
8813
John McCall8b7fd8f12011-01-19 11:48:09 +00008814 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008815 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008816
Richard Smithde63d362012-11-09 23:03:14 +00008817 QualType type = var->getType();
8818 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008819
8820 // __block variables might require us to capture a copy-initializer.
8821 if (var->hasAttr<BlocksAttr>()) {
8822 // It's currently invalid to ever have a __block variable with an
8823 // array type; should we diagnose that here?
8824
8825 // Regardless, we don't want to ignore array nesting when
8826 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008827 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008828 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008829 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008830 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008831 ExprResult result
8832 = PerformMoveOrCopyInitialization(
8833 InitializedEntity::InitializeBlock(poi, type, false),
8834 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008835 if (!result.isInvalid()) {
8836 result = MaybeCreateExprWithCleanups(result);
8837 Expr *init = result.takeAs<Expr>();
8838 Context.setBlockVarCopyInits(var, init);
8839 }
8840 }
8841 }
8842
Richard Smitheda3c842011-11-07 22:16:17 +00008843 Expr *Init = var->getInit();
8844 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008845 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008846
Richard Smithbf830092012-10-29 18:26:47 +00008847 if (!var->getDeclContext()->isDependentContext() &&
8848 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008849 if (IsGlobal && !var->isConstexpr() &&
8850 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8851 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008852 != DiagnosticsEngine::Ignored) {
8853 // Warn about globals which don't have a constant initializer. Don't
8854 // warn about globals with a non-trivial destructor because we already
8855 // warned about them.
8856 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8857 if (!(RD && !RD->hasTrivialDestructor()) &&
8858 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8859 Diag(var->getLocation(), diag::warn_global_constructor)
8860 << Init->getSourceRange();
8861 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008862
Richard Smithd0b4dd62011-12-19 06:19:21 +00008863 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008864 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008865 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8866 SourceLocation DiagLoc = var->getLocation();
8867 // If the note doesn't add any useful information other than a source
8868 // location, fold it into the primary diagnostic.
8869 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8870 diag::note_invalid_subexpr_in_const_expr) {
8871 DiagLoc = Notes[0].first;
8872 Notes.clear();
8873 }
8874 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8875 << var << Init->getSourceRange();
8876 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8877 Diag(Notes[I].first, Notes[I].second);
8878 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008879 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008880 // Check whether the initializer of a const variable of integral or
8881 // enumeration type is an ICE now, since we can't tell whether it was
8882 // initialized by a constant expression if we check later.
8883 var->checkInitIsICE();
8884 }
Richard Smitheda3c842011-11-07 22:16:17 +00008885 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008886
8887 // Require the destructor.
8888 if (const RecordType *recordType = baseType->getAs<RecordType>())
8889 FinalizeVarWithDestructor(var, recordType);
8890}
8891
Richard Smithb2bc2e62011-02-21 20:05:19 +00008892/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8893/// any semantic actions necessary after any initializer has been attached.
8894void
8895Sema::FinalizeDeclaration(Decl *ThisDecl) {
8896 // Note that we are no longer parsing the initializer for this declaration.
8897 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008898
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008899 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008900 if (!VD)
8901 return;
8902
Rafael Espindola87198cd2013-08-16 23:18:50 +00008903 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8904 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8905 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8906 VD->dropAttr<UsedAttr>();
8907 }
8908 }
8909
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008910 if (!VD->isInvalidDecl() &&
8911 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8912 if (const VarDecl *Def = VD->getDefinition()) {
8913 if (Def->hasAttr<AliasAttr>()) {
8914 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8915 << VD->getDeclName();
8916 Diag(Def->getLocation(), diag::note_previous_definition);
8917 VD->setInvalidDecl();
8918 }
8919 }
8920 }
8921
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008922 const DeclContext *DC = VD->getDeclContext();
8923 // If there's a #pragma GCC visibility in scope, and this isn't a class
8924 // member, set the visibility of this variable.
Rafael Espindola3ae00052013-05-13 00:12:11 +00008925 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008926 AddPushedVisibilityAttribute(VD);
8927
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008928 if (VD->isFileVarDecl())
8929 MarkUnusedFileScopedDecl(VD);
8930
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008931 // Now we have parsed the initializer and can update the table of magic
8932 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008933 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8934 !VD->getType()->isIntegralOrEnumerationType())
8935 return;
8936
8937 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8938 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8939 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8940 I != E; ++I) {
8941 const Expr *MagicValueExpr = VD->getInit();
8942 if (!MagicValueExpr) {
8943 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008944 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008945 llvm::APSInt MagicValueInt;
8946 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8947 Diag(I->getRange().getBegin(),
8948 diag::err_type_tag_for_datatype_not_ice)
8949 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8950 continue;
8951 }
8952 if (MagicValueInt.getActiveBits() > 64) {
8953 Diag(I->getRange().getBegin(),
8954 diag::err_type_tag_for_datatype_too_large)
8955 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8956 continue;
8957 }
8958 uint64_t MagicValue = MagicValueInt.getZExtValue();
8959 RegisterTypeTagForDatatype(I->getArgumentKind(),
8960 MagicValue,
8961 I->getMatchingCType(),
8962 I->getLayoutCompatible(),
8963 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008964 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00008965}
8966
Rafael Espindolaab417692013-07-09 12:05:01 +00008967Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8968 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008969 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008970
8971 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00008972 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008973
David Majnemer50ce8352013-09-17 23:57:10 +00008974 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008975 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00008976 if (Decl *D = Group[i]) {
8977 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8978 if (!FirstDeclaratorInGroup)
8979 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00008980 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00008981 }
Richard Smith2abf6762011-02-23 00:37:57 +00008982
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008983 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00008984 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008985 HandleTagNumbering(*this, Tag);
David Majnemer50ce8352013-09-17 23:57:10 +00008986 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8987 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8988 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008989 }
David Blaikie095deba2012-11-14 01:52:05 +00008990
Rafael Espindolaab417692013-07-09 12:05:01 +00008991 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00008992}
8993
8994/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8995/// group, performing any necessary semantic checking.
8996Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00008997Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00008998 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00008999 // C++0x [dcl.spec.auto]p7:
9000 // If the type deduced for the template parameter U is not the same in each
9001 // deduction, the program is ill-formed.
9002 // FIXME: When initializer-list support is added, a distinction is needed
9003 // between the deduced type U and the deduced type which 'auto' stands for.
9004 // auto a = 0, b = { 1, 2, 3 };
9005 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009006 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009007 QualType Deduced;
9008 CanQualType DeducedCanon;
9009 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009010 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009011 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9012 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009013 // Don't reissue diagnostics when instantiating a template.
9014 if (AT && D->isInvalidDecl())
9015 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009016 QualType U = AT ? AT->getDeducedType() : QualType();
9017 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009018 CanQualType UCanon = Context.getCanonicalType(U);
9019 if (Deduced.isNull()) {
9020 Deduced = U;
9021 DeducedCanon = UCanon;
9022 DeducedDecl = D;
9023 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009024 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9025 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009026 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009027 << Deduced << DeducedDecl->getDeclName()
9028 << U << D->getDeclName()
9029 << DeducedDecl->getInit()->getSourceRange()
9030 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009031 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009032 break;
9033 }
9034 }
9035 }
9036 }
9037 }
9038
Rafael Espindolaab417692013-07-09 12:05:01 +00009039 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009040
Rafael Espindolaab417692013-07-09 12:05:01 +00009041 return DeclGroupPtrTy::make(
9042 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009043}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009044
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009045void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009046 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009047}
9048
Rafael Espindolaab417692013-07-09 12:05:01 +00009049void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009050 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009051 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009052 return;
9053
9054 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9055 Group[0]->getLocation())
9056 == DiagnosticsEngine::Ignored)
9057 return;
9058
Rafael Espindolaab417692013-07-09 12:05:01 +00009059 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009060 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009061 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009062 // additional declaration references:
9063 // 'typedef struct S {} S;'
9064 // 'typedef struct S *S;'
9065 // 'struct S *pS;'
9066 // FinalizeDeclaratorGroup adds these as separate declarations.
9067 Decl *MaybeTagDecl = Group[0];
9068 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009069 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009070 }
9071 }
9072
9073 // See if there are any new comments that are not attached to a decl.
9074 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9075 if (!Comments.empty() &&
9076 !Comments.back()->isAttached()) {
9077 // There is at least one comment that not attached to a decl.
9078 // Maybe it should be attached to one of these decls?
9079 //
9080 // Note that this way we pick up not only comments that precede the
9081 // declaration, but also comments that *follow* the declaration -- thanks to
9082 // the lookahead in the lexer: we've consumed the semicolon and looked
9083 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009084 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009085 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009086 }
9087}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009088
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009089/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9090/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009091Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009092 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009093
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009094 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009095
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009096 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009097 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009098 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009099 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009100 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009101 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9102 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009103 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009104 Diag(DS.getStorageClassSpecLoc(),
9105 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009106 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009107 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009108
Richard Smithb4a9e862013-04-12 22:46:28 +00009109 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9110 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9111 << DeclSpec::getSpecifierName(TSCS);
9112 if (DS.isConstexprSpecified())
9113 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009114 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009115
Richard Smithb4a9e862013-04-12 22:46:28 +00009116 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009117
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009118 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009119 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009120
David Blaikiebbafb8a2012-03-11 07:00:24 +00009121 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009122 // Check that there are no default arguments inside the type of this
9123 // parameter.
9124 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009125
9126 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9127 if (D.getCXXScopeSpec().isSet()) {
9128 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9129 << D.getCXXScopeSpec().getRange();
9130 D.getCXXScopeSpec().clear();
9131 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009132 }
9133
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009134 // Ensure we have a valid name
9135 IdentifierInfo *II = 0;
9136 if (D.hasName()) {
9137 II = D.getIdentifier();
9138 if (!II) {
9139 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9140 << GetNameForDeclarator(D).getName().getAsString();
9141 D.setInvalidType(true);
9142 }
9143 }
9144
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009145 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009146 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009147 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9148 ForRedeclaration);
9149 LookupName(R, S);
9150 if (R.isSingleResult()) {
9151 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009152 if (PrevDecl->isTemplateParameter()) {
9153 // Maybe we will complain about the shadowed template parameter.
9154 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9155 // Just pretend that we didn't see the previous declaration.
9156 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009157 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009158 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009159 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009160
Chris Lattnerd9773512009-01-21 02:38:50 +00009161 // Recover by removing the name
9162 II = 0;
9163 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009164 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009165 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009166 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009167 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009168
John McCallf7b2fb52010-01-22 00:28:27 +00009169 // Temporarily put parameter variables in the translation unit, not
9170 // the enclosing context. This prevents them from accidentally
9171 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009172 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009173 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009174 D.getIdentifierLoc(), II,
9175 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009176 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009177
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009178 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009179 New->setInvalidDecl();
9180
9181 assert(S->isFunctionPrototypeScope());
9182 assert(S->getFunctionPrototypeDepth() >= 1);
9183 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9184 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009185
Douglas Gregor91f84212008-12-11 16:49:14 +00009186 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009187 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009188 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009189 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009190
Douglas Gregor758a8692009-06-17 21:51:59 +00009191 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009192
Douglas Gregor41866812011-09-12 18:37:38 +00009193 if (D.getDeclSpec().isModulePrivateSpecified())
9194 Diag(New->getLocation(), diag::err_module_private_local)
9195 << 1 << New->getDeclName()
9196 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9197 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9198
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009199 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009200 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9201 }
John McCall48871652010-08-21 09:40:31 +00009202 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009203}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009204
John McCalla3ccba02010-06-04 11:21:44 +00009205/// \brief Synthesizes a variable for a parameter arising from a
9206/// typedef.
9207ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9208 SourceLocation Loc,
9209 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009210 /* FIXME: setting StartLoc == Loc.
9211 Would it be worth to modify callers so as to provide proper source
9212 location for the unnamed parameters, embedding the parameter's type? */
9213 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009214 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009215 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009216 Param->setImplicit();
9217 return Param;
9218}
9219
John McCallc5990642010-08-24 09:05:15 +00009220void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9221 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009222 // Don't diagnose unused-parameter errors in template instantiations; we
9223 // will already have done so in the template itself.
9224 if (!ActiveTemplateInstantiations.empty())
9225 return;
9226
9227 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009228 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009229 !(*Param)->hasAttr<UnusedAttr>()) {
9230 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9231 << (*Param)->getDeclName();
9232 }
9233 }
9234}
9235
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009236void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9237 ParmVarDecl * const *ParamEnd,
9238 QualType ReturnTy,
9239 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009240 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009241 return;
9242
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009243 // Warn if the return value is pass-by-value and larger than the specified
9244 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009245 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009246 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009247 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009248 Diag(D->getLocation(), diag::warn_return_value_size)
9249 << D->getDeclName() << Size;
9250 }
9251
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009252 // Warn if any parameter is pass-by-value and larger than the specified
9253 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009254 for (; Param != ParamEnd; ++Param) {
9255 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009256 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009257 continue;
9258 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009259 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009260 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9261 << (*Param)->getDeclName() << Size;
9262 }
9263}
9264
Abramo Bagnaradff19302011-03-08 08:55:46 +00009265ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9266 SourceLocation NameLoc, IdentifierInfo *Name,
9267 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009268 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009269 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009270 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009271 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009272 T->isObjCLifetimeType()) {
9273
9274 Qualifiers::ObjCLifetime lifetime;
9275
9276 // Special cases for arrays:
9277 // - if it's const, use __unsafe_unretained
9278 // - otherwise, it's an error
9279 if (T->isArrayType()) {
9280 if (!T.isConstQualified()) {
9281 DelayedDiagnostics.add(
9282 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009283 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009284 }
9285 lifetime = Qualifiers::OCL_ExplicitNone;
9286 } else {
9287 lifetime = T->getObjCARCImplicitLifetime();
9288 }
9289 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009290 }
9291
Abramo Bagnaradff19302011-03-08 08:55:46 +00009292 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009293 Context.getAdjustedParameterType(T),
9294 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009295 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009296
9297 // Parameters can not be abstract class types.
9298 // For record types, this is done by the AbstractClassUsageDiagnoser once
9299 // the class has been completely parsed.
9300 if (!CurContext->isRecord() &&
9301 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9302 AbstractParamType))
9303 New->setInvalidDecl();
9304
9305 // Parameter declarators cannot be interface types. All ObjC objects are
9306 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009307 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009308 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009309 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009310 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009311 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009312 T = Context.getObjCObjectPointerType(T);
9313 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009314 }
9315
9316 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9317 // duration shall not be qualified by an address-space qualifier."
9318 // Since all parameters have automatic store duration, they can not have
9319 // an address space.
9320 if (T.getAddressSpace() != 0) {
9321 Diag(NameLoc, diag::err_arg_with_address_space);
9322 New->setInvalidDecl();
9323 }
9324
9325 return New;
9326}
9327
Douglas Gregor170512f2009-04-01 23:51:29 +00009328void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9329 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009330 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009331
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009332 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9333 // for a K&R function.
9334 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009335 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9336 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009337 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009338 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009339 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00009340 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009341 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009342 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00009343 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00009344 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009345
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009346 // Implicitly declare the argument as type 'int' for lack of a better
9347 // type.
John McCall084e83d2011-03-24 11:26:52 +00009348 AttributeFactory attrs;
9349 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009350 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009351 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00009352 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00009353 PrevSpec, DiagID);
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009354 // Use the identifier location for the type source range.
9355 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9356 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009357 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9358 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00009359 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009360 }
9361 }
Mike Stump11289f42009-09-09 15:08:12 +00009362 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009363}
9364
Richard Smith79a52e52012-04-17 22:30:01 +00009365Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009366 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009367 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009368 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009369
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009370 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009371 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009372 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009373}
9374
Anders Carlsson2a45e402012-12-18 01:29:20 +00009375static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9376 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009377 // Don't warn about invalid declarations.
9378 if (FD->isInvalidDecl())
9379 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009380
Anders Carlsson31c7e882009-12-09 03:30:09 +00009381 // Or declarations that aren't global.
9382 if (!FD->isGlobal())
9383 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009384
Anders Carlsson31c7e882009-12-09 03:30:09 +00009385 // Don't warn about C++ member functions.
9386 if (isa<CXXMethodDecl>(FD))
9387 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009388
Anders Carlsson31c7e882009-12-09 03:30:09 +00009389 // Don't warn about 'main'.
9390 if (FD->isMain())
9391 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009392
Anders Carlsson31c7e882009-12-09 03:30:09 +00009393 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009394 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009395 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009396
9397 // Don't warn about function templates.
9398 if (FD->getDescribedFunctionTemplate())
9399 return false;
9400
9401 // Don't warn about function template specializations.
9402 if (FD->isFunctionTemplateSpecialization())
9403 return false;
9404
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009405 // Don't warn for OpenCL kernels.
9406 if (FD->hasAttr<OpenCLKernelAttr>())
9407 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009408
Anders Carlsson31c7e882009-12-09 03:30:09 +00009409 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009410 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9411 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009412 // Ignore any declarations that occur in function or method
9413 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009414 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009415 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009416
Anders Carlsson31c7e882009-12-09 03:30:09 +00009417 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009418 if (FD->getNumParams() == 0)
9419 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009420 break;
9421 }
Richard Smith541b38b2013-09-20 01:15:31 +00009422
Anders Carlsson31c7e882009-12-09 03:30:09 +00009423 return MissingPrototype;
9424}
9425
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009426void
9427Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9428 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009429 // Don't complain if we're in GNU89 mode and the previous definition
9430 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009431 const FunctionDecl *Definition = EffectiveDefinition;
9432 if (!Definition)
9433 if (!FD->isDefined(Definition))
9434 return;
9435
9436 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009437 return;
9438
9439 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9440 Definition->getStorageClass() == SC_Extern)
9441 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009442 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009443 else
9444 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9445
9446 Diag(Definition->getLocation(), diag::note_previous_definition);
9447 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009448}
Faisal Valia17d19f2013-11-07 05:17:06 +00009449
9450
Faisal Valic1a6dc42013-10-23 16:10:50 +00009451static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9452 Sema &S) {
9453 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009454
9455 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009456 LSI->CallOperator = CallOperator;
9457 LSI->Lambda = LambdaClass;
9458 LSI->ReturnType = CallOperator->getResultType();
9459 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9460
9461 if (LCD == LCD_None)
9462 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9463 else if (LCD == LCD_ByCopy)
9464 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9465 else if (LCD == LCD_ByRef)
9466 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9467 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9468
9469 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9470 LSI->Mutable = !CallOperator->isConst();
9471
Faisal Valia17d19f2013-11-07 05:17:06 +00009472 // Add the captures to the LSI so they can be noted as already
9473 // captured within tryCaptureVar.
9474 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9475 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9476 if (C->capturesVariable()) {
9477 VarDecl *VD = C->getCapturedVar();
9478 if (VD->isInitCapture())
9479 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9480 QualType CaptureType = VD->getType();
9481 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9482 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9483 /*RefersToEnclosingLocal*/true, C->getLocation(),
9484 /*EllipsisLoc*/C->isPackExpansion()
9485 ? C->getEllipsisLoc() : SourceLocation(),
9486 CaptureType, /*Expr*/ 0);
9487
9488 } else if (C->capturesThis()) {
9489 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9490 S.getCurrentThisType(), /*Expr*/ 0);
9491 }
9492 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009493}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009494
John McCall48871652010-08-21 09:40:31 +00009495Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009496 // Clear the last template instantiation error context.
9497 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9498
Douglas Gregor17a7c122009-06-24 00:54:41 +00009499 if (!D)
9500 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009501 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009502
John McCall48871652010-08-21 09:40:31 +00009503 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009504 FD = FunTmpl->getTemplatedDecl();
9505 else
John McCall48871652010-08-21 09:40:31 +00009506 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009507 // If we are instantiating a generic lambda call operator, push
9508 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009509 // that's already been calculated (ActOnLambdaExpr) to prime the current
9510 // LambdaScopeInfo.
9511 // When the template operator is being specialized, the LambdaScopeInfo,
9512 // has to be properly restored so that tryCaptureVariable doesn't try
9513 // and capture any new variables. In addition when calculating potential
9514 // captures during transformation of nested lambdas, it is necessary to
9515 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009516 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009517 assert(ActiveTemplateInstantiations.size() &&
9518 "There should be an active template instantiation on the stack "
9519 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009520 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009521 }
9522 else
9523 // Enter a new function scope
9524 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009525
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009526 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009527 if (!FD->isLateTemplateParsed())
9528 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009529
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009530 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009531 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009532 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9533 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009534 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009535 FD->setInvalidDecl();
9536 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009537 }
9538
Eli Friedman9ad72442009-03-04 07:30:59 +00009539 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009540 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9541 QualType ResultType = FD->getResultType();
9542 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009543 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009544 RequireCompleteType(FD->getLocation(), ResultType,
9545 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009546 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009547
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009548 // GNU warning -Wmissing-prototypes:
9549 // Warn if a global function is defined without a previous
9550 // prototype declaration. This warning is issued even if the
9551 // definition itself provides a prototype. The aim is to detect
9552 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009553 const FunctionDecl *PossibleZeroParamPrototype = 0;
9554 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009555 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009556
Anders Carlsson2a45e402012-12-18 01:29:20 +00009557 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009558 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009559 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009560 if (TypeSourceInfo *TI =
9561 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9562 TypeLoc TL = TI->getTypeLoc();
9563 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9564 Diag(PossibleZeroParamPrototype->getLocation(),
9565 diag::note_declaration_not_a_prototype)
9566 << PossibleZeroParamPrototype
9567 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9568 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009569 }
9570 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009571
Douglas Gregor67da0d92009-05-15 17:59:04 +00009572 if (FnBodyScope)
9573 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009574
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009575 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009576 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9577 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009578
9579 // Introduce our parameters into the function scope
9580 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9581 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00009582 Param->setOwningFunction(FD);
9583
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009584 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009585 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009586 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009587
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009588 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009589 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009590 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009591
James Molloy6f8780b2012-02-29 10:24:19 +00009592 // If we had any tags defined in the function prototype,
9593 // introduce them into the function scope.
9594 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009595 for (ArrayRef<NamedDecl *>::iterator
9596 I = FD->getDeclsInPrototypeScope().begin(),
9597 E = FD->getDeclsInPrototypeScope().end();
9598 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009599 NamedDecl *D = *I;
9600
9601 // Some of these decls (like enums) may have been pinned to the translation unit
9602 // for lack of a real context earlier. If so, remove from the translation unit
9603 // and reattach to the current context.
9604 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9605 // Is the decl actually in the context?
9606 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9607 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9608 if (*DI == D) {
9609 Context.getTranslationUnitDecl()->removeDecl(D);
9610 break;
9611 }
9612 }
9613 // Either way, reassign the lexical decl context to our FunctionDecl.
9614 D->setLexicalDeclContext(CurContext);
9615 }
9616
9617 // If the decl has a non-null name, make accessible in the current scope.
9618 if (!D->getName().empty())
9619 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9620
9621 // Similarly, dive into enums and fish their constants out, making them
9622 // accessible in this scope.
9623 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9624 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9625 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00009626 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009627 }
9628 }
9629 }
9630
Richard Smith79a52e52012-04-17 22:30:01 +00009631 // Ensure that the function's exception specification is instantiated.
9632 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9633 ResolveExceptionSpec(D->getLocation(), FPT);
9634
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009635 // Checking attributes of current function definition
9636 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009637 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9638 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9639 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009640 // Microsoft accepts dllimport for functions defined within class scope.
9641 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009642 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009643 Diag(FD->getLocation(),
9644 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9645 << "dllimport";
9646 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009647 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009648 }
9649
9650 // Visual C++ appears to not think this is an issue, so only issue
9651 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009652 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009653 // If a symbol previously declared dllimport is later defined, the
9654 // attribute is ignored in subsequent references, and a warning is
9655 // emitted.
9656 Diag(FD->getLocation(),
9657 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00009658 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009659 }
9660 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009661 // We want to attach documentation to original Decl (which might be
9662 // a function template).
9663 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009664 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009665}
9666
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009667/// \brief Given the set of return statements within a function body,
9668/// compute the variables that are subject to the named return value
9669/// optimization.
9670///
9671/// Each of the variables that is subject to the named return value
9672/// optimization will be marked as NRVO variables in the AST, and any
9673/// return statement that has a marked NRVO variable as its NRVO candidate can
9674/// use the named return value optimization.
9675///
9676/// This function applies a very simplistic algorithm for NRVO: if every return
9677/// statement in the function has the same NRVO candidate, that candidate is
9678/// the NRVO variable.
9679///
9680/// FIXME: Employ a smarter algorithm that accounts for multiple return
9681/// statements and the lifetimes of the NRVO candidates. We should be able to
9682/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009683void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009684 ReturnStmt **Returns = Scope->Returns.data();
9685
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009686 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009687 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009688 if (!Returns[I]->getNRVOCandidate())
9689 return;
9690
9691 if (!NRVOCandidate)
9692 NRVOCandidate = Returns[I]->getNRVOCandidate();
9693 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9694 return;
9695 }
9696
9697 if (NRVOCandidate)
9698 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9699}
9700
Richard Smith1ab34b32012-11-19 21:13:18 +00009701bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith9219d1b2012-11-27 21:31:01 +00009702 if (!Consumer.shouldSkipFunctionBody(D))
9703 return false;
9704
Richard Smith1ab34b32012-11-19 21:13:18 +00009705 if (isa<ObjCMethodDecl>(D))
9706 return true;
9707
9708 FunctionDecl *FD = 0;
9709 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9710 FD = FTD->getTemplatedDecl();
9711 else
9712 FD = cast<FunctionDecl>(D);
9713
9714 // We cannot skip the body of a function (or function template) which is
9715 // constexpr, since we may need to evaluate its body in order to parse the
9716 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009717 // We cannot skip the body of a function with an undeduced return type,
9718 // because any callers of that function need to know the type.
9719 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1ab34b32012-11-19 21:13:18 +00009720}
9721
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009722Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009723 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009724 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009725 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009726 MD->setHasSkippedBody();
9727 return ActOnFinishFunctionBody(Decl, 0);
9728}
9729
John McCallfaf5fb42010-08-26 23:41:50 +00009730Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009731 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009732}
9733
John McCallb268a282010-08-23 23:25:46 +00009734Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9735 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009736 FunctionDecl *FD = 0;
9737 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9738 if (FunTmpl)
9739 FD = FunTmpl->getTemplatedDecl();
9740 else
9741 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9742
Ted Kremenek0b405322010-03-23 00:13:23 +00009743 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009744 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009745
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009746 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009747 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009748
Richard Smith7500ab22013-05-10 04:31:10 +00009749 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9750 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9751 // If the function has a deduced result type but contains no 'return'
9752 // statements, the result type as written must be exactly 'auto', and
9753 // the deduced result type is 'void'.
9754 if (!FD->getResultType()->getAs<AutoType>()) {
9755 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9756 << FD->getResultType();
9757 FD->setInvalidDecl();
9758 } else {
9759 // Substitute 'void' for the 'auto' in the type.
9760 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9761 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9762 Context.adjustDeducedFunctionResultType(
9763 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009764 }
9765 }
9766
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009767 // The only way to be included in UndefinedButUsed is if there is an
9768 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009769 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009770 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009771 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009772 UndefinedButUsed.erase(FD);
9773 else if (FD->isInlined() &&
9774 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9775 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9776 UndefinedButUsed.erase(FD);
9777 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009778
John McCall5ed3caf2012-02-14 19:50:52 +00009779 // If the function implicitly returns zero (like 'main') or is naked,
9780 // don't complain about missing return statements.
9781 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009782 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009783
Francois Pichet3abc9b82011-05-11 02:14:46 +00009784 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009785 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009786 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009787 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9788
Douglas Gregor88d292c2010-05-13 16:44:06 +00009789 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009790 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009791 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9792 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009793
9794 // If this is a constructor, we need a vtable.
9795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9796 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009797
Jordan Rosed39e5f12012-07-02 21:19:23 +00009798 // Try to apply the named return value optimization. We have to check
9799 // if we can do this here because lambdas keep return statements around
9800 // to deduce an implicit return type.
9801 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9802 !FD->isDependentContext())
9803 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009804 }
9805
Douglas Gregor21f46922012-02-08 20:17:14 +00009806 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9807 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009808 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009809 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009810 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009811 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009812 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009813 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9814 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009815
9816 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009817 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009818 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009819 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009820 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9821 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009822 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009823 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009824 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9825 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009826 bool isDesignated =
9827 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009828 assert(isDesignated && InitMethod);
9829 (void)isDesignated;
9830 Diag(MD->getLocation(),
9831 diag::warn_objc_designated_init_missing_super_call);
9832 Diag(InitMethod->getLocation(),
9833 diag::note_objc_designated_init_marked_here);
9834 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9835 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009836 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9837 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9838 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9839 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009840 } else {
John McCall48871652010-08-21 09:40:31 +00009841 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009842 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009843
Jordan Rose2afd6612012-10-19 16:05:26 +00009844 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009845 "This should only be set for ObjC methods, which should have been "
9846 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009847
Chris Lattnere2473062007-05-28 06:28:18 +00009848 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009849 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009850 // C++ constructors that have function-try-blocks can't have return
9851 // statements in the handlers of that block. (C++ [except.handle]p14)
9852 // Verify this.
9853 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9854 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9855
Richard Smithdef8bdb2011-08-12 18:44:32 +00009856 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009857 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009858 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009859 !hasAnyUnrecoverableErrorsInThisFunction() &&
9860 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009861 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009862
John McCalldeb646e2010-08-04 01:04:25 +00009863 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9864 if (!Destructor->getParent()->isDependentType())
9865 CheckDestructor(Destructor);
9866
John McCalla6309952010-03-16 21:39:52 +00009867 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9868 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009869 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009870
9871 // If any errors have occurred, clear out any temporaries that may have
9872 // been leftover. This ensures that these temporaries won't be picked up for
9873 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009874 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009875 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009876 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009877 }
9878 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9879 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009880 // Since the body is valid, issue any analysis-based warnings that are
9881 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009882 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009883 }
9884
Richard Smith3607ffe2012-02-13 03:54:03 +00009885 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9886 (!CheckConstexprFunctionDecl(FD) ||
9887 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009888 FD->setInvalidDecl();
9889
John McCall28fc7092011-11-10 05:35:25 +00009890 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009891 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009892 assert(MaybeODRUseExprs.empty() &&
9893 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009894 }
9895
John McCalle99d5f32010-03-25 22:08:03 +00009896 if (!IsInstantiation)
9897 PopDeclContext();
9898
Eli Friedman71c80552012-01-05 03:35:19 +00009899 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009900 // If any errors have occurred, clear out any temporaries that may have
9901 // been leftover. This ensures that these temporaries won't be picked up for
9902 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009903 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009904 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009905 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009906
John McCall48871652010-08-21 09:40:31 +00009907 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009908}
9909
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009910
9911/// When we finish delayed parsing of an attribute, we must attach it to the
9912/// relevant Decl.
9913void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9914 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009915 // Always attach attributes to the underlying decl.
9916 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9917 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009918 ProcessDeclAttributeList(S, D, Attrs.getList());
9919
9920 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9921 if (Method->isStatic())
9922 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009923}
9924
9925
Chris Lattnerac18be92006-11-20 06:49:47 +00009926/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9927/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009928NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009929 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009930 // Before we produce a declaration for an implicitly defined
9931 // function, see whether there was a locally-scoped declaration of
9932 // this name as a function or variable. If so, use that
9933 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009934 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9935 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9936 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9937 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009938 }
9939
Chris Lattner00e26072008-05-05 21:18:06 +00009940 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009941 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009942 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009943 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009944 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009945 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009946 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009947 diag_id = diag::warn_implicit_function_decl;
9948 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009949
Hans Wennborg70a13242011-12-08 15:56:07 +00009950 // Because typo correction is expensive, only do it if the implicit
9951 // function declaration is going to be treated as an error.
9952 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9953 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009954 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009955 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009956 LookupOrdinaryName, S, 0, Validator)))
9957 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9958 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009959 }
9960
Chris Lattnerac18be92006-11-20 06:49:47 +00009961 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009962 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009963 AttributeFactory attrFactory;
9964 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009965 unsigned DiagID;
9966 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009967 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009968 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009969 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009970 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009971 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9972 /*IsAmbiguous=*/false,
9973 /*RParenLoc=*/NoLoc,
9974 /*ArgInfo=*/0,
9975 /*NumArgs=*/0,
9976 /*EllipsisLoc=*/NoLoc,
9977 /*RParenLoc=*/NoLoc,
9978 /*TypeQuals=*/0,
9979 /*RefQualifierIsLvalueRef=*/true,
9980 /*RefQualifierLoc=*/NoLoc,
9981 /*ConstQualifierLoc=*/NoLoc,
9982 /*VolatileQualifierLoc=*/NoLoc,
9983 /*MutableLoc=*/NoLoc,
9984 EST_None,
9985 /*ESpecLoc=*/NoLoc,
9986 /*Exceptions=*/0,
9987 /*ExceptionRanges=*/0,
9988 /*NumExceptions=*/0,
9989 /*NoexceptExpr=*/0,
9990 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009991 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009992 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00009993 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009994
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009995 // Insert this function into translation-unit scope.
9996
9997 DeclContext *PrevDC = CurContext;
9998 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009999
Jordan Rosed03d99d2013-03-05 01:27:54 +000010000 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010001 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010002
10003 CurContext = PrevDC;
10004
Douglas Gregore711f702009-02-14 18:57:46 +000010005 AddKnownFunctionAttributes(FD);
10006
Steve Naroff3913ea42008-04-04 14:32:09 +000010007 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010008}
10009
Douglas Gregore711f702009-02-14 18:57:46 +000010010/// \brief Adds any function attributes that we know a priori based on
10011/// the declaration of this function.
10012///
10013/// These attributes can apply both to implicitly-declared builtins
10014/// (like __builtin___printf_chk) or to library-declared functions
10015/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010016///
10017/// We need to check for duplicate attributes both here and where user-written
10018/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010019void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10020 if (FD->isInvalidDecl())
10021 return;
10022
10023 // If this is a built-in function, map its builtin attributes to
10024 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010025 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010026 // Handle printf-formatting attributes.
10027 unsigned FormatIdx;
10028 bool HasVAListArg;
10029 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010030 if (!FD->getAttr<FormatAttr>()) {
10031 const char *fmt = "printf";
10032 unsigned int NumParams = FD->getNumParams();
10033 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10034 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10035 fmt = "NSString";
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010036 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010037 &Context.Idents.get(fmt),
10038 FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +000010039 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010040 }
Douglas Gregore711f702009-02-14 18:57:46 +000010041 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010042 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10043 HasVAListArg)) {
10044 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010045 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010046 &Context.Idents.get("scanf"),
10047 FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +000010048 HasVAListArg ? 0 : FormatIdx+2));
10049 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010050
10051 // Mark const if we don't care about errno and that is the only
10052 // thing preventing the function from being const. This allows
10053 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010054 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010055 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000010056 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010057 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010058 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010059
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010060 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10061 !FD->getAttr<ReturnsTwiceAttr>())
10062 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +000010063 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010064 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +000010065 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010066 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +000010067 }
10068
10069 IdentifierInfo *Name = FD->getIdentifier();
10070 if (!Name)
10071 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010072 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010073 FD->getDeclContext()->isTranslationUnit()) ||
10074 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010075 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010076 LinkageSpecDecl::lang_c)) {
10077 // Okay: this could be a libc/libm/Objective-C function we know
10078 // about.
10079 } else
10080 return;
10081
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010082 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010083 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010084 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000010085 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010086 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010087 &Context.Idents.get("printf"), 2,
Eli Friedmanf4799842009-06-10 04:01:38 +000010088 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010089 }
Jordan Rose742c6072012-08-08 21:17:31 +000010090
10091 if (Name->isStr("__CFStringMakeConstantString")) {
10092 // We already have a __builtin___CFStringMakeConstantString,
10093 // but builds that use -fno-constant-cfstrings don't go through that.
10094 if (!FD->getAttr<FormatArgAttr>())
10095 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10096 }
Douglas Gregore711f702009-02-14 18:57:46 +000010097}
Chris Lattner302b4be2006-11-19 02:31:38 +000010098
John McCall703a3f82009-10-24 08:00:42 +000010099TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010100 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010101 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010102 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010103
John McCallbcd03502009-12-07 02:54:59 +000010104 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010105 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010106 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010107 }
10108
Chris Lattner18b19622007-01-22 07:39:13 +000010109 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010110 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010111 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010112 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010113 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010114 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010115
John McCall04fcd0d2011-02-01 08:20:08 +000010116 // Bail out immediately if we have an invalid declaration.
10117 if (D.isInvalidType()) {
10118 NewTD->setInvalidDecl();
10119 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010120 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010121
Douglas Gregor41866812011-09-12 18:37:38 +000010122 if (D.getDeclSpec().isModulePrivateSpecified()) {
10123 if (CurContext->isFunctionOrMethod())
10124 Diag(NewTD->getLocation(), diag::err_module_private_local)
10125 << 2 << NewTD->getDeclName()
10126 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10127 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10128 else
10129 NewTD->setModulePrivate();
10130 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010131
John McCall04fcd0d2011-02-01 08:20:08 +000010132 // C++ [dcl.typedef]p8:
10133 // If the typedef declaration defines an unnamed class (or
10134 // enum), the first typedef-name declared by the declaration
10135 // to be that class type (or enum type) is used to denote the
10136 // class type (or enum type) for linkage purposes only.
10137 // We need to check whether the type was declared in the declaration.
10138 switch (D.getDeclSpec().getTypeSpecType()) {
10139 case TST_enum:
10140 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010141 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010142 case TST_union:
10143 case TST_class: {
10144 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10145
10146 // Do nothing if the tag is not anonymous or already has an
10147 // associated typedef (from an earlier typedef in this decl group).
10148 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010149 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010150
10151 // A well-formed anonymous tag must always be a TUK_Definition.
10152 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10153
10154 // The type must match the tag exactly; no qualifiers allowed.
10155 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10156 break;
10157
10158 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010159 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010160 break;
10161 }
10162
10163 default:
10164 break;
10165 }
10166
Steve Narofff93b6722007-08-28 20:14:24 +000010167 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010168}
10169
Douglas Gregord9034f02009-05-14 16:41:31 +000010170
Richard Smith4b38ded2012-03-14 23:13:10 +000010171/// \brief Check that this is a valid underlying type for an enum declaration.
10172bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10173 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10174 QualType T = TI->getType();
10175
Eli Friedman52f32b92012-12-18 02:37:32 +000010176 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010177 return false;
10178
Eli Friedman52f32b92012-12-18 02:37:32 +000010179 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10180 if (BT->isInteger())
10181 return false;
10182
Richard Smith4b38ded2012-03-14 23:13:10 +000010183 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10184 return true;
10185}
10186
10187/// Check whether this is a valid redeclaration of a previous enumeration.
10188/// \return true if the redeclaration was invalid.
10189bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10190 QualType EnumUnderlyingTy,
10191 const EnumDecl *Prev) {
10192 bool IsFixed = !EnumUnderlyingTy.isNull();
10193
10194 if (IsScoped != Prev->isScoped()) {
10195 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10196 << Prev->isScoped();
10197 Diag(Prev->getLocation(), diag::note_previous_use);
10198 return true;
10199 }
10200
10201 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010202 if (!EnumUnderlyingTy->isDependentType() &&
10203 !Prev->getIntegerType()->isDependentType() &&
10204 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010205 Prev->getIntegerType())) {
10206 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10207 << EnumUnderlyingTy << Prev->getIntegerType();
10208 Diag(Prev->getLocation(), diag::note_previous_use);
10209 return true;
10210 }
10211 } else if (IsFixed != Prev->isFixed()) {
10212 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10213 << Prev->isFixed();
10214 Diag(Prev->getLocation(), diag::note_previous_use);
10215 return true;
10216 }
10217
10218 return false;
10219}
10220
Joao Matosdc86f942012-08-31 18:45:21 +000010221/// \brief Get diagnostic %select index for tag kind for
10222/// redeclaration diagnostic message.
10223/// WARNING: Indexes apply to particular diagnostics only!
10224///
10225/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010226static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010227 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010228 case TTK_Struct: return 0;
10229 case TTK_Interface: return 1;
10230 case TTK_Class: return 2;
10231 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010232 }
Joao Matosdc86f942012-08-31 18:45:21 +000010233}
10234
10235/// \brief Determine if tag kind is a class-key compatible with
10236/// class for redeclaration (class, struct, or __interface).
10237///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010238/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010239static bool isClassCompatTagKind(TagTypeKind Tag)
10240{
10241 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10242}
10243
Douglas Gregord9034f02009-05-14 16:41:31 +000010244/// \brief Determine whether a tag with a given kind is acceptable
10245/// as a redeclaration of the given tag declaration.
10246///
10247/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010248bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010249 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010250 SourceLocation NewTagLoc,
10251 const IdentifierInfo &Name) {
10252 // C++ [dcl.type.elab]p3:
10253 // The class-key or enum keyword present in the
10254 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010255 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010256 // refers. This rule also applies to the form of
10257 // elaborated-type-specifier that declares a class-name or
10258 // friend class since it can be construed as referring to the
10259 // definition of the class. Thus, in any
10260 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010261 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010262 // used to refer to a union (clause 9), and either the class or
10263 // struct class-key shall be used to refer to a class (clause 9)
10264 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010265 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010266 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010267 if (OldTag == NewTag)
10268 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010269
Joao Matosdc86f942012-08-31 18:45:21 +000010270 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010271 // Warn about the struct/class tag mismatch.
10272 bool isTemplate = false;
10273 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10274 isTemplate = Record->getDescribedClassTemplate();
10275
Richard Trieucaa33d32011-06-10 03:11:26 +000010276 if (!ActiveTemplateInstantiations.empty()) {
10277 // In a template instantiation, do not offer fix-its for tag mismatches
10278 // since they usually mess up the template instead of fixing the problem.
10279 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010280 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10281 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010282 return true;
10283 }
10284
10285 if (isDefinition) {
10286 // On definitions, check previous tags and issue a fix-it for each
10287 // one that doesn't match the current tag.
10288 if (Previous->getDefinition()) {
10289 // Don't suggest fix-its for redefinitions.
10290 return true;
10291 }
10292
10293 bool previousMismatch = false;
10294 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10295 E(Previous->redecls_end()); I != E; ++I) {
10296 if (I->getTagKind() != NewTag) {
10297 if (!previousMismatch) {
10298 previousMismatch = true;
10299 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010300 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10301 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010302 }
10303 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010304 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010305 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010306 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010307 }
10308 }
10309 return true;
10310 }
10311
10312 // Check for a previous definition. If current tag and definition
10313 // are same type, do nothing. If no definition, but disagree with
10314 // with previous tag type, give a warning, but no fix-it.
10315 const TagDecl *Redecl = Previous->getDefinition() ?
10316 Previous->getDefinition() : Previous;
10317 if (Redecl->getTagKind() == NewTag) {
10318 return true;
10319 }
10320
Douglas Gregord9034f02009-05-14 16:41:31 +000010321 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010322 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10323 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010324 Diag(Redecl->getLocation(), diag::note_previous_use);
10325
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010326 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010327 if (Previous->getDefinition()) {
10328 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010329 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010330 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010331 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010332 }
10333
Douglas Gregord9034f02009-05-14 16:41:31 +000010334 return true;
10335 }
10336 return false;
10337}
10338
Steve Naroff30d242c2007-09-15 18:49:24 +000010339/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010340/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010341/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010342/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +000010343Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010344 SourceLocation KWLoc, CXXScopeSpec &SS,
10345 IdentifierInfo *Name, SourceLocation NameLoc,
10346 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010347 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010348 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010349 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010350 SourceLocation ScopedEnumKWLoc,
10351 bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010352 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010353 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010354 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010355 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010356 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010357 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010358
Douglas Gregord6ab8742009-05-28 23:31:59 +000010359 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010360 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010361 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010362
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010363 // FIXME: Check explicit specializations more carefully.
10364 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010365 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010366
10367 // We only need to do this matching if we have template parameters
10368 // or a scope specifier, which also conveniently avoids this work
10369 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010370 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010371 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010372 if (TemplateParameterList *TemplateParams =
10373 MatchTemplateParametersToScopeSpecifier(
10374 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10375 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010376 if (Kind == TTK_Enum) {
10377 Diag(KWLoc, diag::err_enum_template);
10378 return 0;
10379 }
10380
Douglas Gregor3dad8422009-09-26 06:47:28 +000010381 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010382 // This is a declaration or definition of a class template (which may
10383 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010384
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010385 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010386 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010387
Douglas Gregore93e46c2009-07-22 23:48:44 +000010388 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010389 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010390 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010391 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010392 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010393 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010394 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010395 return Result.get();
10396 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010397 // The "template<>" header is extraneous.
10398 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010399 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010400 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010401 }
Mike Stump11289f42009-09-09 15:08:12 +000010402 }
10403 }
10404
Douglas Gregor0bf31402010-10-08 23:50:27 +000010405 // Figure out the underlying type if this a enum declaration. We need to do
10406 // this early, because it's needed to detect if this is an incompatible
10407 // redeclaration.
10408 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10409
10410 if (Kind == TTK_Enum) {
10411 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10412 // No underlying type explicitly specified, or we failed to parse the
10413 // type, default to int.
10414 EnumUnderlying = Context.IntTy.getTypePtr();
10415 else if (UnderlyingType.get()) {
10416 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10417 // integral type; any cv-qualification is ignored.
10418 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010419 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010420 EnumUnderlying = TI;
10421
Richard Smith4b38ded2012-03-14 23:13:10 +000010422 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010423 // Recover by falling back to int.
10424 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010425
Richard Smith4b38ded2012-03-14 23:13:10 +000010426 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010427 UPPC_FixedUnderlyingType))
10428 EnumUnderlying = Context.IntTy.getTypePtr();
10429
David Blaikiebbafb8a2012-03-11 07:00:24 +000010430 } else if (getLangOpts().MicrosoftMode)
Francois Picheta3108062010-10-18 15:01:13 +000010431 // Microsoft enums are always of int type.
10432 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010433 }
10434
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010435 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010436 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010437 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010438
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010439 RedeclarationKind Redecl = ForRedeclaration;
10440 if (TUK == TUK_Friend || TUK == TUK_Reference)
10441 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010442
10443 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010444 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010445 if (Name && SS.isNotEmpty()) {
10446 // We have a nested-name tag ('struct foo::bar').
10447
10448 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010449 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010450 Name = 0;
10451 goto CreateNewDecl;
10452 }
10453
John McCall7f41d982009-09-11 04:59:25 +000010454 // If this is a friend or a reference to a class in a dependent
10455 // context, don't try to make a decl for it.
10456 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10457 DC = computeDeclContext(SS, false);
10458 if (!DC) {
10459 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010460 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010461 }
John McCall0b66eb32010-05-01 00:40:08 +000010462 } else {
10463 DC = computeDeclContext(SS, true);
10464 if (!DC) {
10465 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10466 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010467 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010468 }
John McCall7f41d982009-09-11 04:59:25 +000010469 }
10470
John McCall0b66eb32010-05-01 00:40:08 +000010471 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010472 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010473
Douglas Gregor8761da52009-02-03 00:34:39 +000010474 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010475 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010476 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010477
John McCall1f82f242009-11-18 22:49:29 +000010478 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010479 return 0;
John McCall6538c932009-10-10 05:48:19 +000010480
John McCall1f82f242009-11-18 22:49:29 +000010481 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010482 // Name lookup did not find anything. However, if the
10483 // nested-name-specifier refers to the current instantiation,
10484 // and that current instantiation has any dependent base
10485 // classes, we might find something at instantiation time: treat
10486 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010487 // But this only makes any sense for reference-like lookups.
10488 if (Previous.wasNotFoundInCurrentInstantiation() &&
10489 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010490 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010491 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010492 }
10493
10494 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010495 Diag(NameLoc, diag::err_not_tag_in_scope)
10496 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010497 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010498 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010499 goto CreateNewDecl;
10500 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010501 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010502 // If this is a named struct, check to see if there was a previous forward
10503 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010504 // FIXME: We're looking into outer scopes here, even when we
10505 // shouldn't be. Doing so can result in ambiguities that we
10506 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010507 LookupName(Previous, S);
10508
John McCall3c581bf2013-03-20 01:53:00 +000010509 // When declaring or defining a tag, ignore ambiguities introduced
10510 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010511 if (Previous.isAmbiguous() &&
10512 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010513 LookupResult::Filter F = Previous.makeFilter();
10514 while (F.hasNext()) {
10515 NamedDecl *ND = F.next();
10516 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10517 F.erase();
10518 }
10519 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010520 }
John McCall3c581bf2013-03-20 01:53:00 +000010521
10522 // C++11 [namespace.memdef]p3:
10523 // If the name in a friend declaration is neither qualified nor
10524 // a template-id and the declaration is a function or an
10525 // elaborated-type-specifier, the lookup to determine whether
10526 // the entity has been previously declared shall not consider
10527 // any scopes outside the innermost enclosing namespace.
10528 //
10529 // Does it matter that this should be by scope instead of by
10530 // semantic context?
10531 if (!Previous.empty() && TUK == TUK_Friend) {
10532 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10533 LookupResult::Filter F = Previous.makeFilter();
10534 while (F.hasNext()) {
10535 NamedDecl *ND = F.next();
10536 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010537 if (DC->isFileContext() &&
10538 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010539 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010540 FriendSawTagOutsideEnclosingNamespace = true;
10541 }
John McCall3c581bf2013-03-20 01:53:00 +000010542 }
10543 F.done();
10544 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010545
John McCall1f82f242009-11-18 22:49:29 +000010546 // Note: there used to be some attempt at recovery here.
10547 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010548 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010549
David Blaikiebbafb8a2012-03-11 07:00:24 +000010550 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010551 // FIXME: This makes sure that we ignore the contexts associated
10552 // with C structs, unions, and enums when looking for a matching
10553 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010554 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010555 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10556 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010557 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010558 } else if (S->isFunctionPrototypeScope()) {
10559 // If this is an enum declaration in function prototype scope, set its
10560 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010561 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010562 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010563 }
10564
John McCall1f82f242009-11-18 22:49:29 +000010565 if (Previous.isSingleResult() &&
10566 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010567 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010568 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010569 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010570 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010571 }
10572
David Blaikiebbafb8a2012-03-11 07:00:24 +000010573 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010574 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010575 // This is a declaration of or a reference to "std::bad_alloc".
10576 isStdBadAlloc = true;
10577
John McCall1f82f242009-11-18 22:49:29 +000010578 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010579 // std::bad_alloc has been implicitly declared (but made invisible to
10580 // name lookup). Fill in this implicit declaration as the previous
10581 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010582 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010583 }
10584 }
John McCall1f82f242009-11-18 22:49:29 +000010585
John McCalle9eaf8e2010-03-25 21:28:06 +000010586 // If we didn't find a previous declaration, and this is a reference
10587 // (or friend reference), move to the correct scope. In C++, we
10588 // also need to do a redeclaration lookup there, just in case
10589 // there's a shadow friend decl.
10590 if (Name && Previous.empty() &&
10591 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10592 if (Invalid) goto CreateNewDecl;
10593 assert(SS.isEmpty());
10594
10595 if (TUK == TUK_Reference) {
10596 // C++ [basic.scope.pdecl]p5:
10597 // -- for an elaborated-type-specifier of the form
10598 //
10599 // class-key identifier
10600 //
10601 // if the elaborated-type-specifier is used in the
10602 // decl-specifier-seq or parameter-declaration-clause of a
10603 // function defined in namespace scope, the identifier is
10604 // declared as a class-name in the namespace that contains
10605 // the declaration; otherwise, except as a friend
10606 // declaration, the identifier is declared in the smallest
10607 // non-class, non-function-prototype scope that contains the
10608 // declaration.
10609 //
10610 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10611 // C structs and unions.
10612 //
10613 // It is an error in C++ to declare (rather than define) an enum
10614 // type, including via an elaborated type specifier. We'll
10615 // diagnose that later; for now, declare the enum in the same
10616 // scope as we would have picked for any other tag type.
10617 //
10618 // GNU C also supports this behavior as part of its incomplete
10619 // enum types extension, while GNU C++ does not.
10620 //
10621 // Find the context where we'll be declaring the tag.
10622 // FIXME: We would like to maintain the current DeclContext as the
10623 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010624 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010625 SearchDC = SearchDC->getParent();
10626
10627 // Find the scope where we'll be declaring the tag.
10628 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010629 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010630 S->isFunctionPrototypeScope()) ||
10631 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010632 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010633 S = S->getParent();
10634 } else {
10635 assert(TUK == TUK_Friend);
10636 // C++ [namespace.memdef]p3:
10637 // If a friend declaration in a non-local class first declares a
10638 // class or function, the friend class or function is a member of
10639 // the innermost enclosing namespace.
10640 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010641 }
10642
John McCalle87beb22010-04-23 18:46:30 +000010643 // In C++, we need to do a redeclaration lookup to properly
10644 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010645 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010646 Previous.setRedeclarationKind(ForRedeclaration);
10647 LookupQualifiedName(Previous, SearchDC);
10648 }
10649 }
10650
John McCall1f82f242009-11-18 22:49:29 +000010651 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +000010652 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +000010653
10654 // It's okay to have a tag decl in the same scope as a typedef
10655 // which hides a tag decl in the same scope. Finding this
10656 // insanity with a redeclaration lookup can only actually happen
10657 // in C++.
10658 //
10659 // This is also okay for elaborated-type-specifiers, which is
10660 // technically forbidden by the current standard but which is
10661 // okay according to the likely resolution of an open issue;
10662 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010663 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010664 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010665 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10666 TagDecl *Tag = TT->getDecl();
10667 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010668 Tag->getDeclContext()->getRedeclContext()
10669 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010670 PrevDecl = Tag;
10671 Previous.clear();
10672 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010673 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010674 }
10675 }
10676 }
10677 }
10678
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010679 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010680 // If this is a use of a previous tag, or if the tag is already declared
10681 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010682 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010683 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Richard Smith72bcaec2013-12-05 04:30:04 +000010684 isDeclInScope(PrevDecl, SearchDC, S,
10685 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010686 // Make sure that this wasn't declared as an enum and now used as a
10687 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010688 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10689 TUK == TUK_Definition, KWLoc,
10690 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010691 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010692 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10693 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010694 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010695 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010696 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010697 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10698 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010699 else
10700 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010701 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010702
Mike Stump11289f42009-09-09 15:08:12 +000010703 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010704 Kind = PrevTagDecl->getTagKind();
10705 else {
10706 // Recover by making this an anonymous redefinition.
10707 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010708 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010709 Invalid = true;
10710 }
10711 }
10712
Douglas Gregor0bf31402010-10-08 23:50:27 +000010713 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10714 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10715
Richard Smith0f8ee222012-01-10 01:33:14 +000010716 // If this is an elaborated-type-specifier for a scoped enumeration,
10717 // the 'class' keyword is not necessary and not permitted.
10718 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10719 if (ScopedEnum)
10720 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10721 << PrevEnum->isScoped()
10722 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10723 return PrevTagDecl;
10724 }
10725
Richard Smith4b38ded2012-03-14 23:13:10 +000010726 QualType EnumUnderlyingTy;
10727 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10728 EnumUnderlyingTy = TI->getType();
10729 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10730 EnumUnderlyingTy = QualType(T, 0);
10731
Douglas Gregor0bf31402010-10-08 23:50:27 +000010732 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010733 // returning the previous declaration, unless this is a definition,
10734 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010735 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10736 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010737 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010738 }
10739
David Majnemer55890bf2013-06-11 03:51:23 +000010740 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010741 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010742 // except that a nested class or member class template can be declared
10743 // and then later defined.
10744 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10745 S->isDeclScope(PrevDecl)) {
10746 Diag(NameLoc, diag::ext_member_redeclared);
10747 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10748 }
10749
Douglas Gregor170512f2009-04-01 23:51:29 +000010750 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010751 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010752
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010753 // FIXME: In the future, return a variant or some other clue
10754 // for the consumer of this Decl to know it doesn't own it.
10755 // For our current ASTs this shouldn't be a problem, but will
10756 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010757 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010758 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010759 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010760
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010761 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010762 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010763 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010764 // If we're defining a specialization and the previous definition
10765 // is from an implicit instantiation, don't emit an error
10766 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010767 bool IsExplicitSpecializationAfterInstantiation = false;
10768 if (isExplicitSpecialization) {
10769 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10770 IsExplicitSpecializationAfterInstantiation =
10771 RD->getTemplateSpecializationKind() !=
10772 TSK_ExplicitSpecialization;
10773 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10774 IsExplicitSpecializationAfterInstantiation =
10775 ED->getTemplateSpecializationKind() !=
10776 TSK_ExplicitSpecialization;
10777 }
10778
10779 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010780 // A redeclaration in function prototype scope in C isn't
10781 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010782 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010783 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10784 else
10785 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010786 Diag(Def->getLocation(), diag::note_previous_definition);
10787 // If this is a redefinition, recover by making this
10788 // struct be anonymous, which will make any later
10789 // references get the previous definition.
10790 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010791 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010792 Invalid = true;
10793 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010794 } else {
10795 // If the type is currently being defined, complain
10796 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010797 const TagType *Tag
10798 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010799 if (Tag->isBeingDefined()) {
10800 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010801 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010802 diag::note_previous_definition);
10803 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010804 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010805 Invalid = true;
10806 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010807 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010808
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010809 // Okay, this is definition of a previously declared or referenced
10810 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010811 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010812 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010813 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010814 // have a definition. Just create a new decl.
10815
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010816 } else {
10817 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010818 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010819 // new decl/type. We set PrevDecl to NULL so that the entities
10820 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010821 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010822 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010823 // If we get here, we're going to create a new Decl. If PrevDecl
10824 // is non-NULL, it's a definition of the tag declared by
10825 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010826
10827
10828 // Otherwise, PrevDecl is not a tag, but was found with tag
10829 // lookup. This is only actually possible in C++, where a few
10830 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010831 } else {
John McCalle87beb22010-04-23 18:46:30 +000010832 // Use a better diagnostic if an elaborated-type-specifier
10833 // found the wrong kind of type on the first
10834 // (non-redeclaration) lookup.
10835 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10836 !Previous.isForRedeclaration()) {
10837 unsigned Kind = 0;
10838 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010839 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10840 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010841 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10842 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10843 Invalid = true;
10844
10845 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010846 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10847 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010848 // do nothing
10849
10850 // Diagnose implicit declarations introduced by elaborated types.
10851 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10852 unsigned Kind = 0;
10853 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010854 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10855 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010856 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10857 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10858 Invalid = true;
10859
10860 // Otherwise it's a declaration. Call out a particularly common
10861 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010862 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10863 unsigned Kind = 0;
10864 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010865 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010866 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010867 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10868 Invalid = true;
10869
10870 // Otherwise, diagnose.
10871 } else {
10872 // The tag name clashes with something else in the target scope,
10873 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010874 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010875 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010876 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010877 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010878 }
John McCalle87beb22010-04-23 18:46:30 +000010879
10880 // The existing declaration isn't relevant to us; we're in a
10881 // new scope, so clear out the previous declaration.
10882 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010883 }
Chris Lattner18b19622007-01-22 07:39:13 +000010884 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010885
Chris Lattner438e5012008-12-17 07:13:27 +000010886CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010887
John McCall1f82f242009-11-18 22:49:29 +000010888 TagDecl *PrevDecl = 0;
10889 if (Previous.isSingleResult())
10890 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10891
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010892 // If there is an identifier, use the location of the identifier as the
10893 // location of the decl, otherwise use the location of the struct/union
10894 // keyword.
10895 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010896
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010897 // Otherwise, create a new declaration. If there is a previous
10898 // declaration of the same entity, the two will be linked via
10899 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010900 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010901
Douglas Gregor0bf31402010-10-08 23:50:27 +000010902 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010903 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010904 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10905 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010906 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010907 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010908 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010909 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010910 if (TUK != TUK_Definition && !Invalid) {
10911 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010912 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10913 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010914 // C++0x: 7.2p2: opaque-enum-declaration.
10915 // Conflicts are diagnosed above. Do nothing.
10916 }
10917 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010918 Diag(Loc, diag::ext_forward_ref_enum_def)
10919 << New;
10920 Diag(Def->getLocation(), diag::note_previous_definition);
10921 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010922 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010923 if (getLangOpts().MicrosoftMode)
Francois Pichet488b4a72010-09-12 05:06:55 +000010924 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010925 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010926 DiagID = diag::err_forward_ref_enum;
10927 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010928
10929 // If this is a forward-declared reference to an enumeration, make a
10930 // note of it; we won't actually be introducing the declaration into
10931 // the declaration context.
10932 if (TUK == TUK_Reference)
10933 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010934 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010935 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010936
10937 if (EnumUnderlying) {
10938 EnumDecl *ED = cast<EnumDecl>(New);
10939 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10940 ED->setIntegerTypeSourceInfo(TI);
10941 else
10942 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10943 ED->setPromotionType(ED->getIntegerType());
10944 }
10945
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010946 } else {
10947 // struct/union/class
10948
Chris Lattner776fac82007-06-09 00:53:06 +000010949 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10950 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010951 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010952 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010953 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010954 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010955
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010956 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010957 StdBadAlloc = cast<CXXRecordDecl>(New);
10958 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010959 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010960 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000010961 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010962
John McCall3e11ebe2010-03-15 10:12:16 +000010963 // Maybe add qualifier info.
10964 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010965 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010966 // If this is either a declaration or a definition, check the
10967 // nested-name-specifier against the current context. We don't do this
10968 // for explicit specializations, because they have similar checking
10969 // (with more specific diagnostics) in the call to
10970 // CheckMemberSpecialization, below.
10971 if (!isExplicitSpecialization &&
10972 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10973 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10974 Invalid = true;
10975
Douglas Gregor14454802011-02-25 02:25:35 +000010976 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000010977 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000010978 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000010979 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010980 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000010981 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010982 }
10983 else
10984 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000010985 }
10986
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000010987 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10988 // Add alignment attributes if necessary; these attributes are checked when
10989 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010990 //
10991 // It is important for implementing the correct semantics that this
10992 // happen here (in act on tag decl). The #pragma pack stack is
10993 // maintained as a result of parser callbacks which can occur at
10994 // many points during the parsing of a struct declaration (because
10995 // the #pragma tokens are effectively skipped over during the
10996 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000010997 if (TUK == TUK_Definition) {
10998 AddAlignmentAttributesForRecord(RD);
10999 AddMsStructLayoutForRecord(RD);
11000 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011001 }
11002
Douglas Gregor21823bf2011-12-20 18:11:52 +000011003 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011004 if (isExplicitSpecialization)
11005 Diag(New->getLocation(), diag::err_module_private_specialization)
11006 << 2
11007 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011008 // __module_private__ does not apply to local classes. However, we only
11009 // diagnose this as an error when the declaration specifiers are
11010 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011011 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011012 New->setModulePrivate();
11013 }
11014
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011015 // If this is a specialization of a member class (of a class template),
11016 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011017 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011018 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011019
Douglas Gregordee1be82009-01-17 00:42:38 +000011020 if (Invalid)
11021 New->setInvalidDecl();
11022
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011023 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011024 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011025
Douglas Gregordee1be82009-01-17 00:42:38 +000011026 // If we're declaring or defining a tag in function prototype scope
11027 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011028 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +000011029 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11030
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011031 // Set the lexical context. If the tag has a C++ scope specifier, the
11032 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011033 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011034
John McCallaa74a0c2009-08-28 07:59:38 +000011035 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011036 // In Microsoft mode, a friend declaration also acts as a forward
11037 // declaration so we always pass true to setObjectOfFriendDecl to make
11038 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011039 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011040 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11041 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011042
Anders Carlsson5558ca12009-03-26 01:19:02 +000011043 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011044 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011045 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011046
John McCall9bb74a52009-07-31 02:45:11 +000011047 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011048 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011049
Chris Lattner18b19622007-01-22 07:39:13 +000011050 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011051 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011052 // We might be replacing an existing declaration in the lookup tables;
11053 // if so, borrow its access specifier.
11054 if (PrevDecl)
11055 New->setAccess(PrevDecl->getAccess());
11056
Sebastian Redl50c68252010-08-31 00:36:30 +000011057 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011058 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011059 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011060 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11061 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011062 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011063 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011064 PushOnScopeChains(New, S, !IsForwardReference);
11065 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011066 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011067
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011068 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011069 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011070 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011071
Douglas Gregor27821ce2009-07-07 16:35:42 +000011072 // If this is the C FILE type, notify the AST context.
11073 if (IdentifierInfo *II = New->getIdentifier())
11074 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011075 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011076 II->isStr("FILE"))
11077 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011078
James Molloy6f8780b2012-02-29 10:24:19 +000011079 // If we were in function prototype scope (and not in C++ mode), add this
11080 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011081 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +000011082 InFunctionDeclarator && Name)
11083 DeclsInPrototypeScope.push_back(New);
11084
Rafael Espindolac67f2232012-05-10 02:50:16 +000011085 if (PrevDecl)
11086 mergeDeclAttributes(New, PrevDecl);
11087
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011088 // If there's a #pragma GCC visibility in scope, set the visibility of this
11089 // record.
11090 AddPushedVisibilityAttribute(New);
11091
Douglas Gregord6ab8742009-05-28 23:31:59 +000011092 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011093 // In C++, don't return an invalid declaration. We can't recover well from
11094 // the cases where we make the type anonymous.
11095 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011096}
Chris Lattner1300fb92007-01-23 23:42:53 +000011097
John McCall48871652010-08-21 09:40:31 +000011098void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011099 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011100 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011101
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011102 // Enter the tag context.
11103 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011104
11105 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011106
11107 // If there's a #pragma GCC visibility in scope, set the visibility of this
11108 // record.
11109 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011110}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011111
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011112Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011113 assert(isa<ObjCContainerDecl>(IDecl) &&
11114 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11115 DeclContext *OCD = cast<DeclContext>(IDecl);
11116 assert(getContainingDC(OCD) == CurContext &&
11117 "The next DeclContext should be lexically contained in the current one.");
11118 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011119 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011120}
11121
John McCall48871652010-08-21 09:40:31 +000011122void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011123 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011124 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011125 SourceLocation LBraceLoc) {
11126 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011127 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011128
John McCall1c7e6ec2009-12-20 07:58:13 +000011129 FieldCollector->StartClass();
11130
11131 if (!Record->getIdentifier())
11132 return;
11133
Anders Carlsson30f29442011-03-25 14:31:08 +000011134 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011135 Record->addAttr(new (Context)
11136 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11137
John McCall1c7e6ec2009-12-20 07:58:13 +000011138 // C++ [class]p2:
11139 // [...] The class-name is also inserted into the scope of the
11140 // class itself; this is known as the injected-class-name. For
11141 // purposes of access checking, the injected-class-name is treated
11142 // as if it were a public member name.
11143 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011144 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11145 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011146 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011147 /*PrevDecl=*/0,
11148 /*DelayTypeCreation=*/true);
11149 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011150 InjectedClassName->setImplicit();
11151 InjectedClassName->setAccess(AS_public);
11152 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11153 InjectedClassName->setDescribedClassTemplate(Template);
11154 PushOnScopeChains(InjectedClassName, S);
11155 assert(InjectedClassName->isInjectedClassName() &&
11156 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011157}
11158
John McCall48871652010-08-21 09:40:31 +000011159void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011160 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011161 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011162 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011163 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011164
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011165 // Make sure we "complete" the definition even it is invalid.
11166 if (Tag->isBeingDefined()) {
11167 assert(Tag->isInvalidDecl() && "We should already have completed it");
11168 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11169 RD->completeDefinition();
11170 }
11171
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011172 if (isa<CXXRecordDecl>(Tag))
11173 FieldCollector->FinishClass();
11174
11175 // Exit this scope of this tag's definition.
11176 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011177
11178 if (getCurLexicalContext()->isObjCContainer() &&
11179 Tag->getDeclContext()->isFileContext())
11180 Tag->setTopLevelDeclInObjCContainer();
11181
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011182 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011183 if (!Tag->isInvalidDecl())
11184 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011185}
Chris Lattner535b8302008-06-21 19:39:06 +000011186
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011187void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011188 // Exit this scope of this interface definition.
11189 PopDeclContext();
11190}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011191
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011192void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011193 assert(DC == CurContext && "Mismatch of container contexts");
11194 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011195 ActOnObjCContainerFinishDefinition();
11196}
11197
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011198void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11199 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011200 OriginalLexicalContext = 0;
11201}
11202
John McCall48871652010-08-21 09:40:31 +000011203void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011204 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011205 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011206 Tag->setInvalidDecl();
11207
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011208 // Make sure we "complete" the definition even it is invalid.
11209 if (Tag->isBeingDefined()) {
11210 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11211 RD->completeDefinition();
11212 }
11213
John McCall71ba5f22010-03-17 19:25:57 +000011214 // We're undoing ActOnTagStartDefinition here, not
11215 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11216 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011217
11218 PopDeclContext();
11219}
11220
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011221// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011222ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11223 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011224 QualType FieldTy, bool IsMsStruct,
11225 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011226 // Default to true; that shouldn't confuse checks for emptiness
11227 if (ZeroWidth)
11228 *ZeroWidth = true;
11229
Chris Lattner73bf7b42009-03-05 22:45:59 +000011230 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011231 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011232 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011233 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011234 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011235 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011236 if (FieldName)
11237 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11238 << FieldName << FieldTy << BitWidth->getSourceRange();
11239 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11240 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011241 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11242 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011243 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011244
11245 // If the bit-width is type- or value-dependent, don't try to check
11246 // it now.
11247 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011248 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011249
Anders Carlsson5df391e2008-12-06 20:33:04 +000011250 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011251 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11252 if (ICE.isInvalid())
11253 return ICE;
11254 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011255
Eli Friedmanc96d4962009-08-15 21:55:26 +000011256 if (Value != 0 && ZeroWidth)
11257 *ZeroWidth = false;
11258
Chris Lattner81ed6802008-12-12 04:56:04 +000011259 // Zero-width bitfield is ok for anonymous field.
11260 if (Value == 0 && FieldName)
11261 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011262
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011263 if (Value.isSigned() && Value.isNegative()) {
11264 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011265 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011266 << FieldName << Value.toString(10);
11267 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11268 << Value.toString(10);
11269 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011270
Douglas Gregor1efa4372009-03-11 18:59:21 +000011271 if (!FieldTy->isDependentType()) {
11272 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011273 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011274 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011275 if (FieldName)
11276 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11277 << FieldName << (unsigned)Value.getZExtValue()
11278 << (unsigned)TypeSize;
11279
11280 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11281 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11282 }
11283
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011284 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011285 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11286 << FieldName << (unsigned)Value.getZExtValue()
11287 << (unsigned)TypeSize;
11288 else
11289 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11290 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011291 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011292 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011293
Richard Smithf4c51d92012-02-04 09:53:13 +000011294 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011295}
11296
Richard Smith938f40b2011-06-11 17:19:42 +000011297/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011298/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011299Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011300 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011301 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011302 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011303 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011304 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011305}
11306
11307/// HandleField - Analyze a field of a C struct or a C++ data member.
11308///
11309FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11310 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011311 Declarator &D, Expr *BitWidth,
11312 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011313 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011314 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011315 SourceLocation Loc = DeclStart;
11316 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011317
John McCall8cb7bdf2010-06-04 23:28:52 +000011318 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11319 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011320 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011321 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011322
Douglas Gregora02a72a2010-12-15 23:18:36 +000011323 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11324 UPPC_DataMemberType)) {
11325 D.setInvalidType();
11326 T = Context.IntTy;
11327 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11328 }
11329 }
11330
Matt Arsenault376f7202013-02-26 21:16:00 +000011331 // TR 18037 does not allow fields to be declared with address spaces.
11332 if (T.getQualifiers().hasAddressSpace()) {
11333 Diag(Loc, diag::err_field_with_address_space);
11334 D.setInvalidType();
11335 }
11336
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011337 // OpenCL 1.2 spec, s6.9 r:
11338 // The event type cannot be used to declare a structure or union field.
11339 if (LangOpts.OpenCL && T->isEventT()) {
11340 Diag(Loc, diag::err_event_t_struct_field);
11341 D.setInvalidType();
11342 }
11343
Richard Smithb1402ae2013-03-18 22:52:47 +000011344 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011345
Richard Smithb4a9e862013-04-12 22:46:28 +000011346 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11347 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11348 diag::err_invalid_thread)
11349 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011350
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011351 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011352 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011353 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11354 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011355 switch (Previous.getResultKind()) {
11356 case LookupResult::Found:
11357 case LookupResult::FoundUnresolvedValue:
11358 PrevDecl = Previous.getAsSingle<NamedDecl>();
11359 break;
11360
11361 case LookupResult::FoundOverloaded:
11362 PrevDecl = Previous.getRepresentativeDecl();
11363 break;
11364
11365 case LookupResult::NotFound:
11366 case LookupResult::NotFoundInCurrentInstantiation:
11367 case LookupResult::Ambiguous:
11368 break;
11369 }
11370 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011371
11372 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11373 // Maybe we will complain about the shadowed template parameter.
11374 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11375 // Just pretend that we didn't see the previous declaration.
11376 PrevDecl = 0;
11377 }
11378
Douglas Gregor1efa4372009-03-11 18:59:21 +000011379 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11380 PrevDecl = 0;
11381
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011382 bool Mutable
11383 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011384 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011385 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011386 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011387 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011388
11389 if (NewFD->isInvalidDecl())
11390 Record->setInvalidDecl();
11391
Douglas Gregor3baa6702011-09-12 16:11:24 +000011392 if (D.getDeclSpec().isModulePrivateSpecified())
11393 NewFD->setModulePrivate();
11394
Douglas Gregor1efa4372009-03-11 18:59:21 +000011395 if (NewFD->isInvalidDecl() && PrevDecl) {
11396 // Don't introduce NewFD into scope; there's already something
11397 // with the same name in the same scope.
11398 } else if (II) {
11399 PushOnScopeChains(NewFD, S);
11400 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011401 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011402
11403 return NewFD;
11404}
11405
11406/// \brief Build a new FieldDecl and check its well-formedness.
11407///
11408/// This routine builds a new FieldDecl given the fields name, type,
11409/// record, etc. \p PrevDecl should refer to any previous declaration
11410/// with the same name and in the same scope as the field to be
11411/// created.
11412///
11413/// \returns a new FieldDecl.
11414///
Mike Stump11289f42009-09-09 15:08:12 +000011415/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011416FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011417 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011418 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011419 bool Mutable, Expr *BitWidth,
11420 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011421 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011422 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011423 Declarator *D) {
11424 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011425 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011426 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011427
Douglas Gregor1efa4372009-03-11 18:59:21 +000011428 // If we receive a broken type, recover by assuming 'int' and
11429 // marking this declaration as invalid.
11430 if (T.isNull()) {
11431 InvalidDecl = true;
11432 T = Context.IntTy;
11433 }
11434
Eli Friedmand0e8de22009-12-07 00:22:08 +000011435 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011436 if (!EltTy->isDependentType()) {
11437 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11438 // Fields of incomplete type force their record to be invalid.
11439 Record->setInvalidDecl();
11440 InvalidDecl = true;
11441 } else {
11442 NamedDecl *Def;
11443 EltTy->isIncompleteType(&Def);
11444 if (Def && Def->isInvalidDecl()) {
11445 Record->setInvalidDecl();
11446 InvalidDecl = true;
11447 }
11448 }
John McCall2677e102010-08-16 23:42:35 +000011449 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011450
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011451 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11452 if (BitWidth && getLangOpts().OpenCL) {
11453 Diag(Loc, diag::err_opencl_bitfields);
11454 InvalidDecl = true;
11455 }
11456
Steve Naroff8eeeb132007-05-08 21:09:37 +000011457 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11458 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011459 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011460 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011461 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011462
11463 TypeSourceInfo *FixedTInfo =
11464 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11465 SizeIsNegative,
11466 Oversized);
11467 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011468 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011469 TInfo = FixedTInfo;
11470 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011471 } else {
11472 if (SizeIsNegative)
11473 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011474 else if (Oversized.getBoolValue())
11475 Diag(Loc, diag::err_array_too_large)
11476 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011477 else
11478 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011479 InvalidDecl = true;
11480 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011481 }
Mike Stump11289f42009-09-09 15:08:12 +000011482
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011483 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011484 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11485 diag::err_abstract_type_in_decl,
11486 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011487 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011488
Eli Friedmanc96d4962009-08-15 21:55:26 +000011489 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011490 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011491 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011492 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11493 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011494 if (!BitWidth) {
11495 InvalidDecl = true;
11496 BitWidth = 0;
11497 ZeroWidth = false;
11498 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011499 }
Mike Stump11289f42009-09-09 15:08:12 +000011500
John McCallb1cd7da2010-06-04 08:34:12 +000011501 // Check that 'mutable' is consistent with the type of the declaration.
11502 if (!InvalidDecl && Mutable) {
11503 unsigned DiagID = 0;
11504 if (T->isReferenceType())
11505 DiagID = diag::err_mutable_reference;
11506 else if (T.isConstQualified())
11507 DiagID = diag::err_mutable_const;
11508
11509 if (DiagID) {
11510 SourceLocation ErrLoc = Loc;
11511 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11512 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11513 Diag(ErrLoc, DiagID);
11514 Mutable = false;
11515 InvalidDecl = true;
11516 }
11517 }
11518
Abramo Bagnaradff19302011-03-08 08:55:46 +000011519 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011520 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011521 if (InvalidDecl)
11522 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011523
Douglas Gregor1efa4372009-03-11 18:59:21 +000011524 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11525 Diag(Loc, diag::err_duplicate_member) << II;
11526 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11527 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011528 }
11529
David Blaikiebbafb8a2012-03-11 07:00:24 +000011530 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011531 if (Record->isUnion()) {
11532 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11533 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11534 if (RDecl->getDefinition()) {
11535 // C++ [class.union]p1: An object of a class with a non-trivial
11536 // constructor, a non-trivial copy constructor, a non-trivial
11537 // destructor, or a non-trivial copy assignment operator
11538 // cannot be a member of a union, nor can an array of such
11539 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011540 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011541 NewFD->setInvalidDecl();
11542 }
11543 }
11544
11545 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011546 // the program is ill-formed, except when compiling with MSVC extensions
11547 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011548 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011549 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11550 diag::ext_union_member_of_reference_type :
11551 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011552 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011553 if (!getLangOpts().MicrosoftExt)
11554 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011555 }
11556 }
11557 }
11558
Douglas Gregor1efa4372009-03-11 18:59:21 +000011559 // FIXME: We need to pass in the attributes given an AST
11560 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011561 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011562 // FIXME: The current scope is almost... but not entirely... correct here.
11563 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011564
Richard Smith848e1f12013-02-01 08:12:08 +000011565 if (NewFD->hasAttrs())
11566 CheckAlignasUnderalignment(NewFD);
11567 }
11568
John McCall31168b02011-06-15 23:02:42 +000011569 // In auto-retain/release, infer strong retension for fields of
11570 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011571 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011572 NewFD->setInvalidDecl();
11573
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011574 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011575 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011576
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011577 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011578 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011579}
11580
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011581bool Sema::CheckNontrivialField(FieldDecl *FD) {
11582 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011583 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011584
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011585 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11586 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011587
11588 QualType EltTy = Context.getBaseElementType(FD->getType());
11589 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011590 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011591 if (RDecl->getDefinition()) {
11592 // We check for copy constructors before constructors
11593 // because otherwise we'll never get complaints about
11594 // copy constructors.
11595
11596 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011597 // We're required to check for any non-trivial constructors. Since the
11598 // implicit default constructor is suppressed if there are any
11599 // user-declared constructors, we just need to check that there is a
11600 // trivial default constructor and a trivial copy constructor. (We don't
11601 // worry about move constructors here, since this is a C++98 check.)
11602 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011603 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011604 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011605 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011606 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011607 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011608 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011609 member = CXXDestructor;
11610
11611 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011612 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011613 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011614 // Objective-C++ ARC: it is an error to have a non-trivial field of
11615 // a union. However, system headers in Objective-C programs
11616 // occasionally have Objective-C lifetime objects within unions,
11617 // and rather than cause the program to fail, we make those
11618 // members unavailable.
11619 SourceLocation Loc = FD->getLocation();
11620 if (getSourceManager().isInSystemHeader(Loc)) {
11621 if (!FD->hasAttr<UnavailableAttr>())
11622 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000011623 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000011624 return false;
11625 }
11626 }
Richard Smithf720df02011-10-19 20:41:51 +000011627
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011628 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011629 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11630 diag::err_illegal_union_or_anon_struct_member)
11631 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011632 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011633 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011634 }
11635 }
11636 }
Richard Smith92f241f2012-12-08 02:53:02 +000011637
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011638 return false;
11639}
11640
Mike Stump11289f42009-09-09 15:08:12 +000011641/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011642/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011643static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011644TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011645 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011646 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011647 case tok::objc_private: return ObjCIvarDecl::Private;
11648 case tok::objc_public: return ObjCIvarDecl::Public;
11649 case tok::objc_protected: return ObjCIvarDecl::Protected;
11650 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011651 }
11652}
11653
Mike Stump11289f42009-09-09 15:08:12 +000011654/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011655/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011656Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011657 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011658 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011659 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011660
Fariborz Jahaniande615832008-04-10 23:32:45 +000011661 IdentifierInfo *II = D.getIdentifier();
11662 Expr *BitWidth = (Expr*)BitfieldWidth;
11663 SourceLocation Loc = DeclStart;
11664 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011665
Fariborz Jahaniande615832008-04-10 23:32:45 +000011666 // FIXME: Unnamed fields can be handled in various different ways, for
11667 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011668
John McCall8cb7bdf2010-06-04 23:28:52 +000011669 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11670 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011671
Fariborz Jahaniande615832008-04-10 23:32:45 +000011672 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011673 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011674 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011675 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011676 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011677 } else {
11678 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011679
Fariborz Jahaniande615832008-04-10 23:32:45 +000011680 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011681
Fariborz Jahaniande615832008-04-10 23:32:45 +000011682 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011683 if (T->isReferenceType()) {
11684 Diag(Loc, diag::err_ivar_reference_type);
11685 D.setInvalidType();
11686 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011687 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11688 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011689 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011690 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011691 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011692 }
Mike Stump11289f42009-09-09 15:08:12 +000011693
Ted Kremenek73295fa2008-07-23 18:04:17 +000011694 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011695 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011696 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11697 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011698 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011699 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011700 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11701 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011702 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011703 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011704 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011705 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011706 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011707 EnclosingContext = IMPDecl->getClassInterface();
11708 assert(EnclosingContext && "Implementation has no class interface!");
11709 }
11710 else
11711 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011712 } else {
11713 if (ObjCCategoryDecl *CDecl =
11714 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011715 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011716 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011717 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011718 }
11719 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011720 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011721 }
Mike Stump11289f42009-09-09 15:08:12 +000011722
Ted Kremenek73295fa2008-07-23 18:04:17 +000011723 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011724 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11725 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011726 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011727
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011728 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011729 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011730 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011731 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011732 && !isa<TagDecl>(PrevDecl)) {
11733 Diag(Loc, diag::err_duplicate_member) << II;
11734 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11735 NewID->setInvalidDecl();
11736 }
11737 }
11738
Ted Kremenek73295fa2008-07-23 18:04:17 +000011739 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011740 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011741
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011742 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011743 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011744
John McCall31168b02011-06-15 23:02:42 +000011745 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011746 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011747 NewID->setInvalidDecl();
11748
Douglas Gregor3baa6702011-09-12 16:11:24 +000011749 if (D.getDeclSpec().isModulePrivateSpecified())
11750 NewID->setModulePrivate();
11751
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011752 if (II) {
11753 // FIXME: When interfaces are DeclContexts, we'll need to add
11754 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011755 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011756 IdResolver.AddDecl(NewID);
11757 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011758
John McCall5fb5df92012-06-20 06:18:46 +000011759 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011760 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011761 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011762
John McCall48871652010-08-21 09:40:31 +000011763 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011764}
11765
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011766/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011767/// class and class extensions. For every class \@interface and class
11768/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011769/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011770void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011771 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011772 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011773 return;
11774
11775 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11776 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11777
Richard Smithcaf33902011-10-10 18:28:20 +000011778 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011779 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011780 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011781 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011782 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011783 if (!CD->IsClassExtension())
11784 return;
11785 }
11786 // No need to add this to end of @implementation.
11787 else
11788 return;
11789 }
11790 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011791 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11792 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011793
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011794 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011795 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011796 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011797 Context.getTrivialTypeSourceInfo(Context.CharTy,
11798 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011799 ObjCIvarDecl::Private, BW,
11800 true);
11801 AllIvarDecls.push_back(Ivar);
11802}
11803
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011804void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11805 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11806 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011807 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011808
Eric Christopher7457aaf2012-07-19 22:22:51 +000011809 // If this is an Objective-C @implementation or category and we have
11810 // new fields here we should reset the layout of the interface since
11811 // it will now change.
11812 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11813 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11814 switch (DC->getKind()) {
11815 default: break;
11816 case Decl::ObjCCategory:
11817 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11818 break;
11819 case Decl::ObjCImplementation:
11820 Context.
11821 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11822 break;
11823 }
11824 }
11825
Eli Friedmana7679412012-02-07 05:00:47 +000011826 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11827
11828 // Start counting up the number of named members; make sure to include
11829 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011830 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011831 if (Record) {
11832 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11833 e = Record->decls_end(); i != e; i++) {
11834 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11835 if (IFD->getDeclName())
11836 ++NumNamedMembers;
11837 }
11838 }
11839
11840 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011841 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011842
John McCall31168b02011-06-15 23:02:42 +000011843 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011844 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011845 i != end; ++i) {
11846 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011847
Chris Lattner720a0542007-01-25 00:44:24 +000011848 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011849 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011850
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011851 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011852 // Remember all fields written by the user.
11853 RecFields.push_back(FD);
11854 }
Mike Stump11289f42009-09-09 15:08:12 +000011855
Chris Lattner73bf7b42009-03-05 22:45:59 +000011856 // If the field is already invalid for some reason, don't emit more
11857 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011858 if (FD->isInvalidDecl()) {
11859 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011860 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011861 }
Mike Stump11289f42009-09-09 15:08:12 +000011862
Douglas Gregorac1fb652009-03-24 19:52:54 +000011863 // C99 6.7.2.1p2:
11864 // A structure or union shall not contain a member with
11865 // incomplete or function type (hence, a structure shall not
11866 // contain an instance of itself, but may contain a pointer to
11867 // an instance of itself), except that the last member of a
11868 // structure with more than one named member may have incomplete
11869 // array type; such a structure (and any union containing,
11870 // possibly recursively, a member that is such a structure)
11871 // shall not be a member of a structure or an element of an
11872 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011873 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011874 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011875 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011876 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011877 FD->setInvalidDecl();
11878 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011879 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011880 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011881 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011882 ((getLangOpts().MicrosoftExt ||
11883 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011884 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011885 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011886 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011887 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011888 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011889 unsigned DiagID = 0;
11890 if (Record->isUnion())
11891 DiagID = getLangOpts().MicrosoftExt
11892 ? diag::ext_flexible_array_union_ms
11893 : getLangOpts().CPlusPlus
11894 ? diag::ext_flexible_array_union_gnu
11895 : diag::err_flexible_array_union;
11896 else if (Fields.size() == 1)
11897 DiagID = getLangOpts().MicrosoftExt
11898 ? diag::ext_flexible_array_empty_aggregate_ms
11899 : getLangOpts().CPlusPlus
11900 ? diag::ext_flexible_array_empty_aggregate_gnu
11901 : NumNamedMembers < 1
11902 ? diag::err_flexible_array_empty_aggregate
11903 : 0;
11904
11905 if (DiagID)
11906 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11907 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011908 // While the layout of types that contain virtual bases is not specified
11909 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11910 // virtual bases after the derived members. This would make a flexible
11911 // array member declared at the end of an object not adjacent to the end
11912 // of the type.
11913 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11914 if (RD->getNumVBases() != 0)
11915 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11916 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011917 if (!getLangOpts().C99)
11918 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11919 << FD->getDeclName() << Record->getTagKind();
11920
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011921 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +000011922 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011923 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011924 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011925 FD->setInvalidDecl();
11926 EnclosingDecl->setInvalidDecl();
11927 continue;
11928 }
Chris Lattner720a0542007-01-25 00:44:24 +000011929 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011930 if (Record)
11931 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011932 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011933 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011934 diag::err_field_incomplete)) {
11935 // Incomplete type
11936 FD->setInvalidDecl();
11937 EnclosingDecl->setInvalidDecl();
11938 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011939 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011940 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11941 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011942 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000011943 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011944 } else {
11945 // If this is a struct/class and this is not the last element, reject
11946 // it. Note that GCC supports variable sized arrays in the middle of
11947 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000011948 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011949 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000011950 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011951 else {
11952 // We support flexible arrays at the end of structs in
11953 // other structs as an extension.
11954 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11955 << FD->getDeclName();
11956 if (Record)
11957 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011958 }
Chris Lattner720a0542007-01-25 00:44:24 +000011959 }
11960 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000011961 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11962 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11963 diag::err_abstract_type_in_decl,
11964 AbstractIvarType)) {
11965 // Ivars can not have abstract class types
11966 FD->setInvalidDecl();
11967 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000011968 if (Record && FDTTy->getDecl()->hasObjectMember())
11969 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000011970 if (Record && FDTTy->getDecl()->hasVolatileMember())
11971 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000011972 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011973 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000011974 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11975 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11976 QualType T = Context.getObjCObjectPointerType(FD->getType());
11977 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011978 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11979 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11980 // It's an error in ARC if a field has lifetime.
11981 // We don't want to report this in a system header, though,
11982 // so we just make the field unavailable.
11983 // FIXME: that's really not sufficient; we need to make the type
11984 // itself invalid to, say, initialize or copy.
11985 QualType T = FD->getType();
11986 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11987 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11988 SourceLocation loc = FD->getLocation();
11989 if (getSourceManager().isInSystemHeader(loc)) {
11990 if (!FD->hasAttr<UnavailableAttr>()) {
11991 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11992 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000011993 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011994 } else {
11995 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000011996 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000011997 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011998 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000011999 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012000 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012001 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012002 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012003 if (FD->getType()->isObjCObjectPointerType() ||
12004 FD->getType().isObjCGCStrong())
12005 Record->setHasObjectMember(true);
12006 else if (Context.getAsArrayType(FD->getType())) {
12007 QualType BaseType = Context.getBaseElementType(FD->getType());
12008 if (BaseType->isRecordType() &&
12009 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012010 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012011 else if (BaseType->isObjCObjectPointerType() ||
12012 BaseType.isObjCGCStrong())
12013 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012014 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012015 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012016 if (Record && FD->getType().isVolatileQualified())
12017 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012018 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012019 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012020 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012021 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012022
Chris Lattner82625602007-01-24 02:26:21 +000012023 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012024 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012025 bool Completed = false;
12026 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12027 if (!CXXRecord->isInvalidDecl()) {
12028 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012029 for (CXXRecordDecl::conversion_iterator
12030 I = CXXRecord->conversion_begin(),
12031 E = CXXRecord->conversion_end(); I != E; ++I)
12032 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012033
12034 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012035 if (CXXRecord->hasUserDeclaredDestructor()) {
12036 // Adjust user-defined destructor exception spec.
12037 if (getLangOpts().CPlusPlus11)
12038 AdjustDestructorExceptionSpec(CXXRecord,
12039 CXXRecord->getDestructor());
12040
12041 // The Microsoft ABI requires that we perform the destructor body
12042 // checks (i.e. operator delete() lookup) at every declaration, as
12043 // any translation unit may need to emit a deleting destructor.
12044 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12045 CheckDestructor(CXXRecord->getDestructor());
12046 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012047
Douglas Gregor8fb95122010-09-29 00:15:42 +000012048 // Add any implicitly-declared members to this class.
12049 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12050
12051 // If we have virtual base classes, we may end up finding multiple
12052 // final overriders for a given virtual function. Check for this
12053 // problem now.
12054 if (CXXRecord->getNumVBases()) {
12055 CXXFinalOverriderMap FinalOverriders;
12056 CXXRecord->getFinalOverriders(FinalOverriders);
12057
12058 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12059 MEnd = FinalOverriders.end();
12060 M != MEnd; ++M) {
12061 for (OverridingMethods::iterator SO = M->second.begin(),
12062 SOEnd = M->second.end();
12063 SO != SOEnd; ++SO) {
12064 assert(SO->second.size() > 0 &&
12065 "Virtual function without overridding functions?");
12066 if (SO->second.size() == 1)
12067 continue;
12068
12069 // C++ [class.virtual]p2:
12070 // In a derived class, if a virtual member function of a base
12071 // class subobject has more than one final overrider the
12072 // program is ill-formed.
12073 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012074 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012075 Diag(M->first->getLocation(),
12076 diag::note_overridden_virtual_function);
12077 for (OverridingMethods::overriding_iterator
12078 OM = SO->second.begin(),
12079 OMEnd = SO->second.end();
12080 OM != OMEnd; ++OM)
12081 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012082 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012083
12084 Record->setInvalidDecl();
12085 }
12086 }
12087 CXXRecord->completeDefinition(&FinalOverriders);
12088 Completed = true;
12089 }
12090 }
12091 }
12092 }
12093
12094 if (!Completed)
12095 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012096
Richard Smith848e1f12013-02-01 08:12:08 +000012097 if (Record->hasAttrs())
12098 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012099
Serge Pavlov3cb80222013-11-14 02:13:03 +000012100 // Check if the structure/union declaration is a type that can have zero
12101 // size in C. For C this is a language extension, for C++ it may cause
12102 // compatibility problems.
12103 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012104 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012105 CheckForZeroSize = true;
12106 } else {
12107 // For C++ filter out types that cannot be referenced in C code.
12108 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12109 CheckForZeroSize =
12110 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12111 !CXXRecord->isDependentType() &&
12112 CXXRecord->isCLike();
12113 }
12114 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012115 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012116 bool IsEmpty = true;
12117 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012118 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012119 E = Record->field_end();
12120 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12121 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012122 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012123 if (I->getBitWidthValue(Context) > 0)
12124 ZeroSize = false;
12125 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012126 ++NonBitFields;
12127 QualType FieldType = I->getType();
12128 if (FieldType->isIncompleteType() ||
12129 !Context.getTypeSizeInChars(FieldType).isZero())
12130 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012131 }
12132 }
12133
Serge Pavlov3cb80222013-11-14 02:13:03 +000012134 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12135 // allowed in C++, but warn if its declaration is inside
12136 // extern "C" block.
12137 if (ZeroSize) {
12138 Diag(RecLoc, getLangOpts().CPlusPlus ?
12139 diag::warn_zero_size_struct_union_in_extern_c :
12140 diag::warn_zero_size_struct_union_compat)
12141 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12142 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012143
Serge Pavlov3cb80222013-11-14 02:13:03 +000012144 // Structs without named members are extension in C (C99 6.7.2.1p7),
12145 // but are accepted by GCC.
12146 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12147 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12148 diag::ext_no_named_members_in_struct_union)
12149 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012150 }
12151 }
Chris Lattner622c1932008-02-06 00:51:33 +000012152 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012153 ObjCIvarDecl **ClsFields =
12154 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012155 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012156 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012157 // Add ivar's to class's DeclContext.
12158 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12159 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012160 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012161 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012162 // Must enforce the rule that ivars in the base classes may not be
12163 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012164 if (ID->getSuperClass())
12165 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012166 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012167 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012168 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012169 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12170 // Ivar declared in @implementation never belongs to the implementation.
12171 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012172 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012173 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012174 IMPDecl->setIvarLBraceLoc(LBrac);
12175 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012176 } else if (ObjCCategoryDecl *CDecl =
12177 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012178 // case of ivars in class extension; all other cases have been
12179 // reported as errors elsewhere.
12180 // FIXME. Class extension does not have a LocEnd field.
12181 // CDecl->setLocEnd(RBrac);
12182 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012183 // Diagnose redeclaration of private ivars.
12184 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012185 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012186 if (IDecl) {
12187 if (const ObjCIvarDecl *ClsIvar =
12188 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12189 Diag(ClsFields[i]->getLocation(),
12190 diag::err_duplicate_ivar_declaration);
12191 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12192 continue;
12193 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012194 for (ObjCInterfaceDecl::known_extensions_iterator
12195 Ext = IDecl->known_extensions_begin(),
12196 ExtEnd = IDecl->known_extensions_end();
12197 Ext != ExtEnd; ++Ext) {
12198 if (const ObjCIvarDecl *ClsExtIvar
12199 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012200 Diag(ClsFields[i]->getLocation(),
12201 diag::err_duplicate_ivar_declaration);
12202 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12203 continue;
12204 }
12205 }
12206 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012207 ClsFields[i]->setLexicalDeclContext(CDecl);
12208 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012209 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012210 CDecl->setIvarLBraceLoc(LBrac);
12211 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012212 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012213 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012214
12215 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012216 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012217}
12218
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012219/// \brief Determine whether the given integral value is representable within
12220/// the given type T.
12221static bool isRepresentableIntegerValue(ASTContext &Context,
12222 llvm::APSInt &Value,
12223 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012224 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012225 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012226
Douglas Gregor0bf31402010-10-08 23:50:27 +000012227 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012228 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012229 --BitWidth;
12230 return Value.getActiveBits() <= BitWidth;
12231 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012232 return Value.getMinSignedBits() <= BitWidth;
12233}
12234
12235// \brief Given an integral type, return the next larger integral type
12236// (or a NULL type of no such type exists).
12237static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12238 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12239 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012240 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012241 const unsigned NumTypes = 4;
12242 QualType SignedIntegralTypes[NumTypes] = {
12243 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12244 };
12245 QualType UnsignedIntegralTypes[NumTypes] = {
12246 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12247 Context.UnsignedLongLongTy
12248 };
12249
12250 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012251 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12252 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012253 for (unsigned I = 0; I != NumTypes; ++I)
12254 if (Context.getTypeSize(Types[I]) > BitWidth)
12255 return Types[I];
12256
12257 return QualType();
12258}
12259
Douglas Gregor954f6b272009-03-17 19:05:46 +000012260EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12261 EnumConstantDecl *LastEnumConst,
12262 SourceLocation IdLoc,
12263 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012264 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012265 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012266 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012267 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012268
12269 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12270 Val = 0;
12271
Eli Friedman7c6515a2011-12-06 00:10:34 +000012272 if (Val)
12273 Val = DefaultLvalueConversion(Val).take();
12274
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012275 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012276 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012277 EltTy = Context.DependentTy;
12278 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012279 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012280 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012281 !getLangOpts().MicrosoftMode) {
Richard Smithf8379a02012-01-18 23:55:52 +000012282 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12283 // constant-expression in the enumerator-definition shall be a converted
12284 // constant expression of the underlying type.
12285 EltTy = Enum->getIntegerType();
12286 ExprResult Converted =
12287 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12288 CCEK_Enumerator);
12289 if (Converted.isInvalid())
12290 Val = 0;
12291 else
12292 Val = Converted.take();
12293 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012294 !(Val = VerifyIntegerConstantExpression(Val,
12295 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012296 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012297 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012298 if (Enum->isFixed()) {
12299 EltTy = Enum->getIntegerType();
12300
Richard Smithf8379a02012-01-18 23:55:52 +000012301 // In Obj-C and Microsoft mode, require the enumeration value to be
12302 // representable in the underlying type of the enumeration. In C++11,
12303 // we perform a non-narrowing conversion as part of converted constant
12304 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012305 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012306 if (getLangOpts().MicrosoftMode) {
Francois Picheta3108062010-10-18 15:01:13 +000012307 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012308 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012309 } else
12310 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012311 } else
John Wiegley01296292011-04-08 18:41:53 +000012312 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012313 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012314 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012315 // If the underlying type is not fixed, the type of each enumerator
12316 // is the type of its initializing value:
12317 // - If an initializer is specified for an enumerator, the
12318 // initializing value has the same type as the expression.
12319 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012320 } else {
12321 // C99 6.7.2.2p2:
12322 // The expression that defines the value of an enumeration constant
12323 // shall be an integer constant expression that has a value
12324 // representable as an int.
12325
12326 // Complain if the value is not representable in an int.
12327 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12328 Diag(IdLoc, diag::ext_enum_value_not_int)
12329 << EnumVal.toString(10) << Val->getSourceRange()
12330 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12331 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12332 // Force the type of the expression to 'int'.
12333 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12334 }
12335 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012336 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012337 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012338 }
12339 }
Mike Stump11289f42009-09-09 15:08:12 +000012340
Douglas Gregor954f6b272009-03-17 19:05:46 +000012341 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012342 if (Enum->isDependentType())
12343 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012344 else if (!LastEnumConst) {
12345 // C++0x [dcl.enum]p5:
12346 // If the underlying type is not fixed, the type of each enumerator
12347 // is the type of its initializing value:
12348 // - If no initializer is specified for the first enumerator, the
12349 // initializing value has an unspecified integral type.
12350 //
12351 // GCC uses 'int' for its unspecified integral type, as does
12352 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012353 if (Enum->isFixed()) {
12354 EltTy = Enum->getIntegerType();
12355 }
12356 else {
12357 EltTy = Context.IntTy;
12358 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012359 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012360 // Assign the last value + 1.
12361 EnumVal = LastEnumConst->getInitVal();
12362 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012363 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012364
12365 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012366 if (EnumVal < LastEnumConst->getInitVal()) {
12367 // C++0x [dcl.enum]p5:
12368 // If the underlying type is not fixed, the type of each enumerator
12369 // is the type of its initializing value:
12370 //
12371 // - Otherwise the type of the initializing value is the same as
12372 // the type of the initializing value of the preceding enumerator
12373 // unless the incremented value is not representable in that type,
12374 // in which case the type is an unspecified integral type
12375 // sufficient to contain the incremented value. If no such type
12376 // exists, the program is ill-formed.
12377 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012378 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012379 // There is no integral type larger enough to represent this
12380 // value. Complain, then allow the value to wrap around.
12381 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012382 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012383 ++EnumVal;
12384 if (Enum->isFixed())
12385 // When the underlying type is fixed, this is ill-formed.
12386 Diag(IdLoc, diag::err_enumerator_wrapped)
12387 << EnumVal.toString(10)
12388 << EltTy;
12389 else
12390 Diag(IdLoc, diag::warn_enumerator_too_large)
12391 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012392 } else {
12393 EltTy = T;
12394 }
12395
12396 // Retrieve the last enumerator's value, extent that type to the
12397 // type that is supposed to be large enough to represent the incremented
12398 // value, then increment.
12399 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012400 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012401 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012402 ++EnumVal;
12403
12404 // If we're not in C++, diagnose the overflow of enumerator values,
12405 // which in C99 means that the enumerator value is not representable in
12406 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12407 // permits enumerator values that are representable in some larger
12408 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012409 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012410 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012411 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012412 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12413 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12414 Diag(IdLoc, diag::ext_enum_value_not_int)
12415 << EnumVal.toString(10) << 1;
12416 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012417 }
12418 }
Mike Stump11289f42009-09-09 15:08:12 +000012419
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012420 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012421 // Make the enumerator value match the signedness and size of the
12422 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012423 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012424 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012425 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012426
Douglas Gregor954f6b272009-03-17 19:05:46 +000012427 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012428 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012429}
12430
12431
John McCall811a0f52010-10-22 23:36:17 +000012432Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12433 SourceLocation IdLoc, IdentifierInfo *Id,
12434 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012435 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012436 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012437 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012438 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012439
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012440 // The scope passed in may not be a decl scope. Zip up the scope tree until
12441 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012442 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012443
Chris Lattner8116d1b2007-01-25 22:38:29 +000012444 // Verify that there isn't already something declared with this name in this
12445 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012446 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012447 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012448 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012449 // Maybe we will complain about the shadowed template parameter.
12450 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12451 // Just pretend that we didn't see the previous declaration.
12452 PrevDecl = 0;
12453 }
12454
12455 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012456 // When in C++, we may get a TagDecl with the same name; in this case the
12457 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012458 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012459 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012460 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012461 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012462 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012463 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012464 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012465 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012466 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012467 }
12468 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012469
Aaron Ballman24a10472012-07-19 03:12:23 +000012470 // C++ [class.mem]p15:
12471 // If T is the name of a class, then each of the following shall have a name
12472 // different from T:
12473 // - every enumerator of every member of class T that is an unscoped
12474 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012475 if (CXXRecordDecl *Record
12476 = dyn_cast<CXXRecordDecl>(
12477 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012478 if (!TheEnumDecl->isScoped() &&
12479 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012480 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12481
John McCall811a0f52010-10-22 23:36:17 +000012482 EnumConstantDecl *New =
12483 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012484
John McCall553c0792010-01-23 00:46:32 +000012485 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012486 // Process attributes.
12487 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12488
12489 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012490 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012491 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012492 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012493
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012494 ActOnDocumentableDecl(New);
12495
John McCall48871652010-08-21 09:40:31 +000012496 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012497}
12498
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012499// Returns true when the enum initial expression does not trigger the
12500// duplicate enum warning. A few common cases are exempted as follows:
12501// Element2 = Element1
12502// Element2 = Element1 + 1
12503// Element2 = Element1 - 1
12504// Where Element2 and Element1 are from the same enum.
12505static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12506 Expr *InitExpr = ECD->getInitExpr();
12507 if (!InitExpr)
12508 return true;
12509 InitExpr = InitExpr->IgnoreImpCasts();
12510
12511 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12512 if (!BO->isAdditiveOp())
12513 return true;
12514 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12515 if (!IL)
12516 return true;
12517 if (IL->getValue() != 1)
12518 return true;
12519
12520 InitExpr = BO->getLHS();
12521 }
12522
12523 // This checks if the elements are from the same enum.
12524 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12525 if (!DRE)
12526 return true;
12527
12528 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12529 if (!EnumConstant)
12530 return true;
12531
12532 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12533 Enum)
12534 return true;
12535
12536 return false;
12537}
12538
12539struct DupKey {
12540 int64_t val;
12541 bool isTombstoneOrEmptyKey;
12542 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12543 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12544};
12545
12546static DupKey GetDupKey(const llvm::APSInt& Val) {
12547 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12548 false);
12549}
12550
12551struct DenseMapInfoDupKey {
12552 static DupKey getEmptyKey() { return DupKey(0, true); }
12553 static DupKey getTombstoneKey() { return DupKey(1, true); }
12554 static unsigned getHashValue(const DupKey Key) {
12555 return (unsigned)(Key.val * 37);
12556 }
12557 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12558 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12559 LHS.val == RHS.val;
12560 }
12561};
12562
12563// Emits a warning when an element is implicitly set a value that
12564// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012565static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12566 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012567 QualType EnumType) {
12568 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12569 Enum->getLocation()) ==
12570 DiagnosticsEngine::Ignored)
12571 return;
12572 // Avoid anonymous enums
12573 if (!Enum->getIdentifier())
12574 return;
12575
12576 // Only check for small enums.
12577 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12578 return;
12579
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012580 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12581 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012582
12583 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12584 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12585 ValueToVectorMap;
12586
12587 DuplicatesVector DupVector;
12588 ValueToVectorMap EnumMap;
12589
12590 // Populate the EnumMap with all values represented by enum constants without
12591 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012592 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012593 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012594
12595 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12596 // this constant. Skip this enum since it may be ill-formed.
12597 if (!ECD) {
12598 return;
12599 }
12600
12601 if (ECD->getInitExpr())
12602 continue;
12603
12604 DupKey Key = GetDupKey(ECD->getInitVal());
12605 DeclOrVector &Entry = EnumMap[Key];
12606
12607 // First time encountering this value.
12608 if (Entry.isNull())
12609 Entry = ECD;
12610 }
12611
12612 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012613 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012614 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12615 if (!ValidDuplicateEnum(ECD, Enum))
12616 continue;
12617
12618 DupKey Key = GetDupKey(ECD->getInitVal());
12619
12620 DeclOrVector& Entry = EnumMap[Key];
12621 if (Entry.isNull())
12622 continue;
12623
12624 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12625 // Ensure constants are different.
12626 if (D == ECD)
12627 continue;
12628
12629 // Create new vector and push values onto it.
12630 ECDVector *Vec = new ECDVector();
12631 Vec->push_back(D);
12632 Vec->push_back(ECD);
12633
12634 // Update entry to point to the duplicates vector.
12635 Entry = Vec;
12636
12637 // Store the vector somewhere we can consult later for quick emission of
12638 // diagnostics.
12639 DupVector.push_back(Vec);
12640 continue;
12641 }
12642
12643 ECDVector *Vec = Entry.get<ECDVector*>();
12644 // Make sure constants are not added more than once.
12645 if (*Vec->begin() == ECD)
12646 continue;
12647
12648 Vec->push_back(ECD);
12649 }
12650
12651 // Emit diagnostics.
12652 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12653 DupVectorEnd = DupVector.end();
12654 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12655 ECDVector *Vec = *DupVectorIter;
12656 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12657
12658 // Emit warning for one enum constant.
12659 ECDVector::iterator I = Vec->begin();
12660 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12661 << (*I)->getName() << (*I)->getInitVal().toString(10)
12662 << (*I)->getSourceRange();
12663 ++I;
12664
12665 // Emit one note for each of the remaining enum constants with
12666 // the same value.
12667 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12668 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12669 << (*I)->getName() << (*I)->getInitVal().toString(10)
12670 << (*I)->getSourceRange();
12671 delete Vec;
12672 }
12673}
12674
Mike Stump6814d1c2009-05-16 07:06:02 +000012675void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012676 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012677 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012678 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012679 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012680 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012681
12682 if (Attr)
12683 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012684
Eli Friedmand0e60972009-12-11 01:34:50 +000012685 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012686 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012687 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012688 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012689 if (!ECD) continue;
12690
12691 ECD->setType(EnumType);
12692 }
12693
John McCall9aa35be2010-05-06 08:49:23 +000012694 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012695 return;
12696 }
12697
Chris Lattner67933c02007-08-28 05:10:31 +000012698 // TODO: If the result value doesn't fit in an int, it must be a long or long
12699 // long value. ISO C does not support this, but GCC does as an extension,
12700 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012701 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12702 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12703 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012704
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012705 // Verify that all the values are okay, compute the size of the values, and
12706 // reverse the list.
12707 unsigned NumNegativeBits = 0;
12708 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012709
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012710 // Keep track of whether all elements have type int.
12711 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012712
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012713 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012714 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012715 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012716 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012717
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012718 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012719
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012720 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012721 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012722 NumPositiveBits = std::max(NumPositiveBits,
12723 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012724 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012725 NumNegativeBits = std::max(NumNegativeBits,
12726 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012727
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012728 // Keep track of whether every enum element has type int (very commmon).
12729 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012730 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012731 }
Mike Stump11289f42009-09-09 15:08:12 +000012732
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012733 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012734 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012735 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012736
John McCall56774992009-12-09 09:09:27 +000012737 // C++0x N3000 [conv.prom]p3:
12738 // An rvalue of an unscoped enumeration type whose underlying
12739 // type is not fixed can be converted to an rvalue of the first
12740 // of the following types that can represent all the values of
12741 // the enumeration: int, unsigned int, long int, unsigned long
12742 // int, long long int, or unsigned long long int.
12743 // C99 6.4.4.3p2:
12744 // An identifier declared as an enumeration constant has type int.
12745 // The C99 rule is modified by a gcc extension
12746 QualType BestPromotionType;
12747
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012748 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012749 // -fshort-enums is the equivalent to specifying the packed attribute on all
12750 // enum definitions.
12751 if (LangOpts.ShortEnums)
12752 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012753
Douglas Gregor0bf31402010-10-08 23:50:27 +000012754 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012755 BestType = Enum->getIntegerType();
12756 if (BestType->isPromotableIntegerType())
12757 BestPromotionType = Context.getPromotedIntegerType(BestType);
12758 else
12759 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012760 // We don't need to set BestWidth, because BestType is going to be the type
12761 // of the enumerators, but we do anyway because otherwise some compilers
12762 // warn that it might be used uninitialized.
12763 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012764 }
12765 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012766 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012767 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012768 // If it's packed, check also if it fits a char or a short.
12769 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012770 BestType = Context.SignedCharTy;
12771 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012772 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012773 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012774 BestType = Context.ShortTy;
12775 BestWidth = ShortWidth;
12776 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012777 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012778 BestWidth = IntWidth;
12779 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012780 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012781
John McCall56774992009-12-09 09:09:27 +000012782 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012783 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012784 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012785 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012786
Chris Lattner3a370bf2007-08-29 17:31:48 +000012787 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012788 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12789 BestType = Context.LongLongTy;
12790 }
12791 }
John McCall56774992009-12-09 09:09:27 +000012792 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012793 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012794 // If there is no negative value, figure out the smallest type that fits
12795 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012796 // If it's packed, check also if it fits a char or a short.
12797 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012798 BestType = Context.UnsignedCharTy;
12799 BestPromotionType = Context.IntTy;
12800 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012801 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012802 BestType = Context.UnsignedShortTy;
12803 BestPromotionType = Context.IntTy;
12804 BestWidth = ShortWidth;
12805 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012806 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012807 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012808 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012809 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012810 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012811 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012812 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012813 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012814 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012815 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012816 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012817 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012818 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012819 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012820 "How could an initializer get larger than ULL?");
12821 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012822 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012823 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012824 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012825 }
12826 }
Mike Stump11289f42009-09-09 15:08:12 +000012827
Chris Lattner3a370bf2007-08-29 17:31:48 +000012828 // Loop over all of the enumerator constants, changing their types to match
12829 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012830 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012831 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012832 if (!ECD) continue; // Already issued a diagnostic.
12833
12834 // Standard C says the enumerators have int type, but we allow, as an
12835 // extension, the enumerators to be larger than int size. If each
12836 // enumerator value fits in an int, type it as an int, otherwise type it the
12837 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12838 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012839
12840 // Determine whether the value fits into an int.
12841 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012842
12843 // If it fits into an integer type, force it. Otherwise force it to match
12844 // the enum decl type.
12845 QualType NewTy;
12846 unsigned NewWidth;
12847 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012848 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012849 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012850 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012851 NewTy = Context.IntTy;
12852 NewWidth = IntWidth;
12853 NewSign = true;
12854 } else if (ECD->getType() == BestType) {
12855 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012856 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012857 // C++ [dcl.enum]p4: Following the closing brace of an
12858 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012859 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012860 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012861 continue;
12862 } else {
12863 NewTy = BestType;
12864 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012865 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012866 }
12867
12868 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012869 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012870 InitVal.setIsSigned(NewSign);
12871 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012872
Chris Lattner3a370bf2007-08-29 17:31:48 +000012873 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012874 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012875 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012876 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012877 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012878 ECD->getInitExpr(),
12879 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012880 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012881 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012882 // C++ [dcl.enum]p4: Following the closing brace of an
12883 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012884 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012885 ECD->setType(EnumType);
12886 else
12887 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012888 }
Mike Stump11289f42009-09-09 15:08:12 +000012889
John McCall9aa35be2010-05-06 08:49:23 +000012890 Enum->completeDefinition(BestType, BestPromotionType,
12891 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012892
12893 // If we're declaring a function, ensure this decl isn't forgotten about -
12894 // it needs to go into the function scope.
12895 if (InFunctionDeclarator)
12896 DeclsInPrototypeScope.push_back(Enum);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012897
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012898 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012899
12900 // Now that the enum type is defined, ensure it's not been underaligned.
12901 if (Enum->hasAttrs())
12902 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012903}
Chris Lattner1300fb92007-01-23 23:42:53 +000012904
Abramo Bagnara348823a2011-03-03 14:20:18 +000012905Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12906 SourceLocation StartLoc,
12907 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012908 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012909
Douglas Gregor278f52e2009-05-30 00:08:05 +000012910 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012911 AsmString, StartLoc,
12912 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012913 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012914 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012915}
Eli Friedman5ed51982009-06-05 02:44:36 +000012916
Douglas Gregor22d09742012-01-03 18:04:46 +000012917DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12918 SourceLocation ImportLoc,
12919 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000012920 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000012921 Module::AllVisible,
12922 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000012923 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000012924 return true;
12925
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012926 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000012927 Module *ModCheck = Mod;
12928 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12929 // If we've run out of module parents, just drop the remaining identifiers.
12930 // We need the length to be consistent.
12931 if (!ModCheck)
12932 break;
12933 ModCheck = ModCheck->Parent;
12934
12935 IdentifierLocs.push_back(Path[I].second);
12936 }
12937
12938 ImportDecl *Import = ImportDecl::Create(Context,
12939 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000012940 AtLoc.isValid()? AtLoc : ImportLoc,
12941 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000012942 Context.getTranslationUnitDecl()->addDecl(Import);
12943 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000012944}
12945
Richard Smithce587f52013-11-15 04:24:58 +000012946void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12947 // FIXME: Should we synthesize an ImportDecl here?
12948 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12949 /*Complain=*/true);
12950}
12951
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012952void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12953 // Create the implicit import declaration.
12954 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12955 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12956 Loc, Mod, Loc);
12957 TU->addDecl(ImportD);
12958 Consumer.HandleImplicitImportDecl(ImportD);
12959
12960 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000012961 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12962 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012963}
12964
David Chisnall0867d9c2012-02-18 16:12:34 +000012965void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12966 IdentifierInfo* AliasName,
12967 SourceLocation PragmaLoc,
12968 SourceLocation NameLoc,
12969 SourceLocation AliasNameLoc) {
12970 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12971 LookupOrdinaryName);
12972 AsmLabelAttr *Attr =
12973 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall0867d9c2012-02-18 16:12:34 +000012974
12975 if (PrevDecl)
12976 PrevDecl->addAttr(Attr);
12977 else
12978 (void)ExtnameUndeclaredIdentifiers.insert(
12979 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12980}
12981
Eli Friedman5ed51982009-06-05 02:44:36 +000012982void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12983 SourceLocation PragmaLoc,
12984 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012985 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000012986
Eli Friedman5ed51982009-06-05 02:44:36 +000012987 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +000012988 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +000012989 } else {
12990 (void)WeakUndeclaredIdentifiers.insert(
12991 std::pair<IdentifierInfo*,WeakInfo>
12992 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000012993 }
Eli Friedman5ed51982009-06-05 02:44:36 +000012994}
12995
12996void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12997 IdentifierInfo* AliasName,
12998 SourceLocation PragmaLoc,
12999 SourceLocation NameLoc,
13000 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013001 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13002 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013003 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013004
Eli Friedman5ed51982009-06-05 02:44:36 +000013005 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013006 if (!PrevDecl->hasAttr<AliasAttr>())
13007 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013008 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013009 } else {
13010 (void)WeakUndeclaredIdentifiers.insert(
13011 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013012 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013013}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013014
13015Decl *Sema::getObjCDeclContext() const {
13016 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13017}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013018
13019AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013020 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013021 // If we are within an Objective-C method, we should consult
13022 // both the availability of the method as well as the
13023 // enclosing class. If the class is (say) deprecated,
13024 // the entire method is considered deprecated from the
13025 // purpose of checking if the current context is deprecated.
13026 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13027 AvailabilityResult R = MD->getAvailability();
13028 if (R != AR_Available)
13029 return R;
13030 D = MD->getClassInterface();
13031 }
13032 // If we are within an Objective-c @implementation, it
13033 // gets the same availability context as the @interface.
13034 else if (const ObjCImplementationDecl *ID =
13035 dyn_cast<ObjCImplementationDecl>(D)) {
13036 D = ID->getClassInterface();
13037 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013038 return D->getAvailability();
13039}