blob: 8b750812d9c3d15ae4b6b8ebca16c232c5aab9f8 [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;
Alp Tokerbfa39342014-01-14 12:51:41 +0000470 if (getLangOpts().MSVCCompat && 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)
Aaron Ballman691e2272014-01-03 14:48:20 +0000474 << 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) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000848 (NextIsOp &&
849 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000850 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
851 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
852 DiagnoseUseOfDecl(Type, NameLoc);
853 QualType T = Context.getTypeDeclType(Type);
854 if (SS.isNotEmpty())
855 return buildNestedType(*this, SS, T, NameLoc);
856 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000857 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000858
Richard Smith4f605af2012-08-18 00:55:03 +0000859 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000860 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000861
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000862 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
863 return BuildDeclarationNameExpr(SS, Result, ADL);
864}
865
John McCall5ed6e8f2009-08-18 00:00:49 +0000866// Determines the context to return to after temporarily entering a
867// context. This depends in an unnecessarily complicated way on the
868// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000869DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000870
John McCall5ed6e8f2009-08-18 00:00:49 +0000871 // Functions defined inline within classes aren't parsed until we've
872 // finished parsing the top-level class, so the top-level class is
873 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000874 // A Lambda call operator whose parent is a class must not be treated
875 // as an inline member function. A Lambda can be used legally
876 // either as an in-class member initializer or a default argument. These
877 // are parsed once the class has been marked complete and so the containing
878 // context would be the nested class (when the lambda is defined in one);
879 // If the class is not complete, then the lambda is being used in an
880 // ill-formed fashion (such as to specify the width of a bit-field, or
881 // in an array-bound) - in which case we still want to return the
882 // lexically containing DC (which could be a nested class).
883 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000884 DC = DC->getLexicalParent();
885
886 // A function not defined within a class will always return to its
887 // lexical context.
888 if (!isa<CXXRecordDecl>(DC))
889 return DC;
890
891 // A C++ inline method/friend is parsed *after* the topmost class
892 // it was declared in is fully parsed ("complete"); the topmost
893 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000894 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000895 DC = RD;
896
897 // Return the declaration context of the topmost class the inline method is
898 // declared in.
899 return DC;
900 }
901
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000902 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000903}
904
Douglas Gregor91f84212008-12-11 16:49:14 +0000905void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000906 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000907 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000908 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000909 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000910}
911
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000912void Sema::PopDeclContext() {
913 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000914
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000915 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000916 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000917}
918
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000919/// EnterDeclaratorContext - Used when we must lookup names in the context
920/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000921///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000922void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000923 // C++0x [basic.lookup.unqual]p13:
924 // A name used in the definition of a static data member of class
925 // X (after the qualified-id of the static member) is looked up as
926 // if the name was used in a member function of X.
927 // C++0x [basic.lookup.unqual]p14:
928 // If a variable member of a namespace is defined outside of the
929 // scope of its namespace then any name used in the definition of
930 // the variable member (after the declarator-id) is looked up as
931 // if the definition of the variable member occurred in its
932 // namespace.
933 // Both of these imply that we should push a scope whose context
934 // is the semantic context of the declaration. We can't use
935 // PushDeclContext here because that context is not necessarily
936 // lexically contained in the current context. Fortunately,
937 // the containing scope should have the appropriate information.
938
939 assert(!S->getEntity() && "scope already has entity");
940
941#ifndef NDEBUG
942 Scope *Ancestor = S->getParent();
943 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
944 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
945#endif
946
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000947 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000948 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000949}
950
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000951void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000952 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000953
John McCall6df5fef2009-12-19 10:49:29 +0000954 // Switch back to the lexical context. The safety of this is
955 // enforced by an assert in EnterDeclaratorContext.
956 Scope *Ancestor = S->getParent();
957 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000958 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000959
960 // We don't need to do anything with the scope, which is going to
961 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000962}
963
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000964
965void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +0000966 // We assume that the caller has already called
967 // ActOnReenterTemplateScope so getTemplatedDecl() works.
968 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000969 if (!FD)
970 return;
971
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000972 // Same implementation as PushDeclContext, but enters the context
973 // from the lexical parent, rather than the top-level class.
974 assert(CurContext == FD->getLexicalParent() &&
975 "The next DeclContext should be lexically contained in the current one.");
976 CurContext = FD;
977 S->setEntity(CurContext);
978
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000979 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
980 ParmVarDecl *Param = FD->getParamDecl(P);
981 // If the parameter has an identifier, then add it to the scope
982 if (Param->getIdentifier()) {
983 S->AddDecl(Param);
984 IdResolver.AddDecl(Param);
985 }
986 }
987}
988
989
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000990void Sema::ActOnExitFunctionContext() {
991 // Same implementation as PopDeclContext, but returns to the lexical parent,
992 // rather than the top-level class.
993 assert(CurContext && "DeclContext imbalance!");
994 CurContext = CurContext->getLexicalParent();
995 assert(CurContext && "Popped translation unit!");
996}
997
998
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000999/// \brief Determine whether we allow overloading of the function
1000/// PrevDecl with another declaration.
1001///
1002/// This routine determines whether overloading is possible, not
1003/// whether some new function is actually an overload. It will return
1004/// true in C++ (where we can always provide overloads) or, as an
1005/// extension, in C when the previous function is already an
1006/// overloaded function declaration or has the "overloadable"
1007/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001008static bool AllowOverloadingOfFunction(LookupResult &Previous,
1009 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001010 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001011 return true;
1012
John McCall1f82f242009-11-18 22:49:29 +00001013 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001014 return true;
1015
John McCall1f82f242009-11-18 22:49:29 +00001016 return (Previous.getResultKind() == LookupResult::Found
1017 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001018}
1019
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001020/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001021void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001022 // Move up the scope chain until we find the nearest enclosing
1023 // non-transparent context. The declaration will be introduced into this
1024 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001025 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001026 S = S->getParent();
1027
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001028 // Add scoped declarations into their context, so that they can be
1029 // found later. Declarations without a context won't be inserted
1030 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001031 if (AddToContext)
1032 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001033
Richard Smith541b38b2013-09-20 01:15:31 +00001034 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1035 // are function-local declarations.
1036 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001037 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001038 D->getLexicalDeclContext()->getRedeclContext()) &&
1039 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001040 return;
1041
1042 // Template instantiations should also not be pushed into scope.
1043 if (isa<FunctionDecl>(D) &&
1044 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001045 return;
1046
John McCall9f3059a2009-10-09 21:13:30 +00001047 // If this replaces anything in the current scope,
1048 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1049 IEnd = IdResolver.end();
1050 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001051 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1052 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001053 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001054
John McCall9f3059a2009-10-09 21:13:30 +00001055 // Should only need to replace one decl.
1056 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001057 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001058 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059
John McCall48871652010-08-21 09:40:31 +00001060 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001061
1062 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1063 // Implicitly-generated labels may end up getting generated in an order that
1064 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1065 // the label at the appropriate place in the identifier chain.
1066 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001067 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001068 if (IDC == CurContext) {
1069 if (!S->isDeclScope(*I))
1070 continue;
1071 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001072 break;
1073 }
1074
Douglas Gregor46c04e72011-03-16 16:39:03 +00001075 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001076 } else {
1077 IdResolver.AddDecl(D);
1078 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001079}
1080
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001081void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1082 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1083 TUScope->AddDecl(D);
1084}
1085
Richard Smith1c34fb72013-08-13 18:18:50 +00001086bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001087 bool AllowInlineNamespace) {
1088 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001089}
1090
John McCallcc14d1f2010-08-24 08:50:51 +00001091Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1092 DeclContext *TargetDC = DC->getPrimaryContext();
1093 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001094 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001095 if (ScopeDC->getPrimaryContext() == TargetDC)
1096 return S;
1097 } while ((S = S->getParent()));
1098
1099 return 0;
1100}
1101
John McCall1f82f242009-11-18 22:49:29 +00001102static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1103 DeclContext*,
1104 ASTContext&);
1105
1106/// Filters out lookup results that don't fall within the given scope
1107/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001108void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001109 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001110 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001111 LookupResult::Filter F = R.makeFilter();
1112 while (F.hasNext()) {
1113 NamedDecl *D = F.next();
1114
Richard Smith72bcaec2013-12-05 04:30:04 +00001115 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001116 continue;
1117
Richard Smith72bcaec2013-12-05 04:30:04 +00001118 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001119 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001120
John McCall1f82f242009-11-18 22:49:29 +00001121 F.erase();
1122 }
1123
1124 F.done();
1125}
1126
1127static bool isUsingDecl(NamedDecl *D) {
1128 return isa<UsingShadowDecl>(D) ||
1129 isa<UnresolvedUsingTypenameDecl>(D) ||
1130 isa<UnresolvedUsingValueDecl>(D);
1131}
1132
1133/// Removes using shadow declarations from the lookup results.
1134static void RemoveUsingDecls(LookupResult &R) {
1135 LookupResult::Filter F = R.makeFilter();
1136 while (F.hasNext())
1137 if (isUsingDecl(F.next()))
1138 F.erase();
1139
1140 F.done();
1141}
1142
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001143/// \brief Check for this common pattern:
1144/// @code
1145/// class S {
1146/// S(const S&); // DO NOT IMPLEMENT
1147/// void operator=(const S&); // DO NOT IMPLEMENT
1148/// };
1149/// @endcode
1150static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1151 // FIXME: Should check for private access too but access is set after we get
1152 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001153 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001154 return false;
1155
1156 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1157 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001158 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1159 return Method->isCopyAssignmentOperator();
1160 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001161}
1162
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001163// We need this to handle
1164//
1165// typedef struct {
1166// void *foo() { return 0; }
1167// } A;
1168//
1169// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1170// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001171// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001172// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001173// Callers should verify at the end of the TU if it D has external linkage or
1174// not.
1175bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1176 const DeclContext *DC = D->getDeclContext();
1177 while (!DC->isTranslationUnit()) {
1178 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1179 if (!RD->hasNameForLinkage())
1180 return true;
1181 }
1182 DC = DC->getParent();
1183 }
1184
Rafael Espindola3ae00052013-05-13 00:12:11 +00001185 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001186}
1187
Eli Friedman5ef21752013-09-10 03:05:56 +00001188// FIXME: This needs to be refactored; some other isInMainFile users want
1189// these semantics.
1190static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1191 if (S.TUKind != TU_Complete)
1192 return false;
1193 return S.SourceMgr.isInMainFile(Loc);
1194}
1195
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001196bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1197 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001198
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001199 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1200 return false;
1201
1202 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001203 if (D->getDeclContext()->isDependentContext() ||
1204 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001205 return false;
1206
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001207 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001208 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1209 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001210
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001211 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1212 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1213 return false;
1214 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001215 // 'static inline' functions are defined in headers; don't warn.
1216 if (FD->isInlineSpecified() &&
1217 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001218 return false;
1219 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001220
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001221 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001222 Context.DeclMustBeEmitted(FD))
1223 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001224 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001225 // Constants and utility variables are defined in headers with internal
1226 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1227 // like "inline".)
1228 if (!isMainFileLoc(*this, VD->getLocation()))
1229 return false;
1230
Eli Friedman5ef21752013-09-10 03:05:56 +00001231 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001232 return false;
1233
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001234 if (VD->isStaticDataMember() &&
1235 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1236 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001237 } else {
1238 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001239 }
1240
John McCalld37d35b2010-10-27 01:41:35 +00001241 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001242 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001243}
1244
1245void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001246 if (!D)
1247 return;
1248
1249 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001250 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001251 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1252 return; // First should already be in the vector.
1253 }
1254
1255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001256 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001257 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1258 return; // First should already be in the vector.
1259 }
1260
David Blaikie3d8edc22012-05-26 05:35:39 +00001261 if (ShouldWarnIfUnusedFileScopedDecl(D))
1262 UnusedFileScopedDecls.push_back(D);
1263}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001264
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001265static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001266 if (D->isInvalidDecl())
1267 return false;
1268
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001269 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1270 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001271 return false;
John McCall67da35c2010-02-04 22:26:26 +00001272
Chris Lattnercab02a62011-02-17 20:34:02 +00001273 if (isa<LabelDecl>(D))
1274 return true;
1275
John McCall67da35c2010-02-04 22:26:26 +00001276 // White-list anything that isn't a local variable.
1277 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1278 !D->getDeclContext()->isFunctionOrMethod())
1279 return false;
1280
1281 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001282 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001283
1284 // White-list anything with an __attribute__((unused)) type.
1285 QualType Ty = VD->getType();
1286
1287 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001288 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001289 if (TT->getDecl()->hasAttr<UnusedAttr>())
1290 return false;
1291 }
1292
Douglas Gregor14f232e2010-05-08 23:05:03 +00001293 // If we failed to complete the type for some reason, or if the type is
1294 // dependent, don't diagnose the variable.
1295 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001296 return false;
1297
John McCallcef15822010-03-31 02:47:45 +00001298 if (const TagType *TT = Ty->getAs<TagType>()) {
1299 const TagDecl *Tag = TT->getDecl();
1300 if (Tag->hasAttr<UnusedAttr>())
1301 return false;
1302
1303 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001304 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001305 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001306
1307 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001308 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1309 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001310 const CXXConstructExpr *Construct =
1311 dyn_cast<CXXConstructExpr>(Init);
1312 if (Construct && !Construct->isElidable()) {
1313 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001314 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001315 return false;
1316 }
1317 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001318 }
1319 }
John McCallcef15822010-03-31 02:47:45 +00001320
1321 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001322 }
1323
John McCall67da35c2010-02-04 22:26:26 +00001324 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001325}
1326
Anna Zaks964f4c62011-07-28 20:52:06 +00001327static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1328 FixItHint &Hint) {
1329 if (isa<LabelDecl>(D)) {
1330 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001332 if (AfterColon.isInvalid())
1333 return;
1334 Hint = FixItHint::CreateRemoval(CharSourceRange::
1335 getCharRange(D->getLocStart(), AfterColon));
1336 }
1337 return;
1338}
1339
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001340/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1341/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001342void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001343 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001344 if (!ShouldDiagnoseUnusedDecl(D))
1345 return;
1346
Anna Zaks964f4c62011-07-28 20:52:06 +00001347 GenerateFixForUnusedDecl(D, Context, Hint);
1348
Chris Lattnercab02a62011-02-17 20:34:02 +00001349 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001350 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001351 DiagID = diag::warn_unused_exception_param;
1352 else if (isa<LabelDecl>(D))
1353 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001354 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001355 DiagID = diag::warn_unused_variable;
1356
Anna Zaks964f4c62011-07-28 20:52:06 +00001357 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001358}
1359
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001360static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1361 // Verify that we have no forward references left. If so, there was a goto
1362 // or address of a label taken, but no definition of it. Label fwd
1363 // definitions are indicated with a null substmt.
1364 if (L->getStmt() == 0)
1365 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1366}
1367
Steve Naroffc62adb62007-10-09 22:01:59 +00001368void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001369 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001370 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001371 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001372
Chris Lattner302b4be2006-11-19 02:31:38 +00001373 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1374 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001375 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001376 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001377
Douglas Gregor91f84212008-12-11 16:49:14 +00001378 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1379 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001380
Douglas Gregor91f84212008-12-11 16:49:14 +00001381 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001382
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001383 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001384 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001385 DiagnoseUnusedDecl(D);
1386
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001387 // If this was a forward reference to a label, verify it was defined.
1388 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1389 CheckPoppedLabel(LD, *this);
1390
Douglas Gregor91f84212008-12-11 16:49:14 +00001391 // Remove this name from our lexical scope.
1392 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001393 }
1394}
1395
James Molloy6f8780b2012-02-29 10:24:19 +00001396void Sema::ActOnStartFunctionDeclarator() {
1397 ++InFunctionDeclarator;
1398}
1399
1400void Sema::ActOnEndFunctionDeclarator() {
1401 assert(InFunctionDeclarator);
1402 --InFunctionDeclarator;
1403}
1404
Douglas Gregor1c283312010-08-11 12:19:30 +00001405/// \brief Look for an Objective-C class in the translation unit.
1406///
1407/// \param Id The name of the Objective-C class we're looking for. If
1408/// typo-correction fixes this name, the Id will be updated
1409/// to the fixed name.
1410///
1411/// \param IdLoc The location of the name in the translation unit.
1412///
James Dennett41725122012-06-22 10:16:05 +00001413/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001414/// if there is no class with the given name.
1415///
1416/// \returns The declaration of the named Objective-C class, or NULL if the
1417/// class could not be found.
1418ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1419 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001420 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001421 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1422 // creation from this context.
1423 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1424
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001425 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001426 // Perform typo correction at the given location, but only if we
1427 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001428 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1429 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1430 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001431 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001432 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001433 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001434 Id = IDecl->getIdentifier();
1435 }
1436 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001437 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1438 // This routine must always return a class definition, if any.
1439 if (Def && Def->getDefinition())
1440 Def = Def->getDefinition();
1441 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001442}
1443
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001444/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1445/// from S, where a non-field would be declared. This routine copes
1446/// with the difference between C and C++ scoping rules in structs and
1447/// unions. For example, the following code is well-formed in C but
1448/// ill-formed in C++:
1449/// @code
1450/// struct S6 {
1451/// enum { BAR } e;
1452/// };
Mike Stump11289f42009-09-09 15:08:12 +00001453///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001454/// void test_S6() {
1455/// struct S6 a;
1456/// a.e = BAR;
1457/// }
1458/// @endcode
1459/// For the declaration of BAR, this routine will return a different
1460/// scope. The scope S will be the scope of the unnamed enumeration
1461/// within S6. In C++, this routine will return the scope associated
1462/// with S6, because the enumeration's scope is a transparent
1463/// context but structures can contain non-field names. In C, this
1464/// routine will return the translation unit scope, since the
1465/// enumeration's scope is a transparent context and structures cannot
1466/// contain non-field names.
1467Scope *Sema::getNonFieldDeclScope(Scope *S) {
1468 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001469 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001470 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001471 S = S->getParent();
1472 return S;
1473}
1474
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001475/// \brief Looks up the declaration of "struct objc_super" and
1476/// saves it for later use in building builtin declaration of
1477/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1478/// pre-existing declaration exists no action takes place.
1479static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1480 IdentifierInfo *II) {
1481 if (!II->isStr("objc_msgSendSuper"))
1482 return;
1483 ASTContext &Context = ThisSema.Context;
1484
1485 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1486 SourceLocation(), Sema::LookupTagName);
1487 ThisSema.LookupName(Result, S);
1488 if (Result.getResultKind() == LookupResult::Found)
1489 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1490 Context.setObjCSuperType(Context.getTagDeclType(TD));
1491}
1492
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001493/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1494/// file scope. lazily create a decl for it. ForRedeclaration is true
1495/// if we're creating this built-in in anticipation of redeclaring the
1496/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001497NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001498 Scope *S, bool ForRedeclaration,
1499 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001500 LookupPredefedObjCSuperType(*this, S, II);
1501
Chris Lattner9561a0b2007-01-28 08:20:04 +00001502 Builtin::ID BID = (Builtin::ID)bid;
1503
Chris Lattnerecd79c62009-06-14 00:45:47 +00001504 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001505 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001506 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001507 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001508 // Okay
1509 break;
1510
Mike Stump93246cc2009-07-28 23:57:15 +00001511 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001512 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001513 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001514 << Context.BuiltinInfo.GetName(BID);
1515 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001516
Mike Stump93246cc2009-07-28 23:57:15 +00001517 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001518 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001519 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001520 << Context.BuiltinInfo.GetName(BID);
1521 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001522
1523 case ASTContext::GE_Missing_ucontext:
1524 if (ForRedeclaration)
1525 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1526 << Context.BuiltinInfo.GetName(BID);
1527 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001528 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001529
1530 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1531 Diag(Loc, diag::ext_implicit_lib_function_decl)
1532 << Context.BuiltinInfo.GetName(BID)
1533 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001534 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001535 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001536 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001537 Diag(Loc, diag::note_please_include_header)
1538 << Context.BuiltinInfo.getHeaderName(BID)
1539 << Context.BuiltinInfo.GetName(BID);
1540 }
1541
Warren Hunt445d83e2013-11-01 23:46:51 +00001542 DeclContext *Parent = Context.getTranslationUnitDecl();
1543 if (getLangOpts().CPlusPlus) {
1544 LinkageSpecDecl *CLinkageDecl =
1545 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1546 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001547 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001548 Parent->addDecl(CLinkageDecl);
1549 Parent = CLinkageDecl;
1550 }
1551
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001552 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001553 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001554 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001555 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001556 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001557 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001558 New->setImplicit();
1559
Chris Lattner4dd27102008-05-05 22:18:14 +00001560 // Create Decl objects for each parameter, adding them to the
1561 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001562 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001563 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001564 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001565 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001566 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1567 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001568 parm->setScopeInfo(0, i);
1569 Params.push_back(parm);
1570 }
David Blaikie9c70e042011-09-21 18:16:56 +00001571 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001572 }
Mike Stump11289f42009-09-09 15:08:12 +00001573
1574 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001575 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001577 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001578 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1579 // relate Scopes to DeclContexts, and probably eliminate CurContext
1580 // entirely, but we're not there yet.
1581 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001582 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001583 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001584 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001585 return New;
1586}
1587
Douglas Gregor3552dab2013-01-09 00:47:56 +00001588/// \brief Filter out any previous declarations that the given declaration
1589/// should not consider because they are not permitted to conflict, e.g.,
1590/// because they come from hidden sub-modules and do not refer to the same
1591/// entity.
1592static void filterNonConflictingPreviousDecls(ASTContext &context,
1593 NamedDecl *decl,
1594 LookupResult &previous){
1595 // This is only interesting when modules are enabled.
1596 if (!context.getLangOpts().Modules)
1597 return;
1598
1599 // Empty sets are uninteresting.
1600 if (previous.empty())
1601 return;
1602
Douglas Gregor3552dab2013-01-09 00:47:56 +00001603 LookupResult::Filter filter = previous.makeFilter();
1604 while (filter.hasNext()) {
1605 NamedDecl *old = filter.next();
1606
1607 // Non-hidden declarations are never ignored.
1608 if (!old->isHidden())
1609 continue;
1610
Rafael Espindola3ae00052013-05-13 00:12:11 +00001611 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001612 filter.erase();
1613 }
1614
1615 filter.done();
1616}
1617
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001618bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1619 QualType OldType;
1620 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1621 OldType = OldTypedef->getUnderlyingType();
1622 else
1623 OldType = Context.getTypeDeclType(Old);
1624 QualType NewType = New->getUnderlyingType();
1625
Douglas Gregoraab36982012-01-11 22:33:48 +00001626 if (NewType->isVariablyModifiedType()) {
1627 // Must not redefine a typedef with a variably-modified type.
1628 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1629 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1630 << Kind << NewType;
1631 if (Old->getLocation().isValid())
1632 Diag(Old->getLocation(), diag::note_previous_definition);
1633 New->setInvalidDecl();
1634 return true;
1635 }
1636
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001637 if (OldType != NewType &&
1638 !OldType->isDependentType() &&
1639 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001640 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001641 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1642 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1643 << Kind << NewType << OldType;
1644 if (Old->getLocation().isValid())
1645 Diag(Old->getLocation(), diag::note_previous_definition);
1646 New->setInvalidDecl();
1647 return true;
1648 }
1649 return false;
1650}
1651
Richard Smithdda56e42011-04-15 14:24:37 +00001652/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001653/// same name and scope as a previous declaration 'Old'. Figure out
1654/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001655/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001656///
Richard Smithdda56e42011-04-15 14:24:37 +00001657void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001658 // If the new decl is known invalid already, don't bother doing any
1659 // merging checks.
1660 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001661
Steve Naroff44cfcb62008-09-09 14:32:20 +00001662 // Allow multiple definitions for ObjC built-in typedefs.
1663 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001664 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001665 const IdentifierInfo *TypeID = New->getIdentifier();
1666 switch (TypeID->getLength()) {
1667 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001668 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001669 {
1670 if (!TypeID->isStr("id"))
1671 break;
1672 QualType T = New->getUnderlyingType();
1673 if (!T->isPointerType())
1674 break;
1675 if (!T->isVoidPointerType()) {
1676 QualType PT = T->getAs<PointerType>()->getPointeeType();
1677 if (!PT->isStructureType())
1678 break;
1679 }
1680 Context.setObjCIdRedefinitionType(T);
1681 // Install the built-in type for 'id', ignoring the current definition.
1682 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1683 return;
1684 }
Chris Lattner66e32812008-11-20 05:41:43 +00001685 case 5:
1686 if (!TypeID->isStr("Class"))
1687 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001688 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001689 // Install the built-in type for 'Class', ignoring the current definition.
1690 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001691 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001692 case 3:
1693 if (!TypeID->isStr("SEL"))
1694 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001695 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001696 // Install the built-in type for 'SEL', ignoring the current definition.
1697 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001698 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001699 }
1700 // Fall through - the typedef name was not a builtin type.
1701 }
John McCall1f82f242009-11-18 22:49:29 +00001702
Douglas Gregorfb034662009-01-28 17:15:10 +00001703 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001704 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1705 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001706 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001707 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001708
1709 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001710 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001711 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001712
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001713 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001714 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001715
John McCall1f82f242009-11-18 22:49:29 +00001716 // If the old declaration is invalid, just give up here.
1717 if (Old->isInvalidDecl())
1718 return New->setInvalidDecl();
1719
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001720 // If the typedef types are not identical, reject them in all languages and
1721 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001722 if (isIncompatibleTypedef(Old, New))
1723 return;
Mike Stump11289f42009-09-09 15:08:12 +00001724
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001725 // The types match. Link up the redeclaration chain and merge attributes if
1726 // the old declaration was a typedef.
1727 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001728 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001729 mergeDeclAttributes(New, Old);
1730 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001731
David Blaikiebbafb8a2012-03-11 07:00:24 +00001732 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001733 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001734
David Blaikiebbafb8a2012-03-11 07:00:24 +00001735 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001736 // C++ [dcl.typedef]p2:
1737 // In a given non-class scope, a typedef specifier can be used to
1738 // redefine the name of any type declared in that scope to refer
1739 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001740 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001741 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001742
1743 // C++0x [dcl.typedef]p4:
1744 // In a given class scope, a typedef specifier can be used to redefine
1745 // any class-name declared in that scope that is not also a typedef-name
1746 // to refer to the type to which it already refers.
1747 //
1748 // This wording came in via DR424, which was a correction to the
1749 // wording in DR56, which accidentally banned code like:
1750 //
1751 // struct S {
1752 // typedef struct A { } A;
1753 // };
1754 //
1755 // in the C++03 standard. We implement the C++0x semantics, which
1756 // allow the above but disallow
1757 //
1758 // struct S {
1759 // typedef int I;
1760 // typedef int I;
1761 // };
1762 //
1763 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001764 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001765 return;
1766
Chris Lattner2581fc32009-04-17 22:04:20 +00001767 Diag(New->getLocation(), diag::err_redefinition)
1768 << New->getDeclName();
1769 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001770 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001771 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001772
Douglas Gregor7363fb02012-01-11 04:25:01 +00001773 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001774 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001775 return;
1776
Chris Lattner2581fc32009-04-17 22:04:20 +00001777 // If we have a redefinition of a typedef in C, emit a warning. This warning
1778 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001779 // -Wtypedef-redefinition. If either the original or the redefinition is
1780 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001781 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001782 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1783 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001784 return;
Mike Stump11289f42009-09-09 15:08:12 +00001785
Chris Lattner2581fc32009-04-17 22:04:20 +00001786 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1787 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001788 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001789 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001790}
1791
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001792/// DeclhasAttr - returns true if decl Declaration already has the target
1793/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001794static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001795 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001796 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001797 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1798 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001799 if (Ann) {
1800 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1801 return true;
1802 continue;
1803 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001804 // FIXME: Don't hardcode this check
1805 if (OA && isa<OwnershipAttr>(*i))
1806 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001807 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001808 }
Chris Lattner84966392008-03-03 03:28:21 +00001809
1810 return false;
1811}
1812
Richard Smithbc8caaf2013-02-22 04:55:39 +00001813static bool isAttributeTargetADefinition(Decl *D) {
1814 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1815 return VD->isThisDeclarationADefinition();
1816 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1817 return TD->isCompleteDefinition() || TD->isBeingDefined();
1818 return true;
1819}
1820
1821/// Merge alignment attributes from \p Old to \p New, taking into account the
1822/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1823///
1824/// \return \c true if any attributes were added to \p New.
1825static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1826 // Look for alignas attributes on Old, and pick out whichever attribute
1827 // specifies the strictest alignment requirement.
1828 AlignedAttr *OldAlignasAttr = 0;
1829 AlignedAttr *OldStrictestAlignAttr = 0;
1830 unsigned OldAlign = 0;
1831 for (specific_attr_iterator<AlignedAttr>
1832 I = Old->specific_attr_begin<AlignedAttr>(),
1833 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1834 // FIXME: We have no way of representing inherited dependent alignments
1835 // in a case like:
1836 // template<int A, int B> struct alignas(A) X;
1837 // template<int A, int B> struct alignas(B) X {};
1838 // For now, we just ignore any alignas attributes which are not on the
1839 // definition in such a case.
1840 if (I->isAlignmentDependent())
1841 return false;
1842
1843 if (I->isAlignas())
1844 OldAlignasAttr = *I;
1845
1846 unsigned Align = I->getAlignment(S.Context);
1847 if (Align > OldAlign) {
1848 OldAlign = Align;
1849 OldStrictestAlignAttr = *I;
1850 }
1851 }
1852
1853 // Look for alignas attributes on New.
1854 AlignedAttr *NewAlignasAttr = 0;
1855 unsigned NewAlign = 0;
1856 for (specific_attr_iterator<AlignedAttr>
1857 I = New->specific_attr_begin<AlignedAttr>(),
1858 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1859 if (I->isAlignmentDependent())
1860 return false;
1861
1862 if (I->isAlignas())
1863 NewAlignasAttr = *I;
1864
1865 unsigned Align = I->getAlignment(S.Context);
1866 if (Align > NewAlign)
1867 NewAlign = Align;
1868 }
1869
1870 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1871 // Both declarations have 'alignas' attributes. We require them to match.
1872 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1873 // fall short. (If two declarations both have alignas, they must both match
1874 // every definition, and so must match each other if there is a definition.)
1875
1876 // If either declaration only contains 'alignas(0)' specifiers, then it
1877 // specifies the natural alignment for the type.
1878 if (OldAlign == 0 || NewAlign == 0) {
1879 QualType Ty;
1880 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1881 Ty = VD->getType();
1882 else
1883 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1884
1885 if (OldAlign == 0)
1886 OldAlign = S.Context.getTypeAlign(Ty);
1887 if (NewAlign == 0)
1888 NewAlign = S.Context.getTypeAlign(Ty);
1889 }
1890
1891 if (OldAlign != NewAlign) {
1892 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1893 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1894 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1895 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1896 }
1897 }
1898
1899 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1900 // C++11 [dcl.align]p6:
1901 // if any declaration of an entity has an alignment-specifier,
1902 // every defining declaration of that entity shall specify an
1903 // equivalent alignment.
1904 // C11 6.7.5/7:
1905 // If the definition of an object does not have an alignment
1906 // specifier, any other declaration of that object shall also
1907 // have no alignment specifier.
1908 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001909 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001910 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001911 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001912 }
1913
1914 bool AnyAdded = false;
1915
1916 // Ensure we have an attribute representing the strictest alignment.
1917 if (OldAlign > NewAlign) {
1918 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1919 Clone->setInherited(true);
1920 New->addAttr(Clone);
1921 AnyAdded = true;
1922 }
1923
1924 // Ensure we have an alignas attribute if the old declaration had one.
1925 if (OldAlignasAttr && !NewAlignasAttr &&
1926 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1927 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1928 Clone->setInherited(true);
1929 New->addAttr(Clone);
1930 AnyAdded = true;
1931 }
1932
1933 return AnyAdded;
1934}
1935
1936static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1937 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001938 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001939 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001940 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001941 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1942 AA->getIntroduced(), AA->getDeprecated(),
1943 AA->getObsoleted(), AA->getUnavailable(),
1944 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001945 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001946 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1947 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1948 AttrSpellingListIndex);
1949 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1950 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1951 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001952 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001953 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1954 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001955 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001956 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1957 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001958 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001959 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1960 FA->getFormatIdx(), FA->getFirstArg(),
1961 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001962 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001963 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1964 AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00001965 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr))
1966 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), AttrSpellingListIndex,
1967 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00001968 else if (isa<AlignedAttr>(Attr))
1969 // AlignedAttrs are handled separately, because we need to handle all
1970 // such attributes on a declaration at the same time.
1971 NewAttr = 0;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001972 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001973 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001974
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001975 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001976 NewAttr->setInherited(true);
1977 D->addAttr(NewAttr);
1978 return true;
1979 }
1980
1981 return false;
1982}
1983
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001984static const Decl *getDefinition(const Decl *D) {
1985 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001986 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001987 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1988 const VarDecl *Def = VD->getDefinition();
1989 if (Def)
1990 return Def;
1991 return VD->getActingDefinition();
1992 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001993 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001994 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001995 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001996 return Def;
1997 }
1998 return NULL;
1999}
2000
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002001static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2002 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2003 I != E; ++I) {
2004 Attr *Attribute = *I;
2005 if (Attribute->getKind() == Kind)
2006 return true;
2007 }
2008 return false;
2009}
2010
2011/// checkNewAttributesAfterDef - If we already have a definition, check that
2012/// there are no new attributes in this declaration.
2013static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2014 if (!New->hasAttrs())
2015 return;
2016
2017 const Decl *Def = getDefinition(Old);
2018 if (!Def || Def == New)
2019 return;
2020
2021 AttrVec &NewAttributes = New->getAttrs();
2022 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2023 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002024
2025 if (isa<AliasAttr>(NewAttribute)) {
2026 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2027 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2028 else {
2029 VarDecl *VD = cast<VarDecl>(New);
2030 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2031 VarDecl::TentativeDefinition
2032 ? diag::err_alias_after_tentative
2033 : diag::err_redefinition;
2034 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2035 S.Diag(Def->getLocation(), diag::note_previous_definition);
2036 VD->setInvalidDecl();
2037 }
2038 ++I;
2039 continue;
2040 }
2041
2042 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2043 // Tentative definitions are only interesting for the alias check above.
2044 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2045 ++I;
2046 continue;
2047 }
2048 }
2049
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002050 if (hasAttribute(Def, NewAttribute->getKind())) {
2051 ++I;
2052 continue; // regular attr merging will take care of validating this.
2053 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002054
Richard Smithdebc59d2013-01-30 05:45:05 +00002055 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002056 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002057 ++I;
2058 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002059 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2060 if (AA->isAlignas()) {
2061 // C++11 [dcl.align]p6:
2062 // if any declaration of an entity has an alignment-specifier,
2063 // every defining declaration of that entity shall specify an
2064 // equivalent alignment.
2065 // C11 6.7.5/7:
2066 // If the definition of an object does not have an alignment
2067 // specifier, any other declaration of that object shall also
2068 // have no alignment specifier.
2069 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002070 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002071 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002072 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002073 NewAttributes.erase(NewAttributes.begin() + I);
2074 --E;
2075 continue;
2076 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002077 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002078
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002079 S.Diag(NewAttribute->getLocation(),
2080 diag::warn_attribute_precede_definition);
2081 S.Diag(Def->getLocation(), diag::note_previous_definition);
2082 NewAttributes.erase(NewAttributes.begin() + I);
2083 --E;
2084 }
2085}
2086
John McCallf79e87d2011-03-02 04:00:57 +00002087/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002088void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002089 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002090 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2091 UsedAttr *NewAttr = OldAttr->clone(Context);
2092 NewAttr->setInherited(true);
2093 New->addAttr(NewAttr);
2094 }
2095
Richard Smithe233fbf2013-01-28 22:42:45 +00002096 if (!Old->hasAttrs() && !New->hasAttrs())
2097 return;
2098
Rafael Espindola36191042012-05-18 01:47:00 +00002099 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002100 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002101
Douglas Gregor32c17572012-01-01 20:30:41 +00002102 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002103 return;
John McCallf79e87d2011-03-02 04:00:57 +00002104
Douglas Gregor32c17572012-01-01 20:30:41 +00002105 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002106
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002107 // Ensure that any moving of objects within the allocated map is done before
2108 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002109 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002110
Peter Collingbourneab8bc062011-01-21 02:08:36 +00002111 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00002112 i = Old->specific_attr_begin<InheritableAttr>(),
2113 e = Old->specific_attr_end<InheritableAttr>();
2114 i != e; ++i) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002115 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002116 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002117 if (isa<DeprecatedAttr>(*i) ||
2118 isa<UnavailableAttr>(*i) ||
2119 isa<AvailabilityAttr>(*i)) {
2120 switch (AMK) {
2121 case AMK_None:
2122 continue;
John McCalld2930c22011-07-22 02:45:48 +00002123
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002124 case AMK_Redeclaration:
2125 break;
2126
2127 case AMK_Override:
2128 Override = true;
2129 break;
2130 }
2131 }
2132
Rafael Espindolab0938852013-10-25 01:28:12 +00002133 // Already handled.
2134 if (isa<UsedAttr>(*i))
2135 continue;
2136
Richard Smithbc8caaf2013-02-22 04:55:39 +00002137 if (mergeDeclAttribute(*this, New, *i, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002138 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002139 }
John McCallf79e87d2011-03-02 04:00:57 +00002140
Richard Smithbc8caaf2013-02-22 04:55:39 +00002141 if (mergeAlignedAttrs(*this, New, Old))
2142 foundAny = true;
2143
Douglas Gregor32c17572012-01-01 20:30:41 +00002144 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002145}
2146
2147/// mergeParamDeclAttributes - Copy attributes from the old parameter
2148/// to the new one.
2149static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2150 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002151 Sema &S) {
2152 // C++11 [dcl.attr.depend]p2:
2153 // The first declaration of a function shall specify the
2154 // carries_dependency attribute for its declarator-id if any declaration
2155 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002156 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2157 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2158 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002159 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2160 // Find the first declaration of the parameter.
2161 // FIXME: Should we build redeclaration chains for function parameters?
2162 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002163 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002164 const ParmVarDecl *FirstVD =
2165 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2166 S.Diag(FirstVD->getLocation(),
2167 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2168 }
2169
John McCallf79e87d2011-03-02 04:00:57 +00002170 if (!oldDecl->hasAttrs())
2171 return;
2172
2173 bool foundAny = newDecl->hasAttrs();
2174
2175 // Ensure that any moving of objects within the allocated map is
2176 // done before we process them.
2177 if (!foundAny) newDecl->setAttrs(AttrVec());
2178
2179 for (specific_attr_iterator<InheritableParamAttr>
2180 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2181 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2182 if (!DeclHasAttr(newDecl, *i)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002183 InheritableAttr *newAttr =
2184 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002185 newAttr->setInherited(true);
2186 newDecl->addAttr(newAttr);
2187 foundAny = true;
2188 }
2189 }
2190
2191 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002192}
2193
Dan Gohman28ade552010-07-26 21:25:24 +00002194namespace {
2195
Douglas Gregora74a2972009-03-06 22:43:54 +00002196/// Used in MergeFunctionDecl to keep track of function parameters in
2197/// C.
2198struct GNUCompatibleParamWarning {
2199 ParmVarDecl *OldParm;
2200 ParmVarDecl *NewParm;
2201 QualType PromotedType;
2202};
2203
Dan Gohman28ade552010-07-26 21:25:24 +00002204}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002205
2206/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002207Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002208 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002209 if (Ctor->isDefaultConstructor())
2210 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002211
2212 if (Ctor->isCopyConstructor())
2213 return Sema::CXXCopyConstructor;
2214
2215 if (Ctor->isMoveConstructor())
2216 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002217 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002218 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002219 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002220 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002221 } else if (MD->isMoveAssignmentOperator()) {
2222 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002223 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002224
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002225 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002226}
2227
Sebastian Redl243d9052010-06-09 21:17:41 +00002228/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002229/// only extern inline functions can be redefined, and even then only in
2230/// GNU89 mode.
2231static bool canRedefineFunction(const FunctionDecl *FD,
2232 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002233 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2234 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002235 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002236 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002237}
2238
Reid Kleckner78af0702013-08-27 23:08:25 +00002239const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2240 const AttributedType *AT = T->getAs<AttributedType>();
2241 while (AT && !AT->isCallingConv())
2242 AT = AT->getModifiedType()->getAs<AttributedType>();
2243 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002244}
2245
Benjamin Kramer3e350262013-02-15 12:30:38 +00002246template <typename T>
2247static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002248 const DeclContext *DC = Old->getDeclContext();
2249 if (DC->isRecord())
2250 return false;
2251
2252 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002253 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002254 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002255 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002256 return true;
2257 return false;
2258}
2259
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002260/// MergeFunctionDecl - We just parsed a function 'New' from
2261/// declarator D which has the same name and scope as a previous
2262/// declaration 'Old'. Figure out how to resolve this situation,
2263/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002264///
2265/// In C++, New and Old must be declarations that are not
2266/// overloaded. Use IsOverload to determine whether New and Old are
2267/// overloaded, and to select the Old declaration that New should be
2268/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002269///
2270/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002271bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2272 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002273 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002274 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002275 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002276 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002277 if (New->getFriendObjectKind()) {
2278 Diag(New->getLocation(), diag::err_using_decl_friend);
2279 Diag(Shadow->getTargetDecl()->getLocation(),
2280 diag::note_using_decl_target);
2281 Diag(Shadow->getUsingDecl()->getLocation(),
2282 diag::note_using_decl) << 0;
2283 return true;
2284 }
2285
Richard Smith18819302014-02-06 01:31:33 +00002286 // C++11 [namespace.udecl]p14:
2287 // If a function declaration in namespace scope or block scope has the
2288 // same name and the same parameter-type-list as a function introduced
2289 // by a using-declaration, and the declarations do not declare the same
2290 // function, the program is ill-formed.
2291
2292 // Check whether the two declarations might declare the same function.
2293 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2294 if (Old &&
2295 !Old->getDeclContext()->getRedeclContext()->Equals(
2296 New->getDeclContext()->getRedeclContext()) &&
2297 !(Old->isExternC() && New->isExternC()))
2298 Old = 0;
2299
2300 if (!Old) {
2301 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2302 Diag(Shadow->getTargetDecl()->getLocation(),
2303 diag::note_using_decl_target);
2304 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2305 return true;
2306 }
2307 OldD = Old;
2308 } else {
2309 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2310 << New->getDeclName();
2311 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002312 return true;
2313 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002314 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002315
David Majnemerea5092a2013-07-07 23:49:50 +00002316 // If the old declaration is invalid, just give up here.
2317 if (Old->isInvalidDecl())
2318 return true;
2319
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002320 // Determine whether the previous declaration was a definition,
2321 // implicit declaration, or a declaration.
2322 diag::kind PrevDiag;
Richard Smithbdd14642014-02-04 01:14:30 +00002323 SourceLocation OldLocation = Old->getLocation();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002324 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002325 PrevDiag = diag::note_previous_definition;
Richard Smithbdd14642014-02-04 01:14:30 +00002326 else if (Old->isImplicit()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002327 PrevDiag = diag::note_previous_implicit_declaration;
Richard Smithbdd14642014-02-04 01:14:30 +00002328 if (OldLocation.isInvalid())
2329 OldLocation = New->getLocation();
2330 } else
Chris Lattner0369c572008-11-23 23:12:31 +00002331 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002332
Charles Davisfea48452010-02-18 02:00:42 +00002333 // Don't complain about this if we're in GNU89 mode and the old function
2334 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002335 // Don't complain about specializations. They are not supposed to have
2336 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002337 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002338 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002339 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002340 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002341 !canRedefineFunction(Old, getLangOpts())) {
2342 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002343 Diag(New->getLocation(), diag::warn_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002344 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002345 } else {
2346 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002347 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002348 return true;
2349 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002350 }
2351
Reid Kleckner78af0702013-08-27 23:08:25 +00002352
2353 // If a function is first declared with a calling convention, but is later
2354 // declared or defined without one, all following decls assume the calling
2355 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002356 //
John McCalla5f46fb2012-08-25 02:00:03 +00002357 // It's OK if a function is first declared without a calling convention,
2358 // but is later declared or defined with the default calling convention.
2359 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002360 // To test if either decl has an explicit calling convention, we look for
2361 // AttributedType sugar nodes on the type as written. If they are missing or
2362 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002363 //
2364 // Note also that we DO NOT return at this point, because we still have
2365 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002366 QualType OldQType = Context.getCanonicalType(Old->getType());
2367 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002368 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002369 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002370 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2371 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2372 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002373
Reid Kleckner78af0702013-08-27 23:08:25 +00002374 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002375 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002376 const FunctionType *FT =
2377 First->getType().getCanonicalType()->castAs<FunctionType>();
2378 FunctionType::ExtInfo FI = FT->getExtInfo();
2379 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2380 if (!NewCCExplicit) {
2381 // Inherit the CC from the previous declaration if it was specified
2382 // there but not here.
2383 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2384 RequiresAdjustment = true;
2385 } else {
2386 // Calling conventions aren't compatible, so complain.
2387 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2388 Diag(New->getLocation(), diag::err_cconv_change)
2389 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2390 << !FirstCCExplicit
2391 << (!FirstCCExplicit ? "" :
2392 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002393
Reid Kleckner78af0702013-08-27 23:08:25 +00002394 // Put the note on the first decl, since it is the one that matters.
2395 Diag(First->getLocation(), diag::note_previous_declaration);
2396 return true;
2397 }
John McCallcddbad02010-02-04 05:44:44 +00002398 }
2399
John McCallab26cfa2010-02-05 21:31:56 +00002400 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002401 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2402 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2403 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002404 }
2405
Douglas Gregor77e274f2010-06-18 21:30:25 +00002406 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002407 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2408 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2409 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002410 Diag(New->getLocation(), diag::err_regparm_mismatch)
2411 << NewType->getRegParmType()
2412 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002413 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002414 return true;
2415 }
John McCall4f5019e2010-12-19 02:44:49 +00002416
2417 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2418 RequiresAdjustment = true;
2419 }
2420
Douglas Gregorf1404d72011-10-14 15:55:40 +00002421 // Merge ns_returns_retained attribute.
2422 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2423 if (NewTypeInfo.getProducesResult()) {
2424 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002425 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002426 return true;
2427 }
2428
2429 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2430 RequiresAdjustment = true;
2431 }
2432
John McCall4f5019e2010-12-19 02:44:49 +00002433 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002434 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2435 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2436 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002437 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002438 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002439 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002440
2441 // If this redeclaration makes the function inline, we may need to add it to
2442 // UndefinedButUsed.
2443 if (!Old->isInlined() && New->isInlined() &&
2444 !New->hasAttr<GNUInlineAttr>() &&
2445 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2446 Old->isUsed(false) &&
2447 !Old->isDefined() && !New->isThisDeclarationADefinition())
2448 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2449 SourceLocation()));
2450
2451 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2452 // about it.
2453 if (New->hasAttr<GNUInlineAttr>() &&
2454 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2455 UndefinedButUsed.erase(Old->getCanonicalDecl());
2456 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002457
David Blaikiebbafb8a2012-03-11 07:00:24 +00002458 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002459 // (C++98 13.1p2):
2460 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002461 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002462 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002463
2464 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002465 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002466 // Redeclarations or specializations of a function or function template
2467 // with a declared return type that uses a placeholder type shall also
2468 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002469 QualType OldDeclaredReturnType =
2470 (Old->getTypeSourceInfo()
2471 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2472 : OldType)->getReturnType();
2473 QualType NewDeclaredReturnType =
2474 (New->getTypeSourceInfo()
2475 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2476 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002477 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002478 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2479 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2480 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002481 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2482 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002483 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2484 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002485 if (New->isCXXClassMember() && New->isOutOfLine())
2486 Diag(New->getLocation(),
2487 diag::err_member_def_does_not_match_ret_type) << New;
2488 else
2489 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Richard Smithbdd14642014-02-04 01:14:30 +00002490 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002491 return true;
2492 }
2493 else
2494 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002495 }
2496
Alp Toker314cc812014-01-25 16:55:45 +00002497 QualType OldReturnType = OldType->getReturnType();
2498 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002499 if (OldReturnType != NewReturnType) {
2500 // If this function has a deduced return type and has already been
2501 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002502 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002503 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002504 New->setType(
2505 SubstAutoType(New->getType(),
2506 OldAT->isDependentType() ? Context.DependentTy
2507 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002508 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002509 SubstAutoType(NewQType,
2510 OldAT->isDependentType() ? Context.DependentTy
2511 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002512 }
2513 }
2514
2515 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2516 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002517 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002518 // Preserve triviality.
2519 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002520
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002521 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002522 // 2 CXXMethodDecls referring to the same function will be injected.
2523 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002524 bool IsClassScopeExplicitSpecialization =
2525 OldMethod->isFunctionTemplateSpecialization() &&
2526 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002527 bool isFriend = NewMethod->getFriendObjectKind();
2528
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002529 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2530 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002531 // -- Member function declarations with the same name and the
2532 // same parameter types cannot be overloaded if any of them
2533 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002534 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002535 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002536 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002537 return true;
2538 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002539
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002540 // C++ [class.mem]p1:
2541 // [...] A member shall not be declared twice in the
2542 // member-specification, except that a nested class or member
2543 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002544 if (ActiveTemplateInstantiations.empty()) {
2545 unsigned NewDiag;
2546 if (isa<CXXConstructorDecl>(OldMethod))
2547 NewDiag = diag::err_constructor_redeclared;
2548 else if (isa<CXXDestructorDecl>(NewMethod))
2549 NewDiag = diag::err_destructor_redeclared;
2550 else if (isa<CXXConversionDecl>(NewMethod))
2551 NewDiag = diag::err_conv_function_redeclared;
2552 else
2553 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002554
Richard Smith57e7ff92012-07-13 04:12:04 +00002555 Diag(New->getLocation(), NewDiag);
2556 } else {
2557 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2558 << New << New->getType();
2559 }
Richard Smithbdd14642014-02-04 01:14:30 +00002560 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002561
2562 // Complain if this is an explicit declaration of a special
2563 // member that was initially declared implicitly.
2564 //
2565 // As an exception, it's okay to befriend such methods in order
2566 // to permit the implicit constructor/destructor/operator calls.
2567 } else if (OldMethod->isImplicit()) {
2568 if (isFriend) {
2569 NewMethod->setImplicit();
2570 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002571 Diag(NewMethod->getLocation(),
2572 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002573 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002574 return true;
2575 }
Richard Smith337a5a12012-06-08 01:30:54 +00002576 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002577 Diag(NewMethod->getLocation(),
2578 diag::err_definition_of_explicitly_defaulted_member)
2579 << getSpecialMember(OldMethod);
2580 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002581 }
2582 }
2583
Richard Smith10876ef2013-01-17 01:30:42 +00002584 // C++11 [dcl.attr.noreturn]p1:
2585 // The first declaration of a function shall specify the noreturn
2586 // attribute if any declaration of that function specifies the noreturn
2587 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002588 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2589 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2590 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002591 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002592 diag::note_noreturn_missing_first_decl);
2593 }
2594
Richard Smithe233fbf2013-01-28 22:42:45 +00002595 // C++11 [dcl.attr.depend]p2:
2596 // The first declaration of a function shall specify the
2597 // carries_dependency attribute for its declarator-id if any declaration
2598 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002599 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2600 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2601 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002602 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002603 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002604 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2605 }
2606
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002607 // (C++98 8.3.5p3):
2608 // All declarations for a function shall agree exactly in both the
2609 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002610 // We also want to respect all the extended bits except noreturn.
2611
2612 // noreturn should now match unless the old type info didn't have it.
2613 QualType OldQTypeForComparison = OldQType;
2614 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2615 assert(OldQType == QualType(OldType, 0));
2616 const FunctionType *OldTypeForComparison
2617 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2618 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2619 assert(OldQTypeForComparison.isCanonical());
2620 }
2621
Rafael Espindolaf4187652013-02-14 01:18:37 +00002622 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002623 // As a special case, retain the language linkage from previous
2624 // declarations of a friend function as an extension.
2625 //
2626 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2627 // and is useful because there's otherwise no way to specify language
2628 // linkage within class scope.
2629 //
2630 // Check cautiously as the friend object kind isn't yet complete.
2631 if (New->getFriendObjectKind() != Decl::FOK_None) {
2632 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002633 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002634 } else {
2635 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002636 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002637 return true;
2638 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002639 }
2640
John McCall4f5019e2010-12-19 02:44:49 +00002641 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002642 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002643
Richard Smith541b38b2013-09-20 01:15:31 +00002644 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2645 New->isLocalExternDecl()) {
2646 // It's OK if we couldn't merge types for a local function declaraton
2647 // if either the old or new type is dependent. We'll merge the types
2648 // when we instantiate the function.
2649 return false;
2650 }
2651
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002652 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002653 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002654
2655 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002656 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002657 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002658 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002659 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2660 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002661 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002662 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002663 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002664 // The old declaration provided a function prototype, but the
2665 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002666 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Alp Toker9cacbab2014-01-20 20:26:09 +00002667 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(),
2668 OldProto->param_type_end());
Alp Toker314cc812014-01-25 16:55:45 +00002669 NewQType =
2670 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2671 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002672 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002673 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002674
2675 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002676 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00002677 for (FunctionProtoType::param_type_iterator
2678 ParamType = OldProto->param_type_begin(),
2679 ParamEnd = OldProto->param_type_end();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002680 ParamType != ParamEnd; ++ParamType) {
2681 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002682 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002683 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002684 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002685 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002686 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002687 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002688 Param->setImplicit();
2689 Params.push_back(Param);
2690 }
2691
David Blaikie9c70e042011-09-21 18:16:56 +00002692 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002693 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002694
Richard Smith1c34fb72013-08-13 18:18:50 +00002695 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002696 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002697
Douglas Gregora74a2972009-03-06 22:43:54 +00002698 // GNU C permits a K&R definition to follow a prototype declaration
2699 // if the declared types of the parameters in the K&R definition
2700 // match the types in the prototype declaration, even when the
2701 // promoted types of the parameters from the K&R definition differ
2702 // from the types in the prototype. GCC then keeps the types from
2703 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002704 //
2705 // If a variadic prototype is followed by a non-variadic K&R definition,
2706 // the K&R definition becomes variadic. This is sort of an edge case, but
2707 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2708 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002709 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002710 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002711 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002712 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002713 SmallVector<QualType, 16> ArgTypes;
2714 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002715 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002716 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002717 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002718 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002719
Douglas Gregora74a2972009-03-06 22:43:54 +00002720 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002721 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2722 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002723 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002724 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002725 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002726 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2727 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002728 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002729 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002730 ArgTypes.push_back(NewParm->getType());
2731 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002732 NewParm->getType(),
2733 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002734 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2735 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002736 Warnings.push_back(Warn);
2737 ArgTypes.push_back(NewParm->getType());
2738 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002739 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002740 }
2741
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002742 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002743 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2744 Diag(Warnings[Warn].NewParm->getLocation(),
2745 diag::ext_param_promoted_not_compatible_with_prototype)
2746 << Warnings[Warn].PromotedType
2747 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002748 if (Warnings[Warn].OldParm->getLocation().isValid())
2749 Diag(Warnings[Warn].OldParm->getLocation(),
2750 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002751 }
2752
Richard Smith1c34fb72013-08-13 18:18:50 +00002753 if (MergeTypeWithOld)
2754 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2755 OldProto->getExtProtoInfo()));
2756 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002757 }
2758
2759 // Fall through to diagnose conflicting types.
2760 }
2761
John McCallad327cd2013-04-14 08:50:55 +00002762 // A function that has already been declared has been redeclared or
2763 // defined with a different type; show an appropriate diagnostic.
2764
2765 // If the previous declaration was an implicitly-generated builtin
2766 // declaration, then at the very least we should use a specialized note.
2767 unsigned BuiltinID;
2768 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2769 // If it's actually a library-defined builtin function like 'malloc'
2770 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002771 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002772 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002773 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002774 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002775
2776 // If this is a global redeclaration, just forget hereafter
2777 // about the "builtin-ness" of the function.
2778 //
2779 // Doing this for local extern declarations is problematic. If
2780 // the builtin declaration remains visible, a second invalid
2781 // local declaration will produce a hard error; if it doesn't
2782 // remain visible, a single bogus local redeclaration (which is
2783 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002784 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002785 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2786
Douglas Gregor893c2c92009-03-23 17:47:24 +00002787 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002788 }
Steve Naroff17832a42008-01-16 15:01:34 +00002789
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002790 PrevDiag = diag::note_previous_builtin_declaration;
2791 }
2792
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002793 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002794 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002795 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002796}
2797
Douglas Gregore62c0a42009-02-24 01:23:02 +00002798/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002799/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002800///
2801/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002802/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002803/// the new declaration, once we know that New is in fact a
2804/// redeclaration of Old.
2805///
2806/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002807bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002808 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002809 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002810 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002811
Douglas Gregore62c0a42009-02-24 01:23:02 +00002812 // Merge "pure" flag.
2813 if (Old->isPure())
2814 New->setPure();
2815
Rafael Espindolabefe1302012-11-25 14:07:59 +00002816 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002817 if (Old->getMostRecentDecl()->isUsed(false))
2818 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002819
John McCallf79e87d2011-03-02 04:00:57 +00002820 // Merge attributes from the parameters. These can mismatch with K&R
2821 // declarations.
2822 if (New->getNumParams() == Old->getNumParams())
2823 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2824 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002825 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002826
David Blaikiebbafb8a2012-03-11 07:00:24 +00002827 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002828 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002829
Rafael Espindola8778c282012-11-29 16:09:03 +00002830 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002831 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2832 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002833 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002834 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002835 New->setType(Merged);
2836
Douglas Gregore62c0a42009-02-24 01:23:02 +00002837 return false;
2838}
2839
John McCall31168b02011-06-15 23:02:42 +00002840
John McCallf79e87d2011-03-02 04:00:57 +00002841void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002842 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002843
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002844 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002845 AvailabilityMergeKind MergeKind =
2846 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2847 : AMK_Override;
2848 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002849
2850 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002851 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2852 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002853 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002854 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002855 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002856 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002857
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002858 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002859}
2860
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002861/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2862/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002863/// emitting diagnostics as appropriate.
2864///
2865/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002866/// to here in AddInitializerToDecl. We can't check them before the initializer
2867/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002868void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2869 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002870 if (New->isInvalidDecl() || Old->isInvalidDecl())
2871 return;
2872
2873 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002874 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002875 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002876 // We don't know what the new type is until the initializer is attached.
2877 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002878 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2879 // These could still be something that needs exception specs checked.
2880 return MergeVarDeclExceptionSpecs(New, Old);
2881 }
Richard Smith30482bc2011-02-20 03:19:35 +00002882 // C++ [basic.link]p10:
2883 // [...] the types specified by all declarations referring to a given
2884 // object or function shall be identical, except that declarations for an
2885 // array object can specify array types that differ by the presence or
2886 // absence of a major array bound (8.3.4).
2887 else if (Old->getType()->isIncompleteArrayType() &&
2888 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002889 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2890 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2891 if (Context.hasSameType(OldArray->getElementType(),
2892 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002893 MergedT = New->getType();
2894 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002895 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002896 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2897 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2898 if (Context.hasSameType(OldArray->getElementType(),
2899 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002900 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002901 } else if (New->getType()->isObjCObjectPointerType() &&
2902 Old->getType()->isObjCObjectPointerType()) {
2903 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2904 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002905 }
2906 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002907 // C 6.2.7p2:
2908 // All declarations that refer to the same object or function shall have
2909 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002910 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2911 }
2912 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002913 // It's OK if we couldn't merge types if either type is dependent, for a
2914 // block-scope variable. In other cases (static data members of class
2915 // templates, variable templates, ...), we require the types to be
2916 // equivalent.
2917 // FIXME: The C++ standard doesn't say anything about this.
2918 if ((New->getType()->isDependentType() ||
2919 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2920 // If the old type was dependent, we can't merge with it, so the new type
2921 // becomes dependent for now. We'll reproduce the original type when we
2922 // instantiate the TypeSourceInfo for the variable.
2923 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2924 New->setType(Context.DependentTy);
2925 return;
2926 }
2927
2928 // FIXME: Even if this merging succeeds, some other non-visible declaration
2929 // of this variable might have an incompatible type. For instance:
2930 //
2931 // extern int arr[];
2932 // void f() { extern int arr[2]; }
2933 // void g() { extern int arr[3]; }
2934 //
2935 // Neither C nor C++ requires a diagnostic for this, but we should still try
2936 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002937 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002938 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002939 Diag(Old->getLocation(), diag::note_previous_definition);
2940 return New->setInvalidDecl();
2941 }
John McCallb65e8fe2013-04-01 18:34:28 +00002942
2943 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002944 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002945 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002946 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002947}
2948
Richard Smith3c785782013-09-03 21:00:58 +00002949static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2950 LookupResult &Previous) {
2951 // C11 6.2.7p4:
2952 // For an identifier with internal or external linkage declared
2953 // in a scope in which a prior declaration of that identifier is
2954 // visible, if the prior declaration specifies internal or
2955 // external linkage, the type of the identifier at the later
2956 // declaration becomes the composite type.
2957 //
2958 // If the variable isn't visible, we do not merge with its type.
2959 if (Previous.isShadowed())
2960 return false;
2961
2962 if (S.getLangOpts().CPlusPlus) {
2963 // C++11 [dcl.array]p3:
2964 // If there is a preceding declaration of the entity in the same
2965 // scope in which the bound was specified, an omitted array bound
2966 // is taken to be the same as in that earlier declaration.
2967 return NewVD->isPreviousDeclInSameBlockScope() ||
2968 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2969 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2970 } else {
2971 // If the old declaration was function-local, don't merge with its
2972 // type unless we're in the same function.
2973 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2974 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2975 }
2976}
2977
Chris Lattner01564d92007-01-27 19:27:06 +00002978/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2979/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2980/// situation, merging decls or emitting diagnostics as appropriate.
2981///
Mike Stump11289f42009-09-09 15:08:12 +00002982/// Tentative definition rules (C99 6.9.2p2) are checked by
2983/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002984/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002985///
Richard Smith3c785782013-09-03 21:00:58 +00002986void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002987 // If the new decl is already invalid, don't do any other checking.
2988 if (New->isInvalidDecl())
2989 return;
Mike Stump11289f42009-09-09 15:08:12 +00002990
Richard Smithbeef3452014-01-16 23:39:20 +00002991 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2992
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002993 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002994 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002995 VarTemplateDecl *OldTemplate = 0;
2996 if (Previous.isSingleResult()) {
2997 if (NewTemplate) {
2998 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2999 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
3000 } else
3001 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003002 }
3003 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003004 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003005 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003006 Diag(Previous.getRepresentativeDecl()->getLocation(),
3007 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003008 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003009 }
Chris Lattner84966392008-03-03 03:28:21 +00003010
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003011 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3012 return;
3013
Richard Smithbeef3452014-01-16 23:39:20 +00003014 // Ensure the template parameters are compatible.
3015 if (NewTemplate &&
3016 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3017 OldTemplate->getTemplateParameters(),
3018 /*Complain=*/true, TPL_TemplateMatch))
3019 return;
3020
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003021 // C++ [class.mem]p1:
3022 // A member shall not be declared twice in the member-specification [...]
3023 //
3024 // Here, we need only consider static data members.
3025 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3026 Diag(New->getLocation(), diag::err_duplicate_member)
3027 << New->getIdentifier();
3028 Diag(Old->getLocation(), diag::note_previous_declaration);
3029 New->setInvalidDecl();
3030 }
3031
Douglas Gregor32c17572012-01-01 20:30:41 +00003032 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003033 // Warn if an already-declared variable is made a weak_import in a subsequent
3034 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003035 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003036 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003037 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003038 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3039 Diag(Old->getLocation(), diag::note_previous_definition);
3040 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003041 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003042 }
Chris Lattner84966392008-03-03 03:28:21 +00003043
Richard Smith30482bc2011-02-20 03:19:35 +00003044 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003045 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3046
Richard Smith30482bc2011-02-20 03:19:35 +00003047 if (New->isInvalidDecl())
3048 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003049
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003050 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003051 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003052 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003053 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003054 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003055 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003056 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003057 }
Mike Stump11289f42009-09-09 15:08:12 +00003058 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003059 // For an identifier declared with the storage-class specifier
3060 // extern in a scope in which a prior declaration of that
3061 // identifier is visible,23) if the prior declaration specifies
3062 // internal or external linkage, the linkage of the identifier at
3063 // the later declaration is the same as the linkage specified at
3064 // the prior declaration. If no prior declaration is visible, or
3065 // if the prior declaration specifies no linkage, then the
3066 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003067 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003068 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003069 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003070 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003071 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003072 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003073 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003074 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003075 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003076
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003077 // Check if extern is followed by non-extern and vice-versa.
3078 if (New->hasExternalStorage() &&
3079 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3080 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3081 Diag(Old->getLocation(), diag::note_previous_definition);
3082 return New->setInvalidDecl();
3083 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003084 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3085 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003086 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3087 Diag(Old->getLocation(), diag::note_previous_definition);
3088 return New->setInvalidDecl();
3089 }
3090
Steve Naroffa5629372008-09-17 14:05:40 +00003091 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003092
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003093 // FIXME: The test for external storage here seems wrong? We still
3094 // need to check for mismatches.
3095 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003096 // Don't complain about out-of-line definitions of static members.
3097 !(Old->getLexicalDeclContext()->isRecord() &&
3098 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003099 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003100 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003101 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003102 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003103
Richard Smithfd3834f2013-04-13 02:43:54 +00003104 if (New->getTLSKind() != Old->getTLSKind()) {
3105 if (!Old->getTLSKind()) {
3106 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3107 Diag(Old->getLocation(), diag::note_previous_declaration);
3108 } else if (!New->getTLSKind()) {
3109 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3110 Diag(Old->getLocation(), diag::note_previous_declaration);
3111 } else {
3112 // Do not allow redeclaration to change the variable between requiring
3113 // static and dynamic initialization.
3114 // FIXME: GCC allows this, but uses the TLS keyword on the first
3115 // declaration to determine the kind. Do we need to be compatible here?
3116 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3117 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3118 Diag(Old->getLocation(), diag::note_previous_declaration);
3119 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003120 }
3121
Sebastian Redlf1842912010-02-02 18:35:11 +00003122 // C++ doesn't have tentative definitions, so go right ahead and check here.
3123 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003124 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003125 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003126 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003127 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003128 Diag(Def->getLocation(), diag::note_previous_definition);
3129 New->setInvalidDecl();
3130 return;
3131 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003132
Rafael Espindolaf4187652013-02-14 01:18:37 +00003133 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003134 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3135 Diag(Old->getLocation(), diag::note_previous_definition);
3136 New->setInvalidDecl();
3137 return;
3138 }
3139
Rafael Espindolabefe1302012-11-25 14:07:59 +00003140 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003141 if (Old->getMostRecentDecl()->isUsed(false))
3142 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003143
Douglas Gregor0760fa12009-03-10 23:43:53 +00003144 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003145 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003146 if (NewTemplate)
3147 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003148
3149 // Inherit access appropriately.
3150 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003151 if (NewTemplate)
3152 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003153}
3154
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003155/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3156/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003157Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003158 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003159 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003160}
3161
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003162static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003163 if (!S.Context.getLangOpts().CPlusPlus)
3164 return;
3165
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003166 if (isa<CXXRecordDecl>(Tag->getParent())) {
3167 // If this tag is the direct child of a class, number it if
3168 // it is anonymous.
3169 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3170 return;
3171 MangleNumberingContext &MCtx =
3172 S.Context.getManglingNumberContext(Tag->getParent());
3173 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3174 return;
3175 }
3176
3177 // If this tag isn't a direct child of a class, number it if it is local.
3178 Decl *ManglingContextDecl;
3179 if (MangleNumberingContext *MCtx =
3180 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3181 ManglingContextDecl)) {
3182 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3183 }
3184}
3185
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003186/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003187/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003188/// parameters to cope with template friend declarations.
3189Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3190 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003191 MultiTemplateParamsArg TemplateParams,
3192 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003193 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003194 TagDecl *Tag = 0;
3195 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3196 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003197 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003198 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003199 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003200 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003201
3202 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003203 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003204
John McCall07e91c02009-08-06 02:15:43 +00003205 // Note that the above type specs guarantee that the
3206 // type rep is a Decl, whereas in many of the others
3207 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003208 if (isa<TagDecl>(TagD))
3209 Tag = cast<TagDecl>(TagD);
3210 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3211 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003212 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003213
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003214 if (Tag) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003215 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003216 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003217 if (Tag->isInvalidDecl())
3218 return Tag;
3219 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003220
Nuno Lopese9823fa2009-12-17 11:35:26 +00003221 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3222 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3223 // or incomplete types shall not be restrict-qualified."
3224 if (TypeQuals & DeclSpec::TQ_restrict)
3225 Diag(DS.getRestrictSpecLoc(),
3226 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3227 << DS.getSourceRange();
3228 }
3229
Richard Smitha77a0a62011-08-15 21:04:07 +00003230 if (DS.isConstexprSpecified()) {
3231 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3232 // and definitions of functions and variables.
3233 if (Tag)
3234 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3235 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3236 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003237 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3238 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003239 else
3240 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3241 // Don't emit warnings after this error.
3242 return TagD;
3243 }
3244
Richard Smithb1402ae2013-03-18 22:52:47 +00003245 DiagnoseFunctionSpecifiers(DS);
3246
Douglas Gregor3dad8422009-09-26 06:47:28 +00003247 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003248 // If we're dealing with a decl but not a TagDecl, assume that
3249 // whatever routines created it handled the friendship aspect.
3250 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003251 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003252 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003253 }
John McCallaa017372011-03-22 23:00:04 +00003254
Richard Smithb1402ae2013-03-18 22:52:47 +00003255 CXXScopeSpec &SS = DS.getTypeSpecScope();
3256 bool IsExplicitSpecialization =
3257 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3258 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3259 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3260 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3261 // nested-name-specifier unless it is an explicit instantiation
3262 // or an explicit specialization.
3263 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3264 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3265 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3266 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3267 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3268 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3269 << SS.getRange();
3270 return 0;
3271 }
3272
3273 // Track whether this decl-specifier declares anything.
3274 bool DeclaresAnything = true;
3275
3276 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003277 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003278 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003279 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003280 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003281 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003282 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003283
Richard Smithb1402ae2013-03-18 22:52:47 +00003284 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003285 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003286 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003287
Richard Smithb1402ae2013-03-18 22:52:47 +00003288 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003289 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003290 CurContext->isRecord() &&
3291 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3292 // Handle 2 kinds of anonymous struct:
3293 // struct STRUCT;
3294 // and
3295 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3296 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003297 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003298 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3299 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003300 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003301 << DS.getSourceRange();
3302 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3303 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003304 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003305
3306 // Skip all the checks below if we have a type error.
3307 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3308 (TagD && TagD->isInvalidDecl()))
3309 return TagD;
3310
3311 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003312 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3313 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3314 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003315 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3316 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003317
John McCallaa017372011-03-22 23:00:04 +00003318 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003319 // Customize diagnostic for a typedef missing a name.
3320 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003321 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003322 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003323 else
3324 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003325 }
Mike Stump11289f42009-09-09 15:08:12 +00003326
Richard Smithb1402ae2013-03-18 22:52:47 +00003327 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003328 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3329 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3330 << Tag->getTagKind()
3331 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3332
Richard Smithb1402ae2013-03-18 22:52:47 +00003333 ActOnDocumentableDecl(TagD);
3334
3335 // C 6.7/2:
3336 // A declaration [...] shall declare at least a declarator [...], a tag,
3337 // or the members of an enumeration.
3338 // C++ [dcl.dcl]p3:
3339 // [If there are no declarators], and except for the declaration of an
3340 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3341 // names into the program, or shall redeclare a name introduced by a
3342 // previous declaration.
3343 if (!DeclaresAnything) {
3344 // In C, we allow this as a (popular) extension / bug. Don't bother
3345 // producing further diagnostics for redundant qualifiers after this.
3346 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3347 return TagD;
3348 }
3349
3350 // C++ [dcl.stc]p1:
3351 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3352 // init-declarator-list of the declaration shall not be empty.
3353 // C++ [dcl.fct.spec]p1:
3354 // If a cv-qualifier appears in a decl-specifier-seq, the
3355 // init-declarator-list of the declaration shall not be empty.
3356 //
3357 // Spurious qualifiers here appear to be valid in C.
3358 unsigned DiagID = diag::warn_standalone_specifier;
3359 if (getLangOpts().CPlusPlus)
3360 DiagID = diag::ext_standalone_specifier;
3361
3362 // Note that a linkage-specification sets a storage class, but
3363 // 'extern "C" struct foo;' is actually valid and not theoretically
3364 // useless.
3365 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3366 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3367 Diag(DS.getStorageClassSpecLoc(), DiagID)
3368 << DeclSpec::getSpecifierName(SCS);
3369
Richard Smithb4a9e862013-04-12 22:46:28 +00003370 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3371 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3372 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003373 if (DS.getTypeQualifiers()) {
3374 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3375 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3376 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3377 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3378 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003379 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3380 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003381 }
3382
Eli Friedmane3217952011-12-17 00:36:09 +00003383 // Warn about ignored type attributes, for example:
3384 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003385 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003386 if (!DS.getAttributes().empty()) {
3387 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3388 if (TypeSpecType == DeclSpec::TST_class ||
3389 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003390 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003391 TypeSpecType == DeclSpec::TST_union ||
3392 TypeSpecType == DeclSpec::TST_enum) {
3393 AttributeList* attrs = DS.getAttributes().getList();
3394 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003395 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003396 << attrs->getName()
3397 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3398 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003399 TypeSpecType == DeclSpec::TST_union ? 2 :
3400 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003401 attrs = attrs->getNext();
3402 }
3403 }
3404 }
John McCallaa017372011-03-22 23:00:04 +00003405
John McCall48871652010-08-21 09:40:31 +00003406 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003407}
3408
John McCallea305ed2009-12-18 10:40:03 +00003409/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003410/// check if there's an existing declaration that can't be overloaded.
3411///
3412/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003413static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3414 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003415 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003416 DeclarationName Name,
3417 SourceLocation NameLoc,
3418 unsigned diagnostic) {
3419 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3420 Sema::ForRedeclaration);
3421 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003422
John McCallea305ed2009-12-18 10:40:03 +00003423 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003424 return false;
3425
3426 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003427 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003428 assert(PrevDecl && "Expected a non-null Decl");
3429
3430 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3431 return false;
John McCall1f82f242009-11-18 22:49:29 +00003432
John McCallea305ed2009-12-18 10:40:03 +00003433 SemaRef.Diag(NameLoc, diagnostic) << Name;
3434 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003435
3436 return true;
3437}
3438
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003439/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3440/// anonymous struct or union AnonRecord into the owning context Owner
3441/// and scope S. This routine will be invoked just after we realize
3442/// that an unnamed union or struct is actually an anonymous union or
3443/// struct, e.g.,
3444///
3445/// @code
3446/// union {
3447/// int i;
3448/// float f;
3449/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3450/// // f into the surrounding scope.x
3451/// @endcode
3452///
3453/// This routine is recursive, injecting the names of nested anonymous
3454/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003455static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003456 DeclContext *Owner,
3457 RecordDecl *AnonRecord,
3458 AccessSpecifier AS,
3459 SmallVectorImpl<NamedDecl *> &Chaining,
3460 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003461 unsigned diagKind
3462 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3463 : diag::err_anonymous_struct_member_redecl;
3464
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003465 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003466
3467 // Look every FieldDecl and IndirectFieldDecl with a name.
3468 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3469 DEnd = AnonRecord->decls_end();
3470 D != DEnd; ++D) {
3471 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3472 cast<NamedDecl>(*D)->getDeclName()) {
3473 ValueDecl *VD = cast<ValueDecl>(*D);
3474 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3475 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003476 // C++ [class.union]p2:
3477 // The names of the members of an anonymous union shall be
3478 // distinct from the names of any other entity in the
3479 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003480 Invalid = true;
3481 } else {
3482 // C++ [class.union]p2:
3483 // For the purpose of name lookup, after the anonymous union
3484 // definition, the members of the anonymous union are
3485 // considered to have been defined in the scope in which the
3486 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003487 unsigned OldChainingSize = Chaining.size();
3488 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3489 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3490 PE = IF->chain_end(); PI != PE; ++PI)
3491 Chaining.push_back(*PI);
3492 else
3493 Chaining.push_back(VD);
3494
Francois Pichet783dd6e2010-11-21 06:08:52 +00003495 assert(Chaining.size() >= 2);
3496 NamedDecl **NamedChain =
3497 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3498 for (unsigned i = 0; i < Chaining.size(); i++)
3499 NamedChain[i] = Chaining[i];
3500
3501 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003502 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3503 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003504 NamedChain, Chaining.size());
3505
3506 IndirectField->setAccess(AS);
3507 IndirectField->setImplicit();
3508 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003509
3510 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003511 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003512
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003513 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003514 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003515 }
3516 }
3517
3518 return Invalid;
3519}
3520
Douglas Gregorc4df4072010-04-19 22:54:31 +00003521/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3522/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003523/// illegal input values are mapped to SC_None.
3524static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003525StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3526 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3527 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3528 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003529 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003530 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003531 case DeclSpec::SCS_extern:
3532 if (DS.isExternInLinkageSpec())
3533 return SC_None;
3534 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003535 case DeclSpec::SCS_static: return SC_Static;
3536 case DeclSpec::SCS_auto: return SC_Auto;
3537 case DeclSpec::SCS_register: return SC_Register;
3538 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003539 // Illegal SCSs map to None: error reporting is up to the caller.
3540 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003541 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003542 }
3543 llvm_unreachable("unknown storage class specifier");
3544}
3545
Richard Smithab44d5b2013-12-10 08:25:00 +00003546static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3547 assert(Record->hasInClassInitializer());
3548
3549 for (DeclContext::decl_iterator I = Record->decls_begin(),
3550 E = Record->decls_end();
3551 I != E; ++I) {
3552 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
3553 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
3554 FD = IFD->getAnonField();
3555 if (FD && FD->hasInClassInitializer())
3556 return FD->getLocation();
3557 }
3558
3559 llvm_unreachable("couldn't find in-class initializer");
3560}
3561
3562static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3563 SourceLocation DefaultInitLoc) {
3564 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3565 return;
3566
3567 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3568 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3569}
3570
3571static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3572 CXXRecordDecl *AnonUnion) {
3573 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3574 return;
3575
3576 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3577}
3578
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003579/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003580/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003581/// (C++ [class.union]) and a C11 feature; anonymous structures
3582/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003583Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003584 AccessSpecifier AS,
3585 RecordDecl *Record,
3586 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003587 DeclContext *Owner = Record->getDeclContext();
3588
3589 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003590 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003591 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003592 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003593 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003594 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003595 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003596
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003597 // C and C++ require different kinds of checks for anonymous
3598 // structs/unions.
3599 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003600 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003601 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003602 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003603 if (Record->isUnion()) {
3604 // C++ [class.union]p6:
3605 // Anonymous unions declared in a named namespace or in the
3606 // global namespace shall be declared static.
3607 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3608 (isa<TranslationUnitDecl>(Owner) ||
3609 (isa<NamespaceDecl>(Owner) &&
3610 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003611 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3612 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003613
3614 // Recover by adding 'static'.
3615 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003616 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003617 }
3618 // C++ [class.union]p6:
3619 // A storage class is not allowed in a declaration of an
3620 // anonymous union in a class scope.
3621 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3622 isa<RecordDecl>(Owner)) {
3623 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003624 diag::err_anonymous_union_with_storage_spec)
3625 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003626
3627 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003628 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3629 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003630 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003631 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003632 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003633
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003634 // Ignore const/volatile/restrict qualifiers.
3635 if (DS.getTypeQualifiers()) {
3636 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3637 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003638 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003639 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3640 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003641 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003642 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003643 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003644 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3645 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003646 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003647 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003648 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003649 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003650 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3651 Diag(DS.getAtomicSpecLoc(),
3652 diag::ext_anonymous_struct_union_qualified)
3653 << Record->isUnion() << "_Atomic"
3654 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003655
3656 DS.ClearTypeQualifiers();
3657 }
3658
Mike Stump11289f42009-09-09 15:08:12 +00003659 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003660 // The member-specification of an anonymous union shall only
3661 // define non-static data members. [Note: nested types and
3662 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003663 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3664 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003665 Mem != MemEnd; ++Mem) {
3666 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3667 // C++ [class.union]p3:
3668 // An anonymous union shall not have private or protected
3669 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003670 assert(FD->getAccess() != AS_none);
3671 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003672 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3673 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3674 Invalid = true;
3675 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003676
Alexis Hunt97ab5542011-05-16 22:41:40 +00003677 // C++ [class.union]p1
3678 // An object of a class with a non-trivial constructor, a non-trivial
3679 // copy constructor, a non-trivial destructor, or a non-trivial copy
3680 // assignment operator cannot be a member of a union, nor can an
3681 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003682 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003683 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003684 } else if ((*Mem)->isImplicit()) {
3685 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003686 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3687 // This is a type that showed up in an
3688 // elaborated-type-specifier inside the anonymous struct or
3689 // union, but which actually declares a type outside of the
3690 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003691 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3692 if (!MemRecord->isAnonymousStructOrUnion() &&
3693 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003694 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003695 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003696 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3697 << (int)Record->isUnion();
3698 else {
3699 // This is a nested type declaration.
3700 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3701 << (int)Record->isUnion();
3702 Invalid = true;
3703 }
Richard Smith254d2662013-01-28 00:54:05 +00003704 } else {
3705 // This is an anonymous type definition within another anonymous type.
3706 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3707 // not part of standard C++.
3708 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003709 diag::ext_anonymous_record_with_anonymous_type)
3710 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003711 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003712 } else if (isa<AccessSpecDecl>(*Mem)) {
3713 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003714 } else {
3715 // We have something that isn't a non-static data
3716 // member. Complain about it.
3717 unsigned DK = diag::err_anonymous_record_bad_member;
3718 if (isa<TypeDecl>(*Mem))
3719 DK = diag::err_anonymous_record_with_type;
3720 else if (isa<FunctionDecl>(*Mem))
3721 DK = diag::err_anonymous_record_with_function;
3722 else if (isa<VarDecl>(*Mem))
3723 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003724
3725 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003726 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003727 DK == diag::err_anonymous_record_with_type)
3728 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003729 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003730 else {
3731 Diag((*Mem)->getLocation(), DK)
3732 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003733 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003734 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003735 }
3736 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003737
3738 // C++11 [class.union]p8 (DR1460):
3739 // At most one variant member of a union may have a
3740 // brace-or-equal-initializer.
3741 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3742 Owner->isRecord())
3743 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3744 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003745 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003746
3747 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003748 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003749 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003750 Invalid = true;
3751 }
3752
John McCallfa2d6922009-10-22 23:31:08 +00003753 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003754 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003755 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003756 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003757
Mike Stump11289f42009-09-09 15:08:12 +00003758 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003759 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003760 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003761 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003762 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003763 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003764 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003765 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003766 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003767 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003768 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003769 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003770 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003771 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003772 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003773 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003774 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003775 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003776 // mutable can only appear on non-static class members, so it's always
3777 // an error here
3778 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3779 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003780 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003781 }
3782
Abramo Bagnaradff19302011-03-08 08:55:46 +00003783 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003784 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003785 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003786 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003787 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003788
3789 // Default-initialize the implicit variable. This initialization will be
3790 // trivial in almost all cases, except if a union member has an in-class
3791 // initializer:
3792 // union { int n = 0; };
3793 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003794 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003795 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003796
Richard Smithab44d5b2013-12-10 08:25:00 +00003797 // Mark this as an anonymous struct/union type.
3798 Record->setAnonymousStructOrUnion(true);
3799
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003800 // Add the anonymous struct/union object to the current
3801 // context. We'll be referencing this object when we refer to one of
3802 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003803 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003804
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003805 // Inject the members of the anonymous struct/union into the owning
3806 // context and into the identifier resolver chain for name lookup
3807 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003808 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003809 Chain.push_back(Anon);
3810
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003811 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3812 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003813 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003814
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003815 if (Invalid)
3816 Anon->setInvalidDecl();
3817
John McCall48871652010-08-21 09:40:31 +00003818 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003819}
3820
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003821/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3822/// Microsoft C anonymous structure.
3823/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3824/// Example:
3825///
3826/// struct A { int a; };
3827/// struct B { struct A; int b; };
3828///
3829/// void foo() {
3830/// B var;
3831/// var.a = 3;
3832/// }
3833///
3834Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3835 RecordDecl *Record) {
3836
3837 // If there is no Record, get the record via the typedef.
3838 if (!Record)
3839 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3840
3841 // Mock up a declarator.
3842 Declarator Dc(DS, Declarator::TypeNameContext);
3843 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3844 assert(TInfo && "couldn't build declarator info for anonymous struct");
3845
3846 // Create a declaration for this anonymous struct.
3847 NamedDecl* Anon = FieldDecl::Create(Context,
3848 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003849 DS.getLocStart(),
3850 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003851 /*IdentifierInfo=*/0,
3852 Context.getTypeDeclType(Record),
3853 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003854 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003855 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003856 Anon->setImplicit();
3857
3858 // Add the anonymous struct object to the current context.
3859 CurContext->addDecl(Anon);
3860
3861 // Inject the members of the anonymous struct into the current
3862 // context and into the identifier resolver chain for name lookup
3863 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003864 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003865 Chain.push_back(Anon);
3866
Nico Weberf8bb3de2012-02-01 00:41:00 +00003867 RecordDecl *RecordDef = Record->getDefinition();
3868 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3869 RecordDef, AS_none,
3870 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003871 Anon->setInvalidDecl();
3872
3873 return Anon;
3874}
Steve Naroff2fea1392007-09-02 02:04:30 +00003875
Douglas Gregor92751d42008-11-17 22:58:34 +00003876/// GetNameForDeclarator - Determine the full declaration name for the
3877/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003878DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003879 return GetNameFromUnqualifiedId(D.getName());
3880}
3881
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003882/// \brief Retrieves the declaration name from a parsed unqualified-id.
3883DeclarationNameInfo
3884Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3885 DeclarationNameInfo NameInfo;
3886 NameInfo.setLoc(Name.StartLocation);
3887
Douglas Gregor7861a802009-11-03 01:35:08 +00003888 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003889
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003890 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003891 case UnqualifiedId::IK_Identifier:
3892 NameInfo.setName(Name.Identifier);
3893 NameInfo.setLoc(Name.StartLocation);
3894 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003895
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003896 case UnqualifiedId::IK_OperatorFunctionId:
3897 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3898 Name.OperatorFunctionId.Operator));
3899 NameInfo.setLoc(Name.StartLocation);
3900 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3901 = Name.OperatorFunctionId.SymbolLocations[0];
3902 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3903 = Name.EndLocation.getRawEncoding();
3904 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003905
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003906 case UnqualifiedId::IK_LiteralOperatorId:
3907 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3908 Name.Identifier));
3909 NameInfo.setLoc(Name.StartLocation);
3910 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3911 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003912
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003913 case UnqualifiedId::IK_ConversionFunctionId: {
3914 TypeSourceInfo *TInfo;
3915 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3916 if (Ty.isNull())
3917 return DeclarationNameInfo();
3918 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3919 Context.getCanonicalType(Ty)));
3920 NameInfo.setLoc(Name.StartLocation);
3921 NameInfo.setNamedTypeInfo(TInfo);
3922 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003923 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003924
3925 case UnqualifiedId::IK_ConstructorName: {
3926 TypeSourceInfo *TInfo;
3927 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3928 if (Ty.isNull())
3929 return DeclarationNameInfo();
3930 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3931 Context.getCanonicalType(Ty)));
3932 NameInfo.setLoc(Name.StartLocation);
3933 NameInfo.setNamedTypeInfo(TInfo);
3934 return NameInfo;
3935 }
3936
3937 case UnqualifiedId::IK_ConstructorTemplateId: {
3938 // In well-formed code, we can only have a constructor
3939 // template-id that refers to the current context, so go there
3940 // to find the actual type being constructed.
3941 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3942 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3943 return DeclarationNameInfo();
3944
3945 // Determine the type of the class being constructed.
3946 QualType CurClassType = Context.getTypeDeclType(CurClass);
3947
3948 // FIXME: Check two things: that the template-id names the same type as
3949 // CurClassType, and that the template-id does not occur when the name
3950 // was qualified.
3951
3952 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3953 Context.getCanonicalType(CurClassType)));
3954 NameInfo.setLoc(Name.StartLocation);
3955 // FIXME: should we retrieve TypeSourceInfo?
3956 NameInfo.setNamedTypeInfo(0);
3957 return NameInfo;
3958 }
3959
3960 case UnqualifiedId::IK_DestructorName: {
3961 TypeSourceInfo *TInfo;
3962 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3963 if (Ty.isNull())
3964 return DeclarationNameInfo();
3965 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3966 Context.getCanonicalType(Ty)));
3967 NameInfo.setLoc(Name.StartLocation);
3968 NameInfo.setNamedTypeInfo(TInfo);
3969 return NameInfo;
3970 }
3971
3972 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003973 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003974 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3975 return Context.getNameForTemplate(TName, TNameLoc);
3976 }
3977
3978 } // switch (Name.getKind())
3979
David Blaikie83d382b2011-09-23 05:06:16 +00003980 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003981}
3982
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003983static QualType getCoreType(QualType Ty) {
3984 do {
3985 if (Ty->isPointerType() || Ty->isReferenceType())
3986 Ty = Ty->getPointeeType();
3987 else if (Ty->isArrayType())
3988 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3989 else
3990 return Ty.withoutLocalFastQualifiers();
3991 } while (true);
3992}
3993
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003994/// hasSimilarParameters - Determine whether the C++ functions Declaration
3995/// and Definition have "nearly" matching parameters. This heuristic is
3996/// used to improve diagnostics in the case where an out-of-line function
3997/// definition doesn't match any declaration within the class or namespace.
3998/// Also sets Params to the list of indices to the parameters that differ
3999/// between the declaration and the definition. If hasSimilarParameters
4000/// returns true and Params is empty, then all of the parameters match.
4001static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00004002 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004003 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004004 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004005 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00004006 if (Declaration->param_size() != Definition->param_size())
4007 return false;
4008 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4009 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4010 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4011
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004012 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004013 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004014 continue;
4015
4016 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4017 QualType DefParamBaseTy = getCoreType(DefParamTy);
4018 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4019 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4020
4021 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4022 (DeclTyName && DeclTyName == DefTyName))
4023 Params.push_back(Idx);
4024 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004025 return false;
4026 }
4027
4028 return true;
4029}
4030
John McCall99b2fe52010-04-29 23:50:39 +00004031/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4032/// declarator needs to be rebuilt in the current instantiation.
4033/// Any bits of declarator which appear before the name are valid for
4034/// consideration here. That's specifically the type in the decl spec
4035/// and the base type in any member-pointer chunks.
4036static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4037 DeclarationName Name) {
4038 // The types we specifically need to rebuild are:
4039 // - typenames, typeofs, and decltypes
4040 // - types which will become injected class names
4041 // Of course, we also need to rebuild any type referencing such a
4042 // type. It's safest to just say "dependent", but we call out a
4043 // few cases here.
4044
4045 DeclSpec &DS = D.getMutableDeclSpec();
4046 switch (DS.getTypeSpecType()) {
4047 case DeclSpec::TST_typename:
4048 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004049 case DeclSpec::TST_underlyingType:
4050 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004051 // Grab the type from the parser.
4052 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004053 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004054 if (T.isNull() || !T->isDependentType()) break;
4055
4056 // Make sure there's a type source info. This isn't really much
4057 // of a waste; most dependent types should have type source info
4058 // attached already.
4059 if (!TSI)
4060 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4061
4062 // Rebuild the type in the current instantiation.
4063 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4064 if (!TSI) return true;
4065
4066 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004067 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4068 DS.UpdateTypeRep(LocType);
4069 break;
4070 }
4071
Richard Smith1620ebd2012-10-01 20:35:07 +00004072 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004073 case DeclSpec::TST_typeofExpr: {
4074 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004075 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004076 if (Result.isInvalid()) return true;
4077 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004078 break;
4079 }
4080
4081 default:
4082 // Nothing to do for these decl specs.
4083 break;
4084 }
4085
4086 // It doesn't matter what order we do this in.
4087 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4088 DeclaratorChunk &Chunk = D.getTypeObject(I);
4089
4090 // The only type information in the declarator which can come
4091 // before the declaration name is the base type of a member
4092 // pointer.
4093 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4094 continue;
4095
4096 // Rebuild the scope specifier in-place.
4097 CXXScopeSpec &SS = Chunk.Mem.Scope();
4098 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4099 return true;
4100 }
4101
4102 return false;
4103}
4104
Anders Carlsson1052fd72011-07-04 16:28:17 +00004105Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004106 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004107 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004108
4109 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004110 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004111 Dcl->setTopLevelDeclInObjCContainer();
4112
4113 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004114}
4115
Richard Smithdda56e42011-04-15 14:24:37 +00004116/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4117/// If T is the name of a class, then each of the following shall have a
4118/// name different from T:
4119/// - every static data member of class T;
4120/// - every member function of class T
4121/// - every member of class T that is itself a type;
4122/// \returns true if the declaration name violates these rules.
4123bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4124 DeclarationNameInfo NameInfo) {
4125 DeclarationName Name = NameInfo.getName();
4126
4127 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4128 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4129 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4130 return true;
4131 }
4132
4133 return false;
4134}
Douglas Gregor31feb332012-03-17 23:06:31 +00004135
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004136/// \brief Diagnose a declaration whose declarator-id has the given
4137/// nested-name-specifier.
4138///
4139/// \param SS The nested-name-specifier of the declarator-id.
4140///
4141/// \param DC The declaration context to which the nested-name-specifier
4142/// resolves.
4143///
4144/// \param Name The name of the entity being declared.
4145///
4146/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004147///
4148/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004149bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004150 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004151 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004152 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004153 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004154 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004155
4156 // If the user provided a superfluous scope specifier that refers back to the
4157 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004158 //
4159 // class X {
4160 // void X::f();
4161 // };
Richard Smitha2302242013-12-05 07:51:02 +00004162 //
4163 // Note, it was once ill-formed to give redundant qualification in all
4164 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004165 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004166 if (Cur->isRecord()) {
4167 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4168 : diag::err_member_extra_qualification)
4169 << Name << FixItHint::CreateRemoval(SS.getRange());
4170 SS.clear();
4171 } else {
4172 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4173 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004174 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004175 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004176
4177 // Check whether the qualifying scope encloses the scope of the original
4178 // declaration.
4179 if (!Cur->Encloses(DC)) {
4180 if (Cur->isRecord())
4181 Diag(Loc, diag::err_member_qualification)
4182 << Name << SS.getRange();
4183 else if (isa<TranslationUnitDecl>(DC))
4184 Diag(Loc, diag::err_invalid_declarator_global_scope)
4185 << Name << SS.getRange();
4186 else if (isa<FunctionDecl>(Cur))
4187 Diag(Loc, diag::err_invalid_declarator_in_function)
4188 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004189 else if (isa<BlockDecl>(Cur))
4190 Diag(Loc, diag::err_invalid_declarator_in_block)
4191 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004192 else
4193 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004194 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004195
Douglas Gregor31feb332012-03-17 23:06:31 +00004196 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004197 }
4198
4199 if (Cur->isRecord()) {
4200 // Cannot qualify members within a class.
4201 Diag(Loc, diag::err_member_qualification)
4202 << Name << SS.getRange();
4203 SS.clear();
4204
4205 // C++ constructors and destructors with incorrect scopes can break
4206 // our AST invariants by having the wrong underlying types. If
4207 // that's the case, then drop this declaration entirely.
4208 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4209 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4210 !Context.hasSameType(Name.getCXXNameType(),
4211 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4212 return true;
4213
4214 return false;
4215 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004216
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004217 // C++11 [dcl.meaning]p1:
4218 // [...] "The nested-name-specifier of the qualified declarator-id shall
4219 // not begin with a decltype-specifer"
4220 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4221 while (SpecLoc.getPrefix())
4222 SpecLoc = SpecLoc.getPrefix();
4223 if (dyn_cast_or_null<DecltypeType>(
4224 SpecLoc.getNestedNameSpecifier()->getAsType()))
4225 Diag(Loc, diag::err_decltype_in_declarator)
4226 << SpecLoc.getTypeLoc().getSourceRange();
4227
Douglas Gregor31feb332012-03-17 23:06:31 +00004228 return false;
4229}
4230
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004231NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4232 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004233 // TODO: consider using NameInfo for diagnostic.
4234 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4235 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004236
Chris Lattner02c04392007-07-25 00:24:17 +00004237 // All of these full declarators require an identifier. If it doesn't have
4238 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004239 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004240 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004241 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004242 diag::err_declarator_need_ident)
4243 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004244 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004245 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4246 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004247
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004248 // The scope passed in may not be a decl scope. Zip up the scope tree until
4249 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004250 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004251 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004252 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004253
John McCall99b2fe52010-04-29 23:50:39 +00004254 DeclContext *DC = CurContext;
4255 if (D.getCXXScopeSpec().isInvalid())
4256 D.setInvalidType();
4257 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004258 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4259 UPPC_DeclarationQualifier))
4260 return 0;
4261
John McCall99b2fe52010-04-29 23:50:39 +00004262 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4263 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004264 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004265 // If we could not compute the declaration context, it's because the
4266 // declaration context is dependent but does not refer to a class,
4267 // class template, or class template partial specialization. Complain
4268 // and return early, to avoid the coming semantic disaster.
4269 Diag(D.getIdentifierLoc(),
4270 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004271 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004272 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004273 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004274 }
John McCall99b2fe52010-04-29 23:50:39 +00004275 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004276
John McCall99b2fe52010-04-29 23:50:39 +00004277 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004278 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004279 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004280
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004281 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4282 Diag(D.getIdentifierLoc(),
4283 diag::err_member_def_undefined_record)
4284 << Name << DC << D.getCXXScopeSpec().getRange();
4285 D.setInvalidType();
4286 } else if (!D.getDeclSpec().isFriendSpecified()) {
4287 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4288 Name, D.getIdentifierLoc())) {
4289 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004290 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004291
4292 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004293 }
John McCall99b2fe52010-04-29 23:50:39 +00004294 }
4295
4296 // Check whether we need to rebuild the type of the given
4297 // declaration in the current instantiation.
4298 if (EnteringContext && IsDependentContext &&
4299 TemplateParamLists.size() != 0) {
4300 ContextRAII SavedContext(*this, DC);
4301 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4302 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004303 }
4304 }
Richard Smithdda56e42011-04-15 14:24:37 +00004305
4306 if (DiagnoseClassNameShadow(DC, NameInfo))
4307 // If this is a typedef, we'll end up spewing multiple diagnostics.
4308 // Just return early; it's safer.
4309 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4310 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004311
John McCall8cb7bdf2010-06-04 23:28:52 +00004312 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4313 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004314
Douglas Gregor506bd562010-12-13 22:49:22 +00004315 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4316 UPPC_DeclarationType))
4317 D.setInvalidType();
4318
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004319 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004320 ForRedeclaration);
4321
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004322 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004323 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004324 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004325 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004326
4327 // If the declaration we're planning to build will be a function
4328 // or object with linkage, then look for another declaration with
4329 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004330 //
4331 // If the declaration we're planning to build will be declared with
4332 // external linkage in the translation unit, create any builtin with
4333 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004334 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4335 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004336 else if (CurContext->isFunctionOrMethod() &&
4337 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4338 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004339 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004340 CreateBuiltins =
4341 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4342 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4343 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4344 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004345
4346 if (IsLinkageLookup)
4347 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004348
Richard Smith1c34fb72013-08-13 18:18:50 +00004349 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004350 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004351 LookupQualifiedName(Previous, DC);
4352
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004353 // C++ [dcl.meaning]p1:
4354 // When the declarator-id is qualified, the declaration shall refer to a
4355 // previously declared member of the class or namespace to which the
4356 // qualifier refers (or, in the case of a namespace, of an element of the
4357 // inline namespace set of that namespace (7.3.1)) or to a specialization
4358 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004359 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004360 // Note that we already checked the context above, and that we do not have
4361 // enough information to make sure that Previous contains the declaration
4362 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004363 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004364 // class X {
4365 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004366 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004367 // };
4368 //
Douglas Gregorad590502008-12-15 23:53:10 +00004369 // void X::f(int) { } // ill-formed
4370 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004371 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004372 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004373 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004374
4375 // C++ [dcl.meaning]p1:
4376 // [...] the member shall not merely have been introduced by a
4377 // using-declaration in the scope of the class or namespace nominated by
4378 // the nested-name-specifier of the declarator-id.
4379 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004380 }
4381
John McCall1f82f242009-11-18 22:49:29 +00004382 if (Previous.isSingleResult() &&
4383 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004384 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004385 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004386 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4387 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004388
Douglas Gregor5101c242008-12-05 18:15:24 +00004389 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004390 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004391 }
4392
Douglas Gregor83a586e2008-04-13 21:07:44 +00004393 // In C++, the previous declaration we find might be a tag type
4394 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004395 // tag type. Note that this does does not apply if we're declaring a
4396 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004397 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004398 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004399 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004400
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004401 // Check that there are no default arguments other than in the parameters
4402 // of a function declaration (C++ only).
4403 if (getLangOpts().CPlusPlus)
4404 CheckExtraCXXDefaultArguments(D);
4405
Nico Webercb4c7f42012-12-23 00:40:46 +00004406 NamedDecl *New;
4407
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004408 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004409 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004410 if (TemplateParamLists.size()) {
4411 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004412 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004413 }
Mike Stump11289f42009-09-09 15:08:12 +00004414
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004415 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004416 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004417 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004418 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004419 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004420 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004421 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4422 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004423 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004424
4425 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004426 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004427
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004428 // If this has an identifier and is not an invalid redeclaration or
4429 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004430 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004431 !(D.isRedeclaration() && New->isInvalidDecl())) {
4432 // Only make a locally-scoped extern declaration visible if it is the first
4433 // declaration of this entity. Qualified lookup for such an entity should
4434 // only find this declaration if there is no visible declaration of it.
4435 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4436 PushOnScopeChains(New, S, AddToContext);
4437 if (!AddToContext)
4438 CurContext->addHiddenDecl(New);
4439 }
Mike Stump11289f42009-09-09 15:08:12 +00004440
John McCall48871652010-08-21 09:40:31 +00004441 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004442}
4443
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004444/// Helper method to turn variable array types into constant array
4445/// types in certain situations which would otherwise be errors (for
4446/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004447static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4448 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004449 bool &SizeIsNegative,
4450 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004451 // This method tries to turn a variable array into a constant
4452 // array even when the size isn't an ICE. This is necessary
4453 // for compatibility with code that depends on gcc's buggy
4454 // constant expression folding, like struct {char x[(int)(char*)2];}
4455 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004456 Oversized = 0;
4457
4458 if (T->isDependentType())
4459 return QualType();
4460
John McCall8ccfcb52009-09-24 19:53:00 +00004461 QualifierCollector Qs;
4462 const Type *Ty = Qs.strip(T);
4463
4464 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004465 QualType Pointee = PTy->getPointeeType();
4466 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004467 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4468 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004469 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004470 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004471 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004472 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004473 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4474 QualType Inner = PTy->getInnerType();
4475 QualType FixedType =
4476 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4477 Oversized);
4478 if (FixedType.isNull()) return FixedType;
4479 FixedType = Context.getParenType(FixedType);
4480 return Qs.apply(Context, FixedType);
4481 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004482
4483 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004484 if (!VLATy)
4485 return QualType();
4486 // FIXME: We should probably handle this case
4487 if (VLATy->getElementType()->isVariablyModifiedType())
4488 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004489
Richard Smith42d3af92011-12-07 00:43:50 +00004490 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004491 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004492 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004493 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004494
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004495 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004496 if (Res.isSigned() && Res.isNegative()) {
4497 SizeIsNegative = true;
4498 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004499 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004500
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004501 // Check whether the array is too large to be addressed.
4502 unsigned ActiveSizeBits
4503 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4504 Res);
4505 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4506 Oversized = Res;
4507 return QualType();
4508 }
4509
4510 return Context.getConstantArrayType(VLATy->getElementType(),
4511 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004512}
4513
Abramo Bagnara341ab732012-11-08 14:44:42 +00004514static void
4515FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004516 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4517 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4518 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4519 DstPTL.getPointeeLoc());
4520 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004521 return;
4522 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004523 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4524 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4525 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4526 DstPTL.getInnerLoc());
4527 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4528 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004529 return;
4530 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004531 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4532 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4533 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4534 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004535 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004536 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4537 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4538 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004539}
4540
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004541/// Helper method to turn variable array types into constant array
4542/// types in certain situations which would otherwise be errors (for
4543/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004544static TypeSourceInfo*
4545TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4546 ASTContext &Context,
4547 bool &SizeIsNegative,
4548 llvm::APSInt &Oversized) {
4549 QualType FixedTy
4550 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4551 SizeIsNegative, Oversized);
4552 if (FixedTy.isNull())
4553 return 0;
4554 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4555 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4556 FixedTInfo->getTypeLoc());
4557 return FixedTInfo;
4558}
4559
Richard Smith78165b52013-01-10 23:43:47 +00004560/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004561/// that it can be found later for redeclarations. We include any extern "C"
4562/// declaration that is not visible in the translation unit here, not just
4563/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004564void
Richard Smith39b79682013-06-18 20:15:12 +00004565Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004566 if (!getLangOpts().CPlusPlus &&
4567 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4568 // Don't need to track declarations in the TU in C.
4569 return;
4570
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004571 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004572 // FIXME: There can be multiple such declarations if they are functions marked
4573 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004574 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004575}
4576
Richard Smith39b79682013-06-18 20:15:12 +00004577NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004578 if (ExternalSource) {
4579 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004580 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004581 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004582 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004583 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4584 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004585 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4586 if (Pos == LocallyScopedExternCDecls.end())
4587 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004588 }
4589 }
Richard Smith39b79682013-06-18 20:15:12 +00004590
4591 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004592 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004593}
4594
Eli Friedman574c7452009-04-07 19:37:57 +00004595/// \brief Diagnose function specifiers on a declaration of an identifier that
4596/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004597void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004598 // FIXME: We should probably indicate the identifier in question to avoid
4599 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004600 if (DS.isInlineSpecified())
4601 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004602 diag::err_inline_non_function);
4603
Richard Smithb1402ae2013-03-18 22:52:47 +00004604 if (DS.isVirtualSpecified())
4605 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004606 diag::err_virtual_non_function);
4607
Richard Smithb1402ae2013-03-18 22:52:47 +00004608 if (DS.isExplicitSpecified())
4609 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004610 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004611
Richard Smithb1402ae2013-03-18 22:52:47 +00004612 if (DS.isNoreturnSpecified())
4613 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004614 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004615}
4616
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004617NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004618Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004619 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004620 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4621 if (D.getCXXScopeSpec().isSet()) {
4622 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4623 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004624 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004625 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004626 DC = CurContext;
4627 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004628 }
4629
Richard Smithb1402ae2013-03-18 22:52:47 +00004630 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004631
Richard Smitha77a0a62011-08-15 21:04:07 +00004632 if (D.getDeclSpec().isConstexprSpecified())
4633 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4634 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004635
Douglas Gregord8f446f2010-07-13 06:37:01 +00004636 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4637 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4638 << D.getName().getSourceRange();
4639 return 0;
4640 }
4641
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004642 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004643 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004644
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004645 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004646 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004647
Richard Smith3f1b5d02011-05-05 21:57:07 +00004648 CheckTypedefForVariablyModifiedType(S, NewTD);
4649
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004650 bool Redeclaration = D.isRedeclaration();
4651 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4652 D.setRedeclaration(Redeclaration);
4653 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004654}
4655
Richard Smith3f1b5d02011-05-05 21:57:07 +00004656void
4657Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004658 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4659 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004660 // Note that variably modified types must be fixed before merging the decl so
4661 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004662 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4663 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004664 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004665 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004666
Chris Lattner9fecd742009-04-19 05:21:20 +00004667 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004668 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004669 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004670 TypeSourceInfo *FixedTInfo =
4671 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4672 SizeIsNegative,
4673 Oversized);
4674 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004675 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004676 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004677 } else {
4678 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004679 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004680 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004681 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004682 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004683 Diag(NewTD->getLocation(), diag::err_array_too_large)
4684 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004685 else
Richard Smithdda56e42011-04-15 14:24:37 +00004686 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004687 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004688 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004689 }
4690 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004691}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004692
Richard Smith3f1b5d02011-05-05 21:57:07 +00004693
4694/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4695/// declares a typedef-name, either using the 'typedef' type specifier or via
4696/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4697NamedDecl*
4698Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4699 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004700 // Merge the decl with the existing one if appropriate. If the decl is
4701 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004702 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4703 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004704 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004705 if (!Previous.empty()) {
4706 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004707 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004708 }
4709
Douglas Gregor27821ce2009-07-07 16:35:42 +00004710 // If this is the C FILE type, notify the AST context.
4711 if (IdentifierInfo *II = NewTD->getIdentifier())
4712 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004713 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004714 if (II->isStr("FILE"))
4715 Context.setFILEDecl(NewTD);
4716 else if (II->isStr("jmp_buf"))
4717 Context.setjmp_bufDecl(NewTD);
4718 else if (II->isStr("sigjmp_buf"))
4719 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004720 else if (II->isStr("ucontext_t"))
4721 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004722 }
4723
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004724 return NewTD;
4725}
4726
Douglas Gregor5d68a202009-02-24 19:23:27 +00004727/// \brief Determines whether the given declaration is an out-of-scope
4728/// previous declaration.
4729///
4730/// This routine should be invoked when name lookup has found a
4731/// previous declaration (PrevDecl) that is not in the scope where a
4732/// new declaration by the same name is being introduced. If the new
4733/// declaration occurs in a local scope, previous declarations with
4734/// linkage may still be considered previous declarations (C99
4735/// 6.2.2p4-5, C++ [basic.link]p6).
4736///
4737/// \param PrevDecl the previous declaration found by name
4738/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004739///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004740/// \param DC the context in which the new declaration is being
4741/// declared.
4742///
4743/// \returns true if PrevDecl is an out-of-scope previous declaration
4744/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004745static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004746isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4747 ASTContext &Context) {
4748 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004749 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004750
Douglas Gregoreddf4332009-02-24 20:03:32 +00004751 if (!PrevDecl->hasLinkage())
4752 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004753
David Blaikiebbafb8a2012-03-11 07:00:24 +00004754 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004755 // C++ [basic.link]p6:
4756 // If there is a visible declaration of an entity with linkage
4757 // having the same name and type, ignoring entities declared
4758 // outside the innermost enclosing namespace scope, the block
4759 // scope declaration declares that same entity and receives the
4760 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004761 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004762 if (!OuterContext->isFunctionOrMethod())
4763 // This rule only applies to block-scope declarations.
4764 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004765
4766 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4767 if (PrevOuterContext->isRecord())
4768 // We found a member function: ignore it.
4769 return false;
4770
4771 // Find the innermost enclosing namespace for the new and
4772 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004773 OuterContext = OuterContext->getEnclosingNamespaceContext();
4774 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004775
Douglas Gregorfcee9462010-08-27 22:55:10 +00004776 // The previous declaration is in a different namespace, so it
4777 // isn't the same function.
4778 if (!OuterContext->Equals(PrevOuterContext))
4779 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004780 }
4781
Douglas Gregor5d68a202009-02-24 19:23:27 +00004782 return true;
4783}
4784
John McCall3e11ebe2010-03-15 10:12:16 +00004785static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4786 CXXScopeSpec &SS = D.getCXXScopeSpec();
4787 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004788 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004789}
4790
John McCall31168b02011-06-15 23:02:42 +00004791bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4792 QualType type = decl->getType();
4793 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4794 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4795 // Various kinds of declaration aren't allowed to be __autoreleasing.
4796 unsigned kind = -1U;
4797 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4798 if (var->hasAttr<BlocksAttr>())
4799 kind = 0; // __block
4800 else if (!var->hasLocalStorage())
4801 kind = 1; // global
4802 } else if (isa<ObjCIvarDecl>(decl)) {
4803 kind = 3; // ivar
4804 } else if (isa<FieldDecl>(decl)) {
4805 kind = 2; // field
4806 }
4807
4808 if (kind != -1U) {
4809 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4810 << kind;
4811 }
4812 } else if (lifetime == Qualifiers::OCL_None) {
4813 // Try to infer lifetime.
4814 if (!type->isObjCLifetimeType())
4815 return false;
4816
4817 lifetime = type->getObjCARCImplicitLifetime();
4818 type = Context.getLifetimeQualifiedType(type, lifetime);
4819 decl->setType(type);
4820 }
4821
4822 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4823 // Thread-local variables cannot have lifetime.
4824 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004825 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004826 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004827 << var->getType();
4828 return true;
4829 }
4830 }
4831
4832 return false;
4833}
4834
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004835static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004836 // Ensure that an auto decl is deduced otherwise the checks below might cache
4837 // the wrong linkage.
4838 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4839
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004840 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004841 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004842 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004843 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4844 ND.dropAttr<WeakAttr>();
4845 }
4846 }
4847 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004848 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004849 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4850 ND.dropAttr<WeakRefAttr>();
4851 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004852 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004853
4854 // 'selectany' only applies to externally visible varable declarations.
4855 // It does not apply to functions.
4856 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4857 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4858 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4859 ND.dropAttr<SelectAnyAttr>();
4860 }
4861 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004862}
4863
John McCallc87d9722013-04-02 02:48:58 +00004864/// Given that we are within the definition of the given function,
4865/// will that definition behave like C99's 'inline', where the
4866/// definition is discarded except for optimization purposes?
4867static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4868 // Try to avoid calling GetGVALinkageForFunction.
4869
4870 // All cases of this require the 'inline' keyword.
4871 if (!FD->isInlined()) return false;
4872
4873 // This is only possible in C++ with the gnu_inline attribute.
4874 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4875 return false;
4876
4877 // Okay, go ahead and call the relatively-more-expensive function.
4878
4879#ifndef NDEBUG
4880 // AST quite reasonably asserts that it's working on a function
4881 // definition. We don't really have a way to tell it that we're
4882 // currently defining the function, so just lie to it in +Asserts
4883 // builds. This is an awful hack.
4884 FD->setLazyBody(1);
4885#endif
4886
4887 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4888
4889#ifndef NDEBUG
4890 FD->setLazyBody(0);
4891#endif
4892
4893 return isC99Inline;
4894}
4895
Richard Smithac974a32013-06-30 09:48:50 +00004896/// Determine whether a variable is extern "C" prior to attaching
4897/// an initializer. We can't just call isExternC() here, because that
4898/// will also compute and cache whether the declaration is externally
4899/// visible, which might change when we attach the initializer.
4900///
4901/// This can only be used if the declaration is known to not be a
4902/// redeclaration of an internal linkage declaration.
4903///
4904/// For instance:
4905///
4906/// auto x = []{};
4907///
4908/// Attaching the initializer here makes this declaration not externally
4909/// visible, because its type has internal linkage.
4910///
4911/// FIXME: This is a hack.
4912template<typename T>
4913static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4914 if (S.getLangOpts().CPlusPlus) {
4915 // In C++, the overloadable attribute negates the effects of extern "C".
4916 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4917 return false;
4918 }
4919 return D->isExternC();
4920}
4921
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004922static bool shouldConsiderLinkage(const VarDecl *VD) {
4923 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4924 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004925 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004926 if (DC->isFileContext())
4927 return true;
4928 if (DC->isRecord())
4929 return false;
4930 llvm_unreachable("Unexpected context");
4931}
4932
4933static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4934 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4935 if (DC->isFileContext() || DC->isFunctionOrMethod())
4936 return true;
4937 if (DC->isRecord())
4938 return false;
4939 llvm_unreachable("Unexpected context");
4940}
4941
Richard Smith541b38b2013-09-20 01:15:31 +00004942/// Adjust the \c DeclContext for a function or variable that might be a
4943/// function-local external declaration.
4944bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4945 if (!DC->isFunctionOrMethod())
4946 return false;
4947
4948 // If this is a local extern function or variable declared within a function
4949 // template, don't add it into the enclosing namespace scope until it is
4950 // instantiated; it might have a dependent type right now.
4951 if (DC->isDependentContext())
4952 return true;
4953
4954 // C++11 [basic.link]p7:
4955 // When a block scope declaration of an entity with linkage is not found to
4956 // refer to some other declaration, then that entity is a member of the
4957 // innermost enclosing namespace.
4958 //
4959 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4960 // semantically-enclosing namespace, not a lexically-enclosing one.
4961 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4962 DC = DC->getParent();
4963 return true;
4964}
4965
Larisse Voufo39a1e502013-08-06 01:03:05 +00004966NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004967Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004968 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004969 MultiTemplateParamsArg TemplateParamLists,
4970 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004971 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004972 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004973
Douglas Gregorc4df4072010-04-19 22:54:31 +00004974 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004975 VarDecl::StorageClass SC =
4976 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004977
Richard Smith541b38b2013-09-20 01:15:31 +00004978 DeclContext *OriginalDC = DC;
4979 bool IsLocalExternDecl = SC == SC_Extern &&
4980 adjustContextForLocalExternDecl(DC);
4981
Richard Smith5990db62013-04-15 08:33:22 +00004982 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004983 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4984 // half array type (unless the cl_khr_fp16 extension is enabled).
4985 if (Context.getBaseElementType(R)->isHalfType()) {
4986 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4987 D.setInvalidType();
4988 }
4989 }
4990
Douglas Gregorc4df4072010-04-19 22:54:31 +00004991 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004992 // mutable can only appear on non-static class members, so it's always
4993 // an error here
4994 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004995 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004996 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004997 }
John McCallc87d9722013-04-02 02:48:58 +00004998
Richard Smithf2c9afc2013-06-17 01:34:01 +00004999 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5000 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5001 D.getDeclSpec().getStorageClassSpecLoc())) {
5002 // In C++11, the 'register' storage class specifier is deprecated.
5003 // Suppress the warning in system macros, it's used in macros in some
5004 // popular C system headers, such as in glibc's htonl() macro.
5005 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5006 diag::warn_deprecated_register)
5007 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5008 }
5009
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005010 IdentifierInfo *II = Name.getAsIdentifierInfo();
5011 if (!II) {
5012 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005013 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005014 return 0;
5015 }
5016
Richard Smithb1402ae2013-03-18 22:52:47 +00005017 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005018
Douglas Gregor212cab32009-03-11 20:22:50 +00005019 if (!DC->isRecord() && S->getFnParent() == 0) {
5020 // C99 6.9p2: The storage-class specifiers auto and register shall not
5021 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005022 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005023 // If this is a register variable with an asm label specified, then this
5024 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005025 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005026 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5027 else
5028 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005029 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005030 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005031 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005032
David Blaikiebbafb8a2012-03-11 07:00:24 +00005033 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005034 // Set up the special work-group-local storage class for variables in the
5035 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005036 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005037 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005038 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005039
Guy Benyei61054192013-02-07 10:55:47 +00005040 // OpenCL v1.2 s6.9.b p4:
5041 // The sampler type cannot be used with the __local and __global address
5042 // space qualifiers.
5043 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5044 R.getAddressSpace() == LangAS::opencl_global)) {
5045 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5046 }
5047
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005048 // OpenCL 1.2 spec, p6.9 r:
5049 // The event type cannot be used to declare a program scope variable.
5050 // The event type cannot be used with the __local, __constant and __global
5051 // address space qualifiers.
5052 if (R->isEventT()) {
5053 if (S->getParent() == 0) {
5054 Diag(D.getLocStart(), diag::err_event_t_global_var);
5055 D.setInvalidType();
5056 }
5057
5058 if (R.getAddressSpace()) {
5059 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5060 D.setInvalidType();
5061 }
5062 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005063 }
5064
Larisse Voufo39a1e502013-08-06 01:03:05 +00005065 bool IsExplicitSpecialization = false;
5066 bool IsVariableTemplateSpecialization = false;
5067 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005068 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005069 VarDecl *NewVD = 0;
5070 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005071 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005072 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005073 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005074 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005075 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005076
5077 if (D.isInvalidType())
5078 NewVD->setInvalidDecl();
5079 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005080 bool Invalid = false;
5081
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005082 if (DC->isRecord() && !CurContext->isRecord()) {
5083 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005084 switch (SC) {
5085 case SC_None:
5086 break;
5087 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005088 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5089 diag::err_static_out_of_line)
5090 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005091 break;
5092 case SC_Auto:
5093 case SC_Register:
5094 case SC_Extern:
5095 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5096 // to names of variables declared in a block or to function parameters.
5097 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5098 // of class members
5099
5100 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5101 diag::err_storage_class_for_static_member)
5102 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5103 break;
5104 case SC_PrivateExtern:
5105 llvm_unreachable("C storage class in c++!");
5106 case SC_OpenCLWorkGroupLocal:
5107 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005108 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005109 }
5110
Richard Smith42973752012-02-16 20:41:22 +00005111 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005112 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5113 if (RD->isLocalClass())
5114 Diag(D.getIdentifierLoc(),
5115 diag::err_static_data_member_not_allowed_in_local_class)
5116 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005117
Richard Smith42973752012-02-16 20:41:22 +00005118 // C++98 [class.union]p1: If a union contains a static data member,
5119 // the program is ill-formed. C++11 drops this restriction.
5120 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005121 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005122 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005123 ? diag::warn_cxx98_compat_static_data_member_in_union
5124 : diag::ext_static_data_member_in_union) << Name;
5125 // We conservatively disallow static data members in anonymous structs.
5126 else if (!RD->getDeclName())
5127 Diag(D.getIdentifierLoc(),
5128 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005129 << Name << RD->isUnion();
5130 }
5131 }
5132
5133 // Match up the template parameter lists with the scope specifier, then
5134 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005135 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5136 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5137 D.getCXXScopeSpec(), TemplateParamLists,
5138 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005139
Richard Smithbeef3452014-01-16 23:39:20 +00005140 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5141 !TemplateParams) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005142 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5143
5144 // We have encountered something that the user meant to be a
5145 // specialization (because it has explicitly-specified template
5146 // arguments) but that was not introduced with a "template<>" (or had
5147 // too few of them).
5148 // FIXME: Differentiate between attempts for explicit instantiations
5149 // (starting with "template") and the rest.
5150 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5151 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5152 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5153 "template<> ");
Richard Smith72db5632014-01-25 21:32:06 +00005154 IsExplicitSpecialization = true;
Richard Smithbeef3452014-01-16 23:39:20 +00005155 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5156 SourceLocation(), 0, 0,
5157 SourceLocation());
5158 }
5159
5160 if (TemplateParams) {
5161 if (!TemplateParams->size() &&
5162 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5163 // There is an extraneous 'template<>' for this variable. Complain
5164 // about it, but allow the declaration of the variable.
5165 Diag(TemplateParams->getTemplateLoc(),
5166 diag::err_template_variable_noparams)
5167 << II
5168 << SourceRange(TemplateParams->getTemplateLoc(),
5169 TemplateParams->getRAngleLoc());
5170 TemplateParams = 0;
5171 } else {
5172 // Only C++1y supports variable templates (N3651).
5173 Diag(D.getIdentifierLoc(),
5174 getLangOpts().CPlusPlus1y
5175 ? diag::warn_cxx11_compat_variable_template
5176 : diag::ext_variable_template);
5177
5178 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5179 // This is an explicit specialization or a partial specialization.
5180 // FIXME: Check that we can declare a specialization here.
5181 IsVariableTemplateSpecialization = true;
5182 IsPartialSpecialization = TemplateParams->size() > 0;
5183 } else { // if (TemplateParams->size() > 0)
5184 // This is a template declaration.
5185 IsVariableTemplate = true;
5186
5187 // Check that we can declare a template here.
5188 if (CheckTemplateDeclScope(S, TemplateParams))
5189 return 0;
5190 }
5191 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005192 }
Mike Stump11289f42009-09-09 15:08:12 +00005193
Larisse Voufo39a1e502013-08-06 01:03:05 +00005194 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005195 SourceLocation TemplateKWLoc =
5196 TemplateParamLists.size() > 0
5197 ? TemplateParamLists[0]->getTemplateLoc()
5198 : SourceLocation();
5199 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005200 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005201 IsPartialSpecialization);
5202 if (Res.isInvalid())
5203 return 0;
5204 NewVD = cast<VarDecl>(Res.get());
5205 AddToScope = false;
5206 } else
5207 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5208 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005209
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005210 // If this is supposed to be a variable template, create it as such.
5211 if (IsVariableTemplate) {
5212 NewTemplate =
5213 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005214 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005215 NewVD->setDescribedVarTemplate(NewTemplate);
5216 }
5217
Richard Smithb2bc2e62011-02-21 20:05:19 +00005218 // If this decl has an auto type in need of deduction, make a note of the
5219 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005220 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005221 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005222
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005223 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005224 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005225 if (NewTemplate)
5226 NewTemplate->setInvalidDecl();
5227 }
Mike Stump11289f42009-09-09 15:08:12 +00005228
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005229 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005230
Richard Smith72db5632014-01-25 21:32:06 +00005231 // If we have any template parameter lists that don't directly belong to
5232 // the variable (matching the scope specifier), store them.
5233 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5234 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005235 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005236 Context, TemplateParamLists.size() - VDTemplateParamLists,
5237 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005238
Richard Smith6331c402012-02-13 22:16:19 +00005239 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005240 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005241 }
5242
Douglas Gregor41866812011-09-12 18:37:38 +00005243 // Set the lexical context. If the declarator has a C++ scope specifier, the
5244 // lexical context will be different from the semantic context.
5245 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005246 if (NewTemplate)
5247 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005248
Richard Smith541b38b2013-09-20 01:15:31 +00005249 if (IsLocalExternDecl)
5250 NewVD->setLocalExternDecl();
5251
Richard Smithb4a9e862013-04-12 22:46:28 +00005252 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005253 if (NewVD->hasLocalStorage()) {
5254 // C++11 [dcl.stc]p4:
5255 // When thread_local is applied to a variable of block scope the
5256 // storage-class-specifier static is implied if it does not appear
5257 // explicitly.
5258 // Core issue: 'static' is not implied if the variable is declared
5259 // 'extern'.
5260 if (SCSpec == DeclSpec::SCS_unspecified &&
5261 TSCS == DeclSpec::TSCS_thread_local &&
5262 DC->isFunctionOrMethod())
5263 NewVD->setTSCSpec(TSCS);
5264 else
5265 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5266 diag::err_thread_non_global)
5267 << DeclSpec::getSpecifierName(TSCS);
5268 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005269 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5270 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005271 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005272 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005273 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005274
John McCallc87d9722013-04-02 02:48:58 +00005275 // C99 6.7.4p3
5276 // An inline definition of a function with external linkage shall
5277 // not contain a definition of a modifiable object with static or
5278 // thread storage duration...
5279 // We only apply this when the function is required to be defined
5280 // elsewhere, i.e. when the function is not 'extern inline'. Note
5281 // that a local variable with thread storage duration still has to
5282 // be marked 'static'. Also note that it's possible to get these
5283 // semantics in C++ using __attribute__((gnu_inline)).
5284 if (SC == SC_Static && S->getFnParent() != 0 &&
5285 !NewVD->getType().isConstQualified()) {
5286 FunctionDecl *CurFD = getCurFunctionDecl();
5287 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5288 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5289 diag::warn_static_local_in_extern_inline);
5290 MaybeSuggestAddingStaticToDecl(CurFD);
5291 }
5292 }
5293
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005294 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005295 if (IsVariableTemplateSpecialization)
5296 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5297 << (IsPartialSpecialization ? 1 : 0)
5298 << FixItHint::CreateRemoval(
5299 D.getDeclSpec().getModulePrivateSpecLoc());
5300 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005301 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5302 << 2
5303 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005304 else if (NewVD->hasLocalStorage())
5305 Diag(NewVD->getLocation(), diag::err_module_private_local)
5306 << 0 << NewVD->getDeclName()
5307 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5308 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005309 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005310 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005311 if (NewTemplate)
5312 NewTemplate->setModulePrivate();
5313 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005314 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005315
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005316 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005317 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005318
Richard Smith848e1f12013-02-01 08:12:08 +00005319 if (NewVD->hasAttrs())
5320 CheckAlignasUnderalignment(NewVD);
5321
Peter Collingbournec6b08572012-08-28 20:37:50 +00005322 if (getLangOpts().CUDA) {
5323 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5324 // storage [duration]."
5325 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005326 (NewVD->hasAttr<CUDASharedAttr>() ||
5327 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005328 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005329 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005330 }
5331
John McCall31168b02011-06-15 23:02:42 +00005332 // In auto-retain/release, infer strong retension for variables of
5333 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005334 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005335 NewVD->setInvalidDecl();
5336
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005337 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005338 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005339 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005340 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005341 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005342 if (S->getFnParent() != 0) {
5343 switch (SC) {
5344 case SC_None:
5345 case SC_Auto:
5346 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5347 break;
5348 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005349 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005350 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5351 break;
5352 case SC_Static:
5353 case SC_Extern:
5354 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005355 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005356 break;
5357 }
5358 }
5359
5360 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005361 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005362 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5363 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5364 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5365 if (I != ExtnameUndeclaredIdentifiers.end()) {
5366 NewVD->addAttr(I->second);
5367 ExtnameUndeclaredIdentifiers.erase(I);
5368 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005369 }
5370
John McCalla2a3f7d2010-03-16 21:48:18 +00005371 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005372 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005373 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005374
John McCall1f82f242009-11-18 22:49:29 +00005375 // Don't consider existing declarations that are in a different
5376 // scope and are out-of-semantic-context declarations (if the new
5377 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005378 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5379 D.getCXXScopeSpec().isNotEmpty() ||
5380 IsExplicitSpecialization ||
5381 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005382
Richard Smith1c34fb72013-08-13 18:18:50 +00005383 // Check whether the previous declaration is in the same block scope. This
5384 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5385 if (getLangOpts().CPlusPlus &&
5386 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5387 NewVD->setPreviousDeclInSameBlockScope(
5388 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005389 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005390
David Blaikiebbafb8a2012-03-11 07:00:24 +00005391 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005392 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5393 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005394 // If this is an explicit specialization of a static data member, check it.
5395 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5396 CheckMemberSpecialization(NewVD, Previous))
5397 NewVD->setInvalidDecl();
5398
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005399 // Merge the decl with the existing one if appropriate.
5400 if (!Previous.empty()) {
5401 if (Previous.isSingleResult() &&
5402 isa<FieldDecl>(Previous.getFoundDecl()) &&
5403 D.getCXXScopeSpec().isSet()) {
5404 // The user tried to define a non-static data member
5405 // out-of-line (C++ [dcl.meaning]p1).
5406 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5407 << D.getCXXScopeSpec().getRange();
5408 Previous.clear();
5409 NewVD->setInvalidDecl();
5410 }
5411 } else if (D.getCXXScopeSpec().isSet()) {
5412 // No previous declaration in the qualifying scope.
5413 Diag(D.getIdentifierLoc(), diag::err_no_member)
5414 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005415 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005416 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005417 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005418
Richard Smithbeef3452014-01-16 23:39:20 +00005419 if (!IsVariableTemplateSpecialization)
5420 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005421
Richard Smithbeef3452014-01-16 23:39:20 +00005422 if (NewTemplate) {
5423 VarTemplateDecl *PrevVarTemplate =
5424 NewVD->getPreviousDecl()
5425 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5426 : 0;
5427
5428 // Check the template parameter list of this declaration, possibly
5429 // merging in the template parameter list from the previous variable
5430 // template declaration.
5431 if (CheckTemplateParameterList(
5432 TemplateParams,
5433 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5434 : 0,
5435 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5436 DC->isDependentContext())
5437 ? TPC_ClassTemplateMember
5438 : TPC_VarTemplate))
5439 NewVD->setInvalidDecl();
5440
5441 // If we are providing an explicit specialization of a static variable
5442 // template, make a note of that.
5443 if (PrevVarTemplate &&
5444 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5445 PrevVarTemplate->setMemberSpecialization();
5446 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005447 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005448
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005449 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005450
Richard Smithac974a32013-06-30 09:48:50 +00005451 // If this is the first declaration of an extern C variable, update
5452 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005453 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005454 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005455 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005456
Reid Klecknerd8110b62013-09-10 20:14:30 +00005457 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005458 Decl *ManglingContextDecl;
5459 if (MangleNumberingContext *MCtx =
5460 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5461 ManglingContextDecl)) {
5462 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5463 }
5464 }
5465
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005466 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005467 if (NewVD->isInvalidDecl())
5468 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005469 ActOnDocumentableDecl(NewTemplate);
5470 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005471 }
5472
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005473 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005474}
5475
John McCalldf8b37c2010-03-22 09:20:08 +00005476/// \brief Diagnose variable or built-in function shadowing. Implements
5477/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005478///
John McCalldf8b37c2010-03-22 09:20:08 +00005479/// This method is called whenever a VarDecl is added to a "useful"
5480/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005481///
John McCall2d8c7602010-03-20 04:12:52 +00005482/// \param S the scope in which the shadowing name is being declared
5483/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005484///
John McCalldf8b37c2010-03-22 09:20:08 +00005485void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005486 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005487 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005488 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005489 return;
5490
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005491 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005492 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005493 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005494
5495 DeclContext *NewDC = D->getDeclContext();
5496
John McCall2d8c7602010-03-20 04:12:52 +00005497 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005498 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005499 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005500
John McCalla2a3f7d2010-03-16 21:48:18 +00005501 NamedDecl* ShadowedDecl = R.getFoundDecl();
5502 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5503 return;
5504
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005505 // Fields are not shadowed by variables in C++ static methods.
5506 if (isa<FieldDecl>(ShadowedDecl))
5507 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5508 if (MD->isStatic())
5509 return;
5510
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005511 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5512 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005513 // For shadowing external vars, make sure that we point to the global
5514 // declaration, not a locally scoped extern declaration.
5515 for (VarDecl::redecl_iterator
5516 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5517 I != E; ++I)
5518 if (I->isFileVarDecl()) {
5519 ShadowedDecl = *I;
5520 break;
5521 }
5522 }
5523
5524 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5525
John McCall2d8c7602010-03-20 04:12:52 +00005526 // Only warn about certain kinds of shadowing for class members.
5527 if (NewDC && NewDC->isRecord()) {
5528 // In particular, don't warn about shadowing non-class members.
5529 if (!OldDC->isRecord())
5530 return;
5531
5532 // TODO: should we warn about static data members shadowing
5533 // static data members from base classes?
5534
5535 // TODO: don't diagnose for inaccessible shadowed members.
5536 // This is hard to do perfectly because we might friend the
5537 // shadowing context, but that's just a false negative.
5538 }
5539
5540 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005541 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005542 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005543 if (isa<FieldDecl>(ShadowedDecl))
5544 Kind = 3; // field
5545 else
5546 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005547 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005548 Kind = 1; // global
5549 else
5550 Kind = 0; // local
5551
John McCall2d8c7602010-03-20 04:12:52 +00005552 DeclarationName Name = R.getLookupName();
5553
John McCalla2a3f7d2010-03-16 21:48:18 +00005554 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005555 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5556 return;
John McCall2d8c7602010-03-20 04:12:52 +00005557 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005558 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5559}
5560
John McCalldf8b37c2010-03-22 09:20:08 +00005561/// \brief Check -Wshadow without the advantage of a previous lookup.
5562void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005563 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005564 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005565 return;
5566
John McCalldf8b37c2010-03-22 09:20:08 +00005567 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5568 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5569 LookupName(R, S);
5570 CheckShadow(S, D, R);
5571}
5572
Richard Smithac974a32013-06-30 09:48:50 +00005573/// Check for conflict between this global or extern "C" declaration and
5574/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005575template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005576static bool checkGlobalOrExternCConflict(
5577 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5578 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5579 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005580
Richard Smithac974a32013-06-30 09:48:50 +00005581 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5582 // The common case: this global doesn't conflict with any extern "C"
5583 // declaration.
5584 return false;
5585 }
5586
5587 if (Prev) {
5588 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5589 // Both the old and new declarations have C language linkage. This is a
5590 // redeclaration.
5591 Previous.clear();
5592 Previous.addDecl(Prev);
5593 return true;
5594 }
5595
5596 // This is a global, non-extern "C" declaration, and there is a previous
5597 // non-global extern "C" declaration. Diagnose if this is a variable
5598 // declaration.
5599 if (!isa<VarDecl>(ND))
5600 return false;
5601 } else {
5602 // The declaration is extern "C". Check for any declaration in the
5603 // translation unit which might conflict.
5604 if (IsGlobal) {
5605 // We have already performed the lookup into the translation unit.
5606 IsGlobal = false;
5607 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5608 I != E; ++I) {
5609 if (isa<VarDecl>(*I)) {
5610 Prev = *I;
5611 break;
5612 }
5613 }
5614 } else {
5615 DeclContext::lookup_result R =
5616 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5617 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5618 I != E; ++I) {
5619 if (isa<VarDecl>(*I)) {
5620 Prev = *I;
5621 break;
5622 }
5623 // FIXME: If we have any other entity with this name in global scope,
5624 // the declaration is ill-formed, but that is a defect: it breaks the
5625 // 'stat' hack, for instance. Only variables can have mangled name
5626 // clashes with extern "C" declarations, so only they deserve a
5627 // diagnostic.
5628 }
5629 }
5630
5631 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005632 return false;
5633 }
5634
Richard Smithac974a32013-06-30 09:48:50 +00005635 // Use the first declaration's location to ensure we point at something which
5636 // is lexically inside an extern "C" linkage-spec.
5637 assert(Prev && "should have found a previous declaration to diagnose");
5638 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005639 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005640 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005641 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005642
5643 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5644 << IsGlobal << ND;
5645 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5646 << IsGlobal;
5647 return false;
5648}
5649
5650/// Apply special rules for handling extern "C" declarations. Returns \c true
5651/// if we have found that this is a redeclaration of some prior entity.
5652///
5653/// Per C++ [dcl.link]p6:
5654/// Two declarations [for a function or variable] with C language linkage
5655/// with the same name that appear in different scopes refer to the same
5656/// [entity]. An entity with C language linkage shall not be declared with
5657/// the same name as an entity in global scope.
5658template<typename T>
5659static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5660 LookupResult &Previous) {
5661 if (!S.getLangOpts().CPlusPlus) {
5662 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005663 // variable declared in function scope. We don't need this in C++, because
5664 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005665 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5666 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5667 Previous.clear();
5668 Previous.addDecl(Prev);
5669 return true;
5670 }
5671 }
5672 return false;
5673 }
5674
5675 // A declaration in the translation unit can conflict with an extern "C"
5676 // declaration.
5677 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5678 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5679
5680 // An extern "C" declaration can conflict with a declaration in the
5681 // translation unit or can be a redeclaration of an extern "C" declaration
5682 // in another scope.
5683 if (isIncompleteDeclExternC(S,ND))
5684 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5685
5686 // Neither global nor extern "C": nothing to do.
5687 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005688}
5689
Richard Smith27d807c2013-04-30 13:56:41 +00005690void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005691 // If the decl is already known invalid, don't check it.
5692 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005693 return;
Mike Stump11289f42009-09-09 15:08:12 +00005694
Abramo Bagnara341ab732012-11-08 14:44:42 +00005695 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5696 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005697
Richard Smith27d807c2013-04-30 13:56:41 +00005698 // Defer checking an 'auto' type until its initializer is attached.
5699 if (T->isUndeducedType())
5700 return;
5701
John McCall8b07ec22010-05-15 11:32:37 +00005702 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005703 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5704 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005705 T = Context.getObjCObjectPointerType(T);
5706 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005707 }
Mike Stump11289f42009-09-09 15:08:12 +00005708
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005709 // Emit an error if an address space was applied to decl with local storage.
5710 // This includes arrays of objects with address space qualifiers, but not
5711 // automatic variables that point to other address spaces.
5712 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005713 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005714 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005715 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005716 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005717 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005718
Tanya Lattner713eef42013-04-05 20:14:50 +00005719 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5720 // __constant address space.
5721 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5722 && T.getAddressSpace() != LangAS::opencl_constant
5723 && !T->isSamplerT()){
5724 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5725 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005726 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005727 }
5728
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005729 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5730 // scope.
5731 if ((getLangOpts().OpenCLVersion >= 120)
5732 && NewVD->isStaticLocal()) {
5733 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5734 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005735 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005736 }
5737
Mike Stumpca5ae662009-04-14 00:57:29 +00005738 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005739 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005740 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005741 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005742 else {
5743 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005744 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005745 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005746 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005747
Chris Lattner9fecd742009-04-19 05:21:20 +00005748 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005749 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005750 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005751 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005752
Chris Lattner9fecd742009-04-19 05:21:20 +00005753 if ((isVM && NewVD->hasLinkage()) ||
5754 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005755 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005756 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005757 TypeSourceInfo *FixedTInfo =
5758 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5759 SizeIsNegative, Oversized);
5760 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005761 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005762 // FIXME: This won't give the correct result for
5763 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005764 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005765
Anders Carlsson6c885802009-02-28 21:56:50 +00005766 if (NewVD->isFileVarDecl())
5767 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005768 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005769 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005770 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005771 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005772 else
5773 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005774 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005775 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005776 return;
Mike Stump11289f42009-09-09 15:08:12 +00005777 }
5778
Abramo Bagnara341ab732012-11-08 14:44:42 +00005779 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005780 if (NewVD->isFileVarDecl())
5781 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5782 else
5783 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005784 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005785 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005786 }
Mike Stump11289f42009-09-09 15:08:12 +00005787
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005788 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005789 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005790 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005791 }
5792
David Majnemer0ffa3312013-05-29 00:56:45 +00005793 if (T->isVoidType()) {
5794 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5795 // of objects and functions.
5796 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5797 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5798 << T;
5799 NewVD->setInvalidDecl();
5800 return;
5801 }
Richard Smith27d807c2013-04-30 13:56:41 +00005802 }
5803
5804 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5805 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5806 NewVD->setInvalidDecl();
5807 return;
5808 }
5809
5810 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5811 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5812 NewVD->setInvalidDecl();
5813 return;
5814 }
5815
5816 if (NewVD->isConstexpr() && !T->isDependentType() &&
5817 RequireLiteralType(NewVD->getLocation(), T,
5818 diag::err_constexpr_var_non_literal)) {
5819 // Can't perform this check until the type is deduced.
5820 NewVD->setInvalidDecl();
5821 return;
5822 }
5823}
5824
5825/// \brief Perform semantic checking on a newly-created variable
5826/// declaration.
5827///
5828/// This routine performs all of the type-checking required for a
5829/// variable declaration once it has been built. It is used both to
5830/// check variables after they have been parsed and their declarators
5831/// have been translated into a declaration, and to check variables
5832/// that have been instantiated from a template.
5833///
5834/// Sets NewVD->isInvalidDecl() if an error was encountered.
5835///
5836/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005837bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005838 CheckVariableDeclarationType(NewVD);
5839
5840 // If the decl is already known invalid, don't check it.
5841 if (NewVD->isInvalidDecl())
5842 return false;
5843
John McCallb65e8fe2013-04-01 18:34:28 +00005844 // If we did not find anything by this name, look for a non-visible
5845 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005846 if (Previous.empty() &&
5847 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005848 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005849
Douglas Gregor3552dab2013-01-09 00:47:56 +00005850 // Filter out any non-conflicting previous declarations.
5851 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5852
John McCall1f82f242009-11-18 22:49:29 +00005853 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005854 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005855 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005856 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005857 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005858}
5859
Douglas Gregor36d1b142009-10-06 17:59:45 +00005860/// \brief Data used with FindOverriddenMethod
5861struct FindOverriddenMethodData {
5862 Sema *S;
5863 CXXMethodDecl *Method;
5864};
5865
5866/// \brief Member lookup function that determines whether a given C++
5867/// method overrides a method in a base class, to be used with
5868/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005869static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005870 CXXBasePath &Path,
5871 void *UserData) {
5872 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005873
Douglas Gregor36d1b142009-10-06 17:59:45 +00005874 FindOverriddenMethodData *Data
5875 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005876
5877 DeclarationName Name = Data->Method->getDeclName();
5878
5879 // FIXME: Do we care about other names here too?
5880 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005881 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005882 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5883 CanQualType CT = Data->S->Context.getCanonicalType(T);
5884
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005885 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005886 }
5887
5888 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005889 !Path.Decls.empty();
5890 Path.Decls = Path.Decls.slice(1)) {
5891 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5893 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005894 return true;
5895 }
5896 }
5897
5898 return false;
5899}
5900
David Blaikie7e414262012-10-17 00:47:58 +00005901namespace {
5902 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5903}
5904/// \brief Report an error regarding overriding, along with any relevant
5905/// overriden methods.
5906///
5907/// \param DiagID the primary error to report.
5908/// \param MD the overriding method.
5909/// \param OEK which overrides to include as notes.
5910static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5911 OverrideErrorKind OEK = OEK_All) {
5912 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5913 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5914 E = MD->end_overridden_methods();
5915 I != E; ++I) {
5916 // This check (& the OEK parameter) could be replaced by a predicate, but
5917 // without lambdas that would be overkill. This is still nicer than writing
5918 // out the diag loop 3 times.
5919 if ((OEK == OEK_All) ||
5920 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5921 (OEK == OEK_Deleted && (*I)->isDeleted()))
5922 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5923 }
5924}
5925
Sebastian Redld5b24532009-11-18 21:51:29 +00005926/// AddOverriddenMethods - See if a method overrides any in the base classes,
5927/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005928bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005929 // Look for virtual methods in base classes that this method might override.
5930 CXXBasePaths Paths;
5931 FindOverriddenMethodData Data;
5932 Data.Method = MD;
5933 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005934 bool hasDeletedOverridenMethods = false;
5935 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005936 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005937 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5938 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5939 E = Paths.found_decls_end(); I != E; ++I) {
5940 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005941 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005942 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005943 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005944 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005945 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005946 hasDeletedOverridenMethods |= OldMD->isDeleted();
5947 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005948 AddedAny = true;
5949 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005950 }
5951 }
5952 }
David Blaikie7e414262012-10-17 00:47:58 +00005953
5954 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5955 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5956 }
5957 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5958 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5959 }
5960
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005961 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005962}
5963
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005964namespace {
5965 // Struct for holding all of the extra arguments needed by
5966 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5967 struct ActOnFDArgs {
5968 Scope *S;
5969 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005970 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005971 bool AddToScope;
5972 };
5973}
5974
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005975namespace {
5976
5977// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005978// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005979class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5980 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005981 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5982 CXXRecordDecl *Parent)
5983 : Context(Context), OriginalFD(TypoFD),
5984 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005985
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005986 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005987 if (candidate.getEditDistance() == 0)
5988 return false;
5989
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005990 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005991 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5992 CDeclEnd = candidate.end();
5993 CDecl != CDeclEnd; ++CDecl) {
5994 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5995
5996 if (FD && !FD->hasBody() &&
5997 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5998 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5999 CXXRecordDecl *Parent = MD->getParent();
6000 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6001 return true;
6002 } else if (!ExpectedParent) {
6003 return true;
6004 }
6005 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006006 }
6007
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006008 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006009 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006010
6011 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006012 ASTContext &Context;
6013 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006014 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006015};
6016
6017}
6018
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006019/// \brief Generate diagnostics for an invalid function redeclaration.
6020///
6021/// This routine handles generating the diagnostic messages for an invalid
6022/// function redeclaration, including finding possible similar declarations
6023/// or performing typo correction if there are no previous declarations with
6024/// the same name.
6025///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006026/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006027/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006028static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006029 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006030 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006031 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006032 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006033 SmallVector<unsigned, 1> MismatchedParams;
6034 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006035 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006036 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006037 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6038 : diag::err_member_decl_does_not_match;
6039 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6040 IsLocalFriend ? Sema::LookupLocalFriendName
6041 : Sema::LookupOrdinaryName,
6042 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006043
6044 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006045 if (IsLocalFriend)
6046 SemaRef.LookupName(Prev, S);
6047 else
6048 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006049 assert(!Prev.isAmbiguous() &&
6050 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006051 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006052 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6053 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006054 if (!Prev.empty()) {
6055 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6056 Func != FuncEnd; ++Func) {
6057 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006058 if (FD &&
6059 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006060 // Add 1 to the index so that 0 can mean the mismatch didn't
6061 // involve a parameter
6062 unsigned ParamNum =
6063 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6064 NearMatches.push_back(std::make_pair(FD, ParamNum));
6065 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006066 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006067 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006068 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006069 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6070 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6071 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006072 // Set up everything for the call to ActOnFunctionDeclarator
6073 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6074 ExtraArgs.D.getIdentifierLoc());
6075 Previous.clear();
6076 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006077 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6078 CDeclEnd = Correction.end();
6079 CDecl != CDeclEnd; ++CDecl) {
6080 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006081 if (FD && !FD->hasBody() &&
6082 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006083 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006084 }
6085 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006086 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006087
6088 NamedDecl *Result;
6089 // Retry building the function declaration with the new previous
6090 // declarations, and with errors suppressed.
6091 {
6092 // Trap errors.
6093 Sema::SFINAETrap Trap(SemaRef);
6094
6095 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6096 // pieces need to verify the typo-corrected C++ declaration and hopefully
6097 // eliminate the need for the parameter pack ExtraArgs.
6098 Result = SemaRef.ActOnFunctionDeclarator(
6099 ExtraArgs.S, ExtraArgs.D,
6100 Correction.getCorrectionDecl()->getDeclContext(),
6101 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6102 ExtraArgs.AddToScope);
6103
6104 if (Trap.hasErrorOccurred())
6105 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006106 }
Richard Smithf9b15102013-08-17 00:46:16 +00006107
6108 if (Result) {
6109 // Determine which correction we picked.
6110 Decl *Canonical = Result->getCanonicalDecl();
6111 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6112 I != E; ++I)
6113 if ((*I)->getCanonicalDecl() == Canonical)
6114 Correction.setCorrectionDecl(*I);
6115
6116 SemaRef.diagnoseTypo(
6117 Correction,
6118 SemaRef.PDiag(IsLocalFriend
6119 ? diag::err_no_matching_local_friend_suggest
6120 : diag::err_member_decl_does_not_match_suggest)
6121 << Name << NewDC << IsDefinition);
6122 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006123 }
Richard Smithf9b15102013-08-17 00:46:16 +00006124
6125 // Pretend the typo correction never occurred
6126 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6127 ExtraArgs.D.getIdentifierLoc());
6128 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6129 Previous.clear();
6130 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006131 }
6132
Richard Smithf9b15102013-08-17 00:46:16 +00006133 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6134 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006135
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006136 bool NewFDisConst = false;
6137 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006138 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006139
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006140 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006141 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6142 NearMatch != NearMatchEnd; ++NearMatch) {
6143 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006144 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6145 bool FDisConst = MD && MD->isConst();
6146 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006147
Richard Smith541b38b2013-09-20 01:15:31 +00006148 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006149 if (unsigned Idx = NearMatch->second) {
6150 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006151 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6152 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006153 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6154 : diag::note_local_decl_close_param_match)
6155 << Idx << FDParam->getType()
6156 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006157 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006158 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006159 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006160 } else
Richard Smith114394f2013-08-09 04:35:01 +00006161 SemaRef.Diag(FD->getLocation(),
6162 IsMember ? diag::note_member_def_close_match
6163 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006164 }
Richard Smithf9b15102013-08-17 00:46:16 +00006165 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006166}
6167
David Blaikie30d15442011-10-19 22:56:21 +00006168static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6169 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006170 switch (D.getDeclSpec().getStorageClassSpec()) {
6171 default: llvm_unreachable("Unknown storage class!");
6172 case DeclSpec::SCS_auto:
6173 case DeclSpec::SCS_register:
6174 case DeclSpec::SCS_mutable:
6175 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6176 diag::err_typecheck_sclass_func);
6177 D.setInvalidType();
6178 break;
6179 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006180 case DeclSpec::SCS_extern:
6181 if (D.getDeclSpec().isExternInLinkageSpec())
6182 return SC_None;
6183 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006184 case DeclSpec::SCS_static: {
6185 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6186 // C99 6.7.1p5:
6187 // The declaration of an identifier for a function that has
6188 // block scope shall have no explicit storage-class specifier
6189 // other than extern
6190 // See also (C++ [dcl.stc]p4).
6191 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6192 diag::err_static_block_func);
6193 break;
6194 } else
6195 return SC_Static;
6196 }
6197 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6198 }
6199
6200 // No explicit storage class has already been returned
6201 return SC_None;
6202}
6203
6204static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6205 DeclContext *DC, QualType &R,
6206 TypeSourceInfo *TInfo,
6207 FunctionDecl::StorageClass SC,
6208 bool &IsVirtualOkay) {
6209 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6210 DeclarationName Name = NameInfo.getName();
6211
6212 FunctionDecl *NewFD = 0;
6213 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006214
David Blaikiebbafb8a2012-03-11 07:00:24 +00006215 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006216 // Determine whether the function was written with a
6217 // prototype. This true when:
6218 // - there is a prototype in the declarator, or
6219 // - the type R of the function is some kind of typedef or other reference
6220 // to a type name (which eventually refers to a function type).
6221 bool HasPrototype =
6222 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6223 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6224
David Blaikie30d15442011-10-19 22:56:21 +00006225 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006226 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006227 TInfo, SC, isInline,
6228 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006229 if (D.isInvalidType())
6230 NewFD->setInvalidDecl();
6231
6232 // Set the lexical context.
6233 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6234
6235 return NewFD;
6236 }
6237
6238 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6239 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6240
6241 // Check that the return type is not an abstract class type.
6242 // For record types, this is done by the AbstractClassUsageDiagnoser once
6243 // the class has been completely parsed.
6244 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006245 SemaRef.RequireNonAbstractType(
6246 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6247 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006248 D.setInvalidType();
6249
6250 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6251 // This is a C++ constructor declaration.
6252 assert(DC->isRecord() &&
6253 "Constructors can only be declared in a member context");
6254
6255 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6256 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006257 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006258 R, TInfo, isExplicit, isInline,
6259 /*isImplicitlyDeclared=*/false,
6260 isConstexpr);
6261
6262 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6263 // This is a C++ destructor declaration.
6264 if (DC->isRecord()) {
6265 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6266 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6267 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6268 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006269 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006270 NameInfo, R, TInfo, isInline,
6271 /*isImplicitlyDeclared=*/false);
6272
6273 // If the class is complete, then we now create the implicit exception
6274 // specification. If the class is incomplete or dependent, we can't do
6275 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006276 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006277 Record->getDefinition() && !Record->isBeingDefined() &&
6278 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6279 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6280 }
6281
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006282 // The Microsoft ABI requires that we perform the destructor body
6283 // checks (i.e. operator delete() lookup) at every declaration, as
6284 // any translation unit may need to emit a deleting destructor.
6285 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6286 !Record->isDependentType() && Record->getDefinition() &&
Hans Wennborge955e392013-12-17 17:49:22 +00006287 !Record->isBeingDefined() && !NewDD->isDeleted()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006288 SemaRef.CheckDestructor(NewDD);
6289 }
6290
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006291 IsVirtualOkay = true;
6292 return NewDD;
6293
6294 } else {
6295 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6296 D.setInvalidType();
6297
6298 // Create a FunctionDecl to satisfy the function definition parsing
6299 // code path.
6300 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006301 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006302 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006303 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006304 /*hasPrototype=*/true, isConstexpr);
6305 }
6306
6307 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6308 if (!DC->isRecord()) {
6309 SemaRef.Diag(D.getIdentifierLoc(),
6310 diag::err_conv_function_not_member);
6311 return 0;
6312 }
6313
6314 SemaRef.CheckConversionDeclarator(D, R, SC);
6315 IsVirtualOkay = true;
6316 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006317 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006318 R, TInfo, isInline, isExplicit,
6319 isConstexpr, SourceLocation());
6320
6321 } else if (DC->isRecord()) {
6322 // If the name of the function is the same as the name of the record,
6323 // then this must be an invalid constructor that has a return type.
6324 // (The parser checks for a return type and makes the declarator a
6325 // constructor if it has no return type).
6326 if (Name.getAsIdentifierInfo() &&
6327 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6328 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6329 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6330 << SourceRange(D.getIdentifierLoc());
6331 return 0;
6332 }
6333
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006334 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006335 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6336 cast<CXXRecordDecl>(DC),
6337 D.getLocStart(), NameInfo, R,
6338 TInfo, SC, isInline,
6339 isConstexpr, SourceLocation());
6340 IsVirtualOkay = !Ret->isStatic();
6341 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006342 } else {
6343 // Determine whether the function was written with a
6344 // prototype. This true when:
6345 // - we're in C++ (where every function has a prototype),
6346 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006347 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006348 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006349 true/*HasPrototype*/, isConstexpr);
6350 }
6351}
6352
Eli Friedman8f5e9832012-09-20 01:40:23 +00006353void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6354 // In C++, the empty parameter-type-list must be spelled "void"; a
6355 // typedef of void is not permitted.
6356 if (getLangOpts().CPlusPlus &&
6357 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6358 bool IsTypeAlias = false;
6359 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6360 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6361 else if (const TemplateSpecializationType *TST =
6362 Param->getType()->getAs<TemplateSpecializationType>())
6363 IsTypeAlias = TST->isTypeAlias();
6364 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6365 << IsTypeAlias;
6366 }
6367}
6368
Matt Arsenaultefb38192013-07-23 01:23:36 +00006369enum OpenCLParamType {
6370 ValidKernelParam,
6371 PtrPtrKernelParam,
6372 PtrKernelParam,
6373 InvalidKernelParam,
6374 RecordKernelParam
6375};
6376
6377static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6378 if (PT->isPointerType()) {
6379 QualType PointeeType = PT->getPointeeType();
6380 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6381 }
6382
6383 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6384 // be used as builtin types.
6385
6386 if (PT->isImageType())
6387 return PtrKernelParam;
6388
6389 if (PT->isBooleanType())
6390 return InvalidKernelParam;
6391
6392 if (PT->isEventT())
6393 return InvalidKernelParam;
6394
6395 if (PT->isHalfType())
6396 return InvalidKernelParam;
6397
6398 if (PT->isRecordType())
6399 return RecordKernelParam;
6400
6401 return ValidKernelParam;
6402}
6403
6404static void checkIsValidOpenCLKernelParameter(
6405 Sema &S,
6406 Declarator &D,
6407 ParmVarDecl *Param,
6408 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6409 QualType PT = Param->getType();
6410
6411 // Cache the valid types we encounter to avoid rechecking structs that are
6412 // used again
6413 if (ValidTypes.count(PT.getTypePtr()))
6414 return;
6415
6416 switch (getOpenCLKernelParameterType(PT)) {
6417 case PtrPtrKernelParam:
6418 // OpenCL v1.2 s6.9.a:
6419 // A kernel function argument cannot be declared as a
6420 // pointer to a pointer type.
6421 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6422 D.setInvalidType();
6423 return;
6424
6425 // OpenCL v1.2 s6.9.k:
6426 // Arguments to kernel functions in a program cannot be declared with the
6427 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6428 // uintptr_t or a struct and/or union that contain fields declared to be
6429 // one of these built-in scalar types.
6430
6431 case InvalidKernelParam:
6432 // OpenCL v1.2 s6.8 n:
6433 // A kernel function argument cannot be declared
6434 // of event_t type.
6435 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6436 D.setInvalidType();
6437 return;
6438
6439 case PtrKernelParam:
6440 case ValidKernelParam:
6441 ValidTypes.insert(PT.getTypePtr());
6442 return;
6443
6444 case RecordKernelParam:
6445 break;
6446 }
6447
6448 // Track nested structs we will inspect
6449 SmallVector<const Decl *, 4> VisitStack;
6450
6451 // Track where we are in the nested structs. Items will migrate from
6452 // VisitStack to HistoryStack as we do the DFS for bad field.
6453 SmallVector<const FieldDecl *, 4> HistoryStack;
6454 HistoryStack.push_back((const FieldDecl *) 0);
6455
6456 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6457 VisitStack.push_back(PD);
6458
6459 assert(VisitStack.back() && "First decl null?");
6460
6461 do {
6462 const Decl *Next = VisitStack.pop_back_val();
6463 if (!Next) {
6464 assert(!HistoryStack.empty());
6465 // Found a marker, we have gone up a level
6466 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6467 ValidTypes.insert(Hist->getType().getTypePtr());
6468
6469 continue;
6470 }
6471
6472 // Adds everything except the original parameter declaration (which is not a
6473 // field itself) to the history stack.
6474 const RecordDecl *RD;
6475 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6476 HistoryStack.push_back(Field);
6477 RD = Field->getType()->castAs<RecordType>()->getDecl();
6478 } else {
6479 RD = cast<RecordDecl>(Next);
6480 }
6481
6482 // Add a null marker so we know when we've gone back up a level
6483 VisitStack.push_back((const Decl *) 0);
6484
6485 for (RecordDecl::field_iterator I = RD->field_begin(),
6486 E = RD->field_end(); I != E; ++I) {
6487 const FieldDecl *FD = *I;
6488 QualType QT = FD->getType();
6489
6490 if (ValidTypes.count(QT.getTypePtr()))
6491 continue;
6492
6493 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6494 if (ParamType == ValidKernelParam)
6495 continue;
6496
6497 if (ParamType == RecordKernelParam) {
6498 VisitStack.push_back(FD);
6499 continue;
6500 }
6501
6502 // OpenCL v1.2 s6.9.p:
6503 // Arguments to kernel functions that are declared to be a struct or union
6504 // do not allow OpenCL objects to be passed as elements of the struct or
6505 // union.
6506 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6507 S.Diag(Param->getLocation(),
6508 diag::err_record_with_pointers_kernel_param)
6509 << PT->isUnionType()
6510 << PT;
6511 } else {
6512 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6513 }
6514
6515 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6516 << PD->getDeclName();
6517
6518 // We have an error, now let's go back up through history and show where
6519 // the offending field came from
6520 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6521 E = HistoryStack.end(); I != E; ++I) {
6522 const FieldDecl *OuterField = *I;
6523 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6524 << OuterField->getType();
6525 }
6526
6527 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6528 << QT->isPointerType()
6529 << QT;
6530 D.setInvalidType();
6531 return;
6532 }
6533 } while (!VisitStack.empty());
6534}
6535
Mike Stump11289f42009-09-09 15:08:12 +00006536NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006537Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006538 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006539 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006540 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006541 QualType R = TInfo->getType();
6542
Zhongxing Xubece5d62009-01-16 01:13:29 +00006543 assert(R.getTypePtr()->isFunctionType());
6544
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006545 // TODO: consider using NameInfo for diagnostic.
6546 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6547 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006548 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006549
Richard Smithb4a9e862013-04-12 22:46:28 +00006550 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6551 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6552 diag::err_invalid_thread)
6553 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006554
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006555 if (D.isFirstDeclarationOfMember())
6556 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006557
Douglas Gregor513e63c2010-12-10 19:28:19 +00006558 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006559 FunctionTemplateDecl *FunctionTemplate = 0;
6560 bool isExplicitSpecialization = false;
6561 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006562
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006563 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006564 bool HasExplicitTemplateArgs = false;
6565 TemplateArgumentListInfo TemplateArgs;
6566
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006567 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006568
Richard Smith541b38b2013-09-20 01:15:31 +00006569 DeclContext *OriginalDC = DC;
6570 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6571
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006572 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6573 isVirtualOkay);
6574 if (!NewFD) return 0;
6575
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006576 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6577 NewFD->setTopLevelDeclInObjCContainer();
6578
Richard Smith541b38b2013-09-20 01:15:31 +00006579 // Set the lexical context. If this is a function-scope declaration, or has a
6580 // C++ scope specifier, or is the object of a friend declaration, the lexical
6581 // context will be different from the semantic context.
6582 NewFD->setLexicalDeclContext(CurContext);
6583
6584 if (IsLocalExternDecl)
6585 NewFD->setLocalExternDecl();
6586
David Blaikiebbafb8a2012-03-11 07:00:24 +00006587 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006588 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006589 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6590 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006591 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006592 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006593 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006594 // C++ [class.friend]p5
6595 // A function can be defined in a friend declaration of a
6596 // class . . . . Such a function is implicitly inline.
6597 NewFD->setImplicitlyInline();
6598 }
6599
John McCalldb632ac2012-09-25 07:32:39 +00006600 // If this is a method defined in an __interface, and is not a constructor
6601 // or an overloaded operator, then set the pure flag (isVirtual will already
6602 // return true).
6603 if (const CXXRecordDecl *Parent =
6604 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6605 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006606 NewFD->setPure(true);
6607 }
6608
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006609 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006610 isExplicitSpecialization = false;
6611 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006612 if (D.isInvalidType())
6613 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006614
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006615 // Match up the template parameter lists with the scope specifier, then
6616 // determine whether we have a template or a template specialization.
6617 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006618 if (TemplateParameterList *TemplateParams =
6619 MatchTemplateParametersToScopeSpecifier(
6620 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6621 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6622 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006623 if (TemplateParams->size() > 0) {
6624 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006625
Abramo Bagnara60804e12011-03-18 15:16:37 +00006626 // Check that we can declare a template here.
6627 if (CheckTemplateDeclScope(S, TemplateParams))
6628 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006629
Abramo Bagnara60804e12011-03-18 15:16:37 +00006630 // A destructor cannot be a template.
6631 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6632 Diag(NewFD->getLocation(), diag::err_destructor_template);
6633 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006634 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006635
6636 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006637 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006638 // now that we know what the current instantiation is.
6639 if (DC->isDependentContext()) {
6640 ContextRAII SavedContext(*this, DC);
6641 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6642 Invalid = true;
6643 }
6644
John McCall1f0479e2010-03-24 08:27:58 +00006645
Abramo Bagnara60804e12011-03-18 15:16:37 +00006646 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6647 NewFD->getLocation(),
6648 Name, TemplateParams,
6649 NewFD);
6650 FunctionTemplate->setLexicalDeclContext(CurContext);
6651 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6652
6653 // For source fidelity, store the other template param lists.
6654 if (TemplateParamLists.size() > 1) {
6655 NewFD->setTemplateParameterListsInfo(Context,
6656 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006657 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006658 }
6659 } else {
6660 // This is a function template specialization.
6661 isFunctionTemplateSpecialization = true;
6662 // For source fidelity, store all the template param lists.
6663 NewFD->setTemplateParameterListsInfo(Context,
6664 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006665 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006666
6667 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6668 if (isFriend) {
6669 // We want to remove the "template<>", found here.
6670 SourceRange RemoveRange = TemplateParams->getSourceRange();
6671
6672 // If we remove the template<> and the name is not a
6673 // template-id, we're actually silently creating a problem:
6674 // the friend declaration will refer to an untemplated decl,
6675 // and clearly the user wants a template specialization. So
6676 // we need to insert '<>' after the name.
6677 SourceLocation InsertLoc;
6678 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6679 InsertLoc = D.getName().getSourceRange().getEnd();
6680 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6681 }
6682
6683 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6684 << Name << RemoveRange
6685 << FixItHint::CreateRemoval(RemoveRange)
6686 << FixItHint::CreateInsertion(InsertLoc, "<>");
6687 }
6688 }
6689 }
6690 else {
6691 // All template param lists were matched against the scope specifier:
6692 // this is NOT (an explicit specialization of) a template.
6693 if (TemplateParamLists.size() > 0)
6694 // For source fidelity, store all the template param lists.
6695 NewFD->setTemplateParameterListsInfo(Context,
6696 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006697 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006698 }
6699
6700 if (Invalid) {
6701 NewFD->setInvalidDecl();
6702 if (FunctionTemplate)
6703 FunctionTemplate->setInvalidDecl();
6704 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006705
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006706 // C++ [dcl.fct.spec]p5:
6707 // The virtual specifier shall only be used in declarations of
6708 // nonstatic class member functions that appear within a
6709 // member-specification of a class declaration; see 10.3.
6710 //
6711 if (isVirtual && !NewFD->isInvalidDecl()) {
6712 if (!isVirtualOkay) {
6713 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6714 diag::err_virtual_non_function);
6715 } else if (!CurContext->isRecord()) {
6716 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006717 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6718 diag::err_virtual_out_of_class)
6719 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6720 } else if (NewFD->getDescribedFunctionTemplate()) {
6721 // C++ [temp.mem]p3:
6722 // A member function template shall not be virtual.
6723 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6724 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006725 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6726 } else {
6727 // Okay: Add virtual to the method.
6728 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006729 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006730
6731 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006732 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006733 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006734 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006735
Richard Smithc1564702013-11-15 02:58:23 +00006736 if (getLangOpts().CPlusPlus1y &&
6737 (NewFD->isDependentContext() ||
6738 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006739 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006740 // If the function template is referenced directly (for instance, as a
6741 // member of the current instantiation), pretend it has a dependent type.
6742 // This is not really justified by the standard, but is the only sane
6743 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006744 // FIXME: For a friend function, we have not marked the function as being
6745 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006746 const FunctionProtoType *FPT =
6747 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006748 QualType Result =
6749 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006750 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006751 FPT->getExtProtoInfo()));
6752 }
6753
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006754 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006755 // The inline specifier shall not appear on a block scope function
6756 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006757 if (isInline && !NewFD->isInvalidDecl()) {
6758 if (CurContext->isFunctionOrMethod()) {
6759 // 'inline' is not allowed on block scope function declaration.
6760 Diag(D.getDeclSpec().getInlineSpecLoc(),
6761 diag::err_inline_declaration_block_scope) << Name
6762 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6763 }
6764 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006765
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006766 // C++ [dcl.fct.spec]p6:
6767 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006768 // constructor or conversion function within its class definition;
6769 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006770 if (isExplicit && !NewFD->isInvalidDecl()) {
6771 if (!CurContext->isRecord()) {
6772 // 'explicit' was specified outside of the class.
6773 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6774 diag::err_explicit_out_of_class)
6775 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6776 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6777 !isa<CXXConversionDecl>(NewFD)) {
6778 // 'explicit' was specified on a function that wasn't a constructor
6779 // or conversion function.
6780 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6781 diag::err_explicit_non_ctor_or_conv_function)
6782 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6783 }
6784 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006785
Richard Smitha77a0a62011-08-15 21:04:07 +00006786 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006787 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006788 // are implicitly inline.
6789 NewFD->setImplicitlyInline();
6790
Richard Smith574f4f62013-01-14 05:37:29 +00006791 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006792 // be either constructors or to return a literal type. Therefore,
6793 // destructors cannot be declared constexpr.
6794 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006795 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006796 }
6797
Douglas Gregor26701a42011-09-09 02:06:17 +00006798 // If __module_private__ was specified, mark the function accordingly.
6799 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006800 if (isFunctionTemplateSpecialization) {
6801 SourceLocation ModulePrivateLoc
6802 = D.getDeclSpec().getModulePrivateSpecLoc();
6803 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6804 << 0
6805 << FixItHint::CreateRemoval(ModulePrivateLoc);
6806 } else {
6807 NewFD->setModulePrivate();
6808 if (FunctionTemplate)
6809 FunctionTemplate->setModulePrivate();
6810 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006811 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006812
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006813 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006814 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006815 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006816 FunctionTemplate->setAccess(AS_public);
6817 }
Richard Smith64017682013-07-17 23:53:16 +00006818 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006819 NewFD->setAccess(AS_public);
6820 }
6821
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006822 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006823 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6824 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006825 switch (D.getFunctionDefinitionKind()) {
6826 case FDK_Declaration:
6827 case FDK_Definition:
6828 break;
6829
6830 case FDK_Defaulted:
6831 NewFD->setDefaulted();
6832 break;
6833
6834 case FDK_Deleted:
6835 NewFD->setDeletedAsWritten();
6836 break;
6837 }
6838
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006839 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6840 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006841 // C++ [class.mfct]p2:
6842 // A member function may be defined (8.4) in its class definition, in
6843 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006844 NewFD->setImplicitlyInline();
6845 }
6846
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006847 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6848 !CurContext->isRecord()) {
6849 // C++ [class.static]p1:
6850 // A data or function member of a class may be declared static
6851 // in a class definition, in which case it is a static member of
6852 // the class.
6853
6854 // Complain about the 'static' specifier if it's on an out-of-line
6855 // member function definition.
6856 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6857 diag::err_static_out_of_line)
6858 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6859 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006860
6861 // C++11 [except.spec]p15:
6862 // A deallocation function with no exception-specification is treated
6863 // as if it were specified with noexcept(true).
6864 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6865 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6866 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006867 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006868 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6869 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00006870 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006871 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006872 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006873 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006874
6875 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006876 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006877 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006878 isExplicitSpecialization ||
6879 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006880
Zhongxing Xubece5d62009-01-16 01:13:29 +00006881 // Handle GNU asm-label extension (encoded as an attribute).
6882 if (Expr *E = (Expr*) D.getAsmLabel()) {
6883 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006884 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006885 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006886 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006887 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6888 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6889 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6890 if (I != ExtnameUndeclaredIdentifiers.end()) {
6891 NewFD->addAttr(I->second);
6892 ExtnameUndeclaredIdentifiers.erase(I);
6893 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006894 }
6895
Chris Lattner9af40c12009-04-25 06:12:16 +00006896 // Copy the parameter declarations from the declarator D to the function
6897 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006898 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006899 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006900 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006901
Zhongxing Xubece5d62009-01-16 01:13:29 +00006902 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6903 // function that takes no arguments, not a function that takes a
6904 // single void argument.
6905 // We let through "const void" here because Sema::GetTypeForDeclarator
6906 // already checks for that case.
6907 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6908 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006909 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006910 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00006911 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00006912 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006913 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00006914 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006915 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6916 Param->setDeclContext(NewFD);
6917 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006918
6919 if (Param->isInvalidDecl())
6920 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006921 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006922 }
Mike Stump11289f42009-09-09 15:08:12 +00006923
John McCall9dd450b2009-09-21 23:43:11 +00006924 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006925 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006926 // following example, we'll need to synthesize (unnamed)
6927 // parameters for use in the declaration.
6928 //
6929 // @code
6930 // typedef void fn(int);
6931 // fn f;
6932 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006933
Chris Lattner47c0d002009-04-25 06:03:53 +00006934 // Synthesize a parameter for each argument type.
Alp Toker9cacbab2014-01-20 20:26:09 +00006935 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(),
6936 AE = FT->param_type_end();
6937 AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006938 ParmVarDecl *Param =
6939 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006940 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006941 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006942 }
Chris Lattner49303b22009-04-25 18:38:18 +00006943 } else {
6944 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6945 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006946 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006947
Chris Lattner9af40c12009-04-25 06:12:16 +00006948 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006949 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006950
James Molloy6f8780b2012-02-29 10:24:19 +00006951 // Find all anonymous symbols defined during the declaration of this function
6952 // and add to NewFD. This lets us track decls such 'enum Y' in:
6953 //
6954 // void f(enum Y {AA} x) {}
6955 //
6956 // which would otherwise incorrectly end up in the translation unit scope.
6957 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6958 DeclsInPrototypeScope.clear();
6959
Richard Smithdebc59d2013-01-30 05:45:05 +00006960 if (D.getDeclSpec().isNoreturnSpecified())
6961 NewFD->addAttr(
6962 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00006963 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00006964
Richard Smith84208dc2012-03-13 05:56:40 +00006965 // Functions returning a variably modified type violate C99 6.7.5.2p2
6966 // because all functions have linkage.
6967 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00006968 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00006969 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6970 NewFD->setInvalidDecl();
6971 }
6972
Rafael Espindolac67f2232012-05-10 02:50:16 +00006973 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00006974 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00006975
Alp Toker314cc812014-01-25 16:55:45 +00006976 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006977 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6978 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6979 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6980 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006981 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramer9940a5d2013-10-16 16:21:04 +00006982 // Attach the attribute to the new decl. Don't apply the attribute if it
6983 // returns an instance of the class (e.g. assignment operators).
6984 if (!MD || MD->getParent() != Ret) {
Aaron Ballman36a53502014-01-16 13:03:14 +00006985 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006986 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006987 }
6988
Joey Gouly16cb99d2014-01-06 11:26:18 +00006989 if (getLangOpts().OpenCL) {
6990 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
6991 // type declaration will generate a compilation error.
6992 unsigned AddressSpace = RetType.getAddressSpace();
6993 if (AddressSpace == LangAS::opencl_local ||
6994 AddressSpace == LangAS::opencl_global ||
6995 AddressSpace == LangAS::opencl_constant) {
6996 Diag(NewFD->getLocation(),
6997 diag::err_opencl_return_value_with_address_space);
6998 NewFD->setInvalidDecl();
6999 }
7000 }
7001
David Blaikiebbafb8a2012-03-11 07:00:24 +00007002 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007003 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007004 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007005 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7006 CheckMain(NewFD, D.getDeclSpec());
7007
David Majnemerc729b0b2013-09-16 22:44:20 +00007008 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7009 CheckMSVCRTEntryPoint(NewFD);
7010
David Majnemer027f9c42013-07-06 02:13:46 +00007011 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007012 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7013 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007014 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007015 // Make graceful recovery from an invalid redeclaration.
7016 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007017 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007018 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7019 "previous declaration set still overloaded");
7020 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007021 // C++11 [replacement.functions]p3:
7022 // The program's definitions shall not be specified as inline.
7023 //
7024 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7025 //
7026 // Suppress the diagnostic if the function is __attribute__((used)), since
7027 // that forces an external definition to be emitted.
7028 if (D.getDeclSpec().isInlineSpecified() &&
7029 NewFD->isReplaceableGlobalAllocationFunction() &&
7030 !NewFD->hasAttr<UsedAttr>())
7031 Diag(D.getDeclSpec().getInlineSpecLoc(),
7032 diag::ext_operator_new_delete_declared_inline)
7033 << NewFD->getDeclName();
7034
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007035 // If the declarator is a template-id, translate the parser's template
7036 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007037 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7038 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7039 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7040 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007041 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007042 TemplateId->NumArgs);
7043 translateTemplateArguments(TemplateArgsPtr,
7044 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007045
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007046 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007047
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007048 if (NewFD->isInvalidDecl()) {
7049 HasExplicitTemplateArgs = false;
7050 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007051 // Function template with explicit template arguments.
7052 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7053 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7054
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007055 HasExplicitTemplateArgs = false;
7056 } else if (!isFunctionTemplateSpecialization &&
7057 !D.getDeclSpec().isFriendSpecified()) {
7058 // We have encountered something that the user meant to be a
7059 // specialization (because it has explicitly-specified template
7060 // arguments) but that was not introduced with a "template<>" (or had
7061 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007062 // FIXME: Differentiate between attempts for explicit instantiations
7063 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007064 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7065 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7066 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007067 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007068 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007069 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007070 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007071 // "friend void foo<>(int);" is an implicit specialization decl.
7072 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007073 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007074 } else if (isFriend && isFunctionTemplateSpecialization) {
7075 // This combination is only possible in a recovery case; the user
7076 // wrote something like:
7077 // template <> friend void foo(int);
7078 // which we're recovering from as if the user had written:
7079 // friend void foo<>(int);
7080 // Go ahead and fake up a template id.
7081 HasExplicitTemplateArgs = true;
7082 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7083 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007084 }
John McCallf7cfb222010-10-13 05:45:15 +00007085
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007086 // If it's a friend (and only if it's a friend), it's possible
7087 // that either the specialized function type or the specialized
7088 // template is dependent, and therefore matching will fail. In
7089 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007090 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007091 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007092 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7093 TemplateSpecializationType::anyDependentTemplateArguments(
7094 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7095 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007096 assert(HasExplicitTemplateArgs &&
7097 "friend function specialization without template args");
7098 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7099 Previous))
7100 NewFD->setInvalidDecl();
7101 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007102 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007103 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007104 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007105 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007106 diag::ext_function_specialization_in_class :
7107 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007108 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007109 } else if (CheckFunctionTemplateSpecialization(NewFD,
7110 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7111 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007112 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007113
7114 // C++ [dcl.stc]p1:
7115 // A storage-class-specifier shall not be specified in an explicit
7116 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007117 FunctionTemplateSpecializationInfo *Info =
7118 NewFD->getTemplateSpecializationInfo();
7119 if (Info && SC != SC_None) {
7120 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007121 Diag(NewFD->getLocation(),
7122 diag::err_explicit_specialization_inconsistent_storage_class)
7123 << SC
7124 << FixItHint::CreateRemoval(
7125 D.getDeclSpec().getStorageClassSpecLoc());
7126
7127 else
7128 Diag(NewFD->getLocation(),
7129 diag::ext_explicit_specialization_storage_class)
7130 << FixItHint::CreateRemoval(
7131 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007132 }
7133
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007134 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7135 if (CheckMemberSpecialization(NewFD, Previous))
7136 NewFD->setInvalidDecl();
7137 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007138
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007139 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007140 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007141 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7142 CheckMain(NewFD, D.getDeclSpec());
7143
David Majnemerc729b0b2013-09-16 22:44:20 +00007144 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7145 CheckMSVCRTEntryPoint(NewFD);
7146
Nico Weber7607fce2013-12-21 00:49:51 +00007147 if (!NewFD->isInvalidDecl())
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
Alp Toker314cc812014-01-25 16:55:45 +00007283 QualType R = Context.getFunctionType(FT->getReturnType(), 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.
Alp Toker314cc812014-01-25 16:55:45 +00007322 if (!NewFD->getReturnType()->isVoidType()) {
Tanya Lattner0f864332013-01-30 19:48:52 +00007323 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")) {
Alp Toker314cc812014-01-25 16:55:45 +00007343 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007344 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) {
Alp Toker314cc812014-01-25 16:55:45 +00007385 assert(!NewFD->getReturnType()->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);
Aaron Ballman36a53502014-01-16 13:03:14 +00007442 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007443 }
John McCall1f82f242009-11-18 22:49:29 +00007444 }
Richard Smith574f4f62013-01-14 05:37:29 +00007445 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007446
Richard Smithac974a32013-06-30 09:48:50 +00007447 // Check for a previous extern "C" declaration with this name.
7448 if (!Redeclaration &&
7449 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7450 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7451 if (!Previous.empty()) {
7452 // This is an extern "C" declaration with the same name as a previous
7453 // declaration, and thus redeclares that entity...
7454 Redeclaration = true;
7455 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007456 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007457
7458 // ... except in the presence of __attribute__((overloadable)).
7459 if (OldDecl->hasAttr<OverloadableAttr>()) {
7460 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7461 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7462 << Redeclaration << NewFD;
7463 Diag(Previous.getFoundDecl()->getLocation(),
7464 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007465 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007466 }
7467 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7468 Redeclaration = false;
7469 OldDecl = 0;
7470 }
7471 }
7472 }
7473 }
7474
Richard Smith574f4f62013-01-14 05:37:29 +00007475 // C++11 [dcl.constexpr]p8:
7476 // A constexpr specifier for a non-static member function that is not
7477 // a constructor declares that member function to be const.
7478 //
7479 // This needs to be delayed until we know whether this is an out-of-line
7480 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007481 //
7482 // This rule is not present in C++1y, so we produce a backwards
7483 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007484 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007485 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7486 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007487 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Alp Tokera2794f92014-01-22 07:29:52 +00007488 CXXMethodDecl *OldMD = 0;
7489 if (OldDecl)
7490 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007491 if (!OldMD || !OldMD->isStatic()) {
7492 const FunctionProtoType *FPT =
7493 MD->getType()->castAs<FunctionProtoType>();
7494 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7495 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007496 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007497 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007498
7499 // Warn that we did this, if we're not performing template instantiation.
7500 // In that case, we'll have warned already when the template was defined.
7501 if (ActiveTemplateInstantiations.empty()) {
7502 SourceLocation AddConstLoc;
7503 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7504 .IgnoreParens().getAs<FunctionTypeLoc>())
7505 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7506
7507 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7508 << FixItHint::CreateInsertion(AddConstLoc, " const");
7509 }
Richard Smith574f4f62013-01-14 05:37:29 +00007510 }
7511 }
7512
7513 if (Redeclaration) {
7514 // NewFD and OldDecl represent declarations that need to be
7515 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007516 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007517 NewFD->setInvalidDecl();
7518 return Redeclaration;
7519 }
7520
7521 Previous.clear();
7522 Previous.addDecl(OldDecl);
7523
7524 if (FunctionTemplateDecl *OldTemplateDecl
7525 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7526 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7527 FunctionTemplateDecl *NewTemplateDecl
7528 = NewFD->getDescribedFunctionTemplate();
7529 assert(NewTemplateDecl && "Template/non-template mismatch");
7530 if (CXXMethodDecl *Method
7531 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7532 Method->setAccess(OldTemplateDecl->getAccess());
7533 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007534 }
Richard Smith574f4f62013-01-14 05:37:29 +00007535
7536 // If this is an explicit specialization of a member that is a function
7537 // template, mark it as a member specialization.
7538 if (IsExplicitSpecialization &&
7539 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7540 NewTemplateDecl->setMemberSpecialization();
7541 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007542 }
Richard Smith574f4f62013-01-14 05:37:29 +00007543
7544 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007545 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007546 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007547
7548 if (isa<CXXMethodDecl>(NewFD)) {
7549 // A valid redeclaration of a C++ method must be out-of-line,
7550 // but (unfortunately) it's not necessarily a definition
7551 // because of templates, which means that the previous
7552 // declaration is not necessarily from the class definition.
7553
7554 // For just setting the access, that doesn't matter.
7555 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7556 NewFD->setAccess(oldMethod->getAccess());
7557
7558 // Update the key-function state if necessary for this ABI.
7559 if (NewFD->isInlined() &&
7560 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7561 // setNonKeyFunction needs to work with the original
7562 // declaration from the class definition, and isVirtual() is
7563 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007564 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007565 if (oldMethod->isVirtual()) {
7566 Context.setNonKeyFunction(oldMethod);
7567 }
7568 }
7569 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007570 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007571 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007572
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007573 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007574 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007575 // C++-specific checks.
7576 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7577 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007578 } else if (CXXDestructorDecl *Destructor =
7579 dyn_cast<CXXDestructorDecl>(NewFD)) {
7580 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007581 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007582
Douglas Gregor7454c562010-07-02 20:37:36 +00007583 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007584 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007585 if (!ClassType->isDependentType()) {
7586 DeclarationName Name
7587 = Context.DeclarationNames.getCXXDestructorName(
7588 Context.getCanonicalType(ClassType));
7589 if (NewFD->getDeclName() != Name) {
7590 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007591 NewFD->setInvalidDecl();
7592 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007593 }
7594 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007595 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007596 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007597 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007598 }
7599
7600 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007601 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7602 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007603 !Method->getDescribedFunctionTemplate() &&
7604 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007605 if (AddOverriddenMethods(Method->getParent(), Method)) {
7606 // If the function was marked as "static", we have a problem.
7607 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007608 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007609 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007610 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007611 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007612
7613 if (Method->isStatic())
7614 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007615 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007616
7617 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7618 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007619 CheckOverloadedOperatorDeclaration(NewFD)) {
7620 NewFD->setInvalidDecl();
7621 return Redeclaration;
7622 }
Alexis Huntc88db062010-01-13 09:01:02 +00007623
7624 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7625 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007626 CheckLiteralOperatorDeclaration(NewFD)) {
7627 NewFD->setInvalidDecl();
7628 return Redeclaration;
7629 }
Alexis Huntc88db062010-01-13 09:01:02 +00007630
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007631 // In C++, check default arguments now that we have merged decls. Unless
7632 // the lexical context is the class, because in this case this is done
7633 // during delayed parsing anyway.
7634 if (!CurContext->isRecord())
7635 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007636
Douglas Gregor9246b682010-12-21 19:47:46 +00007637 // If this function declares a builtin function, check the type of this
7638 // declaration against the expected type for the builtin.
7639 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7640 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007641 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007642 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7643 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7644 // The type of this function differs from the type of the builtin,
7645 // so forget about the builtin entirely.
7646 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7647 }
7648 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007649
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007650 // If this function is declared as being extern "C", then check to see if
7651 // the function returns a UDT (class, struct, or union type) that is not C
7652 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007653 // But, issue any diagnostic on the first declaration only.
7654 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007655 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007656 if (R->isIncompleteType() && !R->isVoidType())
7657 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7658 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007659 else if (!R.isPODType(Context) && !R->isVoidType() &&
7660 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007661 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007662 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007663 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007664 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007665}
7666
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007667static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7668 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7669 if (!TSI)
7670 return SourceRange();
7671
7672 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007673 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007674 if (!FunctionTL)
7675 return SourceRange();
7676
Alp Toker42a16a62014-01-25 23:51:36 +00007677 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007678 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007679 return ResultTL.getSourceRange();
7680
7681 return SourceRange();
7682}
7683
David Blaikied937bf12011-09-08 06:33:04 +00007684void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007685 // C++11 [basic.start.main]p3:
7686 // A program that [...] declares main to be inline, static or
7687 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007688 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7689 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007690 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007691 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007692 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007693 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007694 ? diag::err_static_main : diag::warn_static_main)
7695 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7696 if (FD->isInlineSpecified())
7697 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7698 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007699 if (DS.isNoreturnSpecified()) {
7700 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7701 SourceRange NoreturnRange(NoreturnLoc,
7702 PP.getLocForEndOfToken(NoreturnLoc));
7703 Diag(NoreturnLoc, diag::ext_noreturn_main);
7704 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7705 << FixItHint::CreateRemoval(NoreturnRange);
7706 }
Richard Smith3f333f22012-02-04 06:10:17 +00007707 if (FD->isConstexpr()) {
7708 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7709 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7710 FD->setConstexpr(false);
7711 }
John McCall02dee0a2009-07-25 04:36:53 +00007712
Joey Goulya7310a82013-11-05 12:30:39 +00007713 if (getLangOpts().OpenCL) {
7714 Diag(FD->getLocation(), diag::err_opencl_no_main)
7715 << FD->hasAttr<OpenCLKernelAttr>();
7716 FD->setInvalidDecl();
7717 return;
7718 }
7719
John McCall02dee0a2009-07-25 04:36:53 +00007720 QualType T = FD->getType();
7721 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007722 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007723
John McCall5ed3caf2012-02-14 19:50:52 +00007724 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007725 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007726 // In C and C++, main magically returns 0 if you fall off the end;
7727 // set the flag which tells us that.
7728 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7729 FD->setHasImplicitReturnZero(true);
7730
7731 // In C with GNU extensions we allow main() to have non-integer return
7732 // type, but we should warn about the extension, and we disable the
7733 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007734 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007735 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7736
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007737 SourceRange ResultRange = getResultSourceRange(FD);
7738 if (ResultRange.isValid())
7739 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7740 << FixItHint::CreateReplacement(ResultRange, "int");
7741
John McCall5ed3caf2012-02-14 19:50:52 +00007742 // Otherwise, this is just a flat-out error.
7743 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007744 SourceRange ResultRange = getResultSourceRange(FD);
7745 if (ResultRange.isValid())
7746 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7747 << FixItHint::CreateReplacement(ResultRange, "int");
7748 else
7749 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7750
John McCall02dee0a2009-07-25 04:36:53 +00007751 FD->setInvalidDecl(true);
7752 }
7753
7754 // Treat protoless main() as nullary.
7755 if (isa<FunctionNoProtoType>(FT)) return;
7756
7757 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007758 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007759 assert(FD->getNumParams() == nparams);
7760
John McCall0e21fcc2009-12-24 09:58:38 +00007761 bool HasExtraParameters = (nparams > 3);
7762
7763 // Darwin passes an undocumented fourth argument of type char**. If
7764 // other platforms start sprouting these, the logic below will start
7765 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007766 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007767 HasExtraParameters = false;
7768
7769 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007770 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7771 FD->setInvalidDecl(true);
7772 nparams = 3;
7773 }
7774
7775 // FIXME: a lot of the following diagnostics would be improved
7776 // if we had some location information about types.
7777
7778 QualType CharPP =
7779 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007780 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007781
7782 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007783 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007784
7785 bool mismatch = true;
7786
7787 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7788 mismatch = false;
7789 else if (Expected[i] == CharPP) {
7790 // As an extension, the following forms are okay:
7791 // char const **
7792 // char const * const *
7793 // char * const *
7794
John McCall8ccfcb52009-09-24 19:53:00 +00007795 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007796 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007797 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7798 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007799 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7800 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007801 qs.removeConst();
7802 mismatch = !qs.empty();
7803 }
7804 }
7805
7806 if (mismatch) {
7807 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7808 // TODO: suggest replacing given type with expected type
7809 FD->setInvalidDecl(true);
7810 }
7811 }
7812
7813 if (nparams == 1 && !FD->isInvalidDecl()) {
7814 Diag(FD->getLocation(), diag::warn_main_one_arg);
7815 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007816
7817 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007818 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007819 FD->setInvalidDecl();
7820 }
7821}
7822
7823void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7824 QualType T = FD->getType();
7825 assert(T->isFunctionType() && "function decl is not of function type");
7826 const FunctionType *FT = T->castAs<FunctionType>();
7827
7828 // Set an implicit return of 'zero' if the function can return some integral,
7829 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007830 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7831 FT->getReturnType()->isAnyPointerType() ||
7832 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007833 // DllMain is exempt because a return value of zero means it failed.
7834 if (FD->getName() != "DllMain")
7835 FD->setHasImplicitReturnZero(true);
7836
7837 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007838 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007839 FD->setInvalidDecl();
7840 }
John McCalld9baf6a2009-07-24 03:03:21 +00007841}
7842
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007843bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007844 // FIXME: Need strict checking. In C89, we need to check for
7845 // any assignment, increment, decrement, function-calls, or
7846 // commas outside of a sizeof. In C99, it's the same list,
7847 // except that the aforementioned are allowed in unevaluated
7848 // expressions. Everything else falls under the
7849 // "may accept other forms of constant expressions" exception.
7850 // (We never end up here for C++, so the constant expression
7851 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007852 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007853 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007854 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7855 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007856 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007857}
7858
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007859namespace {
7860 // Visits an initialization expression to see if OrigDecl is evaluated in
7861 // its own initialization and throws a warning if it does.
7862 class SelfReferenceChecker
7863 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7864 Sema &S;
7865 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007866 bool isRecordType;
7867 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007868 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007869
7870 public:
7871 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7872
7873 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007874 S(S), OrigDecl(OrigDecl) {
7875 isPODType = false;
7876 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007877 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007878 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7879 isPODType = VD->getType().isPODType(S.Context);
7880 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007881 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007882 }
7883 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007884
Richard Trieu64c51ab2012-05-09 00:21:34 +00007885 // For most expressions, the cast is directly above the DeclRefExpr.
7886 // For conditional operators, the cast can be outside the conditional
7887 // operator if both expressions are DeclRefExpr's.
7888 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007889 if (isReferenceType)
7890 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007891 E = E->IgnoreParenImpCasts();
7892 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7893 HandleDeclRefExpr(DRE);
7894 return;
7895 }
7896
7897 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7898 HandleValue(CO->getTrueExpr());
7899 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007900 return;
7901 }
7902
7903 if (isa<MemberExpr>(E)) {
7904 Expr *Base = E->IgnoreParenImpCasts();
7905 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7906 // Check for static member variables and don't warn on them.
7907 if (!isa<FieldDecl>(ME->getMemberDecl()))
7908 return;
7909 Base = ME->getBase()->IgnoreParenImpCasts();
7910 }
7911 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7912 HandleDeclRefExpr(DRE);
7913 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007914 }
7915 }
7916
Richard Trieu32673472012-10-01 17:39:51 +00007917 // Reference types are handled here since all uses of references are
7918 // bad, not just r-value uses.
7919 void VisitDeclRefExpr(DeclRefExpr *E) {
7920 if (isReferenceType)
7921 HandleDeclRefExpr(E);
7922 }
7923
Richard Trieu64c51ab2012-05-09 00:21:34 +00007924 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007925 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007926 (isRecordType && E->getCastKind() == CK_NoOp))
7927 HandleValue(E->getSubExpr());
7928
7929 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007930 }
7931
Richard Trieua04ad1a2011-09-01 21:44:13 +00007932 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007933 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007934 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007935
Richard Trieu742c6ed2012-10-03 00:41:36 +00007936 // Warn when a non-static method call is followed by non-static member
7937 // field accesses, which is followed by a DeclRefExpr.
7938 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7939 bool Warn = (MD && !MD->isStatic());
7940 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7941 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7942 if (!isa<FieldDecl>(ME->getMemberDecl()))
7943 Warn = false;
7944 Base = ME->getBase()->IgnoreParenImpCasts();
7945 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007946
Richard Trieu742c6ed2012-10-03 00:41:36 +00007947 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7948 if (Warn)
7949 HandleDeclRefExpr(DRE);
7950 return;
7951 }
7952
7953 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7954 // Visit that expression.
7955 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007956 }
7957
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007958 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7959 if (E->getNumArgs() > 0)
7960 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7961 HandleDeclRefExpr(DRE);
7962
7963 Inherited::VisitCXXOperatorCallExpr(E);
7964 }
7965
Richard Trieua04ad1a2011-09-01 21:44:13 +00007966 void VisitUnaryOperator(UnaryOperator *E) {
7967 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007968 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7969 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7970 if (!isPODType)
7971 HandleValue(E->getSubExpr());
7972 return;
7973 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007974 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007975 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007976
7977 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7978
Richard Trieua04ad1a2011-09-01 21:44:13 +00007979 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007980 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007981 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007982 unsigned diag;
7983 if (isReferenceType) {
7984 diag = diag::warn_uninit_self_reference_in_reference_init;
7985 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7986 diag = diag::warn_static_self_reference_in_init;
7987 } else {
7988 diag = diag::warn_uninit_self_reference_in_init;
7989 }
7990
Richard Trieua04ad1a2011-09-01 21:44:13 +00007991 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007992 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007993 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007994 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007995 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007996 }
7997 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007998
Richard Trieu32673472012-10-01 17:39:51 +00007999 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8000 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8001 bool DirectInit) {
8002 // Parameters arguments are occassionially constructed with itself,
8003 // for instance, in recursive functions. Skip them.
8004 if (isa<ParmVarDecl>(OrigDecl))
8005 return;
8006
8007 E = E->IgnoreParens();
8008
8009 // Skip checking T a = a where T is not a record or reference type.
8010 // Doing so is a way to silence uninitialized warnings.
8011 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8012 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8013 if (ICE->getCastKind() == CK_LValueToRValue)
8014 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8015 if (DRE->getDecl() == OrigDecl)
8016 return;
8017
8018 SelfReferenceChecker(S, OrigDecl).Visit(E);
8019 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008020}
8021
Douglas Gregor5fb53972009-01-14 15:45:31 +00008022/// AddInitializerToDecl - Adds the initializer Init to the
8023/// declaration dcl. If DirectInit is true, this is C++ direct
8024/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008025void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8026 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008027 // If there is no declaration, there was an error parsing it. Just ignore
8028 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008029 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008030 return;
Mike Stump11289f42009-09-09 15:08:12 +00008031
Douglas Gregor0c880302009-03-11 23:00:04 +00008032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8033 // With declarators parsed the way they are, the parser cannot
8034 // distinguish between a normal initializer and a pure-specifier.
8035 // Thus this grotesque test.
8036 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008037 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008038 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8039 CheckPureMethod(Method, Init->getSourceRange());
8040 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008041 Diag(Method->getLocation(), diag::err_member_function_initialization)
8042 << Method->getDeclName() << Init->getSourceRange();
8043 Method->setInvalidDecl();
8044 }
8045 return;
8046 }
8047
Steve Naroff437b4d82007-09-12 20:13:48 +00008048 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8049 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008050 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8051 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008052 RealDecl->setInvalidDecl();
8053 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008054 }
Sebastian Redla9351792012-02-11 23:51:47 +00008055 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8056
Richard Smith0cc85782011-12-15 19:20:59 +00008057 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008058 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008059 Expr *DeduceInit = Init;
8060 // Initializer could be a C++ direct-initializer. Deduction only works if it
8061 // contains exactly one expression.
8062 if (CXXDirectInit) {
8063 if (CXXDirectInit->getNumExprs() == 0) {
8064 // It isn't possible to write this directly, but it is possible to
8065 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008066 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008067 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8068 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008069 << VDecl->getDeclName() << VDecl->getType()
8070 << VDecl->getSourceRange();
8071 RealDecl->setInvalidDecl();
8072 return;
8073 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008074 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008075 VDecl->isInitCapture()
8076 ? diag::err_init_capture_multiple_expressions
8077 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008078 << VDecl->getDeclName() << VDecl->getType()
8079 << VDecl->getSourceRange();
8080 RealDecl->setInvalidDecl();
8081 return;
8082 } else {
8083 DeduceInit = CXXDirectInit->getExpr(0);
8084 }
8085 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008086
8087 // Expressions default to 'id' when we're in a debugger.
8088 bool DefaultedToAuto = false;
8089 if (getLangOpts().DebuggerCastResultToId &&
8090 Init->getType() == Context.UnknownAnyTy) {
8091 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8092 if (Result.isInvalid()) {
8093 VDecl->setInvalidDecl();
8094 return;
8095 }
8096 Init = Result.take();
8097 DefaultedToAuto = true;
8098 }
Richard Smith061f1e22013-04-30 21:23:01 +00008099
8100 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008101 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008102 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008103 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008104 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008105 RealDecl->setInvalidDecl();
8106 return;
8107 }
Richard Smith061f1e22013-04-30 21:23:01 +00008108 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008109 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008110
John McCall31168b02011-06-15 23:02:42 +00008111 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008112 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008113 VDecl->setInvalidDecl();
8114
Jordan Rosed8d56692012-06-08 22:46:07 +00008115 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8116 // 'id' instead of a specific object type prevents most of our usual checks.
8117 // We only want to warn outside of template instantiations, though:
8118 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008119 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008120 DeducedType->isObjCIdType()) {
8121 SourceLocation Loc =
8122 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008123 Diag(Loc, diag::warn_auto_var_is_id)
8124 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8125 }
8126
Richard Smith30482bc2011-02-20 03:19:35 +00008127 // If this is a redeclaration, check that the type we just deduced matches
8128 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008129 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8130 // We never need to merge the type, because we cannot form an incomplete
8131 // array of auto, nor deduce such a type.
8132 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8133 }
Richard Smith27d807c2013-04-30 13:56:41 +00008134
8135 // Check the deduced type is valid for a variable declaration.
8136 CheckVariableDeclarationType(VDecl);
8137 if (VDecl->isInvalidDecl())
8138 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008139 }
Richard Smith0cc85782011-12-15 19:20:59 +00008140
8141 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8142 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8143 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8144 VDecl->setInvalidDecl();
8145 return;
8146 }
8147
Sebastian Redla9351792012-02-11 23:51:47 +00008148 if (!VDecl->getType()->isDependentType()) {
8149 // A definition must end up with a complete type, which means it must be
8150 // complete with the restriction that an array type might be completed by
8151 // the initializer; note that later code assumes this restriction.
8152 QualType BaseDeclType = VDecl->getType();
8153 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8154 BaseDeclType = Array->getElementType();
8155 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8156 diag::err_typecheck_decl_incomplete_type)) {
8157 RealDecl->setInvalidDecl();
8158 return;
8159 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008160
Sebastian Redla9351792012-02-11 23:51:47 +00008161 // The variable can not have an abstract class type.
8162 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8163 diag::err_abstract_type_in_decl,
8164 AbstractVariableType))
8165 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008166 }
8167
Sebastian Redl5ca79842010-02-01 20:16:42 +00008168 const VarDecl *Def;
8169 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008170 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008171 << VDecl->getDeclName();
8172 Diag(Def->getLocation(), diag::note_previous_definition);
8173 VDecl->setInvalidDecl();
8174 return;
8175 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008176
Douglas Gregorf0f83692010-08-24 05:27:49 +00008177 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008178 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008179 // C++ [class.static.data]p4
8180 // If a static data member is of const integral or const
8181 // enumeration type, its declaration in the class definition can
8182 // specify a constant-initializer which shall be an integral
8183 // constant expression (5.19). In that case, the member can appear
8184 // in integral constant expressions. The member shall still be
8185 // defined in a namespace scope if it is used in the program and the
8186 // namespace scope definition shall not contain an initializer.
8187 //
8188 // We already performed a redefinition check above, but for static
8189 // data members we also need to check whether there was an in-class
8190 // declaration with an initializer.
8191 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008192 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8193 << VDecl->getDeclName();
8194 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008195 return;
8196 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008197
Douglas Gregor71f39c92010-12-16 01:31:22 +00008198 if (VDecl->hasLocalStorage())
8199 getCurFunction()->setHasBranchProtectedScope();
8200
8201 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8202 VDecl->setInvalidDecl();
8203 return;
8204 }
8205 }
John McCalld4e1b762010-08-01 01:24:59 +00008206
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008207 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8208 // a kernel function cannot be initialized."
8209 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8210 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8211 VDecl->setInvalidDecl();
8212 return;
8213 }
8214
Steve Naroff61091402007-09-12 14:07:44 +00008215 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008216 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008217 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008218
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008219 // Expressions default to 'id' when we're in a debugger
8220 // and we are assigning it to a variable of Objective-C pointer type.
8221 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8222 Init->getType() == Context.UnknownAnyTy) {
8223 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8224 if (Result.isInvalid()) {
8225 VDecl->setInvalidDecl();
8226 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008227 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008228 Init = Result.take();
8229 }
Richard Smith0cc85782011-12-15 19:20:59 +00008230
8231 // Perform the initialization.
8232 if (!VDecl->isInvalidDecl()) {
8233 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8234 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008235 = DirectInit ?
8236 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8237 Init->getLocStart(),
8238 Init->getLocEnd())
8239 : InitializationKind::CreateDirectList(
8240 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008241 : InitializationKind::CreateCopy(VDecl->getLocation(),
8242 Init->getLocStart());
8243
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008244 MultiExprArg Args = Init;
8245 if (CXXDirectInit)
8246 Args = MultiExprArg(CXXDirectInit->getExprs(),
8247 CXXDirectInit->getNumExprs());
8248
8249 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008251 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008252 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008253 return;
Steve Naroff61091402007-09-12 14:07:44 +00008254 }
Richard Smith0cc85782011-12-15 19:20:59 +00008255
8256 Init = Result.takeAs<Expr>();
8257 }
8258
Richard Trieu32673472012-10-01 17:39:51 +00008259 // Check for self-references within variable initializers.
8260 // Variables declared within a function/method body (except for references)
8261 // are handled by a dataflow analysis.
8262 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8263 VDecl->getType()->isReferenceType()) {
8264 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8265 }
8266
Richard Smith0cc85782011-12-15 19:20:59 +00008267 // If the type changed, it means we had an incomplete type that was
8268 // completed by the initializer. For example:
8269 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008270 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008271 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008272 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008273
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008274 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008275 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8276
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008277 if (VDecl->hasAttr<BlocksAttr>())
8278 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008279
8280 // It is safe to assign a weak reference into a strong variable.
8281 // Although this code can still have problems:
8282 // id x = self.weakProp;
8283 // id y = self.weakProp;
8284 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8285 // paths through the function. This should be revisited if
8286 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008287 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008288 DiagnosticsEngine::Level Level =
8289 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8290 Init->getLocStart());
8291 if (Level != DiagnosticsEngine::Ignored)
8292 getCurFunction()->markSafeWeakUse(Init);
8293 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008294 }
8295
Richard Smith945f8d32013-01-14 22:39:08 +00008296 // The initialization is usually a full-expression.
8297 //
8298 // FIXME: If this is a braced initialization of an aggregate, it is not
8299 // an expression, and each individual field initializer is a separate
8300 // full-expression. For instance, in:
8301 //
8302 // struct Temp { ~Temp(); };
8303 // struct S { S(Temp); };
8304 // struct T { S a, b; } t = { Temp(), Temp() }
8305 //
8306 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008307 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8308 false,
8309 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008310 if (Result.isInvalid()) {
8311 VDecl->setInvalidDecl();
8312 return;
8313 }
8314 Init = Result.take();
8315
Richard Smith0cc85782011-12-15 19:20:59 +00008316 // Attach the initializer to the decl.
8317 VDecl->setInit(Init);
8318
8319 if (VDecl->isLocalVarDecl()) {
8320 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8321 // static storage duration shall be constant expressions or string literals.
8322 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008323 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8324 if (VDecl->getStorageClass() == SC_Static)
8325 CheckForConstantInitializer(Init, DclT);
8326 // C89 is stricter than C99 for non-static aggregate types.
8327 // C89 6.5.7p3: All the expressions [...] in an initializer list
8328 // for an object that has aggregate or union type shall be
8329 // constant expressions.
8330 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008331 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008332 !Init->isConstantInitializer(Context, false))
8333 Diag(Init->getExprLoc(),
8334 diag::ext_aggregate_init_not_constant)
8335 << Init->getSourceRange();
8336 }
Mike Stump11289f42009-09-09 15:08:12 +00008337 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008338 VDecl->getLexicalDeclContext()->isRecord()) {
8339 // This is an in-class initialization for a static data member, e.g.,
8340 //
8341 // struct S {
8342 // static const int value = 17;
8343 // };
8344
Douglas Gregor0c880302009-03-11 23:00:04 +00008345 // C++ [class.mem]p4:
8346 // A member-declarator can contain a constant-initializer only
8347 // if it declares a static member (9.4) of const integral or
8348 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008349 //
Richard Smith0cc85782011-12-15 19:20:59 +00008350 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008351 // If a non-volatile const static data member is of integral or
8352 // enumeration type, its declaration in the class definition can
8353 // specify a brace-or-equal-initializer in which every initalizer-clause
8354 // that is an assignment-expression is a constant expression. A static
8355 // data member of literal type can be declared in the class definition
8356 // with the constexpr specifier; if so, its declaration shall specify a
8357 // brace-or-equal-initializer in which every initializer-clause that is
8358 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008359
8360 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008361 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008362
Richard Smith2316cd82011-09-29 19:11:37 +00008363 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008364 // type. We separately check that every constexpr variable is of literal
8365 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008366 } else if (VDecl->isConstexpr()) {
8367
John McCalldb768922010-09-10 23:21:22 +00008368 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008369 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008370 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8371 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008372 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008373
8374 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008375 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008376 // Check whether the expression is a constant expression.
8377 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008378 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008379 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008380 // in-class initializer cannot be volatile.
8381 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8382 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008383 ; // Nothing to check.
8384 else if (Init->isIntegerConstantExpr(Context, &Loc))
8385 ; // Ok, it's an ICE!
8386 else if (Init->isEvaluatable(Context)) {
8387 // If we can constant fold the initializer through heroics, accept it,
8388 // but report this as a use of an extension for -pedantic.
8389 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8390 << Init->getSourceRange();
8391 } else {
8392 // Otherwise, this is some crazy unknown case. Report the issue at the
8393 // location provided by the isIntegerConstantExpr failed check.
8394 Diag(Loc, diag::err_in_class_initializer_non_constant)
8395 << Init->getSourceRange();
8396 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008397 }
8398
Richard Smith0cc85782011-12-15 19:20:59 +00008399 // We allow foldable floating-point constants as an extension.
8400 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008401 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8402 // it anyway and provide a fixit to add the 'constexpr'.
8403 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008404 Diag(VDecl->getLocation(),
8405 diag::ext_in_class_initializer_float_type_cxx11)
8406 << DclT << Init->getSourceRange();
8407 Diag(VDecl->getLocStart(),
8408 diag::note_in_class_initializer_float_type_cxx11)
8409 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008410 } else {
8411 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8412 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008413
Richard Smithcf656382013-01-25 04:22:16 +00008414 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8415 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8416 << Init->getSourceRange();
8417 VDecl->setInvalidDecl();
8418 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008419 }
Richard Smith256336d2011-09-29 23:18:34 +00008420
Richard Smith0cc85782011-12-15 19:20:59 +00008421 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008422 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008423 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008424 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008425 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8426 VDecl->setConstexpr(true);
8427
Richard Smith2316cd82011-09-29 19:11:37 +00008428 } else {
8429 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008430 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008431 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008432 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008433 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008434 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008435 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008436 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008437 VDecl->isExternC())) &&
8438 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008439 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008440
Richard Smith0cc85782011-12-15 19:20:59 +00008441 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008442 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008443 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008444 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8445 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8446 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008447 !Init->isConstantInitializer(
8448 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008449 // GNU C++98 edits for __thread, [basic.start.init]p4:
8450 // An object of thread storage duration shall not require dynamic
8451 // initialization.
8452 // FIXME: Need strict checking here.
8453 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8454 if (getLangOpts().CPlusPlus11)
8455 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8456 }
Steve Naroff61091402007-09-12 14:07:44 +00008457 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008458
Sebastian Redla9351792012-02-11 23:51:47 +00008459 // We will represent direct-initialization similarly to copy-initialization:
8460 // int x(1); -as-> int x = 1;
8461 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8462 //
8463 // Clients that want to distinguish between the two forms, can check for
8464 // direct initializer using VarDecl::getInitStyle().
8465 // A major benefit is that clients that don't particularly care about which
8466 // exactly form was it (like the CodeGen) can handle both cases without
8467 // special case code.
8468
8469 // C++ 8.5p11:
8470 // The form of initialization (using parentheses or '=') is generally
8471 // insignificant, but does matter when the entity being initialized has a
8472 // class type.
8473 if (CXXDirectInit) {
8474 assert(DirectInit && "Call-style initializer must be direct init.");
8475 VDecl->setInitStyle(VarDecl::CallInit);
8476 } else if (DirectInit) {
8477 // This must be list-initialization. No other way is direct-initialization.
8478 VDecl->setInitStyle(VarDecl::ListInit);
8479 }
8480
John McCall8b7fd8f12011-01-19 11:48:09 +00008481 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008482}
8483
John McCalleae5acb2010-03-31 02:13:20 +00008484/// ActOnInitializerError - Given that there was an error parsing an
8485/// initializer for the given declaration, try to return to some form
8486/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008487void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008488 // Our main concern here is re-establishing invariants like "a
8489 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008490 if (!D || D->isInvalidDecl()) return;
8491
8492 VarDecl *VD = dyn_cast<VarDecl>(D);
8493 if (!VD) return;
8494
Richard Smith30482bc2011-02-20 03:19:35 +00008495 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008496 if (ParsingInitForAutoVars.count(D)) {
8497 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008498 return;
8499 }
8500
John McCalleae5acb2010-03-31 02:13:20 +00008501 QualType Ty = VD->getType();
8502 if (Ty->isDependentType()) return;
8503
8504 // Require a complete type.
8505 if (RequireCompleteType(VD->getLocation(),
8506 Context.getBaseElementType(Ty),
8507 diag::err_typecheck_decl_incomplete_type)) {
8508 VD->setInvalidDecl();
8509 return;
8510 }
8511
8512 // Require an abstract type.
8513 if (RequireNonAbstractType(VD->getLocation(), Ty,
8514 diag::err_abstract_type_in_decl,
8515 AbstractVariableType)) {
8516 VD->setInvalidDecl();
8517 return;
8518 }
8519
8520 // Don't bother complaining about constructors or destructors,
8521 // though.
8522}
8523
John McCall48871652010-08-21 09:40:31 +00008524void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008525 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008526 // If there is no declaration, there was an error parsing it. Just ignore it.
8527 if (RealDecl == 0)
8528 return;
8529
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008530 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8531 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008532
Richard Smithf0215fe2011-12-25 21:17:58 +00008533 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008534 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008535 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8536 << Var->getDeclName() << Type;
8537 Var->setInvalidDecl();
8538 return;
8539 }
Mike Stump11289f42009-09-09 15:08:12 +00008540
Richard Smithf0215fe2011-12-25 21:17:58 +00008541 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008542 // the constexpr specifier; if so, its declaration shall specify
8543 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008544 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8545 // the definition of a variable [...] or the declaration of a static data
8546 // member.
8547 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8548 if (Var->isStaticDataMember())
8549 Diag(Var->getLocation(),
8550 diag::err_constexpr_static_mem_var_requires_init)
8551 << Var->getDeclName();
8552 else
8553 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008554 Var->setInvalidDecl();
8555 return;
8556 }
8557
Joey Gouly96b94e62014-01-03 14:16:55 +00008558 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8559 // be initialized.
8560 if (!Var->isInvalidDecl() &&
8561 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008562 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008563 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8564 Var->setInvalidDecl();
8565 return;
8566 }
8567
Douglas Gregore6565622010-02-09 07:26:29 +00008568 switch (Var->isThisDeclarationADefinition()) {
8569 case VarDecl::Definition:
8570 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8571 break;
8572
8573 // We have an out-of-line definition of a static data member
8574 // that has an in-class initializer, so we type-check this like
8575 // a declaration.
8576 //
8577 // Fall through
8578
8579 case VarDecl::DeclarationOnly:
8580 // It's only a declaration.
8581
8582 // Block scope. C99 6.7p7: If an identifier for an object is
8583 // declared with no linkage (C99 6.2.2p6), the type for the
8584 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008585 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008586 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008587 RequireCompleteType(Var->getLocation(), Type,
8588 diag::err_typecheck_decl_incomplete_type))
8589 Var->setInvalidDecl();
8590
8591 // Make sure that the type is not abstract.
8592 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8593 RequireNonAbstractType(Var->getLocation(), Type,
8594 diag::err_abstract_type_in_decl,
8595 AbstractVariableType))
8596 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008597 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008598 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008599 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008600 Diag(Var->getLocation(), diag::note_private_extern);
8601 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008602
Douglas Gregore6565622010-02-09 07:26:29 +00008603 return;
8604
8605 case VarDecl::TentativeDefinition:
8606 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8607 // object that has file scope without an initializer, and without a
8608 // storage-class specifier or with the storage-class specifier "static",
8609 // constitutes a tentative definition. Note: A tentative definition with
8610 // external linkage is valid (C99 6.2.2p5).
8611 if (!Var->isInvalidDecl()) {
8612 if (const IncompleteArrayType *ArrayT
8613 = Context.getAsIncompleteArrayType(Type)) {
8614 if (RequireCompleteType(Var->getLocation(),
8615 ArrayT->getElementType(),
8616 diag::err_illegal_decl_array_incomplete_type))
8617 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008618 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008619 // C99 6.9.2p3: If the declaration of an identifier for an object is
8620 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8621 // declared type shall not be an incomplete type.
8622 // NOTE: code such as the following
8623 // static struct s;
8624 // struct s { int a; };
8625 // is accepted by gcc. Hence here we issue a warning instead of
8626 // an error and we do not invalidate the static declaration.
8627 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008628 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008629 RequireCompleteType(Var->getLocation(), Type,
8630 diag::ext_typecheck_decl_incomplete_type);
8631 }
8632 }
8633
8634 // Record the tentative definition; we're done.
8635 if (!Var->isInvalidDecl())
8636 TentativeDefinitions.push_back(Var);
8637 return;
8638 }
8639
8640 // Provide a specific diagnostic for uninitialized variable
8641 // definitions with incomplete array type.
8642 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008643 Diag(Var->getLocation(),
8644 diag::err_typecheck_incomplete_array_needs_initializer);
8645 Var->setInvalidDecl();
8646 return;
8647 }
8648
John McCalla755f0f2010-08-01 01:25:24 +00008649 // Provide a specific diagnostic for uninitialized variable
8650 // definitions with reference type.
8651 if (Type->isReferenceType()) {
8652 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8653 << Var->getDeclName()
8654 << SourceRange(Var->getLocation(), Var->getLocation());
8655 Var->setInvalidDecl();
8656 return;
8657 }
Douglas Gregore6565622010-02-09 07:26:29 +00008658
8659 // Do not attempt to type-check the default initializer for a
8660 // variable with dependent type.
8661 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008662 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008663
Douglas Gregore6565622010-02-09 07:26:29 +00008664 if (Var->isInvalidDecl())
8665 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008666
Douglas Gregore6565622010-02-09 07:26:29 +00008667 if (RequireCompleteType(Var->getLocation(),
8668 Context.getBaseElementType(Type),
8669 diag::err_typecheck_decl_incomplete_type)) {
8670 Var->setInvalidDecl();
8671 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008672 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008673
Douglas Gregore6565622010-02-09 07:26:29 +00008674 // The variable can not have an abstract class type.
8675 if (RequireNonAbstractType(Var->getLocation(), Type,
8676 diag::err_abstract_type_in_decl,
8677 AbstractVariableType)) {
8678 Var->setInvalidDecl();
8679 return;
8680 }
8681
Douglas Gregor9574af62011-05-21 17:52:48 +00008682 // Check for jumps past the implicit initializer. C++0x
8683 // clarifies that this applies to a "variable with automatic
8684 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008685 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008686 // A program that jumps from a point where a variable with automatic
8687 // storage duration is not in scope to a point where it is in scope is
8688 // ill-formed unless the variable has scalar type, class type with a
8689 // trivial default constructor and a trivial destructor, a cv-qualified
8690 // version of one of these types, or an array of one of the preceding
8691 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008692 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008693 if (const RecordType *Record
8694 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008695 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008696 // Mark the function for further checking even if the looser rules of
8697 // C++11 do not require such checks, so that we can diagnose
8698 // incompatibilities with C++98.
8699 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008700 getCurFunction()->setHasBranchProtectedScope();
8701 }
Douglas Gregore6565622010-02-09 07:26:29 +00008702 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008703
8704 // C++03 [dcl.init]p9:
8705 // If no initializer is specified for an object, and the
8706 // object is of (possibly cv-qualified) non-POD class type (or
8707 // array thereof), the object shall be default-initialized; if
8708 // the object is of const-qualified type, the underlying class
8709 // type shall have a user-declared default
8710 // constructor. Otherwise, if no initializer is specified for
8711 // a non- static object, the object and its subobjects, if
8712 // any, have an indeterminate initial value); if the object
8713 // or any of its subobjects are of const-qualified type, the
8714 // program is ill-formed.
8715 // C++0x [dcl.init]p11:
8716 // If no initializer is specified for an object, the object is
8717 // default-initialized; [...].
8718 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8719 InitializationKind Kind
8720 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008721
8722 InitializationSequence InitSeq(*this, Entity, Kind, None);
8723 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008724 if (Init.isInvalid())
8725 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008726 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008727 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008728 // This is important for template substitution.
8729 Var->setInitStyle(VarDecl::CallInit);
8730 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008731
John McCall8b7fd8f12011-01-19 11:48:09 +00008732 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008733 }
8734}
8735
Richard Smith02e85f32011-04-14 22:09:26 +00008736void Sema::ActOnCXXForRangeDecl(Decl *D) {
8737 VarDecl *VD = dyn_cast<VarDecl>(D);
8738 if (!VD) {
8739 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8740 D->setInvalidDecl();
8741 return;
8742 }
8743
8744 VD->setCXXForRangeDecl(true);
8745
8746 // for-range-declaration cannot be given a storage class specifier.
8747 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008748 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008749 case SC_None:
8750 break;
8751 case SC_Extern:
8752 Error = 0;
8753 break;
8754 case SC_Static:
8755 Error = 1;
8756 break;
8757 case SC_PrivateExtern:
8758 Error = 2;
8759 break;
8760 case SC_Auto:
8761 Error = 3;
8762 break;
8763 case SC_Register:
8764 Error = 4;
8765 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008766 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008767 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008768 }
Richard Smith2316cd82011-09-29 19:11:37 +00008769 if (VD->isConstexpr())
8770 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008771 if (Error != -1) {
8772 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8773 << VD->getDeclName() << Error;
8774 D->setInvalidDecl();
8775 }
8776}
8777
John McCall8b7fd8f12011-01-19 11:48:09 +00008778void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8779 if (var->isInvalidDecl()) return;
8780
John McCall31168b02011-06-15 23:02:42 +00008781 // In ARC, don't allow jumps past the implicit initialization of a
8782 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008783 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008784 var->hasLocalStorage()) {
8785 switch (var->getType().getObjCLifetime()) {
8786 case Qualifiers::OCL_None:
8787 case Qualifiers::OCL_ExplicitNone:
8788 case Qualifiers::OCL_Autoreleasing:
8789 break;
8790
8791 case Qualifiers::OCL_Weak:
8792 case Qualifiers::OCL_Strong:
8793 getCurFunction()->setHasBranchProtectedScope();
8794 break;
8795 }
8796 }
8797
John McCall8a4e2e42014-01-29 08:33:09 +00008798 // Warn about externally-visible variables being defined without a
8799 // prior declaration. We only want to do this for global
8800 // declarations, but we also specifically need to avoid doing it for
8801 // class members because the linkage of an anonymous class can
8802 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008803 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008804 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008805 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008806 getDiagnostics().getDiagnosticLevel(
8807 diag::warn_missing_variable_declarations,
8808 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008809 // Find a previous declaration that's not a definition.
8810 VarDecl *prev = var->getPreviousDecl();
8811 while (prev && prev->isThisDeclarationADefinition())
8812 prev = prev->getPreviousDecl();
8813
8814 if (!prev)
8815 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8816 }
8817
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008818 if (var->getTLSKind() == VarDecl::TLS_Static &&
8819 var->getType().isDestructedType()) {
8820 // GNU C++98 edits for __thread, [basic.start.term]p3:
8821 // The type of an object with thread storage duration shall not
8822 // have a non-trivial destructor.
8823 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8824 if (getLangOpts().CPlusPlus11)
8825 Diag(var->getLocation(), diag::note_use_thread_local);
8826 }
8827
John McCall8b7fd8f12011-01-19 11:48:09 +00008828 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008829 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008830
Richard Smithde63d362012-11-09 23:03:14 +00008831 QualType type = var->getType();
8832 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008833
8834 // __block variables might require us to capture a copy-initializer.
8835 if (var->hasAttr<BlocksAttr>()) {
8836 // It's currently invalid to ever have a __block variable with an
8837 // array type; should we diagnose that here?
8838
8839 // Regardless, we don't want to ignore array nesting when
8840 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008841 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008842 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008843 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008844 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008845 ExprResult result
8846 = PerformMoveOrCopyInitialization(
8847 InitializedEntity::InitializeBlock(poi, type, false),
8848 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008849 if (!result.isInvalid()) {
8850 result = MaybeCreateExprWithCleanups(result);
8851 Expr *init = result.takeAs<Expr>();
8852 Context.setBlockVarCopyInits(var, init);
8853 }
8854 }
8855 }
8856
Richard Smitheda3c842011-11-07 22:16:17 +00008857 Expr *Init = var->getInit();
8858 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008859 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008860
Richard Smithbf830092012-10-29 18:26:47 +00008861 if (!var->getDeclContext()->isDependentContext() &&
8862 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008863 if (IsGlobal && !var->isConstexpr() &&
8864 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8865 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008866 != DiagnosticsEngine::Ignored) {
8867 // Warn about globals which don't have a constant initializer. Don't
8868 // warn about globals with a non-trivial destructor because we already
8869 // warned about them.
8870 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8871 if (!(RD && !RD->hasTrivialDestructor()) &&
8872 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8873 Diag(var->getLocation(), diag::warn_global_constructor)
8874 << Init->getSourceRange();
8875 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008876
Richard Smithd0b4dd62011-12-19 06:19:21 +00008877 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008878 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008879 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8880 SourceLocation DiagLoc = var->getLocation();
8881 // If the note doesn't add any useful information other than a source
8882 // location, fold it into the primary diagnostic.
8883 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8884 diag::note_invalid_subexpr_in_const_expr) {
8885 DiagLoc = Notes[0].first;
8886 Notes.clear();
8887 }
8888 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8889 << var << Init->getSourceRange();
8890 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8891 Diag(Notes[I].first, Notes[I].second);
8892 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008893 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008894 // Check whether the initializer of a const variable of integral or
8895 // enumeration type is an ICE now, since we can't tell whether it was
8896 // initialized by a constant expression if we check later.
8897 var->checkInitIsICE();
8898 }
Richard Smitheda3c842011-11-07 22:16:17 +00008899 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008900
8901 // Require the destructor.
8902 if (const RecordType *recordType = baseType->getAs<RecordType>())
8903 FinalizeVarWithDestructor(var, recordType);
8904}
8905
Richard Smithb2bc2e62011-02-21 20:05:19 +00008906/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8907/// any semantic actions necessary after any initializer has been attached.
8908void
8909Sema::FinalizeDeclaration(Decl *ThisDecl) {
8910 // Note that we are no longer parsing the initializer for this declaration.
8911 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008912
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008913 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008914 if (!VD)
8915 return;
8916
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00008917 checkAttributesAfterMerging(*this, *VD);
8918
Rafael Espindola87198cd2013-08-16 23:18:50 +00008919 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8920 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00008921 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00008922 VD->dropAttr<UsedAttr>();
8923 }
8924 }
8925
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008926 if (!VD->isInvalidDecl() &&
8927 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8928 if (const VarDecl *Def = VD->getDefinition()) {
8929 if (Def->hasAttr<AliasAttr>()) {
8930 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8931 << VD->getDeclName();
8932 Diag(Def->getLocation(), diag::note_previous_definition);
8933 VD->setInvalidDecl();
8934 }
8935 }
8936 }
8937
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008938 const DeclContext *DC = VD->getDeclContext();
8939 // If there's a #pragma GCC visibility in scope, and this isn't a class
8940 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00008941 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008942 AddPushedVisibilityAttribute(VD);
8943
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008944 if (VD->isFileVarDecl())
8945 MarkUnusedFileScopedDecl(VD);
8946
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008947 // Now we have parsed the initializer and can update the table of magic
8948 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008949 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8950 !VD->getType()->isIntegralOrEnumerationType())
8951 return;
8952
8953 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8954 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8955 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8956 I != E; ++I) {
8957 const Expr *MagicValueExpr = VD->getInit();
8958 if (!MagicValueExpr) {
8959 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008960 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008961 llvm::APSInt MagicValueInt;
8962 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8963 Diag(I->getRange().getBegin(),
8964 diag::err_type_tag_for_datatype_not_ice)
8965 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8966 continue;
8967 }
8968 if (MagicValueInt.getActiveBits() > 64) {
8969 Diag(I->getRange().getBegin(),
8970 diag::err_type_tag_for_datatype_too_large)
8971 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8972 continue;
8973 }
8974 uint64_t MagicValue = MagicValueInt.getZExtValue();
8975 RegisterTypeTagForDatatype(I->getArgumentKind(),
8976 MagicValue,
8977 I->getMatchingCType(),
8978 I->getLayoutCompatible(),
8979 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008980 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00008981}
8982
Rafael Espindolaab417692013-07-09 12:05:01 +00008983Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8984 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008985 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008986
8987 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00008988 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008989
David Majnemer50ce8352013-09-17 23:57:10 +00008990 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008991 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00008992 if (Decl *D = Group[i]) {
8993 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8994 if (!FirstDeclaratorInGroup)
8995 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00008996 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00008997 }
Richard Smith2abf6762011-02-23 00:37:57 +00008998
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008999 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009000 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009001 HandleTagNumbering(*this, Tag);
David Majnemer50ce8352013-09-17 23:57:10 +00009002 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9003 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9004 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009005 }
David Blaikie095deba2012-11-14 01:52:05 +00009006
Rafael Espindolaab417692013-07-09 12:05:01 +00009007 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009008}
9009
9010/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9011/// group, performing any necessary semantic checking.
9012Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00009013Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009014 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009015 // C++0x [dcl.spec.auto]p7:
9016 // If the type deduced for the template parameter U is not the same in each
9017 // deduction, the program is ill-formed.
9018 // FIXME: When initializer-list support is added, a distinction is needed
9019 // between the deduced type U and the deduced type which 'auto' stands for.
9020 // auto a = 0, b = { 1, 2, 3 };
9021 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009022 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009023 QualType Deduced;
9024 CanQualType DeducedCanon;
9025 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009026 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009027 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9028 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009029 // Don't reissue diagnostics when instantiating a template.
9030 if (AT && D->isInvalidDecl())
9031 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009032 QualType U = AT ? AT->getDeducedType() : QualType();
9033 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009034 CanQualType UCanon = Context.getCanonicalType(U);
9035 if (Deduced.isNull()) {
9036 Deduced = U;
9037 DeducedCanon = UCanon;
9038 DeducedDecl = D;
9039 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009040 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9041 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009042 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009043 << Deduced << DeducedDecl->getDeclName()
9044 << U << D->getDeclName()
9045 << DeducedDecl->getInit()->getSourceRange()
9046 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009047 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009048 break;
9049 }
9050 }
9051 }
9052 }
9053 }
9054
Rafael Espindolaab417692013-07-09 12:05:01 +00009055 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009056
Rafael Espindolaab417692013-07-09 12:05:01 +00009057 return DeclGroupPtrTy::make(
9058 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009059}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009060
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009061void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009062 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009063}
9064
Rafael Espindolaab417692013-07-09 12:05:01 +00009065void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009066 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009067 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009068 return;
9069
9070 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9071 Group[0]->getLocation())
9072 == DiagnosticsEngine::Ignored)
9073 return;
9074
Rafael Espindolaab417692013-07-09 12:05:01 +00009075 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009076 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009077 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009078 // additional declaration references:
9079 // 'typedef struct S {} S;'
9080 // 'typedef struct S *S;'
9081 // 'struct S *pS;'
9082 // FinalizeDeclaratorGroup adds these as separate declarations.
9083 Decl *MaybeTagDecl = Group[0];
9084 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009085 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009086 }
9087 }
9088
9089 // See if there are any new comments that are not attached to a decl.
9090 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9091 if (!Comments.empty() &&
9092 !Comments.back()->isAttached()) {
9093 // There is at least one comment that not attached to a decl.
9094 // Maybe it should be attached to one of these decls?
9095 //
9096 // Note that this way we pick up not only comments that precede the
9097 // declaration, but also comments that *follow* the declaration -- thanks to
9098 // the lookahead in the lexer: we've consumed the semicolon and looked
9099 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009100 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009101 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009102 }
9103}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009104
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009105/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9106/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009107Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009108 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009109
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009110 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009111
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009112 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009113 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009114 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009115 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009116 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009117 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9118 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009119 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009120 Diag(DS.getStorageClassSpecLoc(),
9121 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009122 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009123 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009124
Richard Smithb4a9e862013-04-12 22:46:28 +00009125 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9126 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9127 << DeclSpec::getSpecifierName(TSCS);
9128 if (DS.isConstexprSpecified())
9129 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009130 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009131
Richard Smithb4a9e862013-04-12 22:46:28 +00009132 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009133
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009134 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009135 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009136
David Blaikiebbafb8a2012-03-11 07:00:24 +00009137 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009138 // Check that there are no default arguments inside the type of this
9139 // parameter.
9140 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009141
9142 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9143 if (D.getCXXScopeSpec().isSet()) {
9144 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9145 << D.getCXXScopeSpec().getRange();
9146 D.getCXXScopeSpec().clear();
9147 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009148 }
9149
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009150 // Ensure we have a valid name
9151 IdentifierInfo *II = 0;
9152 if (D.hasName()) {
9153 II = D.getIdentifier();
9154 if (!II) {
9155 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009156 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009157 D.setInvalidType(true);
9158 }
9159 }
9160
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009161 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009162 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009163 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9164 ForRedeclaration);
9165 LookupName(R, S);
9166 if (R.isSingleResult()) {
9167 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009168 if (PrevDecl->isTemplateParameter()) {
9169 // Maybe we will complain about the shadowed template parameter.
9170 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9171 // Just pretend that we didn't see the previous declaration.
9172 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009173 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009174 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009175 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009176
Chris Lattnerd9773512009-01-21 02:38:50 +00009177 // Recover by removing the name
9178 II = 0;
9179 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009180 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009181 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009182 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009183 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009184
John McCallf7b2fb52010-01-22 00:28:27 +00009185 // Temporarily put parameter variables in the translation unit, not
9186 // the enclosing context. This prevents them from accidentally
9187 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009188 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009189 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009190 D.getIdentifierLoc(), II,
9191 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009192 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009193
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009194 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009195 New->setInvalidDecl();
9196
9197 assert(S->isFunctionPrototypeScope());
9198 assert(S->getFunctionPrototypeDepth() >= 1);
9199 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9200 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009201
Douglas Gregor91f84212008-12-11 16:49:14 +00009202 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009203 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009204 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009205 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009206
Douglas Gregor758a8692009-06-17 21:51:59 +00009207 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009208
Douglas Gregor41866812011-09-12 18:37:38 +00009209 if (D.getDeclSpec().isModulePrivateSpecified())
9210 Diag(New->getLocation(), diag::err_module_private_local)
9211 << 1 << New->getDeclName()
9212 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9213 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9214
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009215 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009216 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9217 }
John McCall48871652010-08-21 09:40:31 +00009218 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009219}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009220
John McCalla3ccba02010-06-04 11:21:44 +00009221/// \brief Synthesizes a variable for a parameter arising from a
9222/// typedef.
9223ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9224 SourceLocation Loc,
9225 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009226 /* FIXME: setting StartLoc == Loc.
9227 Would it be worth to modify callers so as to provide proper source
9228 location for the unnamed parameters, embedding the parameter's type? */
9229 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009230 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009231 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009232 Param->setImplicit();
9233 return Param;
9234}
9235
John McCallc5990642010-08-24 09:05:15 +00009236void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9237 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009238 // Don't diagnose unused-parameter errors in template instantiations; we
9239 // will already have done so in the template itself.
9240 if (!ActiveTemplateInstantiations.empty())
9241 return;
9242
9243 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009244 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009245 !(*Param)->hasAttr<UnusedAttr>()) {
9246 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9247 << (*Param)->getDeclName();
9248 }
9249 }
9250}
9251
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009252void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9253 ParmVarDecl * const *ParamEnd,
9254 QualType ReturnTy,
9255 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009256 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009257 return;
9258
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009259 // Warn if the return value is pass-by-value and larger than the specified
9260 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009261 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009262 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009263 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009264 Diag(D->getLocation(), diag::warn_return_value_size)
9265 << D->getDeclName() << Size;
9266 }
9267
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009268 // Warn if any parameter is pass-by-value and larger than the specified
9269 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009270 for (; Param != ParamEnd; ++Param) {
9271 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009272 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009273 continue;
9274 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009275 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009276 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9277 << (*Param)->getDeclName() << Size;
9278 }
9279}
9280
Abramo Bagnaradff19302011-03-08 08:55:46 +00009281ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9282 SourceLocation NameLoc, IdentifierInfo *Name,
9283 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009284 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009285 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009286 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009287 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009288 T->isObjCLifetimeType()) {
9289
9290 Qualifiers::ObjCLifetime lifetime;
9291
9292 // Special cases for arrays:
9293 // - if it's const, use __unsafe_unretained
9294 // - otherwise, it's an error
9295 if (T->isArrayType()) {
9296 if (!T.isConstQualified()) {
9297 DelayedDiagnostics.add(
9298 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009299 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009300 }
9301 lifetime = Qualifiers::OCL_ExplicitNone;
9302 } else {
9303 lifetime = T->getObjCARCImplicitLifetime();
9304 }
9305 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009306 }
9307
Abramo Bagnaradff19302011-03-08 08:55:46 +00009308 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009309 Context.getAdjustedParameterType(T),
9310 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009311 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009312
9313 // Parameters can not be abstract class types.
9314 // For record types, this is done by the AbstractClassUsageDiagnoser once
9315 // the class has been completely parsed.
9316 if (!CurContext->isRecord() &&
9317 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9318 AbstractParamType))
9319 New->setInvalidDecl();
9320
9321 // Parameter declarators cannot be interface types. All ObjC objects are
9322 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009323 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009324 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009325 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009326 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009327 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009328 T = Context.getObjCObjectPointerType(T);
9329 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009330 }
9331
9332 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9333 // duration shall not be qualified by an address-space qualifier."
9334 // Since all parameters have automatic store duration, they can not have
9335 // an address space.
9336 if (T.getAddressSpace() != 0) {
9337 Diag(NameLoc, diag::err_arg_with_address_space);
9338 New->setInvalidDecl();
9339 }
9340
9341 return New;
9342}
9343
Douglas Gregor170512f2009-04-01 23:51:29 +00009344void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9345 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009346 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009347
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009348 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9349 // for a K&R function.
9350 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009351 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9352 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009353 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009354 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009355 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00009356 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009357 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009358 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00009359 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00009360 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009361
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009362 // Implicitly declare the argument as type 'int' for lack of a better
9363 // type.
John McCall084e83d2011-03-24 11:26:52 +00009364 AttributeFactory attrs;
9365 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009366 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009367 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00009368 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009369 PrevSpec, DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009370 // Use the identifier location for the type source range.
9371 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9372 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009373 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9374 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00009375 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009376 }
9377 }
Mike Stump11289f42009-09-09 15:08:12 +00009378 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009379}
9380
Richard Smith79a52e52012-04-17 22:30:01 +00009381Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009382 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009383 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009384 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009385
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009386 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009387 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009388 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009389}
9390
Anders Carlsson2a45e402012-12-18 01:29:20 +00009391static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9392 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009393 // Don't warn about invalid declarations.
9394 if (FD->isInvalidDecl())
9395 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009396
Anders Carlsson31c7e882009-12-09 03:30:09 +00009397 // Or declarations that aren't global.
9398 if (!FD->isGlobal())
9399 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009400
Anders Carlsson31c7e882009-12-09 03:30:09 +00009401 // Don't warn about C++ member functions.
9402 if (isa<CXXMethodDecl>(FD))
9403 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009404
Anders Carlsson31c7e882009-12-09 03:30:09 +00009405 // Don't warn about 'main'.
9406 if (FD->isMain())
9407 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009408
Anders Carlsson31c7e882009-12-09 03:30:09 +00009409 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009410 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009411 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009412
9413 // Don't warn about function templates.
9414 if (FD->getDescribedFunctionTemplate())
9415 return false;
9416
9417 // Don't warn about function template specializations.
9418 if (FD->isFunctionTemplateSpecialization())
9419 return false;
9420
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009421 // Don't warn for OpenCL kernels.
9422 if (FD->hasAttr<OpenCLKernelAttr>())
9423 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009424
Anders Carlsson31c7e882009-12-09 03:30:09 +00009425 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009426 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9427 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009428 // Ignore any declarations that occur in function or method
9429 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009430 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009431 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009432
Anders Carlsson31c7e882009-12-09 03:30:09 +00009433 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009434 if (FD->getNumParams() == 0)
9435 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009436 break;
9437 }
Richard Smith541b38b2013-09-20 01:15:31 +00009438
Anders Carlsson31c7e882009-12-09 03:30:09 +00009439 return MissingPrototype;
9440}
9441
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009442void
9443Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9444 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009445 // Don't complain if we're in GNU89 mode and the previous definition
9446 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009447 const FunctionDecl *Definition = EffectiveDefinition;
9448 if (!Definition)
9449 if (!FD->isDefined(Definition))
9450 return;
9451
9452 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009453 return;
9454
9455 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9456 Definition->getStorageClass() == SC_Extern)
9457 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009458 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009459 else
9460 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9461
9462 Diag(Definition->getLocation(), diag::note_previous_definition);
9463 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009464}
Faisal Valia17d19f2013-11-07 05:17:06 +00009465
9466
Faisal Valic1a6dc42013-10-23 16:10:50 +00009467static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9468 Sema &S) {
9469 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009470
9471 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009472 LSI->CallOperator = CallOperator;
9473 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009474 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009475 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9476
9477 if (LCD == LCD_None)
9478 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9479 else if (LCD == LCD_ByCopy)
9480 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9481 else if (LCD == LCD_ByRef)
9482 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9483 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9484
9485 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9486 LSI->Mutable = !CallOperator->isConst();
9487
Faisal Valia17d19f2013-11-07 05:17:06 +00009488 // Add the captures to the LSI so they can be noted as already
9489 // captured within tryCaptureVar.
9490 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9491 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9492 if (C->capturesVariable()) {
9493 VarDecl *VD = C->getCapturedVar();
9494 if (VD->isInitCapture())
9495 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9496 QualType CaptureType = VD->getType();
9497 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9498 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9499 /*RefersToEnclosingLocal*/true, C->getLocation(),
9500 /*EllipsisLoc*/C->isPackExpansion()
9501 ? C->getEllipsisLoc() : SourceLocation(),
9502 CaptureType, /*Expr*/ 0);
9503
9504 } else if (C->capturesThis()) {
9505 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9506 S.getCurrentThisType(), /*Expr*/ 0);
9507 }
9508 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009509}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009510
John McCall48871652010-08-21 09:40:31 +00009511Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009512 // Clear the last template instantiation error context.
9513 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9514
Douglas Gregor17a7c122009-06-24 00:54:41 +00009515 if (!D)
9516 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009517 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009518
John McCall48871652010-08-21 09:40:31 +00009519 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009520 FD = FunTmpl->getTemplatedDecl();
9521 else
John McCall48871652010-08-21 09:40:31 +00009522 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009523 // If we are instantiating a generic lambda call operator, push
9524 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009525 // that's already been calculated (ActOnLambdaExpr) to prime the current
9526 // LambdaScopeInfo.
9527 // When the template operator is being specialized, the LambdaScopeInfo,
9528 // has to be properly restored so that tryCaptureVariable doesn't try
9529 // and capture any new variables. In addition when calculating potential
9530 // captures during transformation of nested lambdas, it is necessary to
9531 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009532 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009533 assert(ActiveTemplateInstantiations.size() &&
9534 "There should be an active template instantiation on the stack "
9535 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009536 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009537 }
9538 else
9539 // Enter a new function scope
9540 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009541
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009542 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009543 if (!FD->isLateTemplateParsed())
9544 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009545
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009546 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009547 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009548 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9549 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009550 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009551 FD->setInvalidDecl();
9552 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009553 }
9554
Eli Friedman9ad72442009-03-04 07:30:59 +00009555 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009556 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009557 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009558 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009559 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009560 RequireCompleteType(FD->getLocation(), ResultType,
9561 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009562 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009563
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009564 // GNU warning -Wmissing-prototypes:
9565 // Warn if a global function is defined without a previous
9566 // prototype declaration. This warning is issued even if the
9567 // definition itself provides a prototype. The aim is to detect
9568 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009569 const FunctionDecl *PossibleZeroParamPrototype = 0;
9570 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009571 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009572
Anders Carlsson2a45e402012-12-18 01:29:20 +00009573 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009574 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009575 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009576 if (TypeSourceInfo *TI =
9577 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9578 TypeLoc TL = TI->getTypeLoc();
9579 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9580 Diag(PossibleZeroParamPrototype->getLocation(),
9581 diag::note_declaration_not_a_prototype)
9582 << PossibleZeroParamPrototype
9583 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9584 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009585 }
9586 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009587
Douglas Gregor67da0d92009-05-15 17:59:04 +00009588 if (FnBodyScope)
9589 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009590
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009591 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009592 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9593 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009594
9595 // Introduce our parameters into the function scope
9596 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9597 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00009598 Param->setOwningFunction(FD);
9599
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009600 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009601 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009602 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009603
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009604 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009605 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009606 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009607
James Molloy6f8780b2012-02-29 10:24:19 +00009608 // If we had any tags defined in the function prototype,
9609 // introduce them into the function scope.
9610 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009611 for (ArrayRef<NamedDecl *>::iterator
9612 I = FD->getDeclsInPrototypeScope().begin(),
9613 E = FD->getDeclsInPrototypeScope().end();
9614 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009615 NamedDecl *D = *I;
9616
9617 // Some of these decls (like enums) may have been pinned to the translation unit
9618 // for lack of a real context earlier. If so, remove from the translation unit
9619 // and reattach to the current context.
9620 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9621 // Is the decl actually in the context?
9622 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9623 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9624 if (*DI == D) {
9625 Context.getTranslationUnitDecl()->removeDecl(D);
9626 break;
9627 }
9628 }
9629 // Either way, reassign the lexical decl context to our FunctionDecl.
9630 D->setLexicalDeclContext(CurContext);
9631 }
9632
9633 // If the decl has a non-null name, make accessible in the current scope.
9634 if (!D->getName().empty())
9635 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9636
9637 // Similarly, dive into enums and fish their constants out, making them
9638 // accessible in this scope.
9639 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9640 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9641 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00009642 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009643 }
9644 }
9645 }
9646
Richard Smith79a52e52012-04-17 22:30:01 +00009647 // Ensure that the function's exception specification is instantiated.
9648 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9649 ResolveExceptionSpec(D->getLocation(), FPT);
9650
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009651 // Checking attributes of current function definition
9652 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009653 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009654 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009655 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009656 // Microsoft accepts dllimport for functions defined within class scope.
9657 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009658 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009659 Diag(FD->getLocation(),
9660 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009661 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009662 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009663 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009664 }
9665
9666 // Visual C++ appears to not think this is an issue, so only issue
9667 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009668 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009669 // If a symbol previously declared dllimport is later defined, the
9670 // attribute is ignored in subsequent references, and a warning is
9671 // emitted.
9672 Diag(FD->getLocation(),
9673 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Aaron Ballman44ebc072014-01-02 22:29:41 +00009674 << FD << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009675 }
9676 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009677 // We want to attach documentation to original Decl (which might be
9678 // a function template).
9679 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009680 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009681}
9682
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009683/// \brief Given the set of return statements within a function body,
9684/// compute the variables that are subject to the named return value
9685/// optimization.
9686///
9687/// Each of the variables that is subject to the named return value
9688/// optimization will be marked as NRVO variables in the AST, and any
9689/// return statement that has a marked NRVO variable as its NRVO candidate can
9690/// use the named return value optimization.
9691///
9692/// This function applies a very simplistic algorithm for NRVO: if every return
9693/// statement in the function has the same NRVO candidate, that candidate is
9694/// the NRVO variable.
9695///
9696/// FIXME: Employ a smarter algorithm that accounts for multiple return
9697/// statements and the lifetimes of the NRVO candidates. We should be able to
9698/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009699void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009700 ReturnStmt **Returns = Scope->Returns.data();
9701
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009702 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009703 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009704 if (!Returns[I]->getNRVOCandidate())
9705 return;
9706
9707 if (!NRVOCandidate)
9708 NRVOCandidate = Returns[I]->getNRVOCandidate();
9709 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9710 return;
9711 }
9712
9713 if (NRVOCandidate)
9714 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9715}
9716
Richard Smith1ab34b32012-11-19 21:13:18 +00009717bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009718 // We cannot skip the body of a function (or function template) which is
9719 // constexpr, since we may need to evaluate its body in order to parse the
9720 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009721 // We cannot skip the body of a function with an undeduced return type,
9722 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009723 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009724 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009725 return false;
9726 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009727}
9728
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009729Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009730 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009731 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009732 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009733 MD->setHasSkippedBody();
9734 return ActOnFinishFunctionBody(Decl, 0);
9735}
9736
John McCallfaf5fb42010-08-26 23:41:50 +00009737Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009738 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009739}
9740
John McCallb268a282010-08-23 23:25:46 +00009741Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9742 bool IsInstantiation) {
Alp Tokera2794f92014-01-22 07:29:52 +00009743 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009744
Ted Kremenek0b405322010-03-23 00:13:23 +00009745 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009746 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009747
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009748 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009749 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009750
Richard Smith7500ab22013-05-10 04:31:10 +00009751 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009752 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009753 // If the function has a deduced result type but contains no 'return'
9754 // statements, the result type as written must be exactly 'auto', and
9755 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009756 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009757 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009758 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009759 FD->setInvalidDecl();
9760 } else {
9761 // Substitute 'void' for the 'auto' in the type.
9762 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009763 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009764 Context.adjustDeducedFunctionResultType(
9765 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009766 }
9767 }
9768
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009769 // The only way to be included in UndefinedButUsed is if there is an
9770 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009771 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009772 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009773 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009774 UndefinedButUsed.erase(FD);
9775 else if (FD->isInlined() &&
9776 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9777 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9778 UndefinedButUsed.erase(FD);
9779 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009780
John McCall5ed3caf2012-02-14 19:50:52 +00009781 // If the function implicitly returns zero (like 'main') or is naked,
9782 // don't complain about missing return statements.
9783 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009784 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009785
Francois Pichet3abc9b82011-05-11 02:14:46 +00009786 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009787 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009788 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009789 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9790
Douglas Gregor88d292c2010-05-13 16:44:06 +00009791 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009792 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009793 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009794 FD->getReturnType(), FD);
9795
Douglas Gregor88d292c2010-05-13 16:44:06 +00009796 // If this is a constructor, we need a vtable.
9797 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9798 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009799
Jordan Rosed39e5f12012-07-02 21:19:23 +00009800 // Try to apply the named return value optimization. We have to check
9801 // if we can do this here because lambdas keep return statements around
9802 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +00009803 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +00009804 !FD->isDependentContext())
9805 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009806 }
9807
Douglas Gregor21f46922012-02-08 20:17:14 +00009808 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9809 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009810 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009811 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009812 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009813 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009814 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009815 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009816 MD->getReturnType(), MD);
9817
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009818 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009819 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009820 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009821 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009822 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9823 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009824 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009825 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009826 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9827 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009828 bool isDesignated =
9829 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009830 assert(isDesignated && InitMethod);
9831 (void)isDesignated;
9832 Diag(MD->getLocation(),
9833 diag::warn_objc_designated_init_missing_super_call);
9834 Diag(InitMethod->getLocation(),
9835 diag::note_objc_designated_init_marked_here);
9836 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9837 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009838 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9839 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9840 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9841 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009842 } else {
John McCall48871652010-08-21 09:40:31 +00009843 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009844 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009845
Jordan Rose2afd6612012-10-19 16:05:26 +00009846 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009847 "This should only be set for ObjC methods, which should have been "
9848 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009849
Chris Lattnere2473062007-05-28 06:28:18 +00009850 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009851 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009852 // C++ constructors that have function-try-blocks can't have return
9853 // statements in the handlers of that block. (C++ [except.handle]p14)
9854 // Verify this.
9855 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9856 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9857
Richard Smithdef8bdb2011-08-12 18:44:32 +00009858 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009859 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009860 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009861 !hasAnyUnrecoverableErrorsInThisFunction() &&
9862 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009863 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009864
John McCalldeb646e2010-08-04 01:04:25 +00009865 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9866 if (!Destructor->getParent()->isDependentType())
9867 CheckDestructor(Destructor);
9868
John McCalla6309952010-03-16 21:39:52 +00009869 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9870 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009871 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009872
9873 // If any errors have occurred, clear out any temporaries that may have
9874 // been leftover. This ensures that these temporaries won't be picked up for
9875 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009876 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009877 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009878 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009879 }
9880 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9881 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009882 // Since the body is valid, issue any analysis-based warnings that are
9883 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009884 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009885 }
9886
Richard Smith3607ffe2012-02-13 03:54:03 +00009887 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9888 (!CheckConstexprFunctionDecl(FD) ||
9889 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009890 FD->setInvalidDecl();
9891
John McCall28fc7092011-11-10 05:35:25 +00009892 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009893 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009894 assert(MaybeODRUseExprs.empty() &&
9895 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009896 }
9897
John McCalle99d5f32010-03-25 22:08:03 +00009898 if (!IsInstantiation)
9899 PopDeclContext();
9900
Eli Friedman71c80552012-01-05 03:35:19 +00009901 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009902 // If any errors have occurred, clear out any temporaries that may have
9903 // been leftover. This ensures that these temporaries won't be picked up for
9904 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009905 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009906 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009907 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009908
John McCall48871652010-08-21 09:40:31 +00009909 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009910}
9911
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009912
9913/// When we finish delayed parsing of an attribute, we must attach it to the
9914/// relevant Decl.
9915void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9916 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009917 // Always attach attributes to the underlying decl.
9918 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9919 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009920 ProcessDeclAttributeList(S, D, Attrs.getList());
9921
9922 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9923 if (Method->isStatic())
9924 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009925}
9926
9927
Chris Lattnerac18be92006-11-20 06:49:47 +00009928/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9929/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009930NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009931 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009932 // Before we produce a declaration for an implicitly defined
9933 // function, see whether there was a locally-scoped declaration of
9934 // this name as a function or variable. If so, use that
9935 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009936 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9937 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9938 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9939 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009940 }
9941
Chris Lattner00e26072008-05-05 21:18:06 +00009942 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009943 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009944 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009945 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009946 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009947 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009948 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009949 diag_id = diag::warn_implicit_function_decl;
9950 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009951
Hans Wennborg70a13242011-12-08 15:56:07 +00009952 // Because typo correction is expensive, only do it if the implicit
9953 // function declaration is going to be treated as an error.
9954 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9955 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009956 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009957 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009958 LookupOrdinaryName, S, 0, Validator)))
9959 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9960 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009961 }
9962
Chris Lattnerac18be92006-11-20 06:49:47 +00009963 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009964 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009965 AttributeFactory attrFactory;
9966 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009967 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009968 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9969 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009970 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009971 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009972 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009973 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009974 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9975 /*IsAmbiguous=*/false,
9976 /*RParenLoc=*/NoLoc,
9977 /*ArgInfo=*/0,
9978 /*NumArgs=*/0,
9979 /*EllipsisLoc=*/NoLoc,
9980 /*RParenLoc=*/NoLoc,
9981 /*TypeQuals=*/0,
9982 /*RefQualifierIsLvalueRef=*/true,
9983 /*RefQualifierLoc=*/NoLoc,
9984 /*ConstQualifierLoc=*/NoLoc,
9985 /*VolatileQualifierLoc=*/NoLoc,
9986 /*MutableLoc=*/NoLoc,
9987 EST_None,
9988 /*ESpecLoc=*/NoLoc,
9989 /*Exceptions=*/0,
9990 /*ExceptionRanges=*/0,
9991 /*NumExceptions=*/0,
9992 /*NoexceptExpr=*/0,
9993 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009994 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009995 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00009996 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009997
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009998 // Insert this function into translation-unit scope.
9999
10000 DeclContext *PrevDC = CurContext;
10001 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010002
Jordan Rosed03d99d2013-03-05 01:27:54 +000010003 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010004 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010005
10006 CurContext = PrevDC;
10007
Douglas Gregore711f702009-02-14 18:57:46 +000010008 AddKnownFunctionAttributes(FD);
10009
Steve Naroff3913ea42008-04-04 14:32:09 +000010010 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010011}
10012
Douglas Gregore711f702009-02-14 18:57:46 +000010013/// \brief Adds any function attributes that we know a priori based on
10014/// the declaration of this function.
10015///
10016/// These attributes can apply both to implicitly-declared builtins
10017/// (like __builtin___printf_chk) or to library-declared functions
10018/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010019///
10020/// We need to check for duplicate attributes both here and where user-written
10021/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010022void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10023 if (FD->isInvalidDecl())
10024 return;
10025
10026 // If this is a built-in function, map its builtin attributes to
10027 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010028 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010029 // Handle printf-formatting attributes.
10030 unsigned FormatIdx;
10031 bool HasVAListArg;
10032 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010033 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010034 const char *fmt = "printf";
10035 unsigned int NumParams = FD->getNumParams();
10036 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10037 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10038 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010039 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010040 &Context.Idents.get(fmt),
10041 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010042 HasVAListArg ? 0 : FormatIdx+2,
10043 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010044 }
Douglas Gregore711f702009-02-14 18:57:46 +000010045 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010046 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10047 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010048 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010049 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010050 &Context.Idents.get("scanf"),
10051 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010052 HasVAListArg ? 0 : FormatIdx+2,
10053 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010054 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010055
10056 // Mark const if we don't care about errno and that is the only
10057 // thing preventing the function from being const. This allows
10058 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010059 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010060 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010061 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010062 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010063 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010064
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010065 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010066 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010067 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10068 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010069 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010070 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010071 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010072 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010073 }
10074
10075 IdentifierInfo *Name = FD->getIdentifier();
10076 if (!Name)
10077 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010078 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010079 FD->getDeclContext()->isTranslationUnit()) ||
10080 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010081 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010082 LinkageSpecDecl::lang_c)) {
10083 // Okay: this could be a libc/libm/Objective-C function we know
10084 // about.
10085 } else
10086 return;
10087
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010088 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010089 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010090 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010091 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010092 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010093 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010094 Name->isStr("vasprintf") ? 0 : 3,
10095 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010096 }
Jordan Rose742c6072012-08-08 21:17:31 +000010097
10098 if (Name->isStr("__CFStringMakeConstantString")) {
10099 // We already have a __builtin___CFStringMakeConstantString,
10100 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010101 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010102 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10103 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010104 }
Douglas Gregore711f702009-02-14 18:57:46 +000010105}
Chris Lattner302b4be2006-11-19 02:31:38 +000010106
John McCall703a3f82009-10-24 08:00:42 +000010107TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010108 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010109 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010110 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010111
John McCallbcd03502009-12-07 02:54:59 +000010112 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010113 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010114 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010115 }
10116
Chris Lattner18b19622007-01-22 07:39:13 +000010117 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010118 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010119 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010120 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010121 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010122 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010123
John McCall04fcd0d2011-02-01 08:20:08 +000010124 // Bail out immediately if we have an invalid declaration.
10125 if (D.isInvalidType()) {
10126 NewTD->setInvalidDecl();
10127 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010128 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010129
Douglas Gregor41866812011-09-12 18:37:38 +000010130 if (D.getDeclSpec().isModulePrivateSpecified()) {
10131 if (CurContext->isFunctionOrMethod())
10132 Diag(NewTD->getLocation(), diag::err_module_private_local)
10133 << 2 << NewTD->getDeclName()
10134 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10135 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10136 else
10137 NewTD->setModulePrivate();
10138 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010139
John McCall04fcd0d2011-02-01 08:20:08 +000010140 // C++ [dcl.typedef]p8:
10141 // If the typedef declaration defines an unnamed class (or
10142 // enum), the first typedef-name declared by the declaration
10143 // to be that class type (or enum type) is used to denote the
10144 // class type (or enum type) for linkage purposes only.
10145 // We need to check whether the type was declared in the declaration.
10146 switch (D.getDeclSpec().getTypeSpecType()) {
10147 case TST_enum:
10148 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010149 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010150 case TST_union:
10151 case TST_class: {
10152 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10153
10154 // Do nothing if the tag is not anonymous or already has an
10155 // associated typedef (from an earlier typedef in this decl group).
10156 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010157 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010158
10159 // A well-formed anonymous tag must always be a TUK_Definition.
10160 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10161
10162 // The type must match the tag exactly; no qualifiers allowed.
10163 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10164 break;
10165
John McCall2575d882014-01-30 01:12:53 +000010166 // If we've already computed linkage for the anonymous tag, then
10167 // adding a typedef name for the anonymous decl can change that
10168 // linkage, which might be a serious problem. Diagnose this as
10169 // unsupported and ignore the typedef name. TODO: we should
10170 // pursue this as a language defect and establish a formal rule
10171 // for how to handle it.
10172 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10173 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10174
10175 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10176 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10177 getLangOpts());
10178
10179 llvm::SmallString<40> textToInsert;
10180 textToInsert += ' ';
10181 textToInsert += D.getIdentifier()->getName();
10182 Diag(tagLoc, diag::note_typedef_changes_linkage)
10183 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10184 break;
10185 }
10186
John McCall04fcd0d2011-02-01 08:20:08 +000010187 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010188 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010189 break;
10190 }
10191
10192 default:
10193 break;
10194 }
10195
Steve Narofff93b6722007-08-28 20:14:24 +000010196 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010197}
10198
Douglas Gregord9034f02009-05-14 16:41:31 +000010199
Richard Smith4b38ded2012-03-14 23:13:10 +000010200/// \brief Check that this is a valid underlying type for an enum declaration.
10201bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10202 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10203 QualType T = TI->getType();
10204
Eli Friedman52f32b92012-12-18 02:37:32 +000010205 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010206 return false;
10207
Eli Friedman52f32b92012-12-18 02:37:32 +000010208 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10209 if (BT->isInteger())
10210 return false;
10211
Richard Smith4b38ded2012-03-14 23:13:10 +000010212 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10213 return true;
10214}
10215
10216/// Check whether this is a valid redeclaration of a previous enumeration.
10217/// \return true if the redeclaration was invalid.
10218bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10219 QualType EnumUnderlyingTy,
10220 const EnumDecl *Prev) {
10221 bool IsFixed = !EnumUnderlyingTy.isNull();
10222
10223 if (IsScoped != Prev->isScoped()) {
10224 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10225 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010226 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010227 return true;
10228 }
10229
10230 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010231 if (!EnumUnderlyingTy->isDependentType() &&
10232 !Prev->getIntegerType()->isDependentType() &&
10233 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010234 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010235 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010236 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10237 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010238 Diag(Prev->getLocation(), diag::note_previous_declaration)
10239 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010240 return true;
10241 }
10242 } else if (IsFixed != Prev->isFixed()) {
10243 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10244 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010245 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010246 return true;
10247 }
10248
10249 return false;
10250}
10251
Joao Matosdc86f942012-08-31 18:45:21 +000010252/// \brief Get diagnostic %select index for tag kind for
10253/// redeclaration diagnostic message.
10254/// WARNING: Indexes apply to particular diagnostics only!
10255///
10256/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010257static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010258 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010259 case TTK_Struct: return 0;
10260 case TTK_Interface: return 1;
10261 case TTK_Class: return 2;
10262 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010263 }
Joao Matosdc86f942012-08-31 18:45:21 +000010264}
10265
10266/// \brief Determine if tag kind is a class-key compatible with
10267/// class for redeclaration (class, struct, or __interface).
10268///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010269/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010270static bool isClassCompatTagKind(TagTypeKind Tag)
10271{
10272 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10273}
10274
Douglas Gregord9034f02009-05-14 16:41:31 +000010275/// \brief Determine whether a tag with a given kind is acceptable
10276/// as a redeclaration of the given tag declaration.
10277///
10278/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010279bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010280 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010281 SourceLocation NewTagLoc,
10282 const IdentifierInfo &Name) {
10283 // C++ [dcl.type.elab]p3:
10284 // The class-key or enum keyword present in the
10285 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010286 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010287 // refers. This rule also applies to the form of
10288 // elaborated-type-specifier that declares a class-name or
10289 // friend class since it can be construed as referring to the
10290 // definition of the class. Thus, in any
10291 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010292 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010293 // used to refer to a union (clause 9), and either the class or
10294 // struct class-key shall be used to refer to a class (clause 9)
10295 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010296 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010297 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010298 if (OldTag == NewTag)
10299 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010300
Joao Matosdc86f942012-08-31 18:45:21 +000010301 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010302 // Warn about the struct/class tag mismatch.
10303 bool isTemplate = false;
10304 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10305 isTemplate = Record->getDescribedClassTemplate();
10306
Richard Trieucaa33d32011-06-10 03:11:26 +000010307 if (!ActiveTemplateInstantiations.empty()) {
10308 // In a template instantiation, do not offer fix-its for tag mismatches
10309 // since they usually mess up the template instead of fixing the problem.
10310 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010311 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10312 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010313 return true;
10314 }
10315
10316 if (isDefinition) {
10317 // On definitions, check previous tags and issue a fix-it for each
10318 // one that doesn't match the current tag.
10319 if (Previous->getDefinition()) {
10320 // Don't suggest fix-its for redefinitions.
10321 return true;
10322 }
10323
10324 bool previousMismatch = false;
10325 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10326 E(Previous->redecls_end()); I != E; ++I) {
10327 if (I->getTagKind() != NewTag) {
10328 if (!previousMismatch) {
10329 previousMismatch = true;
10330 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010331 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10332 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010333 }
10334 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010335 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010336 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010337 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010338 }
10339 }
10340 return true;
10341 }
10342
10343 // Check for a previous definition. If current tag and definition
10344 // are same type, do nothing. If no definition, but disagree with
10345 // with previous tag type, give a warning, but no fix-it.
10346 const TagDecl *Redecl = Previous->getDefinition() ?
10347 Previous->getDefinition() : Previous;
10348 if (Redecl->getTagKind() == NewTag) {
10349 return true;
10350 }
10351
Douglas Gregord9034f02009-05-14 16:41:31 +000010352 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010353 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10354 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010355 Diag(Redecl->getLocation(), diag::note_previous_use);
10356
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010357 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010358 if (Previous->getDefinition()) {
10359 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010360 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010361 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010362 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010363 }
10364
Douglas Gregord9034f02009-05-14 16:41:31 +000010365 return true;
10366 }
10367 return false;
10368}
10369
Steve Naroff30d242c2007-09-15 18:49:24 +000010370/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010371/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010372/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010373/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010374///
10375/// IsTypeSpecifier is true if this is a type-specifier (or
10376/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010377Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010378 SourceLocation KWLoc, CXXScopeSpec &SS,
10379 IdentifierInfo *Name, SourceLocation NameLoc,
10380 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010381 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010382 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010383 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010384 SourceLocation ScopedEnumKWLoc,
10385 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010386 TypeResult UnderlyingType,
10387 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010388 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010389 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010390 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010391 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010392 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010393
Douglas Gregord6ab8742009-05-28 23:31:59 +000010394 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010395 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010396 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010397
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010398 // FIXME: Check explicit specializations more carefully.
10399 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010400 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010401
10402 // We only need to do this matching if we have template parameters
10403 // or a scope specifier, which also conveniently avoids this work
10404 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010405 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010406 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010407 if (TemplateParameterList *TemplateParams =
10408 MatchTemplateParametersToScopeSpecifier(
10409 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10410 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010411 if (Kind == TTK_Enum) {
10412 Diag(KWLoc, diag::err_enum_template);
10413 return 0;
10414 }
10415
Douglas Gregor3dad8422009-09-26 06:47:28 +000010416 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010417 // This is a declaration or definition of a class template (which may
10418 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010419
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010420 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010421 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010422
Douglas Gregore93e46c2009-07-22 23:48:44 +000010423 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010424 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010425 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010426 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010427 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010428 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010429 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010430 return Result.get();
10431 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010432 // The "template<>" header is extraneous.
10433 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010434 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010435 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010436 }
Mike Stump11289f42009-09-09 15:08:12 +000010437 }
10438 }
10439
Douglas Gregor0bf31402010-10-08 23:50:27 +000010440 // Figure out the underlying type if this a enum declaration. We need to do
10441 // this early, because it's needed to detect if this is an incompatible
10442 // redeclaration.
10443 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10444
10445 if (Kind == TTK_Enum) {
10446 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10447 // No underlying type explicitly specified, or we failed to parse the
10448 // type, default to int.
10449 EnumUnderlying = Context.IntTy.getTypePtr();
10450 else if (UnderlyingType.get()) {
10451 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10452 // integral type; any cv-qualification is ignored.
10453 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010454 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010455 EnumUnderlying = TI;
10456
Richard Smith4b38ded2012-03-14 23:13:10 +000010457 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010458 // Recover by falling back to int.
10459 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010460
Richard Smith4b38ded2012-03-14 23:13:10 +000010461 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010462 UPPC_FixedUnderlyingType))
10463 EnumUnderlying = Context.IntTy.getTypePtr();
10464
Alp Tokerbfa39342014-01-14 12:51:41 +000010465 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010466 // Microsoft enums are always of int type.
10467 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010468 }
10469
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010470 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010471 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010472 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010473
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010474 RedeclarationKind Redecl = ForRedeclaration;
10475 if (TUK == TUK_Friend || TUK == TUK_Reference)
10476 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010477
10478 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010479 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010480 if (Name && SS.isNotEmpty()) {
10481 // We have a nested-name tag ('struct foo::bar').
10482
10483 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010484 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010485 Name = 0;
10486 goto CreateNewDecl;
10487 }
10488
John McCall7f41d982009-09-11 04:59:25 +000010489 // If this is a friend or a reference to a class in a dependent
10490 // context, don't try to make a decl for it.
10491 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10492 DC = computeDeclContext(SS, false);
10493 if (!DC) {
10494 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010495 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010496 }
John McCall0b66eb32010-05-01 00:40:08 +000010497 } else {
10498 DC = computeDeclContext(SS, true);
10499 if (!DC) {
10500 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10501 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010502 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010503 }
John McCall7f41d982009-09-11 04:59:25 +000010504 }
10505
John McCall0b66eb32010-05-01 00:40:08 +000010506 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010507 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010508
Douglas Gregor8761da52009-02-03 00:34:39 +000010509 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010510 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010511 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010512
John McCall1f82f242009-11-18 22:49:29 +000010513 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010514 return 0;
John McCall6538c932009-10-10 05:48:19 +000010515
John McCall1f82f242009-11-18 22:49:29 +000010516 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010517 // Name lookup did not find anything. However, if the
10518 // nested-name-specifier refers to the current instantiation,
10519 // and that current instantiation has any dependent base
10520 // classes, we might find something at instantiation time: treat
10521 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010522 // But this only makes any sense for reference-like lookups.
10523 if (Previous.wasNotFoundInCurrentInstantiation() &&
10524 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010525 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010526 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010527 }
10528
10529 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010530 Diag(NameLoc, diag::err_not_tag_in_scope)
10531 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010532 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010533 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010534 goto CreateNewDecl;
10535 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010536 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010537 // If this is a named struct, check to see if there was a previous forward
10538 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010539 // FIXME: We're looking into outer scopes here, even when we
10540 // shouldn't be. Doing so can result in ambiguities that we
10541 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010542 LookupName(Previous, S);
10543
John McCall3c581bf2013-03-20 01:53:00 +000010544 // When declaring or defining a tag, ignore ambiguities introduced
10545 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010546 if (Previous.isAmbiguous() &&
10547 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010548 LookupResult::Filter F = Previous.makeFilter();
10549 while (F.hasNext()) {
10550 NamedDecl *ND = F.next();
10551 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10552 F.erase();
10553 }
10554 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010555 }
John McCall3c581bf2013-03-20 01:53:00 +000010556
10557 // C++11 [namespace.memdef]p3:
10558 // If the name in a friend declaration is neither qualified nor
10559 // a template-id and the declaration is a function or an
10560 // elaborated-type-specifier, the lookup to determine whether
10561 // the entity has been previously declared shall not consider
10562 // any scopes outside the innermost enclosing namespace.
10563 //
10564 // Does it matter that this should be by scope instead of by
10565 // semantic context?
10566 if (!Previous.empty() && TUK == TUK_Friend) {
10567 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10568 LookupResult::Filter F = Previous.makeFilter();
10569 while (F.hasNext()) {
10570 NamedDecl *ND = F.next();
10571 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010572 if (DC->isFileContext() &&
10573 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010574 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010575 FriendSawTagOutsideEnclosingNamespace = true;
10576 }
John McCall3c581bf2013-03-20 01:53:00 +000010577 }
10578 F.done();
10579 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010580
John McCall1f82f242009-11-18 22:49:29 +000010581 // Note: there used to be some attempt at recovery here.
10582 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010583 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010584
David Blaikiebbafb8a2012-03-11 07:00:24 +000010585 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010586 // FIXME: This makes sure that we ignore the contexts associated
10587 // with C structs, unions, and enums when looking for a matching
10588 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010589 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010590 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10591 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010592 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010593 } else if (S->isFunctionPrototypeScope()) {
10594 // If this is an enum declaration in function prototype scope, set its
10595 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010596 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010597 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010598 }
10599
John McCall1f82f242009-11-18 22:49:29 +000010600 if (Previous.isSingleResult() &&
10601 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010602 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010603 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010604 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010605 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010606 }
10607
David Blaikiebbafb8a2012-03-11 07:00:24 +000010608 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010609 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010610 // This is a declaration of or a reference to "std::bad_alloc".
10611 isStdBadAlloc = true;
10612
John McCall1f82f242009-11-18 22:49:29 +000010613 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010614 // std::bad_alloc has been implicitly declared (but made invisible to
10615 // name lookup). Fill in this implicit declaration as the previous
10616 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010617 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010618 }
10619 }
John McCall1f82f242009-11-18 22:49:29 +000010620
John McCalle9eaf8e2010-03-25 21:28:06 +000010621 // If we didn't find a previous declaration, and this is a reference
10622 // (or friend reference), move to the correct scope. In C++, we
10623 // also need to do a redeclaration lookup there, just in case
10624 // there's a shadow friend decl.
10625 if (Name && Previous.empty() &&
10626 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10627 if (Invalid) goto CreateNewDecl;
10628 assert(SS.isEmpty());
10629
10630 if (TUK == TUK_Reference) {
10631 // C++ [basic.scope.pdecl]p5:
10632 // -- for an elaborated-type-specifier of the form
10633 //
10634 // class-key identifier
10635 //
10636 // if the elaborated-type-specifier is used in the
10637 // decl-specifier-seq or parameter-declaration-clause of a
10638 // function defined in namespace scope, the identifier is
10639 // declared as a class-name in the namespace that contains
10640 // the declaration; otherwise, except as a friend
10641 // declaration, the identifier is declared in the smallest
10642 // non-class, non-function-prototype scope that contains the
10643 // declaration.
10644 //
10645 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10646 // C structs and unions.
10647 //
10648 // It is an error in C++ to declare (rather than define) an enum
10649 // type, including via an elaborated type specifier. We'll
10650 // diagnose that later; for now, declare the enum in the same
10651 // scope as we would have picked for any other tag type.
10652 //
10653 // GNU C also supports this behavior as part of its incomplete
10654 // enum types extension, while GNU C++ does not.
10655 //
10656 // Find the context where we'll be declaring the tag.
10657 // FIXME: We would like to maintain the current DeclContext as the
10658 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010659 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010660 SearchDC = SearchDC->getParent();
10661
10662 // Find the scope where we'll be declaring the tag.
10663 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010664 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010665 S->isFunctionPrototypeScope()) ||
10666 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010667 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010668 S = S->getParent();
10669 } else {
10670 assert(TUK == TUK_Friend);
10671 // C++ [namespace.memdef]p3:
10672 // If a friend declaration in a non-local class first declares a
10673 // class or function, the friend class or function is a member of
10674 // the innermost enclosing namespace.
10675 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010676 }
10677
John McCalle87beb22010-04-23 18:46:30 +000010678 // In C++, we need to do a redeclaration lookup to properly
10679 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010680 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010681 Previous.setRedeclarationKind(ForRedeclaration);
10682 LookupQualifiedName(Previous, SearchDC);
10683 }
10684 }
10685
John McCall1f82f242009-11-18 22:49:29 +000010686 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010687 NamedDecl *PrevDecl = Previous.getFoundDecl();
10688 NamedDecl *DirectPrevDecl =
10689 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010690
10691 // It's okay to have a tag decl in the same scope as a typedef
10692 // which hides a tag decl in the same scope. Finding this
10693 // insanity with a redeclaration lookup can only actually happen
10694 // in C++.
10695 //
10696 // This is also okay for elaborated-type-specifiers, which is
10697 // technically forbidden by the current standard but which is
10698 // okay according to the likely resolution of an open issue;
10699 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010700 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010701 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010702 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10703 TagDecl *Tag = TT->getDecl();
10704 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010705 Tag->getDeclContext()->getRedeclContext()
10706 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010707 PrevDecl = Tag;
10708 Previous.clear();
10709 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010710 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010711 }
10712 }
10713 }
10714 }
10715
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010716 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010717 // If this is a use of a previous tag, or if the tag is already declared
10718 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010719 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010720 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010721 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010722 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010723 // Make sure that this wasn't declared as an enum and now used as a
10724 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010725 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10726 TUK == TUK_Definition, KWLoc,
10727 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010728 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010729 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10730 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010731 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010732 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010733 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010734 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10735 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010736 else
10737 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010738 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010739
Mike Stump11289f42009-09-09 15:08:12 +000010740 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010741 Kind = PrevTagDecl->getTagKind();
10742 else {
10743 // Recover by making this an anonymous redefinition.
10744 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010745 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010746 Invalid = true;
10747 }
10748 }
10749
Douglas Gregor0bf31402010-10-08 23:50:27 +000010750 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10751 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10752
Richard Smith0f8ee222012-01-10 01:33:14 +000010753 // If this is an elaborated-type-specifier for a scoped enumeration,
10754 // the 'class' keyword is not necessary and not permitted.
10755 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10756 if (ScopedEnum)
10757 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10758 << PrevEnum->isScoped()
10759 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10760 return PrevTagDecl;
10761 }
10762
Richard Smith4b38ded2012-03-14 23:13:10 +000010763 QualType EnumUnderlyingTy;
10764 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010765 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010766 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10767 EnumUnderlyingTy = QualType(T, 0);
10768
Douglas Gregor0bf31402010-10-08 23:50:27 +000010769 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010770 // returning the previous declaration, unless this is a definition,
10771 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010772 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10773 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010774 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010775 }
10776
David Majnemer55890bf2013-06-11 03:51:23 +000010777 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010778 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010779 // except that a nested class or member class template can be declared
10780 // and then later defined.
10781 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10782 S->isDeclScope(PrevDecl)) {
10783 Diag(NameLoc, diag::ext_member_redeclared);
10784 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10785 }
10786
Douglas Gregor170512f2009-04-01 23:51:29 +000010787 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010788 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010789
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010790 // FIXME: In the future, return a variant or some other clue
10791 // for the consumer of this Decl to know it doesn't own it.
10792 // For our current ASTs this shouldn't be a problem, but will
10793 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010794 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010795 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010796 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010797
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010798 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010799 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010800 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010801 // If we're defining a specialization and the previous definition
10802 // is from an implicit instantiation, don't emit an error
10803 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010804 bool IsExplicitSpecializationAfterInstantiation = false;
10805 if (isExplicitSpecialization) {
10806 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10807 IsExplicitSpecializationAfterInstantiation =
10808 RD->getTemplateSpecializationKind() !=
10809 TSK_ExplicitSpecialization;
10810 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10811 IsExplicitSpecializationAfterInstantiation =
10812 ED->getTemplateSpecializationKind() !=
10813 TSK_ExplicitSpecialization;
10814 }
10815
10816 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010817 // A redeclaration in function prototype scope in C isn't
10818 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010819 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010820 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10821 else
10822 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010823 Diag(Def->getLocation(), diag::note_previous_definition);
10824 // If this is a redefinition, recover by making this
10825 // struct be anonymous, which will make any later
10826 // references get the previous definition.
10827 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010828 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010829 Invalid = true;
10830 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010831 } else {
10832 // If the type is currently being defined, complain
10833 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010834 const TagType *Tag
10835 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010836 if (Tag->isBeingDefined()) {
10837 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010838 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010839 diag::note_previous_definition);
10840 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010841 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010842 Invalid = true;
10843 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010844 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010845
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010846 // Okay, this is definition of a previously declared or referenced
10847 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010848 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010849 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010850 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010851 // have a definition. Just create a new decl.
10852
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010853 } else {
10854 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010855 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010856 // new decl/type. We set PrevDecl to NULL so that the entities
10857 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010858 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010859 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010860 // If we get here, we're going to create a new Decl. If PrevDecl
10861 // is non-NULL, it's a definition of the tag declared by
10862 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010863
10864
10865 // Otherwise, PrevDecl is not a tag, but was found with tag
10866 // lookup. This is only actually possible in C++, where a few
10867 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010868 } else {
John McCalle87beb22010-04-23 18:46:30 +000010869 // Use a better diagnostic if an elaborated-type-specifier
10870 // found the wrong kind of type on the first
10871 // (non-redeclaration) lookup.
10872 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10873 !Previous.isForRedeclaration()) {
10874 unsigned Kind = 0;
10875 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010876 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10877 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010878 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10879 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10880 Invalid = true;
10881
10882 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010883 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10884 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010885 // do nothing
10886
10887 // Diagnose implicit declarations introduced by elaborated types.
10888 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10889 unsigned Kind = 0;
10890 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010891 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10892 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010893 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10894 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10895 Invalid = true;
10896
10897 // Otherwise it's a declaration. Call out a particularly common
10898 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010899 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10900 unsigned Kind = 0;
10901 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010902 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010903 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010904 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10905 Invalid = true;
10906
10907 // Otherwise, diagnose.
10908 } else {
10909 // The tag name clashes with something else in the target scope,
10910 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010911 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010912 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010913 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010914 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010915 }
John McCalle87beb22010-04-23 18:46:30 +000010916
10917 // The existing declaration isn't relevant to us; we're in a
10918 // new scope, so clear out the previous declaration.
10919 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010920 }
Chris Lattner18b19622007-01-22 07:39:13 +000010921 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010922
Chris Lattner438e5012008-12-17 07:13:27 +000010923CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010924
John McCall1f82f242009-11-18 22:49:29 +000010925 TagDecl *PrevDecl = 0;
10926 if (Previous.isSingleResult())
10927 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10928
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010929 // If there is an identifier, use the location of the identifier as the
10930 // location of the decl, otherwise use the location of the struct/union
10931 // keyword.
10932 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010933
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010934 // Otherwise, create a new declaration. If there is a previous
10935 // declaration of the same entity, the two will be linked via
10936 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010937 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010938
Douglas Gregor0bf31402010-10-08 23:50:27 +000010939 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010940 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010941 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10942 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010943 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010944 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010945 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010946 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010947 if (TUK != TUK_Definition && !Invalid) {
10948 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010949 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10950 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010951 // C++0x: 7.2p2: opaque-enum-declaration.
10952 // Conflicts are diagnosed above. Do nothing.
10953 }
10954 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010955 Diag(Loc, diag::ext_forward_ref_enum_def)
10956 << New;
10957 Diag(Def->getLocation(), diag::note_previous_definition);
10958 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010959 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000010960 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000010961 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010962 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010963 DiagID = diag::err_forward_ref_enum;
10964 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010965
10966 // If this is a forward-declared reference to an enumeration, make a
10967 // note of it; we won't actually be introducing the declaration into
10968 // the declaration context.
10969 if (TUK == TUK_Reference)
10970 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010971 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010972 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010973
10974 if (EnumUnderlying) {
10975 EnumDecl *ED = cast<EnumDecl>(New);
10976 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10977 ED->setIntegerTypeSourceInfo(TI);
10978 else
10979 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10980 ED->setPromotionType(ED->getIntegerType());
10981 }
10982
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010983 } else {
10984 // struct/union/class
10985
Chris Lattner776fac82007-06-09 00:53:06 +000010986 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10987 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010988 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010989 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010990 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010991 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010992
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010993 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010994 StdBadAlloc = cast<CXXRecordDecl>(New);
10995 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010996 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010997 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000010998 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010999
Richard Smith649c7b062014-01-08 00:56:48 +000011000 // C++11 [dcl.type]p3:
11001 // A type-specifier-seq shall not define a class or enumeration [...].
11002 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11003 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11004 << Context.getTagDeclType(New);
11005 Invalid = true;
11006 }
11007
John McCall3e11ebe2010-03-15 10:12:16 +000011008 // Maybe add qualifier info.
11009 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011010 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011011 // If this is either a declaration or a definition, check the
11012 // nested-name-specifier against the current context. We don't do this
11013 // for explicit specializations, because they have similar checking
11014 // (with more specific diagnostics) in the call to
11015 // CheckMemberSpecialization, below.
11016 if (!isExplicitSpecialization &&
11017 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11018 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11019 Invalid = true;
11020
Douglas Gregor14454802011-02-25 02:25:35 +000011021 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011022 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011023 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011024 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011025 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011026 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011027 }
11028 else
11029 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011030 }
11031
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011032 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11033 // Add alignment attributes if necessary; these attributes are checked when
11034 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011035 //
11036 // It is important for implementing the correct semantics that this
11037 // happen here (in act on tag decl). The #pragma pack stack is
11038 // maintained as a result of parser callbacks which can occur at
11039 // many points during the parsing of a struct declaration (because
11040 // the #pragma tokens are effectively skipped over during the
11041 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011042 if (TUK == TUK_Definition) {
11043 AddAlignmentAttributesForRecord(RD);
11044 AddMsStructLayoutForRecord(RD);
11045 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011046 }
11047
Douglas Gregor21823bf2011-12-20 18:11:52 +000011048 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011049 if (isExplicitSpecialization)
11050 Diag(New->getLocation(), diag::err_module_private_specialization)
11051 << 2
11052 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011053 // __module_private__ does not apply to local classes. However, we only
11054 // diagnose this as an error when the declaration specifiers are
11055 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011056 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011057 New->setModulePrivate();
11058 }
11059
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011060 // If this is a specialization of a member class (of a class template),
11061 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011062 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011063 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011064
Douglas Gregordee1be82009-01-17 00:42:38 +000011065 if (Invalid)
11066 New->setInvalidDecl();
11067
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011068 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011069 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011070
Douglas Gregordee1be82009-01-17 00:42:38 +000011071 // If we're declaring or defining a tag in function prototype scope
11072 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011073 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +000011074 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11075
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011076 // Set the lexical context. If the tag has a C++ scope specifier, the
11077 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011078 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011079
John McCallaa74a0c2009-08-28 07:59:38 +000011080 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011081 // In Microsoft mode, a friend declaration also acts as a forward
11082 // declaration so we always pass true to setObjectOfFriendDecl to make
11083 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011084 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011085 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11086 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011087
Anders Carlsson5558ca12009-03-26 01:19:02 +000011088 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011089 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011090 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011091
John McCall9bb74a52009-07-31 02:45:11 +000011092 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011093 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011094
Chris Lattner18b19622007-01-22 07:39:13 +000011095 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011096 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011097 // We might be replacing an existing declaration in the lookup tables;
11098 // if so, borrow its access specifier.
11099 if (PrevDecl)
11100 New->setAccess(PrevDecl->getAccess());
11101
Sebastian Redl50c68252010-08-31 00:36:30 +000011102 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011103 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011104 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011105 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11106 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011107 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011108 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011109 PushOnScopeChains(New, S, !IsForwardReference);
11110 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011111 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011112
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011113 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011114 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011115 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011116
Douglas Gregor27821ce2009-07-07 16:35:42 +000011117 // If this is the C FILE type, notify the AST context.
11118 if (IdentifierInfo *II = New->getIdentifier())
11119 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011120 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011121 II->isStr("FILE"))
11122 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011123
James Molloy6f8780b2012-02-29 10:24:19 +000011124 // If we were in function prototype scope (and not in C++ mode), add this
11125 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011126 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +000011127 InFunctionDeclarator && Name)
11128 DeclsInPrototypeScope.push_back(New);
11129
Rafael Espindolac67f2232012-05-10 02:50:16 +000011130 if (PrevDecl)
11131 mergeDeclAttributes(New, PrevDecl);
11132
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011133 // If there's a #pragma GCC visibility in scope, set the visibility of this
11134 // record.
11135 AddPushedVisibilityAttribute(New);
11136
Douglas Gregord6ab8742009-05-28 23:31:59 +000011137 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011138 // In C++, don't return an invalid declaration. We can't recover well from
11139 // the cases where we make the type anonymous.
11140 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011141}
Chris Lattner1300fb92007-01-23 23:42:53 +000011142
John McCall48871652010-08-21 09:40:31 +000011143void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011144 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011145 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011146
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011147 // Enter the tag context.
11148 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011149
11150 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011151
11152 // If there's a #pragma GCC visibility in scope, set the visibility of this
11153 // record.
11154 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011155}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011156
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011157Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011158 assert(isa<ObjCContainerDecl>(IDecl) &&
11159 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11160 DeclContext *OCD = cast<DeclContext>(IDecl);
11161 assert(getContainingDC(OCD) == CurContext &&
11162 "The next DeclContext should be lexically contained in the current one.");
11163 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011164 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011165}
11166
John McCall48871652010-08-21 09:40:31 +000011167void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011168 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011169 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011170 SourceLocation LBraceLoc) {
11171 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011172 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011173
John McCall1c7e6ec2009-12-20 07:58:13 +000011174 FieldCollector->StartClass();
11175
11176 if (!Record->getIdentifier())
11177 return;
11178
Anders Carlsson30f29442011-03-25 14:31:08 +000011179 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011180 Record->addAttr(new (Context)
11181 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11182
John McCall1c7e6ec2009-12-20 07:58:13 +000011183 // C++ [class]p2:
11184 // [...] The class-name is also inserted into the scope of the
11185 // class itself; this is known as the injected-class-name. For
11186 // purposes of access checking, the injected-class-name is treated
11187 // as if it were a public member name.
11188 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011189 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11190 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011191 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011192 /*PrevDecl=*/0,
11193 /*DelayTypeCreation=*/true);
11194 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011195 InjectedClassName->setImplicit();
11196 InjectedClassName->setAccess(AS_public);
11197 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11198 InjectedClassName->setDescribedClassTemplate(Template);
11199 PushOnScopeChains(InjectedClassName, S);
11200 assert(InjectedClassName->isInjectedClassName() &&
11201 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011202}
11203
John McCall48871652010-08-21 09:40:31 +000011204void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011205 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011206 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011207 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011208 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011209
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011210 // Make sure we "complete" the definition even it is invalid.
11211 if (Tag->isBeingDefined()) {
11212 assert(Tag->isInvalidDecl() && "We should already have completed it");
11213 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11214 RD->completeDefinition();
11215 }
11216
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011217 if (isa<CXXRecordDecl>(Tag))
11218 FieldCollector->FinishClass();
11219
11220 // Exit this scope of this tag's definition.
11221 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011222
11223 if (getCurLexicalContext()->isObjCContainer() &&
11224 Tag->getDeclContext()->isFileContext())
11225 Tag->setTopLevelDeclInObjCContainer();
11226
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011227 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011228 if (!Tag->isInvalidDecl())
11229 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011230}
Chris Lattner535b8302008-06-21 19:39:06 +000011231
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011232void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011233 // Exit this scope of this interface definition.
11234 PopDeclContext();
11235}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011236
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011237void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011238 assert(DC == CurContext && "Mismatch of container contexts");
11239 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011240 ActOnObjCContainerFinishDefinition();
11241}
11242
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011243void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11244 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011245 OriginalLexicalContext = 0;
11246}
11247
John McCall48871652010-08-21 09:40:31 +000011248void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011249 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011250 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011251 Tag->setInvalidDecl();
11252
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011253 // Make sure we "complete" the definition even it is invalid.
11254 if (Tag->isBeingDefined()) {
11255 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11256 RD->completeDefinition();
11257 }
11258
John McCall71ba5f22010-03-17 19:25:57 +000011259 // We're undoing ActOnTagStartDefinition here, not
11260 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11261 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011262
11263 PopDeclContext();
11264}
11265
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011266// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011267ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11268 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011269 QualType FieldTy, bool IsMsStruct,
11270 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011271 // Default to true; that shouldn't confuse checks for emptiness
11272 if (ZeroWidth)
11273 *ZeroWidth = true;
11274
Chris Lattner73bf7b42009-03-05 22:45:59 +000011275 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011276 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011277 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011278 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011279 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011280 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011281 if (FieldName)
11282 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11283 << FieldName << FieldTy << BitWidth->getSourceRange();
11284 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11285 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011286 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11287 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011288 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011289
11290 // If the bit-width is type- or value-dependent, don't try to check
11291 // it now.
11292 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011293 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011294
Anders Carlsson5df391e2008-12-06 20:33:04 +000011295 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011296 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11297 if (ICE.isInvalid())
11298 return ICE;
11299 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011300
Eli Friedmanc96d4962009-08-15 21:55:26 +000011301 if (Value != 0 && ZeroWidth)
11302 *ZeroWidth = false;
11303
Chris Lattner81ed6802008-12-12 04:56:04 +000011304 // Zero-width bitfield is ok for anonymous field.
11305 if (Value == 0 && FieldName)
11306 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011307
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011308 if (Value.isSigned() && Value.isNegative()) {
11309 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011310 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011311 << FieldName << Value.toString(10);
11312 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11313 << Value.toString(10);
11314 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011315
Douglas Gregor1efa4372009-03-11 18:59:21 +000011316 if (!FieldTy->isDependentType()) {
11317 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011318 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011319 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11320 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011321 if (FieldName)
11322 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11323 << FieldName << (unsigned)Value.getZExtValue()
11324 << (unsigned)TypeSize;
11325
11326 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11327 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11328 }
11329
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011330 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011331 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11332 << FieldName << (unsigned)Value.getZExtValue()
11333 << (unsigned)TypeSize;
11334 else
11335 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11336 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011337 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011338 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011339
Richard Smithf4c51d92012-02-04 09:53:13 +000011340 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011341}
11342
Richard Smith938f40b2011-06-11 17:19:42 +000011343/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011344/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011345Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011346 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011347 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011348 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011349 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011350 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011351}
11352
11353/// HandleField - Analyze a field of a C struct or a C++ data member.
11354///
11355FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11356 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011357 Declarator &D, Expr *BitWidth,
11358 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011359 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011360 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011361 SourceLocation Loc = DeclStart;
11362 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011363
John McCall8cb7bdf2010-06-04 23:28:52 +000011364 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11365 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011366 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011367 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011368
Douglas Gregora02a72a2010-12-15 23:18:36 +000011369 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11370 UPPC_DataMemberType)) {
11371 D.setInvalidType();
11372 T = Context.IntTy;
11373 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11374 }
11375 }
11376
Matt Arsenault376f7202013-02-26 21:16:00 +000011377 // TR 18037 does not allow fields to be declared with address spaces.
11378 if (T.getQualifiers().hasAddressSpace()) {
11379 Diag(Loc, diag::err_field_with_address_space);
11380 D.setInvalidType();
11381 }
11382
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011383 // OpenCL 1.2 spec, s6.9 r:
11384 // The event type cannot be used to declare a structure or union field.
11385 if (LangOpts.OpenCL && T->isEventT()) {
11386 Diag(Loc, diag::err_event_t_struct_field);
11387 D.setInvalidType();
11388 }
11389
Richard Smithb1402ae2013-03-18 22:52:47 +000011390 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011391
Richard Smithb4a9e862013-04-12 22:46:28 +000011392 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11393 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11394 diag::err_invalid_thread)
11395 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011396
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011397 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011398 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011399 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11400 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011401 switch (Previous.getResultKind()) {
11402 case LookupResult::Found:
11403 case LookupResult::FoundUnresolvedValue:
11404 PrevDecl = Previous.getAsSingle<NamedDecl>();
11405 break;
11406
11407 case LookupResult::FoundOverloaded:
11408 PrevDecl = Previous.getRepresentativeDecl();
11409 break;
11410
11411 case LookupResult::NotFound:
11412 case LookupResult::NotFoundInCurrentInstantiation:
11413 case LookupResult::Ambiguous:
11414 break;
11415 }
11416 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011417
11418 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11419 // Maybe we will complain about the shadowed template parameter.
11420 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11421 // Just pretend that we didn't see the previous declaration.
11422 PrevDecl = 0;
11423 }
11424
Douglas Gregor1efa4372009-03-11 18:59:21 +000011425 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11426 PrevDecl = 0;
11427
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011428 bool Mutable
11429 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011430 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011431 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011432 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011433 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011434
11435 if (NewFD->isInvalidDecl())
11436 Record->setInvalidDecl();
11437
Douglas Gregor3baa6702011-09-12 16:11:24 +000011438 if (D.getDeclSpec().isModulePrivateSpecified())
11439 NewFD->setModulePrivate();
11440
Douglas Gregor1efa4372009-03-11 18:59:21 +000011441 if (NewFD->isInvalidDecl() && PrevDecl) {
11442 // Don't introduce NewFD into scope; there's already something
11443 // with the same name in the same scope.
11444 } else if (II) {
11445 PushOnScopeChains(NewFD, S);
11446 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011447 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011448
11449 return NewFD;
11450}
11451
11452/// \brief Build a new FieldDecl and check its well-formedness.
11453///
11454/// This routine builds a new FieldDecl given the fields name, type,
11455/// record, etc. \p PrevDecl should refer to any previous declaration
11456/// with the same name and in the same scope as the field to be
11457/// created.
11458///
11459/// \returns a new FieldDecl.
11460///
Mike Stump11289f42009-09-09 15:08:12 +000011461/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011462FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011463 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011464 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011465 bool Mutable, Expr *BitWidth,
11466 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011467 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011468 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011469 Declarator *D) {
11470 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011471 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011472 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011473
Douglas Gregor1efa4372009-03-11 18:59:21 +000011474 // If we receive a broken type, recover by assuming 'int' and
11475 // marking this declaration as invalid.
11476 if (T.isNull()) {
11477 InvalidDecl = true;
11478 T = Context.IntTy;
11479 }
11480
Eli Friedmand0e8de22009-12-07 00:22:08 +000011481 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011482 if (!EltTy->isDependentType()) {
11483 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11484 // Fields of incomplete type force their record to be invalid.
11485 Record->setInvalidDecl();
11486 InvalidDecl = true;
11487 } else {
11488 NamedDecl *Def;
11489 EltTy->isIncompleteType(&Def);
11490 if (Def && Def->isInvalidDecl()) {
11491 Record->setInvalidDecl();
11492 InvalidDecl = true;
11493 }
11494 }
John McCall2677e102010-08-16 23:42:35 +000011495 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011496
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011497 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11498 if (BitWidth && getLangOpts().OpenCL) {
11499 Diag(Loc, diag::err_opencl_bitfields);
11500 InvalidDecl = true;
11501 }
11502
Steve Naroff8eeeb132007-05-08 21:09:37 +000011503 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11504 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011505 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011506 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011507 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011508
11509 TypeSourceInfo *FixedTInfo =
11510 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11511 SizeIsNegative,
11512 Oversized);
11513 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011514 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011515 TInfo = FixedTInfo;
11516 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011517 } else {
11518 if (SizeIsNegative)
11519 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011520 else if (Oversized.getBoolValue())
11521 Diag(Loc, diag::err_array_too_large)
11522 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011523 else
11524 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011525 InvalidDecl = true;
11526 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011527 }
Mike Stump11289f42009-09-09 15:08:12 +000011528
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011529 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011530 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11531 diag::err_abstract_type_in_decl,
11532 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011533 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011534
Eli Friedmanc96d4962009-08-15 21:55:26 +000011535 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011536 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011537 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011538 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11539 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011540 if (!BitWidth) {
11541 InvalidDecl = true;
11542 BitWidth = 0;
11543 ZeroWidth = false;
11544 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011545 }
Mike Stump11289f42009-09-09 15:08:12 +000011546
John McCallb1cd7da2010-06-04 08:34:12 +000011547 // Check that 'mutable' is consistent with the type of the declaration.
11548 if (!InvalidDecl && Mutable) {
11549 unsigned DiagID = 0;
11550 if (T->isReferenceType())
11551 DiagID = diag::err_mutable_reference;
11552 else if (T.isConstQualified())
11553 DiagID = diag::err_mutable_const;
11554
11555 if (DiagID) {
11556 SourceLocation ErrLoc = Loc;
11557 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11558 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11559 Diag(ErrLoc, DiagID);
11560 Mutable = false;
11561 InvalidDecl = true;
11562 }
11563 }
11564
Richard Smithab44d5b2013-12-10 08:25:00 +000011565 // C++11 [class.union]p8 (DR1460):
11566 // At most one variant member of a union may have a
11567 // brace-or-equal-initializer.
11568 if (InitStyle != ICIS_NoInit)
11569 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11570
Abramo Bagnaradff19302011-03-08 08:55:46 +000011571 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011572 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011573 if (InvalidDecl)
11574 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011575
Douglas Gregor1efa4372009-03-11 18:59:21 +000011576 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11577 Diag(Loc, diag::err_duplicate_member) << II;
11578 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11579 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011580 }
11581
David Blaikiebbafb8a2012-03-11 07:00:24 +000011582 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011583 if (Record->isUnion()) {
11584 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11585 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11586 if (RDecl->getDefinition()) {
11587 // C++ [class.union]p1: An object of a class with a non-trivial
11588 // constructor, a non-trivial copy constructor, a non-trivial
11589 // destructor, or a non-trivial copy assignment operator
11590 // cannot be a member of a union, nor can an array of such
11591 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011592 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011593 NewFD->setInvalidDecl();
11594 }
11595 }
11596
11597 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011598 // the program is ill-formed, except when compiling with MSVC extensions
11599 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011600 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011601 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11602 diag::ext_union_member_of_reference_type :
11603 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011604 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011605 if (!getLangOpts().MicrosoftExt)
11606 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011607 }
11608 }
11609 }
11610
Douglas Gregor1efa4372009-03-11 18:59:21 +000011611 // FIXME: We need to pass in the attributes given an AST
11612 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011613 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011614 // FIXME: The current scope is almost... but not entirely... correct here.
11615 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011616
Richard Smith848e1f12013-02-01 08:12:08 +000011617 if (NewFD->hasAttrs())
11618 CheckAlignasUnderalignment(NewFD);
11619 }
11620
John McCall31168b02011-06-15 23:02:42 +000011621 // In auto-retain/release, infer strong retension for fields of
11622 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011623 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011624 NewFD->setInvalidDecl();
11625
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011626 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011627 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011628
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011629 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011630 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011631}
11632
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011633bool Sema::CheckNontrivialField(FieldDecl *FD) {
11634 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011635 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011636
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011637 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11638 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011639
11640 QualType EltTy = Context.getBaseElementType(FD->getType());
11641 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011642 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011643 if (RDecl->getDefinition()) {
11644 // We check for copy constructors before constructors
11645 // because otherwise we'll never get complaints about
11646 // copy constructors.
11647
11648 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011649 // We're required to check for any non-trivial constructors. Since the
11650 // implicit default constructor is suppressed if there are any
11651 // user-declared constructors, we just need to check that there is a
11652 // trivial default constructor and a trivial copy constructor. (We don't
11653 // worry about move constructors here, since this is a C++98 check.)
11654 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011655 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011656 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011657 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011658 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011659 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011660 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011661 member = CXXDestructor;
11662
11663 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011664 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011665 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011666 // Objective-C++ ARC: it is an error to have a non-trivial field of
11667 // a union. However, system headers in Objective-C programs
11668 // occasionally have Objective-C lifetime objects within unions,
11669 // and rather than cause the program to fail, we make those
11670 // members unavailable.
11671 SourceLocation Loc = FD->getLocation();
11672 if (getSourceManager().isInSystemHeader(Loc)) {
11673 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011674 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11675 "this system field has retaining ownership",
11676 Loc));
John McCall31168b02011-06-15 23:02:42 +000011677 return false;
11678 }
11679 }
Richard Smithf720df02011-10-19 20:41:51 +000011680
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011681 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011682 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11683 diag::err_illegal_union_or_anon_struct_member)
11684 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011685 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011686 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011687 }
11688 }
11689 }
Richard Smith92f241f2012-12-08 02:53:02 +000011690
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011691 return false;
11692}
11693
Mike Stump11289f42009-09-09 15:08:12 +000011694/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011695/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011696static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011697TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011698 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011699 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011700 case tok::objc_private: return ObjCIvarDecl::Private;
11701 case tok::objc_public: return ObjCIvarDecl::Public;
11702 case tok::objc_protected: return ObjCIvarDecl::Protected;
11703 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011704 }
11705}
11706
Mike Stump11289f42009-09-09 15:08:12 +000011707/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011708/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011709Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011710 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011711 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011712 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011713
Fariborz Jahaniande615832008-04-10 23:32:45 +000011714 IdentifierInfo *II = D.getIdentifier();
11715 Expr *BitWidth = (Expr*)BitfieldWidth;
11716 SourceLocation Loc = DeclStart;
11717 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011718
Fariborz Jahaniande615832008-04-10 23:32:45 +000011719 // FIXME: Unnamed fields can be handled in various different ways, for
11720 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011721
John McCall8cb7bdf2010-06-04 23:28:52 +000011722 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11723 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011724
Fariborz Jahaniande615832008-04-10 23:32:45 +000011725 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011726 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011727 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011728 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011729 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011730 } else {
11731 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011732
Fariborz Jahaniande615832008-04-10 23:32:45 +000011733 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011734
Fariborz Jahaniande615832008-04-10 23:32:45 +000011735 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011736 if (T->isReferenceType()) {
11737 Diag(Loc, diag::err_ivar_reference_type);
11738 D.setInvalidType();
11739 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011740 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11741 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011742 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011743 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011744 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011745 }
Mike Stump11289f42009-09-09 15:08:12 +000011746
Ted Kremenek73295fa2008-07-23 18:04:17 +000011747 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011748 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011749 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11750 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011751 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011752 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011753 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11754 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011755 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011756 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011757 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011758 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011759 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011760 EnclosingContext = IMPDecl->getClassInterface();
11761 assert(EnclosingContext && "Implementation has no class interface!");
11762 }
11763 else
11764 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011765 } else {
11766 if (ObjCCategoryDecl *CDecl =
11767 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011768 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011769 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011770 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011771 }
11772 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011773 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011774 }
Mike Stump11289f42009-09-09 15:08:12 +000011775
Ted Kremenek73295fa2008-07-23 18:04:17 +000011776 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011777 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11778 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011779 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011780
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011781 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011782 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011783 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011784 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011785 && !isa<TagDecl>(PrevDecl)) {
11786 Diag(Loc, diag::err_duplicate_member) << II;
11787 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11788 NewID->setInvalidDecl();
11789 }
11790 }
11791
Ted Kremenek73295fa2008-07-23 18:04:17 +000011792 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011793 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011794
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011795 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011796 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011797
John McCall31168b02011-06-15 23:02:42 +000011798 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011799 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011800 NewID->setInvalidDecl();
11801
Douglas Gregor3baa6702011-09-12 16:11:24 +000011802 if (D.getDeclSpec().isModulePrivateSpecified())
11803 NewID->setModulePrivate();
11804
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011805 if (II) {
11806 // FIXME: When interfaces are DeclContexts, we'll need to add
11807 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011808 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011809 IdResolver.AddDecl(NewID);
11810 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011811
John McCall5fb5df92012-06-20 06:18:46 +000011812 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011813 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011814 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011815
John McCall48871652010-08-21 09:40:31 +000011816 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011817}
11818
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011819/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011820/// class and class extensions. For every class \@interface and class
11821/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011822/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011823void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011824 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011825 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011826 return;
11827
11828 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11829 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11830
Richard Smithcaf33902011-10-10 18:28:20 +000011831 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011832 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011833 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011834 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011835 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011836 if (!CD->IsClassExtension())
11837 return;
11838 }
11839 // No need to add this to end of @implementation.
11840 else
11841 return;
11842 }
11843 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011844 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11845 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011846
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011847 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011848 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011849 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011850 Context.getTrivialTypeSourceInfo(Context.CharTy,
11851 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011852 ObjCIvarDecl::Private, BW,
11853 true);
11854 AllIvarDecls.push_back(Ivar);
11855}
11856
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011857void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11858 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11859 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011860 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011861
Eric Christopher7457aaf2012-07-19 22:22:51 +000011862 // If this is an Objective-C @implementation or category and we have
11863 // new fields here we should reset the layout of the interface since
11864 // it will now change.
11865 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11866 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11867 switch (DC->getKind()) {
11868 default: break;
11869 case Decl::ObjCCategory:
11870 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11871 break;
11872 case Decl::ObjCImplementation:
11873 Context.
11874 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11875 break;
11876 }
11877 }
11878
Eli Friedmana7679412012-02-07 05:00:47 +000011879 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11880
11881 // Start counting up the number of named members; make sure to include
11882 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011883 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011884 if (Record) {
11885 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11886 e = Record->decls_end(); i != e; i++) {
11887 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11888 if (IFD->getDeclName())
11889 ++NumNamedMembers;
11890 }
11891 }
11892
11893 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011894 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011895
John McCall31168b02011-06-15 23:02:42 +000011896 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011897 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011898 i != end; ++i) {
11899 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011900
Chris Lattner720a0542007-01-25 00:44:24 +000011901 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011902 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011903
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011904 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011905 // Remember all fields written by the user.
11906 RecFields.push_back(FD);
11907 }
Mike Stump11289f42009-09-09 15:08:12 +000011908
Chris Lattner73bf7b42009-03-05 22:45:59 +000011909 // If the field is already invalid for some reason, don't emit more
11910 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011911 if (FD->isInvalidDecl()) {
11912 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011913 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011914 }
Mike Stump11289f42009-09-09 15:08:12 +000011915
Douglas Gregorac1fb652009-03-24 19:52:54 +000011916 // C99 6.7.2.1p2:
11917 // A structure or union shall not contain a member with
11918 // incomplete or function type (hence, a structure shall not
11919 // contain an instance of itself, but may contain a pointer to
11920 // an instance of itself), except that the last member of a
11921 // structure with more than one named member may have incomplete
11922 // array type; such a structure (and any union containing,
11923 // possibly recursively, a member that is such a structure)
11924 // shall not be a member of a structure or an element of an
11925 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011926 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011927 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011928 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011929 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011930 FD->setInvalidDecl();
11931 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011932 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011933 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011934 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011935 ((getLangOpts().MicrosoftExt ||
11936 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011937 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011938 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011939 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011940 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011941 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011942 unsigned DiagID = 0;
11943 if (Record->isUnion())
11944 DiagID = getLangOpts().MicrosoftExt
11945 ? diag::ext_flexible_array_union_ms
11946 : getLangOpts().CPlusPlus
11947 ? diag::ext_flexible_array_union_gnu
11948 : diag::err_flexible_array_union;
11949 else if (Fields.size() == 1)
11950 DiagID = getLangOpts().MicrosoftExt
11951 ? diag::ext_flexible_array_empty_aggregate_ms
11952 : getLangOpts().CPlusPlus
11953 ? diag::ext_flexible_array_empty_aggregate_gnu
11954 : NumNamedMembers < 1
11955 ? diag::err_flexible_array_empty_aggregate
11956 : 0;
11957
11958 if (DiagID)
11959 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11960 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011961 // While the layout of types that contain virtual bases is not specified
11962 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11963 // virtual bases after the derived members. This would make a flexible
11964 // array member declared at the end of an object not adjacent to the end
11965 // of the type.
11966 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11967 if (RD->getNumVBases() != 0)
11968 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11969 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011970 if (!getLangOpts().C99)
11971 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11972 << FD->getDeclName() << Record->getTagKind();
11973
Richard Smith6fa28ff2014-01-11 00:53:35 +000011974 // If the element type has a non-trivial destructor, we would not
11975 // implicitly destroy the elements, so disallow it for now.
11976 //
11977 // FIXME: GCC allows this. We should probably either implicitly delete
11978 // the destructor of the containing class, or just allow this.
11979 QualType BaseElem = Context.getBaseElementType(FD->getType());
11980 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11981 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011982 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011983 FD->setInvalidDecl();
11984 EnclosingDecl->setInvalidDecl();
11985 continue;
11986 }
Chris Lattner720a0542007-01-25 00:44:24 +000011987 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011988 if (Record)
11989 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011990 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011991 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011992 diag::err_field_incomplete)) {
11993 // Incomplete type
11994 FD->setInvalidDecl();
11995 EnclosingDecl->setInvalidDecl();
11996 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011997 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011998 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11999 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012000 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012001 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012002 } else {
12003 // If this is a struct/class and this is not the last element, reject
12004 // it. Note that GCC supports variable sized arrays in the middle of
12005 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012006 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012007 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012008 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012009 else {
12010 // We support flexible arrays at the end of structs in
12011 // other structs as an extension.
12012 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12013 << FD->getDeclName();
12014 if (Record)
12015 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012016 }
Chris Lattner720a0542007-01-25 00:44:24 +000012017 }
12018 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012019 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12020 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12021 diag::err_abstract_type_in_decl,
12022 AbstractIvarType)) {
12023 // Ivars can not have abstract class types
12024 FD->setInvalidDecl();
12025 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012026 if (Record && FDTTy->getDecl()->hasObjectMember())
12027 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012028 if (Record && FDTTy->getDecl()->hasVolatileMember())
12029 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012030 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012031 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012032 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12033 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12034 QualType T = Context.getObjCObjectPointerType(FD->getType());
12035 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012036 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12037 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12038 // It's an error in ARC if a field has lifetime.
12039 // We don't want to report this in a system header, though,
12040 // so we just make the field unavailable.
12041 // FIXME: that's really not sufficient; we need to make the type
12042 // itself invalid to, say, initialize or copy.
12043 QualType T = FD->getType();
12044 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12045 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12046 SourceLocation loc = FD->getLocation();
12047 if (getSourceManager().isInSystemHeader(loc)) {
12048 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012049 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12050 "this system field has retaining ownership",
12051 loc));
John McCall31168b02011-06-15 23:02:42 +000012052 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012053 } else {
12054 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012055 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012056 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012057 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012058 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012059 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012060 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012061 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012062 if (FD->getType()->isObjCObjectPointerType() ||
12063 FD->getType().isObjCGCStrong())
12064 Record->setHasObjectMember(true);
12065 else if (Context.getAsArrayType(FD->getType())) {
12066 QualType BaseType = Context.getBaseElementType(FD->getType());
12067 if (BaseType->isRecordType() &&
12068 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012069 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012070 else if (BaseType->isObjCObjectPointerType() ||
12071 BaseType.isObjCGCStrong())
12072 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012073 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012074 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012075 if (Record && FD->getType().isVolatileQualified())
12076 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012077 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012078 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012079 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012080 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012081
Chris Lattner82625602007-01-24 02:26:21 +000012082 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012083 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012084 bool Completed = false;
12085 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12086 if (!CXXRecord->isInvalidDecl()) {
12087 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012088 for (CXXRecordDecl::conversion_iterator
12089 I = CXXRecord->conversion_begin(),
12090 E = CXXRecord->conversion_end(); I != E; ++I)
12091 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012092
12093 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012094 if (CXXRecord->hasUserDeclaredDestructor()) {
12095 // Adjust user-defined destructor exception spec.
12096 if (getLangOpts().CPlusPlus11)
12097 AdjustDestructorExceptionSpec(CXXRecord,
12098 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012099 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012100
Douglas Gregor8fb95122010-09-29 00:15:42 +000012101 // Add any implicitly-declared members to this class.
12102 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12103
12104 // If we have virtual base classes, we may end up finding multiple
12105 // final overriders for a given virtual function. Check for this
12106 // problem now.
12107 if (CXXRecord->getNumVBases()) {
12108 CXXFinalOverriderMap FinalOverriders;
12109 CXXRecord->getFinalOverriders(FinalOverriders);
12110
12111 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12112 MEnd = FinalOverriders.end();
12113 M != MEnd; ++M) {
12114 for (OverridingMethods::iterator SO = M->second.begin(),
12115 SOEnd = M->second.end();
12116 SO != SOEnd; ++SO) {
12117 assert(SO->second.size() > 0 &&
12118 "Virtual function without overridding functions?");
12119 if (SO->second.size() == 1)
12120 continue;
12121
12122 // C++ [class.virtual]p2:
12123 // In a derived class, if a virtual member function of a base
12124 // class subobject has more than one final overrider the
12125 // program is ill-formed.
12126 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012127 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012128 Diag(M->first->getLocation(),
12129 diag::note_overridden_virtual_function);
12130 for (OverridingMethods::overriding_iterator
12131 OM = SO->second.begin(),
12132 OMEnd = SO->second.end();
12133 OM != OMEnd; ++OM)
12134 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012135 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012136
12137 Record->setInvalidDecl();
12138 }
12139 }
12140 CXXRecord->completeDefinition(&FinalOverriders);
12141 Completed = true;
12142 }
12143 }
12144 }
12145 }
12146
12147 if (!Completed)
12148 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012149
David Majnemer2c4e00a2014-01-29 22:07:36 +000012150 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012151 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012152
David Majnemer2c4e00a2014-01-29 22:07:36 +000012153 if (MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12154 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12155 IA->getRange(),
12156 IA->getSemanticSpelling());
12157 }
12158
Serge Pavlov3cb80222013-11-14 02:13:03 +000012159 // Check if the structure/union declaration is a type that can have zero
12160 // size in C. For C this is a language extension, for C++ it may cause
12161 // compatibility problems.
12162 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012163 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012164 CheckForZeroSize = true;
12165 } else {
12166 // For C++ filter out types that cannot be referenced in C code.
12167 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12168 CheckForZeroSize =
12169 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12170 !CXXRecord->isDependentType() &&
12171 CXXRecord->isCLike();
12172 }
12173 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012174 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012175 bool IsEmpty = true;
12176 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012177 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012178 E = Record->field_end();
12179 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12180 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012181 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012182 if (I->getBitWidthValue(Context) > 0)
12183 ZeroSize = false;
12184 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012185 ++NonBitFields;
12186 QualType FieldType = I->getType();
12187 if (FieldType->isIncompleteType() ||
12188 !Context.getTypeSizeInChars(FieldType).isZero())
12189 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012190 }
12191 }
12192
Serge Pavlov3cb80222013-11-14 02:13:03 +000012193 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12194 // allowed in C++, but warn if its declaration is inside
12195 // extern "C" block.
12196 if (ZeroSize) {
12197 Diag(RecLoc, getLangOpts().CPlusPlus ?
12198 diag::warn_zero_size_struct_union_in_extern_c :
12199 diag::warn_zero_size_struct_union_compat)
12200 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12201 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012202
Serge Pavlov3cb80222013-11-14 02:13:03 +000012203 // Structs without named members are extension in C (C99 6.7.2.1p7),
12204 // but are accepted by GCC.
12205 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12206 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12207 diag::ext_no_named_members_in_struct_union)
12208 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012209 }
12210 }
Chris Lattner622c1932008-02-06 00:51:33 +000012211 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012212 ObjCIvarDecl **ClsFields =
12213 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012214 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012215 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012216 // Add ivar's to class's DeclContext.
12217 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12218 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012219 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012220 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012221 // Must enforce the rule that ivars in the base classes may not be
12222 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012223 if (ID->getSuperClass())
12224 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012225 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012226 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012227 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012228 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12229 // Ivar declared in @implementation never belongs to the implementation.
12230 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012231 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012232 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012233 IMPDecl->setIvarLBraceLoc(LBrac);
12234 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012235 } else if (ObjCCategoryDecl *CDecl =
12236 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012237 // case of ivars in class extension; all other cases have been
12238 // reported as errors elsewhere.
12239 // FIXME. Class extension does not have a LocEnd field.
12240 // CDecl->setLocEnd(RBrac);
12241 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012242 // Diagnose redeclaration of private ivars.
12243 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012244 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012245 if (IDecl) {
12246 if (const ObjCIvarDecl *ClsIvar =
12247 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12248 Diag(ClsFields[i]->getLocation(),
12249 diag::err_duplicate_ivar_declaration);
12250 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12251 continue;
12252 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012253 for (ObjCInterfaceDecl::known_extensions_iterator
12254 Ext = IDecl->known_extensions_begin(),
12255 ExtEnd = IDecl->known_extensions_end();
12256 Ext != ExtEnd; ++Ext) {
12257 if (const ObjCIvarDecl *ClsExtIvar
12258 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012259 Diag(ClsFields[i]->getLocation(),
12260 diag::err_duplicate_ivar_declaration);
12261 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12262 continue;
12263 }
12264 }
12265 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012266 ClsFields[i]->setLexicalDeclContext(CDecl);
12267 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012268 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012269 CDecl->setIvarLBraceLoc(LBrac);
12270 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012271 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012272 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012273
12274 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012275 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012276}
12277
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012278/// \brief Determine whether the given integral value is representable within
12279/// the given type T.
12280static bool isRepresentableIntegerValue(ASTContext &Context,
12281 llvm::APSInt &Value,
12282 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012283 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012284 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012285
Douglas Gregor0bf31402010-10-08 23:50:27 +000012286 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012287 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012288 --BitWidth;
12289 return Value.getActiveBits() <= BitWidth;
12290 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012291 return Value.getMinSignedBits() <= BitWidth;
12292}
12293
12294// \brief Given an integral type, return the next larger integral type
12295// (or a NULL type of no such type exists).
12296static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12297 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12298 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012299 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012300 const unsigned NumTypes = 4;
12301 QualType SignedIntegralTypes[NumTypes] = {
12302 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12303 };
12304 QualType UnsignedIntegralTypes[NumTypes] = {
12305 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12306 Context.UnsignedLongLongTy
12307 };
12308
12309 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012310 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12311 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012312 for (unsigned I = 0; I != NumTypes; ++I)
12313 if (Context.getTypeSize(Types[I]) > BitWidth)
12314 return Types[I];
12315
12316 return QualType();
12317}
12318
Douglas Gregor954f6b272009-03-17 19:05:46 +000012319EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12320 EnumConstantDecl *LastEnumConst,
12321 SourceLocation IdLoc,
12322 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012323 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012324 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012325 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012326 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012327
12328 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12329 Val = 0;
12330
Eli Friedman7c6515a2011-12-06 00:10:34 +000012331 if (Val)
12332 Val = DefaultLvalueConversion(Val).take();
12333
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012334 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012335 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012336 EltTy = Context.DependentTy;
12337 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012338 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012339 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012340 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012341 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12342 // constant-expression in the enumerator-definition shall be a converted
12343 // constant expression of the underlying type.
12344 EltTy = Enum->getIntegerType();
12345 ExprResult Converted =
12346 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12347 CCEK_Enumerator);
12348 if (Converted.isInvalid())
12349 Val = 0;
12350 else
12351 Val = Converted.take();
12352 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012353 !(Val = VerifyIntegerConstantExpression(Val,
12354 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012355 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012356 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012357 if (Enum->isFixed()) {
12358 EltTy = Enum->getIntegerType();
12359
Richard Smithf8379a02012-01-18 23:55:52 +000012360 // In Obj-C and Microsoft mode, require the enumeration value to be
12361 // representable in the underlying type of the enumeration. In C++11,
12362 // we perform a non-narrowing conversion as part of converted constant
12363 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012364 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012365 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012366 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012367 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012368 } else
12369 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012370 } else
John Wiegley01296292011-04-08 18:41:53 +000012371 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012372 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012373 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012374 // If the underlying type is not fixed, the type of each enumerator
12375 // is the type of its initializing value:
12376 // - If an initializer is specified for an enumerator, the
12377 // initializing value has the same type as the expression.
12378 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012379 } else {
12380 // C99 6.7.2.2p2:
12381 // The expression that defines the value of an enumeration constant
12382 // shall be an integer constant expression that has a value
12383 // representable as an int.
12384
12385 // Complain if the value is not representable in an int.
12386 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12387 Diag(IdLoc, diag::ext_enum_value_not_int)
12388 << EnumVal.toString(10) << Val->getSourceRange()
12389 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12390 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12391 // Force the type of the expression to 'int'.
12392 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12393 }
12394 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012395 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012396 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012397 }
12398 }
Mike Stump11289f42009-09-09 15:08:12 +000012399
Douglas Gregor954f6b272009-03-17 19:05:46 +000012400 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012401 if (Enum->isDependentType())
12402 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012403 else if (!LastEnumConst) {
12404 // C++0x [dcl.enum]p5:
12405 // If the underlying type is not fixed, the type of each enumerator
12406 // is the type of its initializing value:
12407 // - If no initializer is specified for the first enumerator, the
12408 // initializing value has an unspecified integral type.
12409 //
12410 // GCC uses 'int' for its unspecified integral type, as does
12411 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012412 if (Enum->isFixed()) {
12413 EltTy = Enum->getIntegerType();
12414 }
12415 else {
12416 EltTy = Context.IntTy;
12417 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012418 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012419 // Assign the last value + 1.
12420 EnumVal = LastEnumConst->getInitVal();
12421 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012422 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012423
12424 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012425 if (EnumVal < LastEnumConst->getInitVal()) {
12426 // C++0x [dcl.enum]p5:
12427 // If the underlying type is not fixed, the type of each enumerator
12428 // is the type of its initializing value:
12429 //
12430 // - Otherwise the type of the initializing value is the same as
12431 // the type of the initializing value of the preceding enumerator
12432 // unless the incremented value is not representable in that type,
12433 // in which case the type is an unspecified integral type
12434 // sufficient to contain the incremented value. If no such type
12435 // exists, the program is ill-formed.
12436 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012437 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012438 // There is no integral type larger enough to represent this
12439 // value. Complain, then allow the value to wrap around.
12440 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012441 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012442 ++EnumVal;
12443 if (Enum->isFixed())
12444 // When the underlying type is fixed, this is ill-formed.
12445 Diag(IdLoc, diag::err_enumerator_wrapped)
12446 << EnumVal.toString(10)
12447 << EltTy;
12448 else
12449 Diag(IdLoc, diag::warn_enumerator_too_large)
12450 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012451 } else {
12452 EltTy = T;
12453 }
12454
12455 // Retrieve the last enumerator's value, extent that type to the
12456 // type that is supposed to be large enough to represent the incremented
12457 // value, then increment.
12458 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012459 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012460 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012461 ++EnumVal;
12462
12463 // If we're not in C++, diagnose the overflow of enumerator values,
12464 // which in C99 means that the enumerator value is not representable in
12465 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12466 // permits enumerator values that are representable in some larger
12467 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012468 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012469 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012470 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012471 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12472 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12473 Diag(IdLoc, diag::ext_enum_value_not_int)
12474 << EnumVal.toString(10) << 1;
12475 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012476 }
12477 }
Mike Stump11289f42009-09-09 15:08:12 +000012478
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012479 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012480 // Make the enumerator value match the signedness and size of the
12481 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012482 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012483 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012484 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012485
Douglas Gregor954f6b272009-03-17 19:05:46 +000012486 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012487 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012488}
12489
12490
John McCall811a0f52010-10-22 23:36:17 +000012491Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12492 SourceLocation IdLoc, IdentifierInfo *Id,
12493 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012494 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012495 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012496 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012497 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012498
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012499 // The scope passed in may not be a decl scope. Zip up the scope tree until
12500 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012501 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012502
Chris Lattner8116d1b2007-01-25 22:38:29 +000012503 // Verify that there isn't already something declared with this name in this
12504 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012505 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012506 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012507 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012508 // Maybe we will complain about the shadowed template parameter.
12509 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12510 // Just pretend that we didn't see the previous declaration.
12511 PrevDecl = 0;
12512 }
12513
12514 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012515 // When in C++, we may get a TagDecl with the same name; in this case the
12516 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012517 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012518 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012519 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012520 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012521 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012522 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012523 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012524 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012525 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012526 }
12527 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012528
Aaron Ballman24a10472012-07-19 03:12:23 +000012529 // C++ [class.mem]p15:
12530 // If T is the name of a class, then each of the following shall have a name
12531 // different from T:
12532 // - every enumerator of every member of class T that is an unscoped
12533 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012534 if (CXXRecordDecl *Record
12535 = dyn_cast<CXXRecordDecl>(
12536 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012537 if (!TheEnumDecl->isScoped() &&
12538 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012539 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12540
John McCall811a0f52010-10-22 23:36:17 +000012541 EnumConstantDecl *New =
12542 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012543
John McCall553c0792010-01-23 00:46:32 +000012544 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012545 // Process attributes.
12546 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12547
12548 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012549 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012550 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012551 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012552
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012553 ActOnDocumentableDecl(New);
12554
John McCall48871652010-08-21 09:40:31 +000012555 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012556}
12557
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012558// Returns true when the enum initial expression does not trigger the
12559// duplicate enum warning. A few common cases are exempted as follows:
12560// Element2 = Element1
12561// Element2 = Element1 + 1
12562// Element2 = Element1 - 1
12563// Where Element2 and Element1 are from the same enum.
12564static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12565 Expr *InitExpr = ECD->getInitExpr();
12566 if (!InitExpr)
12567 return true;
12568 InitExpr = InitExpr->IgnoreImpCasts();
12569
12570 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12571 if (!BO->isAdditiveOp())
12572 return true;
12573 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12574 if (!IL)
12575 return true;
12576 if (IL->getValue() != 1)
12577 return true;
12578
12579 InitExpr = BO->getLHS();
12580 }
12581
12582 // This checks if the elements are from the same enum.
12583 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12584 if (!DRE)
12585 return true;
12586
12587 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12588 if (!EnumConstant)
12589 return true;
12590
12591 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12592 Enum)
12593 return true;
12594
12595 return false;
12596}
12597
12598struct DupKey {
12599 int64_t val;
12600 bool isTombstoneOrEmptyKey;
12601 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12602 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12603};
12604
12605static DupKey GetDupKey(const llvm::APSInt& Val) {
12606 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12607 false);
12608}
12609
12610struct DenseMapInfoDupKey {
12611 static DupKey getEmptyKey() { return DupKey(0, true); }
12612 static DupKey getTombstoneKey() { return DupKey(1, true); }
12613 static unsigned getHashValue(const DupKey Key) {
12614 return (unsigned)(Key.val * 37);
12615 }
12616 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12617 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12618 LHS.val == RHS.val;
12619 }
12620};
12621
12622// Emits a warning when an element is implicitly set a value that
12623// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012624static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12625 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012626 QualType EnumType) {
12627 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12628 Enum->getLocation()) ==
12629 DiagnosticsEngine::Ignored)
12630 return;
12631 // Avoid anonymous enums
12632 if (!Enum->getIdentifier())
12633 return;
12634
12635 // Only check for small enums.
12636 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12637 return;
12638
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012639 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12640 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012641
12642 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12643 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12644 ValueToVectorMap;
12645
12646 DuplicatesVector DupVector;
12647 ValueToVectorMap EnumMap;
12648
12649 // Populate the EnumMap with all values represented by enum constants without
12650 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012651 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012652 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012653
12654 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12655 // this constant. Skip this enum since it may be ill-formed.
12656 if (!ECD) {
12657 return;
12658 }
12659
12660 if (ECD->getInitExpr())
12661 continue;
12662
12663 DupKey Key = GetDupKey(ECD->getInitVal());
12664 DeclOrVector &Entry = EnumMap[Key];
12665
12666 // First time encountering this value.
12667 if (Entry.isNull())
12668 Entry = ECD;
12669 }
12670
12671 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012672 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012673 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12674 if (!ValidDuplicateEnum(ECD, Enum))
12675 continue;
12676
12677 DupKey Key = GetDupKey(ECD->getInitVal());
12678
12679 DeclOrVector& Entry = EnumMap[Key];
12680 if (Entry.isNull())
12681 continue;
12682
12683 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12684 // Ensure constants are different.
12685 if (D == ECD)
12686 continue;
12687
12688 // Create new vector and push values onto it.
12689 ECDVector *Vec = new ECDVector();
12690 Vec->push_back(D);
12691 Vec->push_back(ECD);
12692
12693 // Update entry to point to the duplicates vector.
12694 Entry = Vec;
12695
12696 // Store the vector somewhere we can consult later for quick emission of
12697 // diagnostics.
12698 DupVector.push_back(Vec);
12699 continue;
12700 }
12701
12702 ECDVector *Vec = Entry.get<ECDVector*>();
12703 // Make sure constants are not added more than once.
12704 if (*Vec->begin() == ECD)
12705 continue;
12706
12707 Vec->push_back(ECD);
12708 }
12709
12710 // Emit diagnostics.
12711 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12712 DupVectorEnd = DupVector.end();
12713 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12714 ECDVector *Vec = *DupVectorIter;
12715 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12716
12717 // Emit warning for one enum constant.
12718 ECDVector::iterator I = Vec->begin();
12719 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12720 << (*I)->getName() << (*I)->getInitVal().toString(10)
12721 << (*I)->getSourceRange();
12722 ++I;
12723
12724 // Emit one note for each of the remaining enum constants with
12725 // the same value.
12726 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12727 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12728 << (*I)->getName() << (*I)->getInitVal().toString(10)
12729 << (*I)->getSourceRange();
12730 delete Vec;
12731 }
12732}
12733
Mike Stump6814d1c2009-05-16 07:06:02 +000012734void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012735 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012736 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012737 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012738 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012739 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012740
12741 if (Attr)
12742 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012743
Eli Friedmand0e60972009-12-11 01:34:50 +000012744 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012745 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012746 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012747 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012748 if (!ECD) continue;
12749
12750 ECD->setType(EnumType);
12751 }
12752
John McCall9aa35be2010-05-06 08:49:23 +000012753 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012754 return;
12755 }
12756
Chris Lattner67933c02007-08-28 05:10:31 +000012757 // TODO: If the result value doesn't fit in an int, it must be a long or long
12758 // long value. ISO C does not support this, but GCC does as an extension,
12759 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012760 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12761 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12762 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012763
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012764 // Verify that all the values are okay, compute the size of the values, and
12765 // reverse the list.
12766 unsigned NumNegativeBits = 0;
12767 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012768
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012769 // Keep track of whether all elements have type int.
12770 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012771
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012772 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012773 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012774 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012775 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012776
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012777 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012778
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012779 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012780 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012781 NumPositiveBits = std::max(NumPositiveBits,
12782 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012783 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012784 NumNegativeBits = std::max(NumNegativeBits,
12785 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012786
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012787 // Keep track of whether every enum element has type int (very commmon).
12788 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012789 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012790 }
Mike Stump11289f42009-09-09 15:08:12 +000012791
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012792 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012793 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012794 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012795
John McCall56774992009-12-09 09:09:27 +000012796 // C++0x N3000 [conv.prom]p3:
12797 // An rvalue of an unscoped enumeration type whose underlying
12798 // type is not fixed can be converted to an rvalue of the first
12799 // of the following types that can represent all the values of
12800 // the enumeration: int, unsigned int, long int, unsigned long
12801 // int, long long int, or unsigned long long int.
12802 // C99 6.4.4.3p2:
12803 // An identifier declared as an enumeration constant has type int.
12804 // The C99 rule is modified by a gcc extension
12805 QualType BestPromotionType;
12806
Aaron Ballman9ead1242013-12-19 02:39:40 +000012807 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012808 // -fshort-enums is the equivalent to specifying the packed attribute on all
12809 // enum definitions.
12810 if (LangOpts.ShortEnums)
12811 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012812
Douglas Gregor0bf31402010-10-08 23:50:27 +000012813 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012814 BestType = Enum->getIntegerType();
12815 if (BestType->isPromotableIntegerType())
12816 BestPromotionType = Context.getPromotedIntegerType(BestType);
12817 else
12818 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012819 // We don't need to set BestWidth, because BestType is going to be the type
12820 // of the enumerators, but we do anyway because otherwise some compilers
12821 // warn that it might be used uninitialized.
12822 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012823 }
12824 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012825 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012826 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012827 // If it's packed, check also if it fits a char or a short.
12828 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012829 BestType = Context.SignedCharTy;
12830 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012831 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012832 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012833 BestType = Context.ShortTy;
12834 BestWidth = ShortWidth;
12835 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012836 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012837 BestWidth = IntWidth;
12838 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012839 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012840
John McCall56774992009-12-09 09:09:27 +000012841 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012842 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012843 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012844 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012845
Chris Lattner3a370bf2007-08-29 17:31:48 +000012846 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012847 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12848 BestType = Context.LongLongTy;
12849 }
12850 }
John McCall56774992009-12-09 09:09:27 +000012851 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012852 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012853 // If there is no negative value, figure out the smallest type that fits
12854 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012855 // If it's packed, check also if it fits a char or a short.
12856 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012857 BestType = Context.UnsignedCharTy;
12858 BestPromotionType = Context.IntTy;
12859 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012860 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012861 BestType = Context.UnsignedShortTy;
12862 BestPromotionType = Context.IntTy;
12863 BestWidth = ShortWidth;
12864 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012865 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012866 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012867 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012868 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012869 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012870 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012871 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012872 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012873 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012874 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012875 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012876 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012877 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012878 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012879 "How could an initializer get larger than ULL?");
12880 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012881 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012882 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012883 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012884 }
12885 }
Mike Stump11289f42009-09-09 15:08:12 +000012886
Chris Lattner3a370bf2007-08-29 17:31:48 +000012887 // Loop over all of the enumerator constants, changing their types to match
12888 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012889 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012890 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012891 if (!ECD) continue; // Already issued a diagnostic.
12892
12893 // Standard C says the enumerators have int type, but we allow, as an
12894 // extension, the enumerators to be larger than int size. If each
12895 // enumerator value fits in an int, type it as an int, otherwise type it the
12896 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12897 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012898
12899 // Determine whether the value fits into an int.
12900 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012901
12902 // If it fits into an integer type, force it. Otherwise force it to match
12903 // the enum decl type.
12904 QualType NewTy;
12905 unsigned NewWidth;
12906 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012907 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012908 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012909 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012910 NewTy = Context.IntTy;
12911 NewWidth = IntWidth;
12912 NewSign = true;
12913 } else if (ECD->getType() == BestType) {
12914 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012915 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012916 // C++ [dcl.enum]p4: Following the closing brace of an
12917 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012918 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012919 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012920 continue;
12921 } else {
12922 NewTy = BestType;
12923 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012924 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012925 }
12926
12927 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012928 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012929 InitVal.setIsSigned(NewSign);
12930 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012931
Chris Lattner3a370bf2007-08-29 17:31:48 +000012932 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012933 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012934 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012935 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012936 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012937 ECD->getInitExpr(),
12938 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012939 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012940 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012941 // C++ [dcl.enum]p4: Following the closing brace of an
12942 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012943 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012944 ECD->setType(EnumType);
12945 else
12946 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012947 }
Mike Stump11289f42009-09-09 15:08:12 +000012948
John McCall9aa35be2010-05-06 08:49:23 +000012949 Enum->completeDefinition(BestType, BestPromotionType,
12950 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012951
12952 // If we're declaring a function, ensure this decl isn't forgotten about -
12953 // it needs to go into the function scope.
12954 if (InFunctionDeclarator)
12955 DeclsInPrototypeScope.push_back(Enum);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012956
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012957 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012958
12959 // Now that the enum type is defined, ensure it's not been underaligned.
12960 if (Enum->hasAttrs())
12961 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012962}
Chris Lattner1300fb92007-01-23 23:42:53 +000012963
Abramo Bagnara348823a2011-03-03 14:20:18 +000012964Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12965 SourceLocation StartLoc,
12966 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012967 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012968
Douglas Gregor278f52e2009-05-30 00:08:05 +000012969 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012970 AsmString, StartLoc,
12971 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012972 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012973 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012974}
Eli Friedman5ed51982009-06-05 02:44:36 +000012975
Douglas Gregor22d09742012-01-03 18:04:46 +000012976DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12977 SourceLocation ImportLoc,
12978 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000012979 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000012980 Module::AllVisible,
12981 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000012982 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000012983 return true;
12984
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012985 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000012986 Module *ModCheck = Mod;
12987 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12988 // If we've run out of module parents, just drop the remaining identifiers.
12989 // We need the length to be consistent.
12990 if (!ModCheck)
12991 break;
12992 ModCheck = ModCheck->Parent;
12993
12994 IdentifierLocs.push_back(Path[I].second);
12995 }
12996
12997 ImportDecl *Import = ImportDecl::Create(Context,
12998 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000012999 AtLoc.isValid()? AtLoc : ImportLoc,
13000 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013001 Context.getTranslationUnitDecl()->addDecl(Import);
13002 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013003}
13004
Richard Smithce587f52013-11-15 04:24:58 +000013005void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13006 // FIXME: Should we synthesize an ImportDecl here?
13007 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13008 /*Complain=*/true);
13009}
13010
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013011void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13012 // Create the implicit import declaration.
13013 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13014 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13015 Loc, Mod, Loc);
13016 TU->addDecl(ImportD);
13017 Consumer.HandleImplicitImportDecl(ImportD);
13018
13019 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000013020 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13021 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013022}
13023
David Chisnall0867d9c2012-02-18 16:12:34 +000013024void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13025 IdentifierInfo* AliasName,
13026 SourceLocation PragmaLoc,
13027 SourceLocation NameLoc,
13028 SourceLocation AliasNameLoc) {
13029 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13030 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013031 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13032 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013033
13034 if (PrevDecl)
13035 PrevDecl->addAttr(Attr);
13036 else
13037 (void)ExtnameUndeclaredIdentifiers.insert(
13038 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13039}
13040
Eli Friedman5ed51982009-06-05 02:44:36 +000013041void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13042 SourceLocation PragmaLoc,
13043 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013044 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013045
Eli Friedman5ed51982009-06-05 02:44:36 +000013046 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013047 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013048 } else {
13049 (void)WeakUndeclaredIdentifiers.insert(
13050 std::pair<IdentifierInfo*,WeakInfo>
13051 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013052 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013053}
13054
13055void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13056 IdentifierInfo* AliasName,
13057 SourceLocation PragmaLoc,
13058 SourceLocation NameLoc,
13059 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013060 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13061 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013062 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013063
Eli Friedman5ed51982009-06-05 02:44:36 +000013064 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013065 if (!PrevDecl->hasAttr<AliasAttr>())
13066 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013067 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013068 } else {
13069 (void)WeakUndeclaredIdentifiers.insert(
13070 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013071 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013072}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013073
13074Decl *Sema::getObjCDeclContext() const {
13075 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13076}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013077
13078AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013079 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013080 // If we are within an Objective-C method, we should consult
13081 // both the availability of the method as well as the
13082 // enclosing class. If the class is (say) deprecated,
13083 // the entire method is considered deprecated from the
13084 // purpose of checking if the current context is deprecated.
13085 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13086 AvailabilityResult R = MD->getAvailability();
13087 if (R != AR_Available)
13088 return R;
13089 D = MD->getClassInterface();
13090 }
13091 // If we are within an Objective-c @implementation, it
13092 // gets the same availability context as the @interface.
13093 else if (const ObjCImplementationDecl *ID =
13094 dyn_cast<ObjCImplementationDecl>(D)) {
13095 D = ID->getClassInterface();
13096 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013097 return D->getAvailability();
13098}